eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! `eclipse config migrate` — bringing a config file forward without touching what its owner chose.
//!
//! [`super::CONFIG_VERSION`] is stamped into the file, so this can tell how old it is. What it
//! cannot tell from the stamp alone is *which lines a person edited*, and that is the whole problem:
//! 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
//! key live. Adding a key is safe. Changing a default is not — unless the file still holds the old
//! default, which is the same shape git's merge uses: *ours* wins where it differs from *base*,
//! *theirs* wins where it does not.
//!
//! So there are three inputs:
//!
//! - **ours** — the file on disk, the one with the operator's edits in it.
//! - **base** — the template this file was generated from, kept beside the state directory
//!   ([`baseline_path`]). Without it there is no way to tell "the operator chose 120" from "0.9.0
//!   shipped 120", so a missing baseline degrades to additions only and says so.
//! - **theirs** — [`super::starter_config()`], what this build ships.
//!
//! Six rules, in the order they matter:
//!
//! 1. A key *theirs* sets and *ours* does not is **added**, at the shipped value.
//! 2. A key with no shipped value at all (a temperature, a cap) is added **as a comment**, which is
//!    how the file says "not in use" for a key whose off state has no spelling. That is what keeps
//!    the file complete without imposing anything.
//! 3. A key *ours* sets to exactly what *base* says, while *theirs* says something else, **moves** —
//!    the default changed and nobody chose the old one.
//! 4. A key *ours* set to anything else **stays**, whatever *theirs* says. This is the rule the
//!    whole thing exists for.
//! 5. A key in [`RENAMED`] is written under its new name and the old line is commented out, so the
//!    value survives a rename. The table is empty until there is a rename to record; the mechanism
//!    is here so the first one is a one-line change rather than a redesign.
//! 6. Nothing is ever deleted. A key this build does not know is left exactly where it is —
//!    `eclipse config check` names it, and a migration that quietly drops a line someone typed is a
//!    migration nobody runs twice.
//!
//! Every write goes through [`super::set_in_text`], which edits one line of text and proves the
//! result loads, so comments, ordering and hand-written formatting survive. The file is copied to
//! `<name>.bak` before the first change, and the baseline is rewritten afterwards — the next
//! migration needs to know what *this* one shipped.

use super::{settings, Config};
use std::path::{Path, PathBuf};

/// Keys that moved. `(old path, new path)`.
///
/// Empty on purpose: 0.10.0 is the first version that stamps a file, so there is nothing older to
/// rename from. When there is, this is the only place to say so — [`a_renamed_key_keeps_its_value`]
/// drives the table with a fake pair so the mechanism is proven before it is needed.
pub const RENAMED: &[(&str, &str)] = &[];

/// What a migration did to one key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
    /// The file did not have the key; this build ships it with a value.
    Added { key: String, value: String },
    /// The file did not have the key, and this build ships it unset: the line is a comment.
    Commented { key: String },
    /// The key moved to the value this build ships, because the file still held the old default.
    DefaultMoved {
        key: String,
        from: String,
        to: String,
    },
    /// The key was renamed, and its value came with it.
    Renamed {
        from: String,
        to: String,
        value: String,
    },
    /// The key was left alone, and here is why: the operator set it.
    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}"),
        }
    }
}

/// The result of planning a migration: the text to write, and what it would do.
#[derive(Debug, Clone)]
pub struct Plan {
    /// The version the file says it was written with.
    pub from: u32,
    /// The version this build writes.
    pub to: u32,
    /// True when there was no baseline, so only additions and renames could be decided.
    pub baseline_missing: bool,
    pub changes: Vec<Change>,
    /// The whole file as it would be written. Equal to the input when nothing changes.
    pub text: String,
}

impl Plan {
    /// Whether writing this plan would change the file: nothing to add, nothing to move, and the
    /// stamp is already this build's. A `Kept` row is not a change — it is the record of a value
    /// that was looked at and left alone.
    pub fn is_current(&self) -> bool {
        self.from == self.to && self.notable().is_empty()
    }

    /// The changes that touch a value the operator might care about, in the order a reader wants.
    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()
    }
}

/// Plan a migration. Pure: no files, no clock, no environment — the caller owns all three.
///
/// `base` is the template the file was generated from, when one was kept. `theirs` is
/// [`super::starter_config()`] for the build doing the migrating.
pub fn plan(ours: &str, base: Option<&str>, theirs: &str) -> Result<Plan, String> {
    plan_with(ours, base, theirs, RENAMED)
}

/// [`plan`], with the rename table supplied — so a test can prove the mechanism with a pair that
/// does not exist in this build.
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();

    // 5. renames first, so a moved key is not also "added" under its new name.
    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) {
            // 1. a key this build ships with a value, absent from the file.
            (None, Some(value)) => {
                text = settings::set_in_text(&text, &path, &value)?;
                changes.push(Change::Added {
                    key: path,
                    value: render(&value),
                });
            }
            // 2. a key this build ships unset: present as a comment, so the file stays complete.
            (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 });
                }
            }
            // 3 and 4. the file sets it: move only what still holds the shipped default.
            (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 });
                }
            }
            // A key the file sets and this build ships unset: the operator's line stays.
            (Some(_), None) => changes.push(Change::Kept { key: path }),
        }
    }

    // 6. nothing is deleted. Anything left over is named by `config check`, not by this.
    let text = super::stamp_version(&text, super::CONFIG_VERSION)?;
    Ok(Plan {
        from,
        to: super::CONFIG_VERSION,
        baseline_missing: base.is_none(),
        changes,
        text,
    })
}

/// Whether this text already carries `# key =` under `[section]`.
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(name) = super::section_header(trimmed) {
            in_section = name == section;
            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(),
    }
}

/// Where the template a file was generated from is kept: `<config dir>/state/config.baseline.toml`.
///
/// It is machine-written, it is not the config, and it is only ever read to answer "did the
/// operator change this or was it us?". Losing it degrades a migration to additions — which is why
/// it lives in `state/`, the directory the docs already say is disposable.
pub fn baseline_path(config_path: &Path) -> PathBuf {
    let dir = config_path.parent().unwrap_or(Path::new("."));
    dir.join("state").join("config.baseline.toml")
}

/// Record the template this build ships as the baseline for `config_path`.
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::*;

    /// The shipped file, and a version of it with one line replaced — the shape every test here
    /// uses, because a migration is always "this build's file" against "another build's file".
    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");
        // The file still says what we shipped, so nobody chose it: take the new default.
        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
        );
        // And the operator's own number stays, whatever the build now ships.
        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();
        // An older file that never had the commented line for a key with no default.
        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);
        // A comment, not a line: the key is still not in use.
        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");
        // A rename that does not exist in this build, so the mechanism is proven before it is
        // needed: both names are real settings of the same type.
        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");
        // And spaced like the file `config init` writes, so a migrated config and a fresh one are
        // the same document.
        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}");
    }
}