1use super::{settings, Config};
41use std::path::{Path, PathBuf};
42
43pub const RENAMED: &[(&str, &str)] = &[];
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum Change {
53 Added { key: String, value: String },
55 Commented { key: String },
57 DefaultMoved {
59 key: String,
60 from: String,
61 to: String,
62 },
63 Renamed {
65 from: String,
66 to: String,
67 value: String,
68 },
69 Kept { key: String },
71}
72
73impl Change {
74 pub fn key(&self) -> &str {
75 match self {
76 Change::Added { key, .. }
77 | Change::Commented { key }
78 | Change::DefaultMoved { key, .. }
79 | Change::Kept { key } => key,
80 Change::Renamed { to, .. } => to,
81 }
82 }
83}
84
85impl std::fmt::Display for Change {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 match self {
88 Change::Added { key, value } => write!(f, "added {key} = {value}"),
89 Change::Commented { key } => write!(f, "added # {key} = (not set)"),
90 Change::DefaultMoved { key, from, to } => {
91 write!(
92 f,
93 "moved {key}: {from} -> {to} (you had not changed it)"
94 )
95 }
96 Change::Renamed { from, to, value } => write!(f, "renamed {from} -> {to} = {value}"),
97 Change::Kept { key } => write!(f, "kept {key}"),
98 }
99 }
100}
101
102#[derive(Debug, Clone)]
104pub struct Plan {
105 pub from: u32,
107 pub to: u32,
109 pub baseline_missing: bool,
111 pub changes: Vec<Change>,
112 pub text: String,
114}
115
116impl Plan {
117 pub fn is_current(&self) -> bool {
121 self.from == self.to && self.notable().is_empty()
122 }
123
124 pub fn notable(&self) -> Vec<&Change> {
126 self.changes
127 .iter()
128 .filter(|c| !matches!(c, Change::Kept { .. }))
129 .collect()
130 }
131
132 pub fn kept(&self) -> usize {
133 self.changes
134 .iter()
135 .filter(|c| matches!(c, Change::Kept { .. }))
136 .count()
137 }
138}
139
140pub fn plan(ours: &str, base: Option<&str>, theirs: &str) -> Result<Plan, String> {
145 plan_with(ours, base, theirs, RENAMED)
146}
147
148pub fn plan_with(
151 ours: &str,
152 base: Option<&str>,
153 theirs: &str,
154 renames: &[(&str, &str)],
155) -> Result<Plan, String> {
156 let loaded = Config::from_toml_str(ours)
157 .map_err(|e| format!("this file does not load, so nothing was planned: {e}"))?;
158 let from = loaded.config_version;
159 let our_doc: toml::Value =
160 toml::from_str(ours).map_err(|e| format!("this file is not valid TOML: {e}"))?;
161 let base_doc: Option<toml::Value> = match base {
162 Some(text) => {
163 Some(toml::from_str(text).map_err(|e| format!("the baseline is not valid TOML: {e}"))?)
164 }
165 None => None,
166 };
167 let their_doc: toml::Value = toml::from_str(theirs)
168 .map_err(|e| format!("the shipped template is not valid TOML: {e}"))?;
169
170 let lookup = |doc: &toml::Value, path: &str| -> Option<toml::Value> {
171 let (section, key) = path.split_once('.')?;
172 doc.get(section)?.get(key).cloned()
173 };
174
175 let mut text = ours.to_string();
176 let mut changes: Vec<Change> = Vec::new();
177
178 for (old, new) in renames {
180 let Some(value) = lookup(&our_doc, old) else {
181 continue;
182 };
183 text = settings::set_in_text(&text, new, &value)?;
184 if let Some((section, key)) = old.split_once('.') {
185 text = super::toml_comment_out(&text, section, key);
186 }
187 changes.push(Change::Renamed {
188 from: (*old).to_string(),
189 to: (*new).to_string(),
190 value: render(&value),
191 });
192 }
193
194 for setting in Config::default().settings() {
195 let path = setting.path();
196 if renames.iter().any(|(old, _)| *old == path) {
197 continue;
198 }
199 let ours_value = lookup(&our_doc, &path);
200 let theirs_value = lookup(&their_doc, &path);
201 match (ours_value, theirs_value) {
202 (None, Some(value)) => {
204 text = settings::set_in_text(&text, &path, &value)?;
205 changes.push(Change::Added {
206 key: path,
207 value: render(&value),
208 });
209 }
210 (None, None) => {
212 if super::toml_value(&text, &setting.section, &setting.key).is_none()
213 && !has_commented_line(&text, &setting.section, &setting.key)
214 {
215 text = super::comment_in_text(&text, &setting.section, &setting.key);
216 changes.push(Change::Commented { key: path });
217 }
218 }
219 (Some(ours_value), Some(their_value)) => {
221 let base_value = base_doc.as_ref().and_then(|b| lookup(b, &path));
222 let untouched = base_value.as_ref().is_some_and(|b| *b == ours_value)
223 && ours_value != their_value;
224 if untouched {
225 text = settings::set_in_text(&text, &path, &their_value)?;
226 changes.push(Change::DefaultMoved {
227 key: path,
228 from: render(&ours_value),
229 to: render(&their_value),
230 });
231 } else {
232 changes.push(Change::Kept { key: path });
233 }
234 }
235 (Some(_), None) => changes.push(Change::Kept { key: path }),
237 }
238 }
239
240 let text = super::stamp_version(&text, super::CONFIG_VERSION)?;
242 Ok(Plan {
243 from,
244 to: super::CONFIG_VERSION,
245 baseline_missing: base.is_none(),
246 changes,
247 text,
248 })
249}
250
251fn has_commented_line(text: &str, section: &str, key: &str) -> bool {
253 let mut in_section = false;
254 for line in text.lines() {
255 let trimmed = line.trim();
256 if let Some(name) = super::section_header(trimmed) {
257 in_section = name == section;
258 continue;
259 }
260 if !in_section {
261 continue;
262 }
263 let Some(rest) = trimmed.strip_prefix('#') else {
264 continue;
265 };
266 if let Some((k, _)) = super::key_value(rest.trim()) {
267 if k == key {
268 return true;
269 }
270 }
271 }
272 false
273}
274
275fn render(value: &toml::Value) -> String {
276 match value {
277 toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
278 other => other.to_string(),
279 }
280}
281
282pub fn baseline_path(config_path: &Path) -> PathBuf {
288 let dir = config_path.parent().unwrap_or(Path::new("."));
289 dir.join("state").join("config.baseline.toml")
290}
291
292pub fn write_baseline(config_path: &Path) -> std::io::Result<PathBuf> {
294 let path = baseline_path(config_path);
295 if let Some(dir) = path.parent() {
296 std::fs::create_dir_all(dir)?;
297 }
298 let template = super::starter_config().map_err(io_err)?;
299 std::fs::write(&path, template)?;
300 Ok(path)
301}
302
303fn io_err(message: crate::error::Error) -> std::io::Error {
304 std::io::Error::new(std::io::ErrorKind::InvalidData, message.to_string())
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 fn shipped() -> String {
314 super::super::starter_config().expect("the shipped template generates")
315 }
316
317 fn with(text: &str, from: &str, to: &str) -> String {
318 assert!(text.contains(from), "the fixture line `{from}` is there");
319 text.replace(from, to)
320 }
321
322 #[test]
323 fn the_shipped_file_is_already_current() {
324 let text = shipped();
325 let plan = plan(&text, Some(&text), &text).unwrap();
326 assert!(plan.is_current(), "{:?}", plan.notable());
327 assert_eq!(plan.text, text, "and writing it would change nothing");
328 assert_eq!(plan.from, super::super::CONFIG_VERSION);
329 }
330
331 #[test]
332 fn a_key_the_file_lacks_is_added_at_the_shipped_value() {
333 let theirs = shipped();
334 let ours = with(&theirs, "max_retries = 3\n", "");
335 let plan = plan(&ours, None, &theirs).unwrap();
336 assert!(
337 plan.changes.iter().any(|c| matches!(
338 c,
339 Change::Added { key, value } if key == "provider.max_retries" && value == "3"
340 )),
341 "{:?}",
342 plan.notable()
343 );
344 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
345 assert_eq!(after.provider.max_retries, 3);
346 }
347
348 #[test]
349 fn a_default_that_moved_is_applied_only_where_the_file_still_held_it() {
350 let base = shipped();
351 let theirs = with(&base, "timeout_secs = 120", "timeout_secs = 180");
352 let untouched = plan(&base, Some(&base), &theirs).unwrap();
354 assert!(
355 untouched.changes.iter().any(|c| matches!(
356 c,
357 Change::DefaultMoved { key, from, to }
358 if key == "provider.timeout_secs" && from == "120" && to == "180"
359 )),
360 "{:?}",
361 untouched.notable()
362 );
363 assert_eq!(
364 super::super::Config::from_toml_str(&untouched.text)
365 .unwrap()
366 .provider
367 .timeout_secs,
368 180
369 );
370 let chosen = with(&base, "timeout_secs = 120", "timeout_secs = 300");
372 let kept = plan(&chosen, Some(&base), &theirs).unwrap();
373 assert!(!kept
374 .changes
375 .iter()
376 .any(|c| matches!(c, Change::DefaultMoved { .. })));
377 assert!(kept.text.contains("timeout_secs = 300"), "{}", kept.text);
378 }
379
380 #[test]
381 fn a_value_someone_chose_survives_every_kind_of_change_at_once() {
382 let base = shipped();
383 let theirs = with(
384 &with(&base, "timeout_secs = 120", "timeout_secs = 180"),
385 "max_retries = 3",
386 "max_retries = 5",
387 );
388 let ours = with(
389 &with(&base, "max_retries = 3", "max_retries = 9"),
390 "# Every setting this build reads, and nothing else.",
391 "# Every setting this build reads, and nothing else.\n# my note, kept",
392 );
393 let plan = plan(&ours, Some(&base), &theirs).unwrap();
394 assert!(
395 plan.text.contains("max_retries = 9"),
396 "the operator's value"
397 );
398 assert!(
399 plan.text.contains("timeout_secs = 180"),
400 "the moved default"
401 );
402 assert!(plan.text.contains("# my note, kept"), "a comment survived");
403 assert_eq!(
404 super::super::Config::from_toml_str(&plan.text)
405 .unwrap()
406 .provider
407 .max_retries,
408 9
409 );
410 }
411
412 #[test]
413 fn a_key_this_build_ships_unset_is_added_as_a_comment_not_a_value() {
414 let theirs = shipped();
415 let ours = with(&theirs, "# temperature =\n", "");
417 let plan = plan(&ours, Some(&theirs), &theirs).unwrap();
418 assert!(
419 plan.changes
420 .iter()
421 .any(|c| matches!(c, Change::Commented { key } if key == "provider.temperature")),
422 "{:?}",
423 plan.notable()
424 );
425 assert!(plan.text.contains("# temperature ="), "{}", plan.text);
426 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
428 assert_eq!(after.provider.temperature, None);
429 }
430
431 #[test]
432 fn a_renamed_key_keeps_its_value_and_its_old_line_is_commented() {
433 let base = shipped();
434 let ours = with(&base, "max_output_bytes = 32768", "max_output_bytes = 4096");
435 let plan = plan_with(
438 &ours,
439 Some(&base),
440 &base,
441 &[("tools.max_output_bytes", "tools.rewrite_guard_bytes")],
442 )
443 .unwrap();
444 assert!(
445 plan.changes.iter().any(|c| matches!(
446 c,
447 Change::Renamed { from, to, value }
448 if from == "tools.max_output_bytes"
449 && to == "tools.rewrite_guard_bytes"
450 && value == "4096"
451 )),
452 "{:?}",
453 plan.notable()
454 );
455 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
456 assert_eq!(
457 after.tools.rewrite_guard_bytes, 4096,
458 "the value came with the key"
459 );
460 assert!(
461 plan.text.contains("# max_output_bytes = 4096"),
462 "the old line is kept as a record, not deleted: {}",
463 plan.text
464 );
465 }
466
467 #[test]
468 fn a_key_this_build_does_not_know_is_left_exactly_where_it_is() {
469 let base = shipped();
470 let ours = with(
471 &base,
472 "max_retries = 3",
473 "max_retries = 3\nnot_a_setting = \"mine\"",
474 );
475 let plan = plan(&ours, Some(&base), &base).unwrap();
476 assert!(
477 !plan
478 .changes
479 .iter()
480 .any(|c| c.key() == "provider.not_a_setting"),
481 "a migration never reports what it does not touch: {:?}",
482 plan.notable()
483 );
484 assert!(
485 plan.text.contains("not_a_setting = \"mine\""),
486 "{}",
487 plan.text
488 );
489 }
490
491 #[test]
492 fn a_missing_baseline_degrades_to_additions_and_says_so() {
493 let base = shipped();
494 let theirs = with(&base, "timeout_secs = 120", "timeout_secs = 180");
495 let plan = plan(&base, None, &theirs).unwrap();
496 assert!(plan.baseline_missing);
497 assert!(
498 !plan
499 .changes
500 .iter()
501 .any(|c| matches!(c, Change::DefaultMoved { .. })),
502 "with nothing to compare against, no value is touched: {:?}",
503 plan.notable()
504 );
505 assert!(plan.text.contains("timeout_secs = 120"), "{}", plan.text);
506 }
507
508 #[test]
509 fn the_version_is_stamped_and_a_file_from_before_the_stamp_reports_zero() {
510 let base = shipped();
511 let old = with(&base, "config_version = 1\n", "");
512 assert_eq!(
513 super::super::Config::from_toml_str(&old)
514 .unwrap()
515 .config_version,
516 0,
517 "no stamp reads as version 0, which is every install older than this key"
518 );
519 let plan = plan(&old, None, &base).unwrap();
520 assert_eq!(plan.from, 0);
521 assert_eq!(plan.to, super::super::CONFIG_VERSION);
522 assert!(plan.text.starts_with("# Every setting this build reads"));
523 let stamp_at = plan.text.find("config_version = 1").expect("stamped");
524 let first_table = plan.text.find("\n[").expect("a table");
525 assert!(stamp_at < first_table, "top level, above the first table");
526 let head: Vec<&str> = plan.text.lines().take(5).collect();
529 assert_eq!(
530 head,
531 vec![
532 "# Every setting this build reads, and nothing else.",
533 "# What one does, and what it accepts: `eclipse config docs`.",
534 "# A commented key is not in use; an empty value means the same.",
535 "config_version = 1",
536 "",
537 ],
538 "{:?}",
539 plan.text.lines().take(6).collect::<Vec<_>>()
540 );
541 }
542
543 #[test]
544 fn a_file_that_does_not_load_is_refused_rather_than_migrated() {
545 let err = plan("this is not toml", None, &shipped()).unwrap_err();
546 assert!(err.contains("does not load"), "{err}");
547 }
548}