Skip to content

Commit

Permalink
Use UUID's to generate random tempname on Windows (#33785)
Browse files Browse the repository at this point in the history
* Use UIUD to create random tempname on Windows

* Use underscores and remove extension

* Truncate to 10 chars the UUID

* Generate the random name from a random byte array

* Update file.jl
  • Loading branch information
musm authored and Keno committed Jan 18, 2020
1 parent ca5642d commit d759b5b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
31 changes: 19 additions & 12 deletions base/file.jl
Original file line number Diff line number Diff line change
Expand Up @@ -517,20 +517,27 @@ function mktemp(parent::AbstractString=tempdir(); cleanup::Bool=true)
return (filename, Base.open(filename, "r+"))
end

# generate a random string from random bytes
function _rand_string()
nchars = 10
A = Vector{UInt8}(undef, nchars)
ccall((:SystemFunction036, :Advapi32), stdcall, UInt8, (Ptr{Cvoid}, UInt32), A, sizeof(A))

slug = Base.StringVector(10)
chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i = 1:nchars
slug[i] = chars[(A[i] % length(chars)) + 1]
end
return name = String(slug)
end

function tempname(parent::AbstractString=tempdir(); cleanup::Bool=true)
isdir(parent) || throw(ArgumentError("$(repr(parent)) is not a directory"))
seed::UInt32 = rand(UInt32)
while true
if (seed & typemax(UInt16)) == 0
seed += 1
end
filename = _win_tempname(parent, seed)
if !ispath(filename)
cleanup && temp_cleanup_later(filename)
return filename
end
seed += 1
end
name = _rand_string()
filename = joinpath(parent, temp_prefix * name)
@assert !ispath(filename)
cleanup && temp_cleanup_later(filename)
return filename
end

else # !windows
Expand Down
12 changes: 12 additions & 0 deletions test/file.jl
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ end

using Random

@testset "that temp names are actually unique" begin
temps = [tempname(cleanup=false) for _ = 1:100]
@test allunique(temps)
temps = map(1:100) do _
path, io = mktemp(cleanup=false)
close(io)
rm(path, force=true)
return path
end
@test allunique(temps)
end

@testset "tempname with parent" begin
t = tempname()
@test dirname(t) == tempdir()
Expand Down

0 comments on commit d759b5b

Please sign in to comment.