z_mirror/fmm

git clone https://git.raiguard.me/z_mirror/fmm

raiguardDon't unwrapdcdad62

rewrite
1.9 KiB58 linesraw
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 {
10    pub directory: Option<PathBuf>,
11}
12
13impl ConfigFile {
14    pub 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
16        let config_path: Option<PathBuf> = path.clone().or({
17            if let Some(base_dirs) = BaseDirs::new() {
18                let mut config_path: PathBuf = base_dirs.config_dir().into();
19                config_path.push("fmm");
20                if !config_path.exists() {
21                    fs::create_dir_all(&config_path)
22                        .map_err(|_| ConfigFileErr::CouldNotCreatePath)?;
23                }
24                config_path.push("fmm.toml");
25                if !config_path.exists() {
26                    config_path.push("fmm.toml");
27                    File::create(&config_path).map_err(|_| ConfigFileErr::CouldNotCreateFile)?;
28                };
29                Some(config_path)
30            } else {
31                None
32            }
33        });
34        if config_path.is_none() {
35            return Ok(None);
36        }
37
38        let file = std::fs::read_to_string(config_path.unwrap())
39            .map_err(|_| ConfigFileErr::CouldNotOpenFile)?;
40
41        let config: ConfigFile =
42            toml::from_str(&file).map_err(|_| ConfigFileErr::CouldNotParseFile)?;
43        Ok(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.")]
51    CouldNotOpenFile,
52    #[error("Could not create config file path.")]
53    CouldNotCreatePath,
54    #[error("Could not create config file.")]
55    CouldNotCreateFile,
56    #[error("Could not parse config file.")]
57    CouldNotParseFile,
58}