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    // `#536`: the paths step 5 moved a value *to*. The settings loop below reads values out of
178    // `our_doc`, which still describes the file as it was — the new name is not in it — so without
179    // this it found nothing under the new key and wrote the shipped default over the value the
180    // rename had just carried across.
181    let mut renamed_to: Vec<&str> = Vec::new();
182
183    // 5. renames first, so a moved key is not also "added" under its new name.
184    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            // 1. a key this build ships with a value, absent from the file.
210            (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            // 2. a key this build ships unset: present as a comment, so the file stays complete.
218            (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            // 3 and 4. the file sets it: move only what still holds the shipped default.
227            (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            // A key the file sets and this build ships unset: the operator's line stays.
243            (Some(_), None) => changes.push(Change::Kept { key: path }),
244        }
245    }
246
247    // 6. nothing is deleted. Anything left over is named by `config check`, not by this.
248    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
258/// Whether this text already carries `# key =` under `[section]`.
259fn 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
289/// Where the template a file was generated from is kept: `<config dir>/state/config.baseline.toml`.
290///
291/// It is machine-written, it is not the config, and it is only ever read to answer "did the
292/// operator change this or was it us?". Losing it degrades a migration to additions — which is why
293/// it lives in `state/`, the directory the docs already say is disposable.
294pub 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
299/// Record the template this build ships as the baseline for `config_path`.
300pub 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    /// The shipped file, and a version of it with one line replaced — the shape every test here
319    /// uses, because a migration is always "this build's file" against "another build's file".
320    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        // The file still says what we shipped, so nobody chose it: take the new default.
360        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        // And the operator's own number stays, whatever the build now ships.
378        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        // An older file that never had the commented line for a key with no default.
423        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        // A comment, not a line: the key is still not in use.
434        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        // A rename that does not exist in this build, so the mechanism is proven before it is
443        // needed: both names are real settings of the same type.
444        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        // `#536`: the file predates the new name entirely — which is the ordinary case for a
477        // rename, since the key was added under its old name before it moved. Step 5 wrote the old
478        // value under the new name; the settings loop then looked that name up in the parsed *old*
479        // file, found nothing, and treated it as a key this build ships with a value it is missing,
480        // writing the shipped default straight over it.
481        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        // And spaced like the file `config init` writes, so a migrated config and a fresh one are
569        // the same document.
570        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}