use super::{settings, Config};
use std::path::{Path, PathBuf};
pub const RENAMED: &[(&str, &str)] = &[];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
Added { key: String, value: String },
Commented { key: String },
DefaultMoved {
key: String,
from: String,
to: String,
},
Renamed {
from: String,
to: String,
value: String,
},
Kept { key: String },
}
impl Change {
pub fn key(&self) -> &str {
match self {
Change::Added { key, .. }
| Change::Commented { key }
| Change::DefaultMoved { key, .. }
| Change::Kept { key } => key,
Change::Renamed { to, .. } => to,
}
}
}
impl std::fmt::Display for Change {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Change::Added { key, value } => write!(f, "added {key} = {value}"),
Change::Commented { key } => write!(f, "added # {key} = (not set)"),
Change::DefaultMoved { key, from, to } => {
write!(
f,
"moved {key}: {from} -> {to} (you had not changed it)"
)
}
Change::Renamed { from, to, value } => write!(f, "renamed {from} -> {to} = {value}"),
Change::Kept { key } => write!(f, "kept {key}"),
}
}
}
#[derive(Debug, Clone)]
pub struct Plan {
pub from: u32,
pub to: u32,
pub baseline_missing: bool,
pub changes: Vec<Change>,
pub text: String,
}
impl Plan {
pub fn is_current(&self) -> bool {
self.from == self.to && self.notable().is_empty()
}
pub fn notable(&self) -> Vec<&Change> {
self.changes
.iter()
.filter(|c| !matches!(c, Change::Kept { .. }))
.collect()
}
pub fn kept(&self) -> usize {
self.changes
.iter()
.filter(|c| matches!(c, Change::Kept { .. }))
.count()
}
}
pub fn plan(ours: &str, base: Option<&str>, theirs: &str) -> Result<Plan, String> {
plan_with(ours, base, theirs, RENAMED)
}
pub fn plan_with(
ours: &str,
base: Option<&str>,
theirs: &str,
renames: &[(&str, &str)],
) -> Result<Plan, String> {
let loaded = Config::from_toml_str(ours)
.map_err(|e| format!("this file does not load, so nothing was planned: {e}"))?;
let from = loaded.config_version;
let our_doc: toml::Value =
toml::from_str(ours).map_err(|e| format!("this file is not valid TOML: {e}"))?;
let base_doc: Option<toml::Value> = match base {
Some(text) => {
Some(toml::from_str(text).map_err(|e| format!("the baseline is not valid TOML: {e}"))?)
}
None => None,
};
let their_doc: toml::Value = toml::from_str(theirs)
.map_err(|e| format!("the shipped template is not valid TOML: {e}"))?;
let lookup = |doc: &toml::Value, path: &str| -> Option<toml::Value> {
let (section, key) = path.split_once('.')?;
doc.get(section)?.get(key).cloned()
};
let mut text = ours.to_string();
let mut changes: Vec<Change> = Vec::new();
for (old, new) in renames {
let Some(value) = lookup(&our_doc, old) else {
continue;
};
text = settings::set_in_text(&text, new, &value)?;
if let Some((section, key)) = old.split_once('.') {
text = super::toml_comment_out(&text, section, key);
}
changes.push(Change::Renamed {
from: (*old).to_string(),
to: (*new).to_string(),
value: render(&value),
});
}
for setting in Config::default().settings() {
let path = setting.path();
if renames.iter().any(|(old, _)| *old == path) {
continue;
}
let ours_value = lookup(&our_doc, &path);
let theirs_value = lookup(&their_doc, &path);
match (ours_value, theirs_value) {
(None, Some(value)) => {
text = settings::set_in_text(&text, &path, &value)?;
changes.push(Change::Added {
key: path,
value: render(&value),
});
}
(None, None) => {
if super::toml_value(&text, &setting.section, &setting.key).is_none()
&& !has_commented_line(&text, &setting.section, &setting.key)
{
text = super::comment_in_text(&text, &setting.section, &setting.key);
changes.push(Change::Commented { key: path });
}
}
(Some(ours_value), Some(their_value)) => {
let base_value = base_doc.as_ref().and_then(|b| lookup(b, &path));
let untouched = base_value.as_ref().is_some_and(|b| *b == ours_value)
&& ours_value != their_value;
if untouched {
text = settings::set_in_text(&text, &path, &their_value)?;
changes.push(Change::DefaultMoved {
key: path,
from: render(&ours_value),
to: render(&their_value),
});
} else {
changes.push(Change::Kept { key: path });
}
}
(Some(_), None) => changes.push(Change::Kept { key: path }),
}
}
let text = super::stamp_version(&text, super::CONFIG_VERSION)?;
Ok(Plan {
from,
to: super::CONFIG_VERSION,
baseline_missing: base.is_none(),
changes,
text,
})
}
fn has_commented_line(text: &str, section: &str, key: &str) -> bool {
let mut in_section = false;
for line in text.lines() {
let trimmed = line.trim();
if let Some(state) = super::header_state(trimmed, section) {
in_section = state;
continue;
}
if !in_section {
continue;
}
let Some(rest) = trimmed.strip_prefix('#') else {
continue;
};
if let Some((k, _)) = super::key_value(rest.trim()) {
if k == key {
return true;
}
}
}
false
}
fn render(value: &toml::Value) -> String {
match value {
toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
other => other.to_string(),
}
}
pub fn baseline_path(config_path: &Path) -> PathBuf {
let dir = config_path.parent().unwrap_or(Path::new("."));
dir.join("state").join("config.baseline.toml")
}
pub fn write_baseline(config_path: &Path) -> std::io::Result<PathBuf> {
let path = baseline_path(config_path);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let template = super::starter_config().map_err(io_err)?;
std::fs::write(&path, template)?;
Ok(path)
}
fn io_err(message: crate::error::Error) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::InvalidData, message.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn shipped() -> String {
super::super::starter_config().expect("the shipped template generates")
}
fn with(text: &str, from: &str, to: &str) -> String {
assert!(text.contains(from), "the fixture line `{from}` is there");
text.replace(from, to)
}
#[test]
fn the_shipped_file_is_already_current() {
let text = shipped();
let plan = plan(&text, Some(&text), &text).unwrap();
assert!(plan.is_current(), "{:?}", plan.notable());
assert_eq!(plan.text, text, "and writing it would change nothing");
assert_eq!(plan.from, super::super::CONFIG_VERSION);
}
#[test]
fn a_key_the_file_lacks_is_added_at_the_shipped_value() {
let theirs = shipped();
let ours = with(&theirs, "max_retries = 3\n", "");
let plan = plan(&ours, None, &theirs).unwrap();
assert!(
plan.changes.iter().any(|c| matches!(
c,
Change::Added { key, value } if key == "provider.max_retries" && value == "3"
)),
"{:?}",
plan.notable()
);
let after = super::super::Config::from_toml_str(&plan.text).unwrap();
assert_eq!(after.provider.max_retries, 3);
}
#[test]
fn a_default_that_moved_is_applied_only_where_the_file_still_held_it() {
let base = shipped();
let theirs = with(&base, "timeout_secs = 120", "timeout_secs = 180");
let untouched = plan(&base, Some(&base), &theirs).unwrap();
assert!(
untouched.changes.iter().any(|c| matches!(
c,
Change::DefaultMoved { key, from, to }
if key == "provider.timeout_secs" && from == "120" && to == "180"
)),
"{:?}",
untouched.notable()
);
assert_eq!(
super::super::Config::from_toml_str(&untouched.text)
.unwrap()
.provider
.timeout_secs,
180
);
let chosen = with(&base, "timeout_secs = 120", "timeout_secs = 300");
let kept = plan(&chosen, Some(&base), &theirs).unwrap();
assert!(!kept
.changes
.iter()
.any(|c| matches!(c, Change::DefaultMoved { .. })));
assert!(kept.text.contains("timeout_secs = 300"), "{}", kept.text);
}
#[test]
fn a_value_someone_chose_survives_every_kind_of_change_at_once() {
let base = shipped();
let theirs = with(
&with(&base, "timeout_secs = 120", "timeout_secs = 180"),
"max_retries = 3",
"max_retries = 5",
);
let ours = with(
&with(&base, "max_retries = 3", "max_retries = 9"),
"# Every setting this build reads, and nothing else.",
"# Every setting this build reads, and nothing else.\n# my note, kept",
);
let plan = plan(&ours, Some(&base), &theirs).unwrap();
assert!(
plan.text.contains("max_retries = 9"),
"the operator's value"
);
assert!(
plan.text.contains("timeout_secs = 180"),
"the moved default"
);
assert!(plan.text.contains("# my note, kept"), "a comment survived");
assert_eq!(
super::super::Config::from_toml_str(&plan.text)
.unwrap()
.provider
.max_retries,
9
);
}
#[test]
fn a_key_this_build_ships_unset_is_added_as_a_comment_not_a_value() {
let theirs = shipped();
let ours = with(&theirs, "# temperature =\n", "");
let plan = plan(&ours, Some(&theirs), &theirs).unwrap();
assert!(
plan.changes
.iter()
.any(|c| matches!(c, Change::Commented { key } if key == "provider.temperature")),
"{:?}",
plan.notable()
);
assert!(plan.text.contains("# temperature ="), "{}", plan.text);
let after = super::super::Config::from_toml_str(&plan.text).unwrap();
assert_eq!(after.provider.temperature, None);
}
#[test]
fn a_renamed_key_keeps_its_value_and_its_old_line_is_commented() {
let base = shipped();
let ours = with(&base, "max_output_bytes = 32768", "max_output_bytes = 4096");
let plan = plan_with(
&ours,
Some(&base),
&base,
&[("tools.max_output_bytes", "tools.rewrite_guard_bytes")],
)
.unwrap();
assert!(
plan.changes.iter().any(|c| matches!(
c,
Change::Renamed { from, to, value }
if from == "tools.max_output_bytes"
&& to == "tools.rewrite_guard_bytes"
&& value == "4096"
)),
"{:?}",
plan.notable()
);
let after = super::super::Config::from_toml_str(&plan.text).unwrap();
assert_eq!(
after.tools.rewrite_guard_bytes, 4096,
"the value came with the key"
);
assert!(
plan.text.contains("# max_output_bytes = 4096"),
"the old line is kept as a record, not deleted: {}",
plan.text
);
}
#[test]
fn a_key_this_build_does_not_know_is_left_exactly_where_it_is() {
let base = shipped();
let ours = with(
&base,
"max_retries = 3",
"max_retries = 3\nnot_a_setting = \"mine\"",
);
let plan = plan(&ours, Some(&base), &base).unwrap();
assert!(
!plan
.changes
.iter()
.any(|c| c.key() == "provider.not_a_setting"),
"a migration never reports what it does not touch: {:?}",
plan.notable()
);
assert!(
plan.text.contains("not_a_setting = \"mine\""),
"{}",
plan.text
);
}
#[test]
fn a_missing_baseline_degrades_to_additions_and_says_so() {
let base = shipped();
let theirs = with(&base, "timeout_secs = 120", "timeout_secs = 180");
let plan = plan(&base, None, &theirs).unwrap();
assert!(plan.baseline_missing);
assert!(
!plan
.changes
.iter()
.any(|c| matches!(c, Change::DefaultMoved { .. })),
"with nothing to compare against, no value is touched: {:?}",
plan.notable()
);
assert!(plan.text.contains("timeout_secs = 120"), "{}", plan.text);
}
#[test]
fn the_version_is_stamped_and_a_file_from_before_the_stamp_reports_zero() {
let base = shipped();
let old = with(&base, "config_version = 1\n", "");
assert_eq!(
super::super::Config::from_toml_str(&old)
.unwrap()
.config_version,
0,
"no stamp reads as version 0, which is every install older than this key"
);
let plan = plan(&old, None, &base).unwrap();
assert_eq!(plan.from, 0);
assert_eq!(plan.to, super::super::CONFIG_VERSION);
assert!(plan.text.starts_with("# Every setting this build reads"));
let stamp_at = plan.text.find("config_version = 1").expect("stamped");
let first_table = plan.text.find("\n[").expect("a table");
assert!(stamp_at < first_table, "top level, above the first table");
let head: Vec<&str> = plan.text.lines().take(5).collect();
assert_eq!(
head,
vec![
"# Every setting this build reads, and nothing else.",
"# What one does, and what it accepts: `eclipse config docs`.",
"# A commented key is not in use; an empty value means the same.",
"config_version = 1",
"",
],
"{:?}",
plan.text.lines().take(6).collect::<Vec<_>>()
);
}
#[test]
fn a_file_that_does_not_load_is_refused_rather_than_migrated() {
let err = plan("this is not toml", None, &shipped()).unwrap_err();
assert!(err.contains("does not load"), "{err}");
}
}