pyrinas_cli/
config.rs

1use std::{io, path::PathBuf};
2
3use thiserror::Error;
4
5use crate::{Config, ConfigCmd, ConfigSubCommand};
6
7#[derive(Debug, Error)]
8pub enum Error {
9    #[error("unable to get home path")]
10    HomeError,
11
12    #[error("filesystem error: {source}")]
13    FileError {
14        #[from]
15        source: io::Error,
16    },
17
18    #[error("toml error: {source}")]
19    TomlError {
20        #[from]
21        source: toml::de::Error,
22    },
23}
24
25pub fn get_config_path() -> Result<PathBuf, Error> {
26    // Get the config file from standard location
27    let mut config_path = home::home_dir().ok_or(Error::HomeError)?;
28
29    // Append config path to home directory
30    config_path.push(".pyrinas");
31
32    // Return it
33    Ok(config_path)
34}
35
36/// Set config
37pub fn set_config(init: &Config) -> Result<(), Error> {
38    // Get config path
39    let mut path = get_config_path()?;
40
41    // Create the config path
42    std::fs::create_dir_all(&path)?;
43
44    // Add file to path
45    path.push("config.toml");
46
47    // With init data create config.toml
48    let config_string = toml::to_string(&init).unwrap();
49
50    // Save config toml
51    std::fs::write(path, config_string)?;
52
53    Ok(())
54}
55
56/// Fetch the configuration from the provided folder path
57pub fn get_config() -> Result<Config, Error> {
58    // Get config path
59    let mut path = get_config_path()?;
60
61    // Add file to path
62    path.push("config.toml");
63
64    // Read file to end
65    let config = std::fs::read_to_string(path)?;
66
67    // Deserialize
68    let config: Config = toml::from_str(&config)?;
69    Ok(config)
70}
71
72pub fn process(config: &Config, c: &ConfigCmd) -> Result<(), Error> {
73    match c.subcmd {
74        ConfigSubCommand::Show(_) => {
75            println!("{:?}", config);
76        }
77        ConfigSubCommand::Init => {
78            // Default config (blank)
79            let c = Default::default();
80
81            // TODO: migrate config on update..
82
83            // Set the config from init struct
84            set_config(&c)?;
85
86            println!("Config successfully added!");
87        }
88    };
89
90    Ok(())
91}