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 let mut renamed_to: Vec<&str> = Vec::new();
182
183 for (old, new) in renames {
185 let Some(value) = lookup(&our_doc, old) else {
186 continue;
187 };
188 text = settings::set_in_text(&text, new, &value)?;
189 renamed_to.push(new);
190 if let Some((section, key)) = old.split_once('.') {
191 text = super::toml_comment_out(&text, section, key);
192 }
193 changes.push(Change::Renamed {
194 from: (*old).to_string(),
195 to: (*new).to_string(),
196 value: render(&value),
197 });
198 }
199
200 for setting in Config::default().settings() {
201 let path = setting.path();
202 if renames.iter().any(|(old, _)| *old == path) || renamed_to.iter().any(|new| *new == path)
203 {
204 continue;
205 }
206 let ours_value = lookup(&our_doc, &path);
207 let theirs_value = lookup(&their_doc, &path);
208 match (ours_value, theirs_value) {
209 (None, Some(value)) => {
211 text = settings::set_in_text(&text, &path, &value)?;
212 changes.push(Change::Added {
213 key: path,
214 value: render(&value),
215 });
216 }
217 (None, None) => {
219 if super::toml_value(&text, &setting.section, &setting.key).is_none()
220 && !has_commented_line(&text, &setting.section, &setting.key)
221 {
222 text = super::comment_in_text(&text, &setting.section, &setting.key);
223 changes.push(Change::Commented { key: path });
224 }
225 }
226 (Some(ours_value), Some(their_value)) => {
228 let base_value = base_doc.as_ref().and_then(|b| lookup(b, &path));
229 let untouched = base_value.as_ref().is_some_and(|b| *b == ours_value)
230 && ours_value != their_value;
231 if untouched {
232 text = settings::set_in_text(&text, &path, &their_value)?;
233 changes.push(Change::DefaultMoved {
234 key: path,
235 from: render(&ours_value),
236 to: render(&their_value),
237 });
238 } else {
239 changes.push(Change::Kept { key: path });
240 }
241 }
242 (Some(_), None) => changes.push(Change::Kept { key: path }),
244 }
245 }
246
247 let text = super::stamp_version(&text, super::CONFIG_VERSION)?;
249 Ok(Plan {
250 from,
251 to: super::CONFIG_VERSION,
252 baseline_missing: base.is_none(),
253 changes,
254 text,
255 })
256}
257
258fn has_commented_line(text: &str, section: &str, key: &str) -> bool {
260 let mut in_section = false;
261 for line in text.lines() {
262 let trimmed = line.trim();
263 if let Some(state) = super::header_state(trimmed, section) {
264 in_section = state;
265 continue;
266 }
267 if !in_section {
268 continue;
269 }
270 let Some(rest) = trimmed.strip_prefix('#') else {
271 continue;
272 };
273 if let Some((k, _)) = super::key_value(rest.trim()) {
274 if k == key {
275 return true;
276 }
277 }
278 }
279 false
280}
281
282fn render(value: &toml::Value) -> String {
283 match value {
284 toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
285 other => other.to_string(),
286 }
287}
288
289pub fn baseline_path(config_path: &Path) -> PathBuf {
295 let dir = config_path.parent().unwrap_or(Path::new("."));
296 dir.join("state").join("config.baseline.toml")
297}
298
299pub fn write_baseline(config_path: &Path) -> std::io::Result<PathBuf> {
301 let path = baseline_path(config_path);
302 if let Some(dir) = path.parent() {
303 std::fs::create_dir_all(dir)?;
304 }
305 let template = super::starter_config().map_err(io_err)?;
306 std::fs::write(&path, template)?;
307 Ok(path)
308}
309
310fn io_err(message: crate::error::Error) -> std::io::Error {
311 std::io::Error::new(std::io::ErrorKind::InvalidData, message.to_string())
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 fn shipped() -> String {
321 super::super::starter_config().expect("the shipped template generates")
322 }
323
324 fn with(text: &str, from: &str, to: &str) -> String {
325 assert!(text.contains(from), "the fixture line `{from}` is there");
326 text.replace(from, to)
327 }
328
329 #[test]
330 fn the_shipped_file_is_already_current() {
331 let text = shipped();
332 let plan = plan(&text, Some(&text), &text).unwrap();
333 assert!(plan.is_current(), "{:?}", plan.notable());
334 assert_eq!(plan.text, text, "and writing it would change nothing");
335 assert_eq!(plan.from, super::super::CONFIG_VERSION);
336 }
337
338 #[test]
339 fn a_key_the_file_lacks_is_added_at_the_shipped_value() {
340 let theirs = shipped();
341 let ours = with(&theirs, "max_retries = 3\n", "");
342 let plan = plan(&ours, None, &theirs).unwrap();
343 assert!(
344 plan.changes.iter().any(|c| matches!(
345 c,
346 Change::Added { key, value } if key == "provider.max_retries" && value == "3"
347 )),
348 "{:?}",
349 plan.notable()
350 );
351 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
352 assert_eq!(after.provider.max_retries, 3);
353 }
354
355 #[test]
356 fn a_default_that_moved_is_applied_only_where_the_file_still_held_it() {
357 let base = shipped();
358 let theirs = with(&base, "timeout_secs = 120", "timeout_secs = 180");
359 let untouched = plan(&base, Some(&base), &theirs).unwrap();
361 assert!(
362 untouched.changes.iter().any(|c| matches!(
363 c,
364 Change::DefaultMoved { key, from, to }
365 if key == "provider.timeout_secs" && from == "120" && to == "180"
366 )),
367 "{:?}",
368 untouched.notable()
369 );
370 assert_eq!(
371 super::super::Config::from_toml_str(&untouched.text)
372 .unwrap()
373 .provider
374 .timeout_secs,
375 180
376 );
377 let chosen = with(&base, "timeout_secs = 120", "timeout_secs = 300");
379 let kept = plan(&chosen, Some(&base), &theirs).unwrap();
380 assert!(!kept
381 .changes
382 .iter()
383 .any(|c| matches!(c, Change::DefaultMoved { .. })));
384 assert!(kept.text.contains("timeout_secs = 300"), "{}", kept.text);
385 }
386
387 #[test]
388 fn a_value_someone_chose_survives_every_kind_of_change_at_once() {
389 let base = shipped();
390 let theirs = with(
391 &with(&base, "timeout_secs = 120", "timeout_secs = 180"),
392 "max_retries = 3",
393 "max_retries = 5",
394 );
395 let ours = with(
396 &with(&base, "max_retries = 3", "max_retries = 9"),
397 "# Every setting this build reads, and nothing else.",
398 "# Every setting this build reads, and nothing else.\n# my note, kept",
399 );
400 let plan = plan(&ours, Some(&base), &theirs).unwrap();
401 assert!(
402 plan.text.contains("max_retries = 9"),
403 "the operator's value"
404 );
405 assert!(
406 plan.text.contains("timeout_secs = 180"),
407 "the moved default"
408 );
409 assert!(plan.text.contains("# my note, kept"), "a comment survived");
410 assert_eq!(
411 super::super::Config::from_toml_str(&plan.text)
412 .unwrap()
413 .provider
414 .max_retries,
415 9
416 );
417 }
418
419 #[test]
420 fn a_key_this_build_ships_unset_is_added_as_a_comment_not_a_value() {
421 let theirs = shipped();
422 let ours = with(&theirs, "# temperature =\n", "");
424 let plan = plan(&ours, Some(&theirs), &theirs).unwrap();
425 assert!(
426 plan.changes
427 .iter()
428 .any(|c| matches!(c, Change::Commented { key } if key == "provider.temperature")),
429 "{:?}",
430 plan.notable()
431 );
432 assert!(plan.text.contains("# temperature ="), "{}", plan.text);
433 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
435 assert_eq!(after.provider.temperature, None);
436 }
437
438 #[test]
439 fn a_renamed_key_keeps_its_value_and_its_old_line_is_commented() {
440 let base = shipped();
441 let ours = with(&base, "max_output_bytes = 32768", "max_output_bytes = 4096");
442 let plan = plan_with(
445 &ours,
446 Some(&base),
447 &base,
448 &[("tools.max_output_bytes", "tools.rewrite_guard_bytes")],
449 )
450 .unwrap();
451 assert!(
452 plan.changes.iter().any(|c| matches!(
453 c,
454 Change::Renamed { from, to, value }
455 if from == "tools.max_output_bytes"
456 && to == "tools.rewrite_guard_bytes"
457 && value == "4096"
458 )),
459 "{:?}",
460 plan.notable()
461 );
462 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
463 assert_eq!(
464 after.tools.rewrite_guard_bytes, 4096,
465 "the value came with the key"
466 );
467 assert!(
468 plan.text.contains("# max_output_bytes = 4096"),
469 "the old line is kept as a record, not deleted: {}",
470 plan.text
471 );
472 }
473
474 #[test]
475 fn a_renamed_key_that_the_old_file_never_had_keeps_its_value() {
476 let base = shipped();
482 let ours = with(&base, "max_output_bytes = 32768", "max_output_bytes = 999")
483 .lines()
484 .filter(|l| !l.trim_start().starts_with("rewrite_guard_bytes ="))
485 .collect::<Vec<_>>()
486 .join("\n")
487 + "\n";
488 assert!(
489 !ours.contains("rewrite_guard_bytes ="),
490 "the fixture must not hold the new name: {}",
491 ours
492 );
493
494 let plan = plan_with(
495 &ours,
496 Some(&base),
497 &base,
498 &[("tools.max_output_bytes", "tools.rewrite_guard_bytes")],
499 )
500 .unwrap();
501 let after = super::super::Config::from_toml_str(&plan.text).unwrap();
502 assert_eq!(
503 after.tools.rewrite_guard_bytes, 999,
504 "the value the rename carried across was replaced by the shipped default: {}",
505 plan.text
506 );
507 }
508
509 #[test]
510 fn a_key_this_build_does_not_know_is_left_exactly_where_it_is() {
511 let base = shipped();
512 let ours = with(
513 &base,
514 "max_retries = 3",
515 "max_retries = 3\nnot_a_setting = \"mine\"",
516 );
517 let plan = plan(&ours, Some(&base), &base).unwrap();
518 assert!(
519 !plan
520 .changes
521 .iter()
522 .any(|c| c.key() == "provider.not_a_setting"),
523 "a migration never reports what it does not touch: {:?}",
524 plan.notable()
525 );
526 assert!(
527 plan.text.contains("not_a_setting = \"mine\""),
528 "{}",
529 plan.text
530 );
531 }
532
533 #[test]
534 fn a_missing_baseline_degrades_to_additions_and_says_so() {
535 let base = shipped();
536 let theirs = with(&base, "timeout_secs = 120", "timeout_secs = 180");
537 let plan = plan(&base, None, &theirs).unwrap();
538 assert!(plan.baseline_missing);
539 assert!(
540 !plan
541 .changes
542 .iter()
543 .any(|c| matches!(c, Change::DefaultMoved { .. })),
544 "with nothing to compare against, no value is touched: {:?}",
545 plan.notable()
546 );
547 assert!(plan.text.contains("timeout_secs = 120"), "{}", plan.text);
548 }
549
550 #[test]
551 fn the_version_is_stamped_and_a_file_from_before_the_stamp_reports_zero() {
552 let base = shipped();
553 let old = with(&base, "config_version = 1\n", "");
554 assert_eq!(
555 super::super::Config::from_toml_str(&old)
556 .unwrap()
557 .config_version,
558 0,
559 "no stamp reads as version 0, which is every install older than this key"
560 );
561 let plan = plan(&old, None, &base).unwrap();
562 assert_eq!(plan.from, 0);
563 assert_eq!(plan.to, super::super::CONFIG_VERSION);
564 assert!(plan.text.starts_with("# Every setting this build reads"));
565 let stamp_at = plan.text.find("config_version = 1").expect("stamped");
566 let first_table = plan.text.find("\n[").expect("a table");
567 assert!(stamp_at < first_table, "top level, above the first table");
568 let head: Vec<&str> = plan.text.lines().take(5).collect();
571 assert_eq!(
572 head,
573 vec![
574 "# Every setting this build reads, and nothing else.",
575 "# What one does, and what it accepts: `eclipse config docs`.",
576 "# A commented key is not in use; an empty value means the same.",
577 "config_version = 1",
578 "",
579 ],
580 "{:?}",
581 plan.text.lines().take(6).collect::<Vec<_>>()
582 );
583 }
584
585 #[test]
586 fn a_file_that_does_not_load_is_refused_rather_than_migrated() {
587 let err = plan("this is not toml", None, &shipped()).unwrap_err();
588 assert!(err.contains("does not load"), "{err}");
589 }
590}