use eclipse_core::config::{self, Config};
use std::path::Path;
pub fn table(path: &Path, profile: Option<&str>) -> String {
let cfg = match Config::load_with_profile(Some(path), profile, &config::process_env) {
Ok(cfg) => cfg,
Err(e) => return format!("{} does not load: {e}", path.display()),
};
let mut out = format!(
"{} — profile {}, {} key(s)\n",
path.display(),
cfg.profile_name(),
cfg.settings().len()
);
for s in cfg.settings() {
out.push_str(&format!(
" {} = {}{}\n",
s.path(),
shown(&s),
if s.is_default() { " (default)" } else { "" }
));
}
out.push_str(
"\n/set <key> <value> writes one; `eclipse config keys` prints this outside the interface",
);
out
}
pub(crate) fn shown(s: &config::Setting) -> String {
if s.secret {
return if s.value.is_some() {
"(set)".to_string()
} else {
"(not set)".to_string()
};
}
s.rendered()
}
pub fn set_one(
path: &Path,
profile: Option<&str>,
key: &str,
value: &str,
) -> Result<String, String> {
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
let typed = config::parse_value(value);
let edited = config::set_in_text(&text, key, &typed)?;
let cfg = load_before_saving(path, &edited, |p| {
Ok(Config::load_with_profile(
Some(p),
profile,
&config::process_env,
)?)
})?;
config::save_config_text(path, &edited).map_err(|e| e.to_string())?;
let setting = cfg
.setting(key)
.ok_or_else(|| format!("`{key}` was written but nothing in this build reads it"))?;
Ok(format!(
"{} = {}\n{}",
setting.path(),
shown(&setting),
setting.applies.as_str()
))
}
pub(crate) fn load_before_saving(
path: &Path,
edited: &str,
load: impl FnOnce(&Path) -> anyhow::Result<Config>,
) -> Result<Config, String> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let staged = path.with_extension(format!("toml.check-{}-{n}", std::process::id()));
config::save_config_text(&staged, edited).map_err(|e| format!("{}: {e}", staged.display()))?;
let loaded = load(&staged);
let _ = std::fs::remove_file(&staged);
loaded.map_err(|e| format!("that would not load, so nothing was saved: {e:#}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn written(text: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, text).unwrap();
(dir, path)
}
#[test]
fn an_edit_the_loader_refuses_is_not_saved() {
let before = "[provider]\nmodel = \"m\"\n";
let (_dir, path) = written(before);
let err = set_one(&path, None, "provider.fallback", "[\"nope\"]").unwrap_err();
assert!(
err.contains("nothing was saved"),
"the refusal says the file is untouched: {err}"
);
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
before,
"and it is: the config still holds what it held"
);
}
#[test]
fn an_edit_that_loads_is_written_and_read_back() {
let (_dir, path) = written("[provider]\nmodel = \"m\"\n");
let said = set_one(&path, None, "provider.model", "other-model").unwrap();
assert!(said.contains("other-model"), "{said}");
assert!(
std::fs::read_to_string(&path)
.unwrap()
.contains("model = \"other-model\""),
"the file holds it"
);
}
}