use anyhow::{Result, bail}; use serde::Deserialize; use std::{env, path::PathBuf}; #[derive(Default, Deserialize)] #[serde(default)] pub struct Config { pub server: String, pub username: String, pub password: String, pub api_key: String, pub volume: Option, pub theme: Option, } pub fn directory() -> PathBuf { env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(env::var_os("HOME").unwrap_or_default()).join(".config")) .join("octo-tui") } impl Config { /// Environment overrides keep credentials out of command-line arguments. pub fn load(path: Option) -> Result { let explicit = path.is_some(); let path = path.unwrap_or_else(|| directory().join("config.toml")); let mut config: Self = match std::fs::read_to_string(&path) { Ok(text) => { toml::from_str(&text).map_err(|_| anyhow::anyhow!("Invalid configuration TOML"))? } Err(e) if !explicit && e.kind() == std::io::ErrorKind::NotFound => Self::default(), Err(_) => bail!("Cannot read configuration file"), }; for (name, field) in [ ("OCTO_SERVER", &mut config.server), ("OCTO_USERNAME", &mut config.username), ("OCTO_PASSWORD", &mut config.password), ("OCTO_API_KEY", &mut config.api_key), ] { if let Ok(value) = env::var(name) { *field = value; } } if config.server.is_empty() { bail!("Set OCTO_SERVER or configure server in ~/.config/octo-tui/config.toml."); } if config.api_key.is_empty() && (config.username.is_empty() || config.password.is_empty()) { bail!("Set OCTO_USERNAME and OCTO_PASSWORD, or OCTO_API_KEY."); } Ok(config) } }