Skip to content

Commit d528522

Browse files
Rewrote tempfile() and tempdir() for portability
1 parent 08cfa4c commit d528522

File tree

1 file changed

+57
-8
lines changed

1 file changed

+57
-8
lines changed

base/file.jl

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -220,21 +220,70 @@ function dir_remove(directory_name::String)
220220
run(`rmdir $directory_name`)
221221
end
222222

223-
@linux_only function tempdir()
224-
chomp(readall(`mktemp -d`))
223+
# Find an appropriate temporary directory
224+
function base_tempdir()
225+
# First, try environment variables
226+
for environment_variable in ["TMPDIR", "TEMP", "TMP"]
227+
if has(ENV, environment_variable)
228+
if isdir(ENV[environment_variable])
229+
return ENV[environment_variable]
230+
end
231+
end
232+
end
233+
234+
# Second, try locations based on OS
235+
if OS_NAME == :Windows
236+
for windows_dir in ["c:\\temp", "c:\\tmp", "\\temp", "\\tmp"]
237+
if isdir(windows_dir)
238+
return windows_dir
239+
end
240+
end
241+
else
242+
for unix_dir in ["/tmp", "/var/tmp", "/usr/tmp"]
243+
if isdir(unix_dir)
244+
return unix_dir
245+
end
246+
end
247+
end
248+
249+
# In worst case, return the current directory
250+
return cwd()
225251
end
226252

227-
@osx_only function tempdir()
228-
chomp(readall(`mktemp -d -t tmp`))
253+
# Construct a temporary path using randstring() within an
254+
# appropriate temporary directory
255+
function tempname()
256+
dir = base_tempdir()
257+
temp_name = file_path(dir, randstring(8))
258+
while ispath(temp_name)
259+
temp_name = file_path(dir, randstring(8))
260+
end
261+
return temp_name
229262
end
230263

231-
@linux_only function tempfile()
232-
chomp(readall(`mktemp`))
264+
# Create and return the name of a temporary file
265+
function tempfile()
266+
filename = tempname()
267+
try
268+
f = open(filename, "w")
269+
close(f)
270+
catch
271+
error("Unable to create tempfile: $filename")
272+
end
273+
return filename
233274
end
234275

235-
@osx_only function tempfile()
236-
chomp(readall(`mktemp -t tmp`))
276+
# Create and return the name of a temporary directory
277+
function tempdir()
278+
dirname = tempname()
279+
try
280+
dir_create(dirname)
281+
catch
282+
error("Unable to create tempdir: $dirname")
283+
end
284+
return dirname
237285
end
286+
238287
function download_file(url::String)
239288
filename = tempfile()
240289
run(`curl -o $filename $url`)

0 commit comments

Comments
 (0)