use std::{io, path::PathBuf};
use thiserror::Error;
use crate::{Config, ConfigCmd, ConfigSubCommand};
#[derive(Debug, Error)]
pub enum Error {
#[error("unable to get home path")]
HomeError,
#[error("filesystem error: {source}")]
FileError {
#[from]
source: io::Error,
},
#[error("toml error: {source}")]
TomlError {
#[from]
source: toml::de::Error,
},
}
pub fn get_config_path() -> Result<PathBuf, Error> {
let mut config_path = home::home_dir().ok_or(Error::HomeError)?;
config_path.push(".pyrinas");
Ok(config_path)
}
pub fn set_config(init: &Config) -> Result<(), Error> {
let mut path = get_config_path()?;
std::fs::create_dir_all(&path)?;
path.push("config.toml");
let config_string = toml::to_string(&init).unwrap();
std::fs::write(path, config_string)?;
Ok(())
}
pub fn get_config() -> Result<Config, Error> {
let mut path = get_config_path()?;
path.push("config.toml");
let config = std::fs::read_to_string(path)?;
let config: Config = toml::from_str(&config)?;
Ok(config)
}
pub fn process(config: &Config, c: &ConfigCmd) -> Result<(), Error> {
match c.subcmd {
ConfigSubCommand::Show(_) => {
println!("{:?}", config);
}
ConfigSubCommand::Init => {
let c = Default::default();
set_config(&c)?;
println!("Config successfully added!");
}
};
Ok(())
}