diff options
Diffstat (limited to 'cli/deno_dir.rs')
-rw-r--r-- | cli/deno_dir.rs | 66 |
1 files changed, 65 insertions, 1 deletions
diff --git a/cli/deno_dir.rs b/cli/deno_dir.rs index 1447682ec..076692621 100644 --- a/cli/deno_dir.rs +++ b/cli/deno_dir.rs @@ -6,7 +6,7 @@ use std::path::PathBuf; /// in single directory that can be controlled with `$DENO_DIR` env variable. #[derive(Clone)] pub struct DenoDir { - // Example: /Users/rld/.deno/ + /// Example: /Users/rld/.deno/ pub root: PathBuf, /// Used by TsCompiler to cache compiler output. pub gen_cache: DiskCache, @@ -45,3 +45,67 @@ impl DenoDir { Ok(deno_dir) } } + +/// To avoid the poorly managed dirs crate +#[cfg(not(windows))] +mod dirs { + use std::path::PathBuf; + + pub fn cache_dir() -> Option<PathBuf> { + if cfg!(target_os = "macos") { + home_dir().map(|h| h.join("Library/Caches")) + } else { + std::env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .or_else(|| home_dir().map(|h| h.join(".cache"))) + } + } + + pub fn home_dir() -> Option<PathBuf> { + std::env::var_os("HOME") + .and_then(|h| if h.is_empty() { None } else { Some(h) }) + .map(PathBuf::from) + } +} + +/// To avoid the poorly managed dirs crate +// Copied from +// https://github.com/dirs-dev/dirs-sys-rs/blob/ec7cee0b3e8685573d847f0a0f60aae3d9e07fa2/src/lib.rs#L140-L164 +// MIT license. Copyright (c) 2018-2019 dirs-rs contributors +#[cfg(windows)] +mod dirs { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::path::PathBuf; + use winapi::shared::winerror; + use winapi::um::{combaseapi, knownfolders, shlobj, shtypes, winbase, winnt}; + + fn known_folder(folder_id: shtypes::REFKNOWNFOLDERID) -> Option<PathBuf> { + unsafe { + let mut path_ptr: winnt::PWSTR = std::ptr::null_mut(); + let result = shlobj::SHGetKnownFolderPath( + folder_id, + 0, + std::ptr::null_mut(), + &mut path_ptr, + ); + if result == winerror::S_OK { + let len = winbase::lstrlenW(path_ptr) as usize; + let path = std::slice::from_raw_parts(path_ptr, len); + let ostr: OsString = OsStringExt::from_wide(path); + combaseapi::CoTaskMemFree(path_ptr as *mut winapi::ctypes::c_void); + Some(PathBuf::from(ostr)) + } else { + None + } + } + } + + pub fn cache_dir() -> Option<PathBuf> { + known_folder(&knownfolders::FOLDERID_LocalAppData) + } + + pub fn home_dir() -> Option<PathBuf> { + known_folder(&knownfolders::FOLDERID_Profile) + } +} |