octo-tui/src/config.rs
src/config.rsRaw
1use anyhow::{Result, bail};
2use serde::Deserialize;
3use std::{env, path::PathBuf};
4
5#[derive(Default, Deserialize)]
6#[serde(default)]
7pub struct Config {
8 pub server: String,
9 pub username: String,
10 pub password: String,
11 pub api_key: String,
12 pub volume: Option<u8>,
13 pub theme: Option<String>,
14}
15
16pub fn directory() -> PathBuf {
17 env::var_os("XDG_CONFIG_HOME")
18 .map(PathBuf::from)
19 .unwrap_or_else(|| PathBuf::from(env::var_os("HOME").unwrap_or_default()).join(".config"))
20 .join("octo-tui")
21}
22
23impl Config {
24 /// Environment overrides keep credentials out of command-line arguments.
25 pub fn load(path: Option<PathBuf>) -> Result<Self> {
26 let explicit = path.is_some();
27 let path = path.unwrap_or_else(|| directory().join("config.toml"));
28 let mut config: Self = match std::fs::read_to_string(&path) {
29 Ok(text) => {
30 toml::from_str(&text).map_err(|_| anyhow::anyhow!("Invalid configuration TOML"))?
31 }
32 Err(e) if !explicit && e.kind() == std::io::ErrorKind::NotFound => Self::default(),
33 Err(_) => bail!("Cannot read configuration file"),
34 };
35 for (name, field) in [
36 ("OCTO_SERVER", &mut config.server),
37 ("OCTO_USERNAME", &mut config.username),
38 ("OCTO_PASSWORD", &mut config.password),
39 ("OCTO_API_KEY", &mut config.api_key),
40 ] {
41 if let Ok(value) = env::var(name) {
42 *field = value;
43 }
44 }
45 if config.server.is_empty() {
46 bail!("Set OCTO_SERVER or configure server in ~/.config/octo-tui/config.toml.");
47 }
48 if config.api_key.is_empty() && (config.username.is_empty() || config.password.is_empty()) {
49 bail!("Set OCTO_USERNAME and OCTO_PASSWORD, or OCTO_API_KEY.");
50 }
51 Ok(config)
52 }
53}