| 1 | // Based on code from https://github.com/sharkdp/bat e981e974076a926a38f124b7d8746de2ca5f0a28 |
| 2 | // See src/utils/bat/LICENSE |
| 3 | |
| 4 | use lazy_static::lazy_static; |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | #[cfg(target_os = "macos")] |
| 8 | use std::env; |
| 9 | |
| 10 | /// Wrapper for 'dirs' that treats MacOS more like Linux, by following the XDG specification. |
| 11 | /// This means that the `XDG_CACHE_HOME` and `XDG_CONFIG_HOME` environment variables are |
| 12 | /// checked first. The fallback directories are `~/.cache/bat` and `~/.config/bat`, respectively. |
| 13 | pub struct BatProjectDirs { |
| 14 | cache_dir: PathBuf, |
| 15 | } |
| 16 | |
| 17 | impl BatProjectDirs { |
| 18 | fn new() -> Option<BatProjectDirs> { |
| 19 | #[cfg(target_os = "macos")] |
| 20 | let cache_dir_op = env::var_os("XDG_CACHE_HOME") |
| 21 | .map(PathBuf::from) |
| 22 | .filter(|p| p.is_absolute()) |
| 23 | .or_else(|| dirs::home_dir().map(|d| d.join(".cache"))); |
| 24 | |
| 25 | #[cfg(not(target_os = "macos"))] |
| 26 | let cache_dir_op = dirs::cache_dir(); |
| 27 | |
| 28 | let cache_dir = cache_dir_op.map(|d| d.join("bat"))?; |
| 29 | |
| 30 | Some(BatProjectDirs { cache_dir }) |
| 31 | } |
| 32 | |
| 33 | pub fn cache_dir(&self) -> &Path { |
| 34 | &self.cache_dir |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | lazy_static! { |
| 39 | pub static ref PROJECT_DIRS: BatProjectDirs = |
| 40 | BatProjectDirs::new().unwrap_or_else(|| panic!("Could not get home directory")); |
| 41 | } |