diff --git a/Cargo.lock b/Cargo.lock index d2301709..67698968 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3338,6 +3338,7 @@ dependencies = [ "ed25519-dalek", "hotwatch", "komorebi-layouts", + "komorebi-protocol", "komorebi-scrolling", "komorebi-themes", "lazy_static", diff --git a/crates/komorebi-protocol/src/pathext.rs b/crates/komorebi-protocol/src/pathext.rs index b548f4f1..81f61ea7 100644 --- a/crates/komorebi-protocol/src/pathext.rs +++ b/crates/komorebi-protocol/src/pathext.rs @@ -1 +1,229 @@ -//! Placeholder: filled in by a later step 2 revision. +//! Resolving environment variables in the paths of the configuration. + +use std::collections::HashMap; +use std::ffi::OsStr; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use serde::Deserialize; +use serde::Serialize; + +/// Path extension trait +pub trait PathExt { + /// Resolve environment variable components in a path. + /// + /// Resolves the following formats: + /// - CMD: `%variable%` + /// - PowerShell: `$Env:variable` + /// - Bash: `$variable`. + fn replace_env(&self) -> PathBuf; +} + +/// Blanket implementation for all types that can be converted to a `Path`. +impl> PathExt for P { + fn replace_env(&self) -> PathBuf { + let mut out = PathBuf::new(); + + 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% + let var = if bytes[0] == b'%' && bytes[bytes.len() - 1] == b'%' { + Some(&bytes[1..bytes.len() - 1]) + } else { + // prefix length is 5 for $Env: and 1 for $ + // so we take the minimum of 5 and the length of the bytes + let prefix = &bytes[..5.min(bytes.len())]; + let prefix = unsafe { OsStr::from_encoded_bytes_unchecked(prefix) }; + + // $Env:LOCALAPPDATA + if prefix.eq_ignore_ascii_case("$Env:") { + Some(&bytes[5..]) + } else if bytes[0] == b'$' { + // $LOCALAPPDATA + Some(&bytes[1..]) + } else { + // not a variable + None + } + }; + + // if component is a variable, get the value from the environment + if let Some(var) = var { + let var = unsafe { OsStr::from_encoded_bytes_unchecked(var) }; + if let Some(value) = std::env::var_os(var) { + out.push(value); + continue; + } + } + + // if not a variable, or a value couldn't be obtained from environemnt + // then push the component as is + out.push(c); + } + + // other components are pushed as is + _ => out.push(c), + } + } + + out + } +} + +/// Replace environment variables in a path. This is a wrapper around +/// [`PathExt::replace_env`] to be used in Clap arguments parsing. +pub fn replace_env_in_path(input: &str) -> Result { + Ok(input.replace_env()) +} + +/// A wrapper around [`PathBuf`] that has a custom [Deserialize] implementation +/// that uses [`PathExt::replace_env`] to resolve environment variables +#[derive(Clone, Debug)] +pub struct ResolvedPathBuf(PathBuf); + +impl ResolvedPathBuf { + /// Create a new [`ResolvedPathBuf`] from a [`PathBuf`] + pub fn new(path: PathBuf) -> Self { + Self(path.replace_env()) + } +} + +impl From for PathBuf { + fn from(path: ResolvedPathBuf) -> Self { + path.0 + } +} + +impl serde_with::SerializeAs for ResolvedPathBuf { + fn serialize_as(path: &PathBuf, serializer: S) -> Result + where + S: serde::Serializer, + { + path.serialize(serializer) + } +} + +impl<'de> serde_with::DeserializeAs<'de, PathBuf> for ResolvedPathBuf { + fn deserialize_as(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let path = PathBuf::deserialize(deserializer)?; + Ok(path.replace_env()) + } +} + +#[cfg(feature = "schemars")] +impl serde_with::schemars_1::JsonSchemaAs for ResolvedPathBuf { + fn schema_name() -> std::borrow::Cow<'static, str> { + std::borrow::Cow::Borrowed("PathBuf") + } + + 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": description + }) + } +} + +/// Custom deserializer for [`Option>`] that uses +/// [`PathExt::replace_env`] to resolve environment variables in the paths. +/// +/// This is used in `WorkspaceConfig` struct because we can't use +/// #[serde_with::serde_as] as it doesn't handle [`Option>`] +/// quite well and generated compiler errors that can't be fixed because of Rust's orphan rule. +pub fn resolve_option_hashmap_usize_path<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let map = Option::>::deserialize(deserializer)?; + Ok(map.map(|map| map.into_iter().map(|(k, v)| (k, v.replace_env())).collect())) +} + +#[cfg(test)] +mod tests { + use super::*; + + // helper functions + fn expected>(p: P) -> PathBuf { + // Ensure that the path is using the correct path separator for the OS. + p.as_ref().components().collect::() + } + + fn resolve>(p: P) -> PathBuf { + p.replace_env() + } + + #[test] + fn resolves_env_vars() { + // Set a variable for testing + unsafe { + std::env::set_var("VAR", "VALUE"); + } + + // %VAR% format + assert_eq!(resolve("/path/%VAR%/d"), expected("/path/VALUE/d")); + // $env:VAR format + assert_eq!(resolve("/path/$env:VAR/d"), expected("/path/VALUE/d")); + // $VAR format + assert_eq!(resolve("/path/$VAR/d"), expected("/path/VALUE/d")); + + // non-existent variable + assert_eq!(resolve("/path/%ASD%/to/d"), expected("/path/%ASD%/to/d")); + assert_eq!( + resolve("/path/$env:ASD/to/d"), + expected("/path/$env:ASD/to/d") + ); + assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d")); + + #[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")); + } + + #[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")); + } + } +} diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index ae09be10..e00d1c62 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -11,6 +11,7 @@ edition = "2024" komorebi-layouts = { path = "../komorebi-layouts", features = ["win32"] } komorebi-scrolling = { path = "../komorebi-scrolling" } komorebi-themes = { path = "../komorebi-themes" } +komorebi-protocol = { path = "../crates/komorebi-protocol", default-features = false } base64 = "0.22" bitflags = { version = "2", features = ["serde"] } @@ -65,4 +66,4 @@ uuid = { version = "1", features = ["v4"] } [features] default = ["schemars"] deadlock_detection = ["parking_lot/deadlock_detection"] -schemars = ["dep:schemars", "komorebi-layouts/schemars"] +schemars = ["dep:schemars", "komorebi-layouts/schemars", "komorebi-protocol/schemars"] diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index ed2b67a3..8d9f14ac 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -56,7 +56,7 @@ pub use pathext::resolve_option_hashmap_usize_path; pub mod animation; pub mod asc; pub mod config_generation; -pub mod pathext; +pub use komorebi_protocol::pathext; // serde_as must be before derive #[serde_with::serde_as] diff --git a/komorebi/src/core/pathext.rs b/komorebi/src/core/pathext.rs deleted file mode 100644 index 81f61ea7..00000000 --- a/komorebi/src/core/pathext.rs +++ /dev/null @@ -1,229 +0,0 @@ -//! Resolving environment variables in the paths of the configuration. - -use std::collections::HashMap; -use std::ffi::OsStr; -use std::path::Component; -use std::path::Path; -use std::path::PathBuf; - -use serde::Deserialize; -use serde::Serialize; - -/// Path extension trait -pub trait PathExt { - /// Resolve environment variable components in a path. - /// - /// Resolves the following formats: - /// - CMD: `%variable%` - /// - PowerShell: `$Env:variable` - /// - Bash: `$variable`. - fn replace_env(&self) -> PathBuf; -} - -/// Blanket implementation for all types that can be converted to a `Path`. -impl> PathExt for P { - fn replace_env(&self) -> PathBuf { - let mut out = PathBuf::new(); - - 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% - let var = if bytes[0] == b'%' && bytes[bytes.len() - 1] == b'%' { - Some(&bytes[1..bytes.len() - 1]) - } else { - // prefix length is 5 for $Env: and 1 for $ - // so we take the minimum of 5 and the length of the bytes - let prefix = &bytes[..5.min(bytes.len())]; - let prefix = unsafe { OsStr::from_encoded_bytes_unchecked(prefix) }; - - // $Env:LOCALAPPDATA - if prefix.eq_ignore_ascii_case("$Env:") { - Some(&bytes[5..]) - } else if bytes[0] == b'$' { - // $LOCALAPPDATA - Some(&bytes[1..]) - } else { - // not a variable - None - } - }; - - // if component is a variable, get the value from the environment - if let Some(var) = var { - let var = unsafe { OsStr::from_encoded_bytes_unchecked(var) }; - if let Some(value) = std::env::var_os(var) { - out.push(value); - continue; - } - } - - // if not a variable, or a value couldn't be obtained from environemnt - // then push the component as is - out.push(c); - } - - // other components are pushed as is - _ => out.push(c), - } - } - - out - } -} - -/// Replace environment variables in a path. This is a wrapper around -/// [`PathExt::replace_env`] to be used in Clap arguments parsing. -pub fn replace_env_in_path(input: &str) -> Result { - Ok(input.replace_env()) -} - -/// A wrapper around [`PathBuf`] that has a custom [Deserialize] implementation -/// that uses [`PathExt::replace_env`] to resolve environment variables -#[derive(Clone, Debug)] -pub struct ResolvedPathBuf(PathBuf); - -impl ResolvedPathBuf { - /// Create a new [`ResolvedPathBuf`] from a [`PathBuf`] - pub fn new(path: PathBuf) -> Self { - Self(path.replace_env()) - } -} - -impl From for PathBuf { - fn from(path: ResolvedPathBuf) -> Self { - path.0 - } -} - -impl serde_with::SerializeAs for ResolvedPathBuf { - fn serialize_as(path: &PathBuf, serializer: S) -> Result - where - S: serde::Serializer, - { - path.serialize(serializer) - } -} - -impl<'de> serde_with::DeserializeAs<'de, PathBuf> for ResolvedPathBuf { - fn deserialize_as(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let path = PathBuf::deserialize(deserializer)?; - Ok(path.replace_env()) - } -} - -#[cfg(feature = "schemars")] -impl serde_with::schemars_1::JsonSchemaAs for ResolvedPathBuf { - fn schema_name() -> std::borrow::Cow<'static, str> { - std::borrow::Cow::Borrowed("PathBuf") - } - - 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": description - }) - } -} - -/// Custom deserializer for [`Option>`] that uses -/// [`PathExt::replace_env`] to resolve environment variables in the paths. -/// -/// This is used in `WorkspaceConfig` struct because we can't use -/// #[serde_with::serde_as] as it doesn't handle [`Option>`] -/// quite well and generated compiler errors that can't be fixed because of Rust's orphan rule. -pub fn resolve_option_hashmap_usize_path<'de, D>( - deserializer: D, -) -> Result>, D::Error> -where - D: serde::Deserializer<'de>, -{ - let map = Option::>::deserialize(deserializer)?; - Ok(map.map(|map| map.into_iter().map(|(k, v)| (k, v.replace_env())).collect())) -} - -#[cfg(test)] -mod tests { - use super::*; - - // helper functions - fn expected>(p: P) -> PathBuf { - // Ensure that the path is using the correct path separator for the OS. - p.as_ref().components().collect::() - } - - fn resolve>(p: P) -> PathBuf { - p.replace_env() - } - - #[test] - fn resolves_env_vars() { - // Set a variable for testing - unsafe { - std::env::set_var("VAR", "VALUE"); - } - - // %VAR% format - assert_eq!(resolve("/path/%VAR%/d"), expected("/path/VALUE/d")); - // $env:VAR format - assert_eq!(resolve("/path/$env:VAR/d"), expected("/path/VALUE/d")); - // $VAR format - assert_eq!(resolve("/path/$VAR/d"), expected("/path/VALUE/d")); - - // non-existent variable - assert_eq!(resolve("/path/%ASD%/to/d"), expected("/path/%ASD%/to/d")); - assert_eq!( - resolve("/path/$env:ASD/to/d"), - expected("/path/$env:ASD/to/d") - ); - assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d")); - - #[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")); - } - - #[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")); - } - } -}