Skip to main content

eclipse_core/config/
migrate.rs

1//! `eclipse config migrate` — bringing a config file forward without touching what its owner chose.
2//!
3//! [`super::CONFIG_VERSION`] is stamped into the file, so this can tell how old it is. What it
4//! cannot tell from the stamp alone is *which lines a person edited*, and that is the whole problem:
5//! a file written by 0.9.0 has every key in it as a comment, and a file written by 0.10.0 has every
6//! key live. Adding a key is safe. Changing a default is not — unless the file still holds the old
7//! default, which is the same shape git's merge uses: *ours* wins where it differs from *base*,
8//! *theirs* wins where it does not.
9//!
10//! So there are three inputs:
11//!
12//! - **ours** — the file on disk, the one with the operator's edits in it.
13//! - **base** — the template this file was generated from, kept beside the state directory
14//!   ([`baseline_path`]). Without it there is no way to tell "the operator chose 120" from "0.9.0
15//!   shipped 120", so a missing baseline degrades to additions only and says so.
16//! - **theirs** — [`super::starter_config()`], what this build ships.
17//!
18//! Six rules, in the order they matter:
19//!
20//! 1. A key *theirs* sets and *ours* does not is **added**, at the shipped value.
21//! 2. A key with no shipped value at all (a temperature, a cap) is added **as a comment**, which is
22//!    how the file says "not in use" for a key whose off state has no spelling. That is what keeps
23//!    the file complete without imposing anything.
24//! 3. A key *ours* sets to exactly what *base* says, while *theirs* says something else, **moves** —
25//!    the default changed and nobody chose the old one.
26//! 4. A key *ours* set to anything else **stays**, whatever *theirs* says. This is the rule the
27//!    whole thing exists for.
28//! 5. A key in [`RENAMED`] is written under its new name and the old line is commented out, so the
29//!    value survives a rename. The table is empty until there is a rename to record; the mechanism
30//!    is here so the first one is a one-line change rather than a redesign.
31//! 6. Nothing is ever deleted. A key this build does not know is left exactly where it is —
32//!    `eclipse config check` names it, and a migration that quietly drops a line someone typed is a
33//!    migration nobody runs twice.
34//!
35//! Every write goes through [`super::set_in_text`], which edits one line of text and proves the
36//! result loads, so comments, ordering and hand-written formatting survive. The file is copied to
37//! `<name>.bak` before the first change, and the baseline is rewritten afterwards — the next
38//! migration needs to know what *this* one shipped.
39
40use super::{settings, Config};
41use std::path::{Path, PathBuf};
42
43/// Keys that moved. `(old path, new path)`.
44///
45/// Empty on purpose: 0.10.0 is the first version that stamps a file, so there is nothing older to
46/// rename from. When there is, this is the only place to say so — [`a_renamed_key_keeps_its_value`]
47/// drives the table with a fake pair so the mechanism is proven before it is needed.
48pub const RENAMED: &[(&str, &str)] = &[];
49
50/// What a migration did to one key.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum Change {
53    /// The file did not have the key; this build ships it with a value.
54    Added { key: String, value: String },
55    /// The file did not have the key, and this build ships it unset: the line is a comment.
56    Commented { key: String },
57    /// The key moved to the value this build ships, because the file still held the old default.
58    DefaultMoved {
59        key: String,
60        from: String,
61        to: String,
62    },
63    /// The key was renamed, and its value came with it.
64    Renamed {
65        from: String,
66        to: String,
67        value: String,
68    },
69    /// The key was left alone, and here is why: the operator set it.
70    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/// The result of planning a migration: the text to write, and what it would do.
103#[derive(Debug, Clone)]
104pub struct Plan {
105    /// The version the file says it was written with.
106    pub from: u32,
107    /// The version this build writes.
108    pub to: u32,
109    /// True when there was no baseline, so only additions and renames could be decided.
110    pub baseline_missing: bool,
111    pub changes: Vec<Change>,
112    /// The whole file as it would be written. Equal to the input when nothing changes.
113    pub text: String,
114}
115
116impl Plan {
117    /// Whether writing this plan would change the file: nothing to add, nothing to move, and the
118    /// stamp is already this build's. A `Kept` row is not a change — it is the record of a value
119    /// that was looked at and left alone.
120    pub fn is_current(&self) -> bool {
121        self.from == self.to && self.notable().is_empty()
122    }
123
124    /// The changes that touch a value the operator might care about, in the order a reader wants.
125    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
140/// Plan a migration. Pure: no files, no clock, no environment — the caller owns all three.
141///
142/// `base` is the template the file was generated from, when one was kept. `theirs` is
143/// [`super::starter_config()`] for the build doing the migrating.
144pub fn plan(ours: &str, base: Option<&str>, theirs: &str) -> Result<Plan, String> {
145    plan_with(ours, base, theirs, RENAMED)
146}
147
148/// [`plan`], with the rename table supplied — so a test can prove the mechanism with a pair that
149/// does not exist in this build.
150pub 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    // 5. renames first, so a moved key is not also "added" under its new name.
179    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            // 1. a key this build ships with a value, absent from the file.
203            (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            // 2. a key this build ships unset: present as a comment, so the file stays complete.
211            (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            // 3 and 4. the file sets it: move only what still holds the shipped default.
220            (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            // A key the file sets and this build ships unset: the operator's line stays.
236            (Some(_), None) => changes.push(Change::Kept { key: path }),
237        }
238    }
239
240    // 6. nothing is deleted. Anything left over is named by `config check`, not by this.
241    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
251/// Whether this text already carries `# key =` under `[section]`.
252fn 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
282/// Where the template a file was generated from is kept: `<config dir>/state/config.baseline.toml`.
283///
284/// It is machine-written, it is not the config, and it is only ever read to answer "did the
285/// operator change this or was it us?". Losing it degrades a migration to additions — which is why
286/// it lives in `state/`, the directory the docs already say is disposable.
287pub 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
292/// Record the template this build ships as the baseline for `config_path`.
293pub 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    /// The shipped file, and a version of it with one line replaced — the shape every test here
312    /// uses, because a migration is always "this build's file" against "another build's file".
313    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        // The file still says what we shipped, so nobody chose it: take the new default.
353        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        // And the operator's own number stays, whatever the build now ships.
371        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        // An older file that never had the commented line for a key with no default.
416        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        // A comment, not a line: the key is still not in use.
427        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        // A rename that does not exist in this build, so the mechanism is proven before it is
436        // needed: both names are real settings of the same type.
437        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        // And spaced like the file `config init` writes, so a migrated config and a fresh one are
527        // the same document.
528        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}