use std::fs;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Config {
pub quota_providers: Option<Vec<String>>,
}
pub fn config_path() -> Option<PathBuf> {
let base = config_base(
std::env::var_os("XDG_CONFIG_HOME"),
std::env::var_os("HOME"),
)?;
Some(base.join("crew-watch").join("config"))
}
fn config_base(
xdg: Option<std::ffi::OsString>,
home: Option<std::ffi::OsString>,
) -> Option<PathBuf> {
let non_empty = |v: std::ffi::OsString| (!v.is_empty()).then(|| PathBuf::from(v));
xdg.and_then(non_empty)
.or_else(|| home.and_then(non_empty).map(|h| h.join(".config")))
}
pub fn load(path: &Path) -> Config {
let Ok(content) = fs::read_to_string(path) else {
return Config::default();
};
parse(&content)
}
pub fn parse(content: &str) -> Config {
let mut cfg = Config::default();
for line in content.lines() {
let Some((key, val)) = line.split_once('=') else {
continue;
};
if key.trim() == "quota_providers" {
cfg.quota_providers = Some(
val.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
);
}
}
cfg
}
pub fn save_quota_providers(path: &Path, ids: &[String]) -> Result<(), String> {
let mut out = String::new();
if let Ok(existing) = fs::read_to_string(path) {
for line in existing.lines() {
let is_quota = line
.split_once('=')
.map(|(k, _)| k.trim() == "quota_providers")
.unwrap_or(false);
if !is_quota {
out.push_str(line);
out.push('\n');
}
}
}
if out.is_empty() {
out.push_str("# crew-watch configuration\n");
}
out.push_str("quota_providers=");
out.push_str(&ids.join(","));
out.push('\n');
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("create config dir: {e}"))?;
}
fs::write(path, out).map_err(|e| format!("write config: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn tempfile_dir(label: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"crew-watch-cfg-test-{}-{}-{}",
label,
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn config_base_prefers_xdg_and_treats_empty_as_unset() {
let os = |s: &str| std::ffi::OsString::from(s);
assert_eq!(
config_base(Some(os("/xdg")), Some(os("/home/u"))),
Some(PathBuf::from("/xdg"))
);
let base = config_base(Some(os("")), Some(os("/home/u")));
assert_eq!(base, Some(PathBuf::from("/home/u/.config")));
assert_eq!(config_base(Some(os("")), Some(os(""))), None);
assert_eq!(config_base(None, None), None);
assert!(base.unwrap().is_absolute());
}
#[test]
fn missing_file_is_auto_mode() {
let cfg = load(Path::new("/nonexistent/crew-watch-cfg-99999/config"));
assert_eq!(cfg.quota_providers, None);
}
#[test]
fn parse_key_absent_is_none() {
let cfg = parse("# comment\nother_key=val\n");
assert_eq!(cfg.quota_providers, None);
}
#[test]
fn parse_empty_value_is_explicit_empty() {
let cfg = parse("quota_providers=\n");
assert_eq!(cfg.quota_providers, Some(Vec::new()));
}
#[test]
fn parse_single_and_multi() {
assert_eq!(
parse("quota_providers=claude\n").quota_providers,
Some(vec!["claude".to_string()])
);
assert_eq!(
parse("quota_providers=claude, codex ,grok\n").quota_providers,
Some(vec![
"claude".to_string(),
"codex".to_string(),
"grok".to_string()
])
);
}
#[test]
fn parse_trailing_comma_drops_empties() {
assert_eq!(
parse("quota_providers=claude,\n").quota_providers,
Some(vec!["claude".to_string()])
);
}
#[test]
fn round_trip_preserves_selection() {
let dir = tempfile_dir("roundtrip");
let path = dir.join("config");
save_quota_providers(&path, &["claude".into(), "codex".into()]).unwrap();
let loaded = load(&path);
assert_eq!(
loaded.quota_providers,
Some(vec!["claude".to_string(), "codex".to_string()])
);
}
#[test]
fn save_unknown_keys_preserved() {
let dir = tempfile_dir("preserve");
let path = dir.join("config");
fs::write(&path, "# header\nfuture_key=42\nquota_providers=claude\n").unwrap();
save_quota_providers(&path, &["codex".into()]).unwrap();
let content = fs::read_to_string(&path).unwrap();
assert!(
content.contains("future_key=42"),
"unknown key kept: {content}"
);
assert!(
content.contains("quota_providers=codex")
&& !content.contains("quota_providers=claude"),
"old selection replaced: {content}"
);
}
#[test]
fn save_empty_writes_explicit_empty() {
let dir = tempfile_dir("empty");
let path = dir.join("config");
save_quota_providers(&path, &[]).unwrap();
assert_eq!(load(&path).quota_providers, Some(Vec::new()));
}
#[test]
fn save_unwritable_returns_err_no_panic() {
let dir = tempfile_dir("unwritable");
let blocker = dir.join("blocker");
fs::write(&blocker, "x").unwrap();
let path = blocker.join("config"); let res = save_quota_providers(&path, &["claude".into()]);
assert!(res.is_err(), "expected err, got {res:?}");
}
}