Store per-user configuration with confy
A desktop or CLI program that remembers a user’s preferences should write them
to the platform’s standard config location, not next to the binary.
confy handles that: it serializes a Default-able, Serialize +
Deserialize struct to the per-user config directory and reads it back, creating
the file from the defaults on first run.
confy::load takes an application name and resolves ~/.config/<app>/<app>.toml
on Linux (and the platform equivalent elsewhere); get_configuration_file_path
returns that location without writing anything. To keep the recipe from touching
your real config directory, it round-trips through an explicit path with
load_path and store_path instead.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Prefs {
username: String,
theme: String,
autosave: bool,
}
impl Default for Prefs {
fn default() -> Self {
Prefs {
username: "anonymous".to_owned(),
theme: "dark".to_owned(),
autosave: true,
}
}
}
fn main() -> Result<(), confy::ConfyError> {
let path = confy::get_configuration_file_path("cookbook-prefs", None)?;
println!("per-user config path: {}", path.display());
let scratch = std::env::temp_dir().join("cookbook-prefs.toml");
let mut prefs: Prefs = confy::load_path(&scratch)?;
println!("loaded {prefs:?}");
prefs.theme = "light".to_owned();
confy::store_path(&scratch, &prefs)?;
println!("saved {prefs:?} to {}", scratch.display());
Ok(())
}