eclipse-core 0.13.3

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
//! Moving an install that predates the one-directory layout into it.
//!
//! Before `~/.eclipse`, an install put its files in three places — the binaries wherever
//! `--prefix` said, config in `$XDG_CONFIG_HOME/eclipse`, machine-written files in
//! `$XDG_STATE_HOME/eclipse` — and remembered nothing about the workspace. That is the mess this
//! moves out of, once.
//!
//! Two rules, because this touches somebody's files:
//!
//! - **Plan first, move second.** [`plan`] returns the exact list of moves and touches nothing.
//!   `eclipse migrate --dry-run` prints it; the automatic pass at startup applies it. One
//!   implementation, so what you previewed is what happens.
//! - **Never overwrite, never merge blindly.** If the destination exists, that entry is skipped
//!   and named in the report. A migration that quietly merged two `config.toml` files would be
//!   worse than one that refused.
//!
//! The memory files are the one place a file changes directory *semantics*: `AGENT.md`, `USER.md`
//! and `MEMORY.md` used to sit beside `config.toml` and now live in `memory/`, so they move as a
//! group with their names intact.

use crate::config::{home_root, EnvFn};
use std::path::{Path, PathBuf};

/// Where the old layout put things.
pub struct Legacy {
    /// `$XDG_CONFIG_HOME/eclipse` or `~/.config/eclipse`.
    pub config: PathBuf,
    /// `$XDG_STATE_HOME/eclipse` or `~/.local/state/eclipse`.
    pub state: PathBuf,
}

/// The old paths for this environment, when they can be worked out at all.
pub fn legacy(env: EnvFn) -> Option<Legacy> {
    let xdg = |var: &str, fallback: &[&str]| -> Option<PathBuf> {
        if let Some(x) = env(var) {
            if !x.is_empty() {
                return Some(PathBuf::from(x).join("eclipse"));
            }
        }
        let home = crate::config::home_dir(env)?;
        let mut p = home;
        for part in fallback {
            p = p.join(part);
        }
        Some(p.join("eclipse"))
    };
    Some(Legacy {
        config: xdg("XDG_CONFIG_HOME", &[".config"])?,
        state: xdg("XDG_STATE_HOME", &[".local", "state"])?,
    })
}

/// One move: what, from where, to where, and whether it happens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Step {
    /// A short name for the report: `config.toml`, `sessions`, `MEMORY.md`.
    pub what: String,
    pub from: PathBuf,
    pub to: PathBuf,
    /// Why it will not happen, when it will not. `None` means it will.
    pub skip: Option<String>,
}

/// Everything the old layout holds that the new one should have.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Plan {
    pub steps: Vec<Step>,
    /// True when the old layout is not there at all, so there is nothing to do and nothing to
    /// say. A fresh install must not be greeted by a migration notice.
    pub absent: bool,
}

impl Plan {
    /// The steps that will actually run.
    pub fn moving(&self) -> impl Iterator<Item = &Step> {
        self.steps.iter().filter(|s| s.skip.is_none())
    }

    pub fn is_empty(&self) -> bool {
        self.moving().next().is_none()
    }

    /// The lines to show a person before it happens, or after.
    pub fn report(&self, root: &Path) -> Vec<String> {
        let mut out = Vec::new();
        for step in &self.steps {
            match &step.skip {
                None => out.push(format!("  {} → {}", step.from.display(), step.to.display())),
                Some(why) => out.push(format!("  kept {} ({why})", step.from.display())),
            }
        }
        if !out.is_empty() {
            out.push(format!("  root: {}", root.display()));
        }
        out
    }
}

/// The entries of the old config and state directories that have an obvious home in the root.
///
/// Named one by one rather than "move everything", because a file the new layout does not know
/// about is a file whose meaning nobody has decided — better visible where it is than silently
/// relocated into a directory whose layout claims to be complete.
const CONFIG_ENTRIES: &[&str] = &["config.toml", ".env", "plugins", "skills", "scripts"];
const STATE_ENTRIES: &[&str] = &["sessions", "install.json", "update.json", "history"];
/// Context files that move into `memory/`.
const MEMORY_ENTRIES: &[&str] = &["AGENT.md", "USER.md", "MEMORY.md"];

fn exists(p: &Path) -> bool {
    std::fs::symlink_metadata(p).is_ok()
}

/// Work out what to move without touching anything.
pub fn plan(env: EnvFn) -> Plan {
    let (Some(root), Some(old)) = (home_root(env), legacy(env)) else {
        return Plan {
            steps: Vec::new(),
            absent: true,
        };
    };
    let mut steps = Vec::new();
    let mut add = |what: &str, from: PathBuf, to: PathBuf| {
        if !exists(&from) {
            return;
        }
        let skip = if exists(&to) {
            // Already there. The likeliest reason is that this ran before; the second likeliest
            // is a hand-made install, and neither wants the old copy merged on top.
            Some("already in the new location".to_string())
        } else {
            None
        };
        steps.push(Step {
            what: what.to_string(),
            from,
            to,
            skip,
        });
    };

    for entry in CONFIG_ENTRIES {
        add(entry, old.config.join(entry), root.join(entry));
    }
    for entry in MEMORY_ENTRIES {
        add(
            entry,
            old.config.join(entry),
            root.join("memory").join(entry),
        );
    }
    for entry in STATE_ENTRIES {
        add(entry, old.state.join(entry), root.join("state").join(entry));
    }
    // A profile's own state used to hang under the shared state directory; it belongs beside the
    // profile now. One rename per profile, so each is an atomic move of a subtree.
    if let Ok(entries) = std::fs::read_dir(old.state.join("profiles")) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if crate::config::validate_profile_name(&name).is_err() {
                continue;
            }
            add(
                &format!("profiles/{name}/state"),
                entry.path(),
                root.join("profiles").join(&name).join("state"),
            );
        }
    }

    Plan {
        steps,
        absent: !exists(&old.config) && !exists(&old.state),
    }
}

/// Do it. Returns one line per step: what moved, what was kept and why, what failed.
///
/// Every move is a `rename`, so it is atomic where source and destination share a filesystem —
/// and the root and the old locations are both under `$HOME` in every normal install. A failure
/// is reported against its own step and does not stop the rest: half a migration is better than
/// none, and the report says exactly which half.
pub fn apply(plan: &Plan) -> Vec<String> {
    let mut out = Vec::new();
    for step in &plan.steps {
        if let Some(why) = &step.skip {
            out.push(format!("  kept {} ({why})", step.from.display()));
            continue;
        }
        let prepared = match step.to.parent() {
            Some(parent) => std::fs::create_dir_all(parent),
            None => Ok(()),
        };
        match prepared.and_then(|()| std::fs::rename(&step.from, &step.to)) {
            Ok(()) => out.push(format!(
                "  moved {} → {}",
                step.from.display(),
                step.to.display()
            )),
            Err(e) => out.push(format!("  could not move {}: {e}", step.from.display())),
        }
    }
    out
}

/// Plan, apply and tidy in one call: what the automatic pass and `eclipse migrate` both run, so
/// there is one implementation of "what migrating means" and the two cannot drift.
///
/// Returns the lines to print. Empty only when there is nothing at all to say — a fresh install,
/// or one already moved. A plan whose every step is skipped still reports: "kept, because the
/// destination exists" is the line a person needs, and it is the one an early return used to eat.
pub fn run(env: EnvFn) -> Vec<String> {
    let plan = plan(env);
    if plan.steps.is_empty() {
        return Vec::new();
    }
    let mut out = apply(&plan);
    if let Some(old) = legacy(env) {
        out.extend(tidy(&old));
    }
    out
}

/// The old directories, once emptied, are removed if nothing is left in them — an empty
/// `~/.eclipse` would otherwise be exactly the confusion this migration exists to end.
/// A directory still holding something unknown is left alone, and said so.
pub fn tidy(legacy: &Legacy) -> Vec<String> {
    let mut out = Vec::new();
    // The one nested thing that moves out is a profile's state, which leaves `profiles/` behind
    // as an empty directory. Empty is empty: removing it is what makes the old location go away.
    let _ = std::fs::remove_dir(legacy.state.join("profiles"));
    for dir in [&legacy.config, &legacy.state] {
        let empty = std::fs::read_dir(dir)
            .map(|mut d| d.next().is_none())
            .unwrap_or(false);
        if empty && std::fs::remove_dir(dir).is_ok() {
            out.push(format!("  removed the empty {}", dir.display()));
        } else if exists(dir) {
            out.push(format!(
                "  left {} — it still holds something this did not move",
                dir.display()
            ));
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{config_dir, profile_dir, state_dir, state_dir_for};
    use std::collections::HashMap;

    fn env_of(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    fn write(p: &Path, text: &str) {
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, text).unwrap();
    }

    #[test]
    fn the_root_is_eclipse_home_else_dot_eclipse_under_home() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        assert_eq!(home_root(env).unwrap(), home.path().join(".eclipse"));

        // `~` in ECLIPSE_HOME is expanded against HOME, like every other path in the config.
        let m = env_of(&[("HOME", &h), ("ECLIPSE_HOME", "~/elsewhere/.eclipse")]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        assert_eq!(
            home_root(env).unwrap(),
            home.path().join("elsewhere/.eclipse")
        );
    }

    #[test]
    fn everything_is_under_the_one_root() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        let root = home_root(env).unwrap();
        for dir in [config_dir(env).unwrap(), state_dir(env).unwrap()] {
            assert!(
                dir.starts_with(&root),
                "{} outside {}",
                dir.display(),
                root.display()
            );
        }
        assert_eq!(state_dir(env).unwrap(), root.join("state"));
        // A profile is a subtree of the root, with its own state beside its own config.
        let p = profile_dir(env, "work").unwrap();
        assert_eq!(p, root.join("profiles/work"));
        assert_eq!(state_dir_for(env, Some("work")).unwrap(), p.join("state"));
        assert_eq!(state_dir_for(env, None).unwrap(), root.join("state"));
    }

    #[test]
    fn a_fresh_machine_plans_nothing_and_says_nothing() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        let planned = plan(env);
        assert!(planned.absent, "no old layout, so no notice");
        assert!(planned.is_empty());
        assert!(planned.report(&home.path().join(".eclipse")).is_empty());
    }

    #[test]
    fn the_old_layout_is_planned_into_the_root_with_memory_in_its_own_folder() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        let cfg = home.path().join(".config/eclipse");
        let state = home.path().join(".local/state/eclipse");
        write(&cfg.join("config.toml"), "a = 1\n");
        write(&cfg.join(".env"), "K=V\n");
        write(&cfg.join("MEMORY.md"), "- a fact\n");
        write(&cfg.join("USER.md"), "I am Max\n");
        write(&cfg.join("skills/x/SKILL.md"), "# x\n");
        write(&state.join("sessions/sessions.db"), "db");
        write(&state.join("install.json"), "{}");

        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        let planned = plan(env);
        assert!(!planned.absent);
        let root = home.path().join(".eclipse");
        let moving: Vec<(String, PathBuf)> = planned
            .moving()
            .map(|s| {
                (
                    s.what.clone(),
                    s.to.strip_prefix(&root).unwrap().to_path_buf(),
                )
            })
            .collect();
        assert!(moving.contains(&("config.toml".into(), PathBuf::from("config.toml"))));
        assert!(moving.contains(&(".env".into(), PathBuf::from(".env"))));
        assert!(moving.contains(&("MEMORY.md".into(), PathBuf::from("memory/MEMORY.md"))));
        assert!(moving.contains(&("USER.md".into(), PathBuf::from("memory/USER.md"))));
        assert!(moving.contains(&("skills".into(), PathBuf::from("skills"))));
        assert!(moving.contains(&("sessions".into(), PathBuf::from("state/sessions"))));
        assert!(moving.contains(&("install.json".into(), PathBuf::from("state/install.json"))));
        assert!(
            planned.steps.iter().all(|s| s.skip.is_none()),
            "nothing to skip yet"
        );
    }

    #[test]
    fn what_is_already_in_the_new_place_is_kept_rather_than_merged() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        write(
            &home.path().join(".config/eclipse/config.toml"),
            "old = 1\n",
        );
        write(&home.path().join(".eclipse/config.toml"), "new = 1\n");
        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        let planned = plan(env);
        let step = planned
            .steps
            .iter()
            .find(|s| s.what == "config.toml")
            .unwrap();
        assert_eq!(
            step.skip.as_deref(),
            Some("already in the new location"),
            "a migration that merged two config.toml files would be worse than one that refused"
        );
        let report = planned.report(&home.path().join(".eclipse")).join("\n");
        assert!(report.contains("kept"), "{report}");
    }

    #[test]
    fn applying_moves_the_entries_and_leaves_the_old_directories_empty() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        let cfg = home.path().join(".config/eclipse");
        let state = home.path().join(".local/state/eclipse");
        write(&cfg.join("config.toml"), "a = 1\n");
        write(&cfg.join("MEMORY.md"), "- a fact\n");
        write(&state.join("sessions/sessions.db"), "db");
        write(&state.join("profiles/work/sessions.db"), "pdb");

        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        let planned = plan(env);
        let log = apply(&planned).join("\n");
        let root = home.path().join(".eclipse");
        assert!(root.join("config.toml").exists(), "{log}");
        assert!(root.join("memory/MEMORY.md").exists(), "{log}");
        assert!(root.join("state/sessions/sessions.db").exists(), "{log}");
        assert!(
            root.join("profiles/work/state/sessions.db").exists(),
            "a profile's state belongs beside the profile: {log}"
        );
        assert!(!cfg.join("config.toml").exists(), "{log}");
        assert!(!state.join("sessions").exists(), "{log}");

        let tidy_log = tidy(&legacy(env).unwrap()).join("\n");
        assert!(
            !cfg.exists(),
            "an empty old directory is removed: {tidy_log}"
        );
        assert!(!state.exists(), "{tidy_log}");

        // Idempotent: a second pass finds nothing old and does nothing.
        let again = plan(env);
        assert!(again.is_empty(), "{:?}", again.steps);
    }

    #[test]
    fn a_file_the_new_layout_does_not_know_about_stays_where_it_is_and_is_named() {
        let home = tempfile::tempdir().unwrap();
        let h = home.path().to_str().unwrap().to_string();
        let cfg = home.path().join(".config/eclipse");
        write(&cfg.join("config.toml"), "a = 1\n");
        write(&cfg.join("notes-of-mine.txt"), "keep me\n");
        let m = env_of(&[("HOME", &h)]);
        let f = |k: &str| m.get(k).cloned();
        let env: EnvFn = &f;
        let planned = plan(env);
        apply(&planned);
        let log = tidy(&legacy(env).unwrap()).join("\n");
        assert!(
            cfg.join("notes-of-mine.txt").exists(),
            "nothing unknown is moved"
        );
        assert!(log.contains("still holds something"), "{log}");
    }
}