2022-01-24 22:15:55 +00:00
|
|
|
use super::Config;
|
2022-01-22 21:02:51 +00:00
|
|
|
|
2022-01-26 19:57:51 +00:00
|
|
|
use anyhow::Error;
|
2022-01-26 18:55:08 +00:00
|
|
|
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,
|
|
|
|
};
|
2022-01-26 18:55:08 +00:00
|
|
|
use toml::from_str;
|
2022-01-24 22:15:55 +00:00
|
|
|
|
2022-01-26 19:57:51 +00:00
|
|
|
const CONFIG_DIR: &str = "/imgurs/config.toml";
|
|
|
|
|
2022-01-24 22:15:55 +00:00
|
|
|
pub fn parse() -> Config {
|
2022-01-25 18:47:08 +00:00
|
|
|
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();
|
2022-01-26 19:57:51 +00:00
|
|
|
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");
|
|
|
|
|
2022-01-25 18:47:08 +00:00
|
|
|
toml().unwrap_or_else(|e| {
|
|
|
|
error!("parse toml config: {e}");
|
2022-01-26 19:57:51 +00:00
|
|
|
exit(3);
|
2022-01-24 22:15:55 +00:00
|
|
|
})
|
|
|
|
})
|
2022-01-24 19:48:24 +00:00
|
|
|
}
|
|
|
|
|
2022-01-26 19:57:51 +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
|
|
|
|
2022-01-26 19:57:51 +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)
|
|
|
|
}
|