Skip to content

Commit b0949b8

Browse files
committed
config: implement r/w functions
1 parent e99e4ee commit b0949b8

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/config.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
use anyhow::Result;
12
use serde::{Deserialize, Serialize};
3+
use std::{fs, path::Path};
4+
25
use crate::{
36
cli::{NumberSeparator, When},
47
info::utils::info_field::InfoType,
@@ -53,3 +56,48 @@ impl Default for ConfigOptions {
5356
}
5457
}
5558
}
59+
60+
impl ConfigOptions {
61+
pub fn read<P>(path: P) -> Self
62+
// Is it even should panic?
63+
where
64+
P: AsRef<Path>,
65+
{
66+
let contents = fs::read_to_string(path);
67+
match contents {
68+
Err(_) => Self::default(),
69+
Ok(contents) => {
70+
// I wish to print exact error here, like syntax errors
71+
toml::from_str(&contents).unwrap()
72+
}
73+
}
74+
}
75+
76+
pub fn write<P>(self, path: P) -> Result<()>
77+
// I believe user would like to generate config with CLI flags
78+
// I mean to write disabled_fields with --disabled-fields flag
79+
where
80+
P: AsRef<Path>,
81+
{
82+
// I dont think this can panic so i simply unwrapped it
83+
let contents = toml::to_string(&self).unwrap();
84+
match fs::create_dir_all(&path.as_ref().parent().unwrap_or(Path::new("/"))) {
85+
Ok(_) => match fs::write(&path, &contents) {
86+
Ok(_) => {
87+
let path = path.as_ref().display();
88+
println!("Config config file created at: {path}")
89+
}
90+
Err(e) => {
91+
let path = path.as_ref().display();
92+
eprintln!("Failed to write config file at {path}: {e}")
93+
}
94+
},
95+
Err(e) => {
96+
let path = path.as_ref().display();
97+
eprintln!("Failed to create config directory {path}: {e}");
98+
}
99+
}
100+
// Im not sure it should return simple Ok(())?
101+
Ok(())
102+
}
103+
}

0 commit comments

Comments
 (0)