z_mirror/fmm
git clone https://git.raiguard.me/z_mirror/fmm
dcdad62
rewrite
1use directories:: BaseDirs ; 2use serde::{ Deserialize , Serialize }; 3use std:: fs; 4use std:: fs:: File ; 5use std:: path:: PathBuf ; 6use thiserror:: Error ; 7 8# [ derive ( Deserialize , Serialize )] 9pub struct ConfigFile { 10pub directory : Option < PathBuf >, 11} 12 13impl ConfigFile { 14pub fn new ( path : & Option < PathBuf >) ->Result < Option < Self >, ConfigFileErr > { 15// Pass custom config path, or create the default config file it it doesn't exist 16let config_path: Option < PathBuf > = path. clone (). or ({ 17if let Some ( base_dirs) =BaseDirs :: new () { 18let mut config_path: PathBuf = base_dirs. config_dir (). into (); 19 config_path. push ( "fmm" ); 20if !config_path. exists () { 21 fs:: create_dir_all ( & config_path) 22. map_err ( |_|ConfigFileErr :: CouldNotCreatePath ) ?; 23} 24 config_path. push ( "fmm.toml" ); 25if !config_path. exists () { 26 config_path. push ( "fmm.toml" ); 27File :: create ( & config_path). map_err ( |_|ConfigFileErr :: CouldNotCreateFile ) ?; 28}; 29Some ( config_path) 30} else { 31None 32} 33}); 34if config_path. is_none () { 35return Ok ( None ); 36} 37 38let file = std:: fs:: read_to_string ( config_path. unwrap ()) 39. map_err ( |_|ConfigFileErr :: CouldNotOpenFile ) ?; 40 41let config: ConfigFile = 42 toml:: from_str ( & file). map_err ( |_|ConfigFileErr :: CouldNotParseFile ) ?; 43Ok ( Some ( config)) 44} 45} 46 47# [ allow ( clippy :: enum_variant_names )] 48# [ derive ( Debug , Error )] 49pub enum ConfigFileErr { 50# [ error ( "Could not open config file." )] 51CouldNotOpenFile , 52# [ error ( "Could not create config file path." )] 53CouldNotCreatePath , 54# [ error ( "Could not create config file." )] 55CouldNotCreateFile , 56# [ error ( "Could not parse config file." )] 57CouldNotParseFile , 58}