Files
rusty-tasks/src/config/mod.rs

85 lines
2.4 KiB
Rust
Raw Normal View History

2023-06-22 13:39:14 -04:00
extern crate serde;
extern crate serde_json;
use figment::providers::{Env, Format, Json, Serialized};
use figment::Figment;
use serde::{Deserialize, Serialize};
use std::env::var;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
#[derive(Deserialize, Serialize, Debug)]
pub struct Config {
2024-02-28 17:20:55 -05:00
pub editor: String,
pub sections: Vec<String>,
pub notes_dir: String,
2023-06-22 13:39:14 -04:00
}
impl Default for Config {
fn default() -> Self {
Config {
2024-02-28 17:20:55 -05:00
editor: "nano".into(),
sections: vec!["Daily".into(), "Weekly".into(), "Monthly".into()],
notes_dir: "./Notes".into(),
2023-06-22 13:39:14 -04:00
}
}
}
2023-06-24 23:57:43 -04:00
#[derive(Debug)]
2024-02-28 15:12:19 -05:00
pub enum ConfigError {
2023-06-24 23:57:43 -04:00
IOError(&'static str),
ParseError(&'static str),
2024-02-28 15:12:19 -05:00
EnvError(&'static str),
2023-06-24 23:57:43 -04:00
}
2023-06-22 13:39:14 -04:00
impl Config {
2023-06-24 23:57:43 -04:00
pub fn load(cfg_file: &str) -> Result<Self, ConfigError> {
2023-06-22 13:39:14 -04:00
Figment::from(Serialized::defaults(Config::default()))
.merge(Env::raw().only(&["EDITOR"]))
.merge(Json::file(cfg_file))
.extract()
2023-06-24 23:57:43 -04:00
.or(Err(ConfigError::IOError("Could not load config")))
2023-06-22 13:39:14 -04:00
}
2023-06-24 23:57:43 -04:00
pub fn write_default(cfg_file: &str) -> Result<(), ConfigError> {
2024-02-28 15:12:19 -05:00
let buf = serde_json::to_string_pretty(&Self::default()).or_else(|_| {
2024-02-28 17:20:55 -05:00
Err(ConfigError::ParseError(
2024-02-28 15:12:19 -05:00
"could not serialize default config",
2024-02-28 17:20:55 -05:00
))
2024-02-28 15:12:19 -05:00
})?;
2023-06-22 13:39:14 -04:00
2024-02-28 15:12:19 -05:00
let mut f = File::create(cfg_file)
.or_else(|_| Err(ConfigError::IOError("Could not open config file")))?;
f.write_all(&buf.as_bytes()).or_else(|_| {
2024-02-28 17:20:55 -05:00
Err(ConfigError::IOError(
2024-02-28 15:12:19 -05:00
"could not write default config to file",
2024-02-28 17:20:55 -05:00
))
2024-02-28 15:12:19 -05:00
})?;
2023-06-22 13:39:14 -04:00
Ok(())
}
2023-06-24 23:57:43 -04:00
pub fn expected_locations() -> Result<Vec<PathBuf>, ConfigError> {
2023-06-22 13:39:14 -04:00
let cfg_name = "rusty_task.json";
2024-02-28 15:12:19 -05:00
let home = var("HOME").or(Err(ConfigError::EnvError(
"$HOME environment variable not set",
)))?;
let pwd = var("PWD").or(Err(ConfigError::EnvError(
"$PWD environment variable not set",
)))?;
2023-06-22 13:39:14 -04:00
let mut home_config_cfg = PathBuf::from(home.clone());
home_config_cfg.push(".config");
home_config_cfg.push(cfg_name);
let mut home_cfg = PathBuf::from(home.clone());
home_cfg.push(format!(".{}", cfg_name));
let mut pwd_cfg = PathBuf::from(pwd.clone());
pwd_cfg.push(format!(".{}", cfg_name));
Ok(vec![home_config_cfg, home_cfg, pwd_cfg])
}
}