diff --git a/cosmic-config/src/lib.rs b/cosmic-config/src/lib.rs index 27f3a13e1a2..9a73835b74f 100644 --- a/cosmic-config/src/lib.rs +++ b/cosmic-config/src/lib.rs @@ -132,6 +132,41 @@ impl Config { Err(Error::InvalidName(name.to_string())) } } + + /// Get state for the given application name and config version. State is meant to be used to + /// store items that may need to be exposed to other programs but will change regularly without + /// user action + // Use folder at XDG config/name for config storage, return Config if successful + //TODO: fallbacks for flatpak (HOST_XDG_CONFIG_HOME, xdg-desktop settings proxy) + pub fn new_state(name: &str, version: u64) -> Result { + // Get libcosmic system defaults path + //TODO: support non-UNIX OS + let cosmic_system_path = Path::new("/var/lib/cosmic"); + // Append [name]/v[version] + let system_path = cosmic_system_path.join(name).join(format!("v{}", version)); + + // Get libcosmic user configuration directory + let cosmic_user_path = dirs::state_dir() + .ok_or(Error::NoConfigDirectory)? + .join("cosmic"); + // Append [name]/v[version] + let user_path = cosmic_user_path.join(name).join(format!("v{}", version)); + + // If the app paths are children of the cosmic paths + if system_path.starts_with(&cosmic_system_path) && user_path.starts_with(&cosmic_user_path) + { + // Create app user path + fs::create_dir_all(&user_path)?; + // Return Config + Ok(Self { + system_path, + user_path, + }) + } else { + // Return error for invalid name + Err(Error::InvalidName(name.to_string())) + } + } // Start a transaction (to set multiple configs at the same time) pub fn transaction<'a>(&'a self) -> ConfigTransaction<'a> { diff --git a/examples/config/src/main.rs b/examples/config/src/main.rs index 4fad7a79a58..892936d57e6 100644 --- a/examples/config/src/main.rs +++ b/examples/config/src/main.rs @@ -3,9 +3,7 @@ use cosmic_config::{Config, ConfigGet, ConfigSet}; -pub fn main() { - let config = Config::new("com.system76.Example", 1).unwrap(); - +fn test_config(config: Config) { let watcher = config .watch(|config, keys| { println!("Changed: {:?}", keys); @@ -83,3 +81,11 @@ pub fn main() { println!("Committing transaction"); println!("Commit transaction: {:?}", tx.commit()); } + +pub fn main() { + println!("Testing config"); + test_config(Config::new("com.system76.Example", 1).unwrap()); + + println!("Testing state"); + test_config(Config::new_state("com.system76.Example", 1).unwrap()); +}