1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
//! Zero-boilerplate configuration management //! //! ## Why? //! //! There are a lot of different requirements when //! selecting, loading and writing a config, //! depending on the operating system and other //! environment factors. //! //! In many applications this burden is left to you, //! the developer of an application, to figure out //! where to place the configuration files. //! //! This is where `confy` comes in. //! //! ## Idea //! //! `confy` takes care of figuring out operating system //! specific and environment paths before reading and //! writing a configuration. //! //! It gives you easy access to a configuration file //! which is mirrored into a Rust `struct` via [serde]. //! This way you only need to worry about the layout of //! your configuration, not where and how to store it. //! //! [serde]: https://docs.rs/crates/serde //! //! `confy` uses the [`Default`] trait in Rust to automatically //! create a new configuration, if none is available to read //! from yet. //! This means that you can simply assume your application //! to have a configuration, which will be created with //! default values of your choosing, without requiring //! any special logic to handle creation. //! //! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html //! //! ```rust,no_run //! # use serde_derive::{Serialize, Deserialize}; //! //! #[derive(Serialize, Deserialize)] //! struct MyConfig { //! version: u8, //! api_key: String, //! } //! //! /// `MyConfig` implements `Default` //! impl ::std::default::Default for MyConfig { //! fn default() -> Self { Self { version: 0, api_key: "".into() } } //! } //! //! fn main() -> Result<(), confy::ConfyError> { //! let cfg = confy::load("my-app-name")?; //! Ok(()) //! } //! ``` //! //! Updating the configuration is then done via the [`store`] function. //! //! [`store`]: fn.store.html //! mod utils; use utils::*; use directories::ProjectDirs; use serde::{de::DeserializeOwned, Serialize}; use std::error::Error; use std::fmt; use std::fs::{self, File, OpenOptions}; use std::io::{ErrorKind::NotFound, Write}; use std::path::{Path, PathBuf}; /// Load an application configuration from disk /// /// A new configuration file is created with default values if none /// exists. /// /// Errors that are returned from this function are I/O related, /// for example if the writing of the new configuration fails /// or `confy` encounters an operating system or environment /// that it does not support. /// /// **Note:** The type of configuration needs to be declared in some way /// that is inferrable by the compiler. Also note that your /// configuration needs to implement `Default`. /// /// ```rust,no_run /// # use confy::ConfyError; /// # use serde_derive::{Serialize, Deserialize}; /// # fn main() -> Result<(), ConfyError> { /// #[derive(Serialize, Deserialize)] /// struct MyConfig {} /// # impl ::std::default::Default for MyConfig { /// # fn default() -> Self { Self {} } /// # } /// let cfg: MyConfig = confy::load("my-app-name")?; /// # Ok(()) /// # } /// ``` pub fn load<T: Serialize + DeserializeOwned + Default>(name: &str) -> Result<T, ConfyError> { let project = ProjectDirs::from("rs", "", name).ok_or(ConfyError::BadConfigDirectoryStr)?; let config_dir_str = get_configuration_directory_str(&project)?; let path: PathBuf = [config_dir_str, &format!("{}.toml", name)].iter().collect(); load_path(path) } /// Load an application configuration from a specified path. /// /// This is an alternate version of [`load`] that allows the specification of /// an aritrary path instead of a system one. For more information on errors /// and behavior, see [`load`]'s documentation. /// /// [`load`]: fn.load.html pub fn load_path<T: Serialize + DeserializeOwned + Default>(path: impl AsRef<Path>) -> Result<T, ConfyError> { match File::open(&path) { Ok(mut cfg) => { let cfg_string = cfg .get_string() .map_err(ConfyError::ReadConfigurationFileError)?; let cfg_data = toml::from_str(&cfg_string); cfg_data.map_err(ConfyError::BadTomlData) } Err(ref e) if e.kind() == NotFound => { if let Some(parent) = path.as_ref().parent() { fs::create_dir_all(parent) .map_err(ConfyError::DirectoryCreationFailed)?; } store_path(path, T::default())?; Ok(T::default()) } Err(e) => Err(ConfyError::GeneralLoadError(e)), } } #[derive(Debug)] pub enum ConfyError { BadTomlData(toml::de::Error), DirectoryCreationFailed(std::io::Error), GeneralLoadError(std::io::Error), BadConfigDirectoryStr, SerializeTomlError(toml::ser::Error), WriteConfigurationFileError(std::io::Error), ReadConfigurationFileError(std::io::Error), OpenConfigurationFileError(std::io::Error), } impl fmt::Display for ConfyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ConfyError::BadTomlData(e) => write!(f, "Bad TOML data: {}", e), ConfyError::DirectoryCreationFailed(e) => write!(f, "Failed to create directory: {}", e), ConfyError::GeneralLoadError(_) => write!(f, "Failed to load configuration file."), ConfyError::BadConfigDirectoryStr => write!(f, "Failed to convert directory name to str."), ConfyError::SerializeTomlError(_) => write!(f, "Failed to serialize configuration data into TOML."), ConfyError::WriteConfigurationFileError(_) => write!(f, "Failed to write configuration file."), ConfyError::ReadConfigurationFileError(_) => write!(f, "Failed to read configuration file."), ConfyError::OpenConfigurationFileError(_) => write!(f, "Failed to open configuration file."), } } } impl Error for ConfyError {} /// Save changes made to a configuration object /// /// This function will update a configuration, /// with the provided values, and create a new one, /// if none exists. /// /// You can also use this function to create a new configuration /// with different initial values than which are provided /// by your `Default` trait implementation, or if your /// configuration structure _can't_ implement `Default`. /// /// ```rust,no_run /// # use serde_derive::{Serialize, Deserialize}; /// # use confy::ConfyError; /// # fn main() -> Result<(), ConfyError> { /// # #[derive(Serialize, Deserialize)] /// # struct MyConf {} /// let my_cfg = MyConf {}; /// confy::store("my-app-name", my_cfg)?; /// # Ok(()) /// # } /// ``` /// /// Errors returned are I/O errors related to not being /// able to write the configuration file or if `confy` /// encounters an operating system or environment it does /// not support. pub fn store<T: Serialize>(name: &str, cfg: T) -> Result<(), ConfyError> { let project = ProjectDirs::from("rs", "", name).ok_or(ConfyError::BadConfigDirectoryStr)?; fs::create_dir_all(project.config_dir()).map_err(ConfyError::DirectoryCreationFailed)?; let config_dir_str = get_configuration_directory_str(&project)?; let path: PathBuf = [config_dir_str, &format!("{}.toml", name)].iter().collect(); store_path(path, cfg) } /// Save changes made to a configuration object at a specified path /// /// This is an alternate version of [`store`] that allows the specification of /// an aritrary path instead of a system one. For more information on errors /// and behavior, see [`store`]'s documentation. /// /// [`store`]: fn.store.html pub fn store_path<T: Serialize>(path: impl AsRef<Path>, cfg: T) -> Result<(), ConfyError> { let mut f = OpenOptions::new() .write(true) .create(true) .truncate(true) .open(path) .map_err(ConfyError::OpenConfigurationFileError)?; let s = toml::to_string_pretty(&cfg).map_err(ConfyError::SerializeTomlError)?; f.write_all(s.as_bytes()) .map_err(ConfyError::WriteConfigurationFileError)?; Ok(()) } fn get_configuration_directory_str(project: &ProjectDirs) -> Result<&str, ConfyError> { let config_dir_option = project.config_dir().to_str(); match config_dir_option { Some(x) => Ok(x), None => Err(ConfyError::BadConfigDirectoryStr), } }