diff --git a/komorebi/src/core/pathext.rs b/komorebi/src/core/pathext.rs index d203b7a9..81f61ea7 100644 --- a/komorebi/src/core/pathext.rs +++ b/komorebi/src/core/pathext.rs @@ -1,3 +1,5 @@ +//! Resolving environment variables in the paths of the configuration. + use std::collections::HashMap; use std::ffi::OsStr; use std::path::Component; @@ -25,12 +27,20 @@ impl> PathExt for P { for c in self.as_ref().components() { match c { + #[allow(unused_mut)] Component::Normal(mut c) => { + #[cfg(target_os = "windows")] // Special case for ~ and $HOME, replace with $Env:USERPROFILE if c == OsStr::new("~") || c.eq_ignore_ascii_case("$HOME") { c = OsStr::new("$Env:USERPROFILE"); } + #[cfg(unix)] + // Special case for ~, replace with $HOME (macOS and Linux) + if c == OsStr::new("~") { + c = OsStr::new("$HOME"); + } + let bytes = c.as_encoded_bytes(); // %LOCALAPPDATA% @@ -127,9 +137,15 @@ impl serde_with::schemars_1::JsonSchemaAs for ResolvedPathBuf { } fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + // the description is part of the checked-in schemas, which differ per platform + #[cfg(target_os = "windows")] + let description = "A file system path. Environment variables like %VAR%, $Env:VAR, or $VAR are automatically resolved."; + #[cfg(not(target_os = "windows"))] + let description = "A file system path. Environment variables like $VAR are automatically resolved."; + schemars::json_schema!({ "type": "string", - "description": "A file system path. Environment variables like %VAR%, $Env:VAR, or $VAR are automatically resolved." + "description": description }) } } @@ -186,13 +202,28 @@ mod tests { ); assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d")); - // Set a $env:USERPROFILE variable for testing - unsafe { - std::env::set_var("USERPROFILE", "C:\\Users\\user"); + #[cfg(target_os = "windows")] + { + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("USERPROFILE", "C:\\Users\\user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("C:\\Users\\user")); + assert_eq!(resolve("$HOME"), expected("C:\\Users\\user")); } - // ~ and $HOME should be replaced with $Env:USERPROFILE - assert_eq!(resolve("~"), expected("C:\\Users\\user")); - assert_eq!(resolve("$HOME"), expected("C:\\Users\\user")); + #[cfg(unix)] + { + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("HOME", "/Users/user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("/Users/user")); + assert_eq!(resolve("$HOME"), expected("/Users/user")); + } } }