1use crate::config::{home_root, EnvFn};
22use std::path::{Path, PathBuf};
23
24pub struct Legacy {
26 pub config: PathBuf,
28 pub state: PathBuf,
30}
31
32pub 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#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Step {
56 pub what: String,
58 pub from: PathBuf,
59 pub to: PathBuf,
60 pub skip: Option<String>,
62}
63
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct Plan {
67 pub steps: Vec<Step>,
68 pub absent: bool,
71}
72
73impl Plan {
74 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 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
99const CONFIG_ENTRIES: &[&str] = &["config.toml", ".env", "plugins", "skills", "scripts"];
105const STATE_ENTRIES: &[&str] = &["sessions", "install.json", "update.json", "history"];
106const 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
113pub 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 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 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
176pub 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
205pub 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
223pub fn tidy(legacy: &Legacy) -> Vec<String> {
227 let mut out = Vec::new();
228 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 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 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 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}