nd / nd-cli/src/config.rs

raw file 1325 bytes
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Simple local config: ~/.config/notdouble/config.toml
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
}

/// HOME, USERPROFILE fallback sane across platforms.
pub fn home_dir() -> Result<PathBuf> {
    for k in ["HOME", "USERPROFILE"] {
        if let Ok(h) = std::env::var(k) {
            if !h.trim().is_empty() {
                return Ok(PathBuf::from(h));
            }
        }
    }
    Err(anyhow::anyhow!(
        "cannot determine home dir (set HOME or USERPROFILE)"
    ))
}

pub fn config_path() -> Result<PathBuf> {
    Ok(home_dir()?.join(".config/notdouble/config.toml"))
}

/// The local keypair that signs uploads/deletes (ownership identity).
pub fn identity_path() -> Result<PathBuf> {
    let p = config_path()?;
    Ok(p.parent()
        .map(|d| d.join("identity.key"))
        .unwrap_or_else(|| PathBuf::from("identity.key")))
}

pub fn load() -> Config {
    config_path()
        .ok()
        .and_then(|p| std::fs::read_to_string(p).ok())
        .and_then(|s| toml::from_str(&s).ok())
        .unwrap_or_default()
}