|
1 | | -use std::env; |
2 | 1 | use std::ffi::{OsStr, OsString}; |
3 | 2 | use std::path::{Path, PathBuf}; |
4 | 3 | use std::sync::{LazyLock, OnceLock}; |
| 4 | +use std::{env, io}; |
5 | 5 |
|
6 | 6 | #[cfg(doc)] |
7 | 7 | use crate::{Builder, tempdir_in, tempfile_in}; |
8 | 8 |
|
9 | | -static ENV_TEMPDIR: LazyLock<PathBuf> = LazyLock::new(env::temp_dir); |
| 9 | +static ENV_TEMPDIR: LazyLock<Option<PathBuf>> = |
| 10 | + // Only call env::temp_dir() on platforms known to not panic. |
| 11 | + LazyLock::new(if cfg!(any(unix, windows, target_os = "hermit")) { |
| 12 | + || Some(env::temp_dir()) |
| 13 | + } else { |
| 14 | + || None |
| 15 | + }); |
10 | 16 | static DEFAULT_TEMPDIR: OnceLock<PathBuf> = OnceLock::new(); |
11 | 17 | static DEFAULT_PREFIX: OnceLock<OsString> = OnceLock::new(); |
12 | 18 |
|
@@ -36,16 +42,22 @@ pub fn override_temp_dir(path: impl Into<PathBuf>) -> Result<&'static Path, &'st |
36 | 42 | /// Returns the default temporary directory, used for both temporary directories and files if no |
37 | 43 | /// directory is explicitly specified. |
38 | 44 | /// |
39 | | -/// This function simply delegates to [`std::env::temp_dir`] unless the default temporary directory |
40 | | -/// has been overridden by a call to [`override_temp_dir`]. |
| 45 | +/// Unless the default temporary directory has been overridden by a call to [`override_temp_dir`], |
| 46 | +/// this function delegates to [`std::env::temp_dir`] (when supported by the platform). It returns |
| 47 | +/// an error on platforms with no default temporary directory (e.g., WASI/WASM) unless |
| 48 | +/// [`override_temp_dir`] has already been called to set the temporary directory. |
41 | 49 | /// |
42 | 50 | /// **NOTE:** |
43 | 51 | /// |
44 | 52 | /// 1. This function does not check if the returned directory exists and/or is writable. |
45 | 53 | /// 2. This function caches the result of [`std::env::temp_dir`]. Any future changes to, e.g., the |
46 | 54 | /// `TMPDIR` environment variable won't have any effect. |
47 | | -pub fn temp_dir() -> &'static Path { |
48 | | - DEFAULT_TEMPDIR.get().unwrap_or_else(|| &ENV_TEMPDIR) |
| 55 | +pub fn temp_dir() -> io::Result<&'static Path> { |
| 56 | + DEFAULT_TEMPDIR |
| 57 | + .get() |
| 58 | + .or_else(|| ENV_TEMPDIR.as_ref()) |
| 59 | + .map(|a| &**a) |
| 60 | + .ok_or_else(|| io::Error::other("no temporary directory configured")) |
49 | 61 | } |
50 | 62 |
|
51 | 63 | /// Override the default prefix for new temporary files (defaults to "tmp"). This function changes |
|
0 commit comments