Skip to content

Commit

Permalink
use crystal for generating tempfile name
Browse files Browse the repository at this point in the history
  • Loading branch information
Joakim Reinert committed Nov 9, 2017
1 parent e0559e5 commit cb0fca5
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/tempfile.cr
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ require "c/stdlib"
# Tempfile.new("foo", ".png").path # => "/tmp/foo.ulBCPS.png"
# ```
class Tempfile < IO::FileDescriptor
OPEN_FLAGS = LibC::O_EXCL | LibC::O_RDWR | LibC::O_CREAT |
LibC::S_IRUSR | LibC::S_IWUSR
# Creates a `Tempfile` with the given filename and extension.
def initialize(name, extension = nil)
tmpdir = self.class.dirname + File::SEPARATOR
@path = "#{tmpdir}#{name}.XXXXXX#{extension}"
fileno = LibC.mkstemp(@path)
if fileno == -1
raise Errno.new("mkstemp")
end
@path = build_path(name, extension)
fileno = LibC.open(@path, OPEN_FLAGS)

super(fileno, blocking: true)
end

Expand Down Expand Up @@ -96,4 +96,15 @@ class Tempfile < IO::FileDescriptor
def unlink
delete
end

private def build_path(name, extension = nil)
result = String.build do |io|
io << name
io << Time.now.to_s("%Y%m%d")
io << "#{Process.pid}-#{rand(0x100000000).to_s(36)}"
io << extension
end

result.check_no_null_byte
end
end

0 comments on commit cb0fca5

Please sign in to comment.