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 let mut config_path = home::home_dir().ok_or(Error::HomeError)?;
28
29 config_path.push(".pyrinas");
31
32 Ok(config_path)
34}
35
36pub fn set_config(init: &Config) -> Result<(), Error> {
38 let mut path = get_config_path()?;
40
41 std::fs::create_dir_all(&path)?;
43
44 path.push("config.toml");
46
47 let config_string = toml::to_string(&init).unwrap();
49
50 std::fs::write(path, config_string)?;
52
53 Ok(())
54}
55
56pub fn get_config() -> Result<Config, Error> {
58 let mut path = get_config_path()?;
60
61 path.push("config.toml");
63
64 let config = std::fs::read_to_string(path)?;
66
67 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 let c = Default::default();
80
81 set_config(&c)?;
85
86 println!("Config successfully added!");
87 }
88 };
89
90 Ok(())
91}