Skip to content

Commit

Permalink
cosmic-config: Add new_state constructor for storing state
Browse files Browse the repository at this point in the history
  • Loading branch information
jackpot51 committed Oct 9, 2023
1 parent 50cc1d2 commit f000516
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
35 changes: 35 additions & 0 deletions cosmic-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self, Error> {
// 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> {
Expand Down
12 changes: 9 additions & 3 deletions examples/config/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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());
}

0 comments on commit f000516

Please sign in to comment.