use crate::model::Config;
use anyhow::{Context, Result};
use std::{
ffi::OsString,
fs,
path::{Path, PathBuf},
};
fn path() -> Result<PathBuf> {
path_in(std::env::var_os("GCT_CONFIG_DIR"))
}
fn path_in(dir: Option<OsString>) -> Result<PathBuf> {
if let Some(dir) = dir.map(PathBuf::from).filter(|dir| 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> {
load_from(&path()?)
}
fn load_from(file: &Path) -> Result<Config> {
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<()> {
save_to(&path()?, config)
}
fn save_to(file: &Path, config: &Config) -> Result<()> {
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 {
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_round_trip() {
let repo = crate::testutil::TempRepo::outside();
let file = repo.path().join("cfg").join("config.json");
assert_eq!(
load_from(&file).unwrap().last_branch,
Config::default().last_branch
);
let cfg = Config {
last_branch: "dev".into(),
..Config::default()
};
save_to(&file, &cfg).unwrap();
save_to(&file, &cfg).unwrap();
assert!(file.exists());
assert!(!file.with_extension("json.tmp").exists());
assert_eq!(load_from(&file).unwrap().last_branch, "dev");
fs::write(&file, "{ not json").unwrap();
assert!(load_from(&file)
.unwrap_err()
.to_string()
.contains("invalid config file"));
}
#[test]
fn dir_validation() {
let absolute = std::env::temp_dir().join("gct-cfg-dir");
assert_eq!(
path_in(Some(absolute.clone().into_os_string())).unwrap(),
absolute.join("config.json")
);
for bad in [Some(""), Some("relative/dir"), None] {
let file = path_in(bad.map(OsString::from)).unwrap();
assert!(file.is_absolute(), "{bad:?}");
assert!(file.ends_with("git-commit-tui/config.json"), "{bad:?}");
}
}
}