Skip to main content

eclipse_core/
migrate.rs

1//! Moving an install that predates the one-directory layout into it.
2//!
3//! Before `~/.eclipse`, an install put its files in three places — the binaries wherever
4//! `--prefix` said, config in `$XDG_CONFIG_HOME/eclipse`, machine-written files in
5//! `$XDG_STATE_HOME/eclipse` — and remembered nothing about the workspace. That is the mess this
6//! moves out of, once.
7//!
8//! Two rules, because this touches somebody's files:
9//!
10//! - **Plan first, move second.** [`plan`] returns the exact list of moves and touches nothing.
11//!   `eclipse migrate --dry-run` prints it; the automatic pass at startup applies it. One
12//!   implementation, so what you previewed is what happens.
13//! - **Never overwrite, never merge blindly.** If the destination exists, that entry is skipped
14//!   and named in the report. A migration that quietly merged two `config.toml` files would be
15//!   worse than one that refused.
16//!
17//! The memory files are the one place a file changes directory *semantics*: `AGENT.md`, `USER.md`
18//! and `MEMORY.md` used to sit beside `config.toml` and now live in `memory/`, so they move as a
19//! group with their names intact.
20
21use crate::config::{home_root, EnvFn};
22use std::path::{Path, PathBuf};
23
24/// Where the old layout put things.
25pub struct Legacy {
26    /// `$XDG_CONFIG_HOME/eclipse` or `~/.config/eclipse`.
27    pub config: PathBuf,
28    /// `$XDG_STATE_HOME/eclipse` or `~/.local/state/eclipse`.
29    pub state: PathBuf,
30}
31
32/// The old paths for this environment, when they can be worked out at all.
33pub fn legacy(env: EnvFn) -> Option<Legacy> {
34    let xdg = |var: &str, fallback: &[&str]| -> Option<PathBuf> {
35        if let Some(x) = env(var) {
36            if !x.is_empty() {
37                return Some(PathBuf::from(x).join("eclipse"));
38            }
39        }
40        let home = crate::config::home_dir(env)?;
41        let mut p = home;
42        for part in fallback {
43            p = p.join(part);
44        }
45        Some(p.join("eclipse"))
46    };
47    Some(Legacy {
48        config: xdg("XDG_CONFIG_HOME", &[".config"])?,
49        state: xdg("XDG_STATE_HOME", &[".local", "state"])?,
50    })
51}
52
53/// One move: what, from where, to where, and whether it happens.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Step {
56    /// A short name for the report: `config.toml`, `sessions`, `MEMORY.md`.
57    pub what: String,
58    pub from: PathBuf,
59    pub to: PathBuf,
60    /// Why it will not happen, when it will not. `None` means it will.
61    pub skip: Option<String>,
62}
63
64/// Everything the old layout holds that the new one should have.
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct Plan {
67    pub steps: Vec<Step>,
68    /// True when the old layout is not there at all, so there is nothing to do and nothing to
69    /// say. A fresh install must not be greeted by a migration notice.
70    pub absent: bool,
71}
72
73impl Plan {
74    /// The steps that will actually run.
75    pub fn moving(&self) -> impl Iterator<Item = &Step> {
76        self.steps.iter().filter(|s| s.skip.is_none())
77    }
78
79    pub fn is_empty(&self) -> bool {
80        self.moving().next().is_none()
81    }
82
83    /// The lines to show a person before it happens, or after.
84    pub fn report(&self, root: &Path) -> Vec<String> {
85        let mut out = Vec::new();
86        for step in &self.steps {
87            match &step.skip {
88                None => out.push(format!("  {} → {}", step.from.display(), step.to.display())),
89                Some(why) => out.push(format!("  kept {} ({why})", step.from.display())),
90            }
91        }
92        if !out.is_empty() {
93            out.push(format!("  root: {}", root.display()));
94        }
95        out
96    }
97}
98
99/// The entries of the old config and state directories that have an obvious home in the root.
100///
101/// Named one by one rather than "move everything", because a file the new layout does not know
102/// about is a file whose meaning nobody has decided — better visible where it is than silently
103/// relocated into a directory whose layout claims to be complete.
104const CONFIG_ENTRIES: &[&str] = &["config.toml", ".env", "plugins", "skills", "scripts"];
105const STATE_ENTRIES: &[&str] = &["sessions", "install.json", "update.json", "history"];
106/// Context files that move into `memory/`.
107const MEMORY_ENTRIES: &[&str] = &["AGENT.md", "USER.md", "MEMORY.md"];
108
109fn exists(p: &Path) -> bool {
110    std::fs::symlink_metadata(p).is_ok()
111}
112
113/// Work out what to move without touching anything.
114pub fn plan(env: EnvFn) -> Plan {
115    let (Some(root), Some(old)) = (home_root(env), legacy(env)) else {
116        return Plan {
117            steps: Vec::new(),
118            absent: true,
119        };
120    };
121    let mut steps = Vec::new();
122    let mut add = |what: &str, from: PathBuf, to: PathBuf| {
123        if !exists(&from) {
124            return;
125        }
126        let skip = if exists(&to) {
127            // Already there. The likeliest reason is that this ran before; the second likeliest
128            // is a hand-made install, and neither wants the old copy merged on top.
129            Some("already in the new location".to_string())
130        } else {
131            None
132        };
133        steps.push(Step {
134            what: what.to_string(),
135            from,
136            to,
137            skip,
138        });
139    };
140
141    for entry in CONFIG_ENTRIES {
142        add(entry, old.config.join(entry), root.join(entry));
143    }
144    for entry in MEMORY_ENTRIES {
145        add(
146            entry,
147            old.config.join(entry),
148            root.join("memory").join(entry),
149        );
150    }
151    for entry in STATE_ENTRIES {
152        add(entry, old.state.join(entry), root.join("state").join(entry));
153    }
154    // A profile's own state used to hang under the shared state directory; it belongs beside the
155    // profile now. One rename per profile, so each is an atomic move of a subtree.
156    if let Ok(entries) = std::fs::read_dir(old.state.join("profiles")) {
157        for entry in entries.flatten() {
158            let name = entry.file_name().to_string_lossy().into_owned();
159            if crate::config::validate_profile_name(&name).is_err() {
160                continue;
161            }
162            add(
163                &format!("profiles/{name}/state"),
164                entry.path(),
165                root.join("profiles").join(&name).join("state"),
166            );
167        }
168    }
169
170    Plan {
171        steps,
172        absent: !exists(&old.config) && !exists(&old.state),
173    }
174}
175
176/// Do it. Returns one line per step: what moved, what was kept and why, what failed.
177///
178/// Every move is a `rename`, so it is atomic where source and destination share a filesystem —
179/// and the root and the old locations are both under `$HOME` in every normal install. A failure
180/// is reported against its own step and does not stop the rest: half a migration is better than
181/// none, and the report says exactly which half.
182pub fn apply(plan: &Plan) -> Vec<String> {
183    let mut out = Vec::new();
184    for step in &plan.steps {
185        if let Some(why) = &step.skip {
186            out.push(format!("  kept {} ({why})", step.from.display()));
187            continue;
188        }
189        let prepared = match step.to.parent() {
190            Some(parent) => std::fs::create_dir_all(parent),
191            None => Ok(()),
192        };
193        match prepared.and_then(|()| std::fs::rename(&step.from, &step.to)) {
194            Ok(()) => out.push(format!(
195                "  moved {} → {}",
196                step.from.display(),
197                step.to.display()
198            )),
199            Err(e) => out.push(format!("  could not move {}: {e}", step.from.display())),
200        }
201    }
202    out
203}
204
205/// Plan, apply and tidy in one call: what the automatic pass and `eclipse migrate` both run, so
206/// there is one implementation of "what migrating means" and the two cannot drift.
207///
208/// Returns the lines to print. Empty only when there is nothing at all to say — a fresh install,
209/// or one already moved. A plan whose every step is skipped still reports: "kept, because the
210/// destination exists" is the line a person needs, and it is the one an early return used to eat.
211pub fn run(env: EnvFn) -> Vec<String> {
212    let plan = plan(env);
213    if plan.steps.is_empty() {
214        return Vec::new();
215    }
216    let mut out = apply(&plan);
217    if let Some(old) = legacy(env) {
218        out.extend(tidy(&old));
219    }
220    out
221}
222
223/// The old directories, once emptied, are removed if nothing is left in them — an empty
224/// `~/.eclipse` would otherwise be exactly the confusion this migration exists to end.
225/// A directory still holding something unknown is left alone, and said so.
226pub fn tidy(legacy: &Legacy) -> Vec<String> {
227    let mut out = Vec::new();
228    // The one nested thing that moves out is a profile's state, which leaves `profiles/` behind
229    // as an empty directory. Empty is empty: removing it is what makes the old location go away.
230    let _ = std::fs::remove_dir(legacy.state.join("profiles"));
231    for dir in [&legacy.config, &legacy.state] {
232        let empty = std::fs::read_dir(dir)
233            .map(|mut d| d.next().is_none())
234            .unwrap_or(false);
235        if empty && std::fs::remove_dir(dir).is_ok() {
236            out.push(format!("  removed the empty {}", dir.display()));
237        } else if exists(dir) {
238            out.push(format!(
239                "  left {} — it still holds something this did not move",
240                dir.display()
241            ));
242        }
243    }
244    out
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use crate::config::{config_dir, profile_dir, state_dir, state_dir_for};
251    use std::collections::HashMap;
252
253    fn env_of(pairs: &[(&str, &str)]) -> HashMap<String, String> {
254        pairs
255            .iter()
256            .map(|(k, v)| (k.to_string(), v.to_string()))
257            .collect()
258    }
259
260    fn write(p: &Path, text: &str) {
261        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
262        std::fs::write(p, text).unwrap();
263    }
264
265    #[test]
266    fn the_root_is_eclipse_home_else_dot_eclipse_under_home() {
267        let home = tempfile::tempdir().unwrap();
268        let h = home.path().to_str().unwrap().to_string();
269        let m = env_of(&[("HOME", &h)]);
270        let f = |k: &str| m.get(k).cloned();
271        let env: EnvFn = &f;
272        assert_eq!(home_root(env).unwrap(), home.path().join(".eclipse"));
273
274        // `~` in ECLIPSE_HOME is expanded against HOME, like every other path in the config.
275        let m = env_of(&[("HOME", &h), ("ECLIPSE_HOME", "~/elsewhere/.eclipse")]);
276        let f = |k: &str| m.get(k).cloned();
277        let env: EnvFn = &f;
278        assert_eq!(
279            home_root(env).unwrap(),
280            home.path().join("elsewhere/.eclipse")
281        );
282    }
283
284    #[test]
285    fn everything_is_under_the_one_root() {
286        let home = tempfile::tempdir().unwrap();
287        let h = home.path().to_str().unwrap().to_string();
288        let m = env_of(&[("HOME", &h)]);
289        let f = |k: &str| m.get(k).cloned();
290        let env: EnvFn = &f;
291        let root = home_root(env).unwrap();
292        for dir in [config_dir(env).unwrap(), state_dir(env).unwrap()] {
293            assert!(
294                dir.starts_with(&root),
295                "{} outside {}",
296                dir.display(),
297                root.display()
298            );
299        }
300        assert_eq!(state_dir(env).unwrap(), root.join("state"));
301        // A profile is a subtree of the root, with its own state beside its own config.
302        let p = profile_dir(env, "work").unwrap();
303        assert_eq!(p, root.join("profiles/work"));
304        assert_eq!(state_dir_for(env, Some("work")).unwrap(), p.join("state"));
305        assert_eq!(state_dir_for(env, None).unwrap(), root.join("state"));
306    }
307
308    #[test]
309    fn a_fresh_machine_plans_nothing_and_says_nothing() {
310        let home = tempfile::tempdir().unwrap();
311        let h = home.path().to_str().unwrap().to_string();
312        let m = env_of(&[("HOME", &h)]);
313        let f = |k: &str| m.get(k).cloned();
314        let env: EnvFn = &f;
315        let planned = plan(env);
316        assert!(planned.absent, "no old layout, so no notice");
317        assert!(planned.is_empty());
318        assert!(planned.report(&home.path().join(".eclipse")).is_empty());
319    }
320
321    #[test]
322    fn the_old_layout_is_planned_into_the_root_with_memory_in_its_own_folder() {
323        let home = tempfile::tempdir().unwrap();
324        let h = home.path().to_str().unwrap().to_string();
325        let cfg = home.path().join(".config/eclipse");
326        let state = home.path().join(".local/state/eclipse");
327        write(&cfg.join("config.toml"), "a = 1\n");
328        write(&cfg.join(".env"), "K=V\n");
329        write(&cfg.join("MEMORY.md"), "- a fact\n");
330        write(&cfg.join("USER.md"), "I am Max\n");
331        write(&cfg.join("skills/x/SKILL.md"), "# x\n");
332        write(&state.join("sessions/sessions.db"), "db");
333        write(&state.join("install.json"), "{}");
334
335        let m = env_of(&[("HOME", &h)]);
336        let f = |k: &str| m.get(k).cloned();
337        let env: EnvFn = &f;
338        let planned = plan(env);
339        assert!(!planned.absent);
340        let root = home.path().join(".eclipse");
341        let moving: Vec<(String, PathBuf)> = planned
342            .moving()
343            .map(|s| {
344                (
345                    s.what.clone(),
346                    s.to.strip_prefix(&root).unwrap().to_path_buf(),
347                )
348            })
349            .collect();
350        assert!(moving.contains(&("config.toml".into(), PathBuf::from("config.toml"))));
351        assert!(moving.contains(&(".env".into(), PathBuf::from(".env"))));
352        assert!(moving.contains(&("MEMORY.md".into(), PathBuf::from("memory/MEMORY.md"))));
353        assert!(moving.contains(&("USER.md".into(), PathBuf::from("memory/USER.md"))));
354        assert!(moving.contains(&("skills".into(), PathBuf::from("skills"))));
355        assert!(moving.contains(&("sessions".into(), PathBuf::from("state/sessions"))));
356        assert!(moving.contains(&("install.json".into(), PathBuf::from("state/install.json"))));
357        assert!(
358            planned.steps.iter().all(|s| s.skip.is_none()),
359            "nothing to skip yet"
360        );
361    }
362
363    #[test]
364    fn what_is_already_in_the_new_place_is_kept_rather_than_merged() {
365        let home = tempfile::tempdir().unwrap();
366        let h = home.path().to_str().unwrap().to_string();
367        write(
368            &home.path().join(".config/eclipse/config.toml"),
369            "old = 1\n",
370        );
371        write(&home.path().join(".eclipse/config.toml"), "new = 1\n");
372        let m = env_of(&[("HOME", &h)]);
373        let f = |k: &str| m.get(k).cloned();
374        let env: EnvFn = &f;
375        let planned = plan(env);
376        let step = planned
377            .steps
378            .iter()
379            .find(|s| s.what == "config.toml")
380            .unwrap();
381        assert_eq!(
382            step.skip.as_deref(),
383            Some("already in the new location"),
384            "a migration that merged two config.toml files would be worse than one that refused"
385        );
386        let report = planned.report(&home.path().join(".eclipse")).join("\n");
387        assert!(report.contains("kept"), "{report}");
388    }
389
390    #[test]
391    fn applying_moves_the_entries_and_leaves_the_old_directories_empty() {
392        let home = tempfile::tempdir().unwrap();
393        let h = home.path().to_str().unwrap().to_string();
394        let cfg = home.path().join(".config/eclipse");
395        let state = home.path().join(".local/state/eclipse");
396        write(&cfg.join("config.toml"), "a = 1\n");
397        write(&cfg.join("MEMORY.md"), "- a fact\n");
398        write(&state.join("sessions/sessions.db"), "db");
399        write(&state.join("profiles/work/sessions.db"), "pdb");
400
401        let m = env_of(&[("HOME", &h)]);
402        let f = |k: &str| m.get(k).cloned();
403        let env: EnvFn = &f;
404        let planned = plan(env);
405        let log = apply(&planned).join("\n");
406        let root = home.path().join(".eclipse");
407        assert!(root.join("config.toml").exists(), "{log}");
408        assert!(root.join("memory/MEMORY.md").exists(), "{log}");
409        assert!(root.join("state/sessions/sessions.db").exists(), "{log}");
410        assert!(
411            root.join("profiles/work/state/sessions.db").exists(),
412            "a profile's state belongs beside the profile: {log}"
413        );
414        assert!(!cfg.join("config.toml").exists(), "{log}");
415        assert!(!state.join("sessions").exists(), "{log}");
416
417        let tidy_log = tidy(&legacy(env).unwrap()).join("\n");
418        assert!(
419            !cfg.exists(),
420            "an empty old directory is removed: {tidy_log}"
421        );
422        assert!(!state.exists(), "{tidy_log}");
423
424        // Idempotent: a second pass finds nothing old and does nothing.
425        let again = plan(env);
426        assert!(again.is_empty(), "{:?}", again.steps);
427    }
428
429    #[test]
430    fn a_file_the_new_layout_does_not_know_about_stays_where_it_is_and_is_named() {
431        let home = tempfile::tempdir().unwrap();
432        let h = home.path().to_str().unwrap().to_string();
433        let cfg = home.path().join(".config/eclipse");
434        write(&cfg.join("config.toml"), "a = 1\n");
435        write(&cfg.join("notes-of-mine.txt"), "keep me\n");
436        let m = env_of(&[("HOME", &h)]);
437        let f = |k: &str| m.get(k).cloned();
438        let env: EnvFn = &f;
439        let planned = plan(env);
440        apply(&planned);
441        let log = tidy(&legacy(env).unwrap()).join("\n");
442        assert!(
443            cfg.join("notes-of-mine.txt").exists(),
444            "nothing unknown is moved"
445        );
446        assert!(log.contains("still holds something"), "{log}");
447    }
448}