git-custom-cli 2.3.2

Fast, keyboard-driven terminal UI for dated Git commits
use crate::model::Config;
use anyhow::{Context, Result};
use std::{fs, path::PathBuf};

fn path() -> Result<PathBuf> {
    // GCT_CONFIG_DIR lets tests and portable setups keep the config elsewhere.
    // Empty or relative values are ignored so the config can never land inside a repo.
    if let Some(dir) = std::env::var_os("GCT_CONFIG_DIR") {
        let dir = PathBuf::from(dir);
        if dir.is_absolute() {
            return Ok(dir.join("config.json"));
        }
    }
    let home = dirs::home_dir().context("could not locate the home directory")?;
    Ok(home
        .join(".config")
        .join("git-commit-tui")
        .join("config.json"))
}

pub fn load() -> Result<Config> {
    let file = path()?;
    if !file.exists() {
        return Ok(Config::default());
    }
    let data =
        fs::read_to_string(&file).with_context(|| format!("could not read {}", file.display()))?;
    serde_json::from_str(&data).with_context(|| format!("invalid config file {}", file.display()))
}

pub fn save(config: &Config) -> Result<()> {
    let file = path()?;
    if let Some(parent) = file.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("could not create {}", parent.display()))?;
    }
    let tmp = file.with_extension("json.tmp");
    fs::write(&tmp, format!("{}\n", serde_json::to_string_pretty(config)?))
        .with_context(|| format!("could not write {}", tmp.display()))?;
    let mut renamed = false;
    for attempt in 0..4 {
        if fs::rename(&tmp, &file).is_ok() {
            renamed = true;
            break;
        }
        if attempt < 3 {
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    }
    if !renamed {
        // The old file stays in place until this write succeeds; the temp is kept on failure.
        let contents = fs::read(&tmp).with_context(|| format!("could not read {}", tmp.display()))?;
        fs::write(&file, contents)
            .with_context(|| format!("could not write {}", file.display()))?;
        let _ = fs::remove_file(&tmp);
    }
    Ok(())
}

pub fn clear() -> Result<()> {
    let file = path()?;
    if file.exists() {
        fs::remove_file(&file).with_context(|| format!("could not remove {}", file.display()))?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn save_load_and_dir_validation() {
        let dir = std::env::temp_dir().join(format!("gct-cfg-test-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        std::env::set_var("GCT_CONFIG_DIR", &dir);
        let cfg = Config {
            last_branch: "dev".into(),
            ..Config::default()
        };
        save(&cfg).unwrap();
        save(&cfg).unwrap();
        assert!(dir.join("config.json").exists());
        assert!(!dir.join("config.json.tmp").exists());
        assert_eq!(load().unwrap().last_branch, "dev");
        let _ = fs::remove_dir_all(&dir);

        for bad in ["", "relative/dir"] {
            std::env::set_var("GCT_CONFIG_DIR", bad);
            assert!(path().unwrap().is_absolute());
        }
        std::env::remove_var("GCT_CONFIG_DIR");
    }
}