imgurs/src/config/toml.rs

53 lines
1.4 KiB
Rust
Raw Normal View History

2022-01-24 22:15:55 +00:00
use super::Config;
2022-01-22 21:02:51 +00:00
use anyhow::Error;
use dirs::config_dir;
use log::{error, warn};
2022-01-24 22:15:55 +00:00
use std::{
fs::{create_dir_all, read_to_string, File},
io::Write as _,
path::Path,
process::exit,
};
use toml::from_str;
2022-01-24 22:15:55 +00:00
const CONFIG_DIR: &str = "/imgurs/config.toml";
2022-01-24 22:15:55 +00:00
pub fn parse() -> Config {
toml().unwrap_or_else(|e| {
warn!("Parse toml config: {e}! Creating config file...");
2022-01-24 22:15:55 +00:00
let default_config = include_str!(concat!("../../config.toml"));
let sys_config_dir = config_dir().unwrap();
let config_dir = format!("{}{CONFIG_DIR}", sys_config_dir.to_string_lossy());
2022-01-24 22:15:55 +00:00
let config_path = Path::new(&config_dir);
2022-01-22 21:02:51 +00:00
2022-01-24 22:15:55 +00:00
let prefix = config_path.parent().unwrap();
create_dir_all(prefix).unwrap();
let mut file_ref = File::create(config_path).expect("create failed");
file_ref
.write_all(default_config.as_bytes())
.expect("failed write default config to file");
toml().unwrap_or_else(|e| {
error!("parse toml config: {e}");
exit(3);
2022-01-24 22:15:55 +00:00
})
})
}
fn toml() -> Result<Config, Error> {
2022-01-22 21:02:51 +00:00
let config_dir = config_dir().unwrap();
2022-01-24 22:15:55 +00:00
let file_dir: String = String::from(config_dir.to_string_lossy()) + CONFIG_DIR;
2022-01-22 21:02:51 +00:00
2022-01-27 10:03:37 +00:00
let toml_str = read_to_string(file_dir).map_err(Error::new)?;
2022-01-22 21:02:51 +00:00
2022-01-27 10:03:37 +00:00
let decode = from_str(&toml_str).map_err(Error::new)?;
2022-01-22 21:02:51 +00:00
Ok(decode)
}