diff --git a/src/libcore/os.rs b/src/libcore/os.rs index 329172bb69ad9..be50c71697fe1 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -30,7 +30,7 @@ export close, fclose, fsync_fd, waitpid; export env, getenv, setenv, fdopen, pipe; export getcwd, dll_filename, self_exe_path; export exe_suffix, dll_suffix, sysname, arch, family; -export homedir, list_dir, list_dir_path, path_is_dir, path_exists, +export homedir, tmpdir, list_dir, list_dir_path, path_is_dir, path_exists, make_absolute, make_dir, remove_dir, change_dir, remove_file, copy_file; export last_os_error; @@ -464,6 +464,46 @@ fn homedir() -> option { } } +/** + * Returns the path to a temporary directory. + * + * On Unix, returns the value of the 'TMPDIR' environment variable if it is + * set and non-empty and '/tmp' otherwise. + * + * On Windows, returns the value of, in order, the 'TMP', 'TEMP', + * 'USERPROFILE' environment variable if any are set and not the empty + * string. Otherwise, tmpdir returns the path to the Windows directory. + */ +fn tmpdir() -> Path { + return lookup(); + + fn getenv_nonempty(v: Path) -> option { + match getenv(v) { + some(x) => + if str::is_empty(x) { + none + } else { + some(x) + }, + _ => none + } + } + + #[cfg(unix)] + fn lookup() -> Path { + option::get_default(getenv_nonempty(~"TMPDIR"), ~"/tmp") + } + + #[cfg(windows)] + fn lookup() -> Path { + option::get_default( + option::or(getenv_nonempty(~"TMP"), + option::or(getenv_nonempty(~"TEMP"), + option::or(getenv_nonempty(~"USERPROFILE"), + getenv_nonempty(~"WINDIR")))), + ~"C:\\Windows") + } +} /// Recursively walk a directory structure fn walk_dir(p: Path, f: fn(Path) -> bool) { @@ -931,6 +971,11 @@ mod tests { |s| setenv(~"USERPROFILE", s)); } + #[test] + fn tmpdir() { + assert !str::is_empty(os::tmpdir()); + } + // Issue #712 #[test] fn test_list_dir_no_invalid_memory_access() { os::list_dir(~"."); }