use crate::config::{home_root, EnvFn};
use std::path::{Path, PathBuf};
pub struct Legacy {
pub config: PathBuf,
pub state: PathBuf,
}
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"])?,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Step {
pub what: String,
pub from: PathBuf,
pub to: PathBuf,
pub skip: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Plan {
pub steps: Vec<Step>,
pub absent: bool,
}
impl Plan {
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()
}
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
}
}
const CONFIG_ENTRIES: &[&str] = &["config.toml", ".env", "plugins", "skills", "scripts"];
const STATE_ENTRIES: &[&str] = &["sessions", "install.json", "update.json", "history"];
const MEMORY_ENTRIES: &[&str] = &["AGENT.md", "USER.md", "MEMORY.md"];
fn exists(p: &Path) -> bool {
std::fs::symlink_metadata(p).is_ok()
}
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) {
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));
}
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),
}
}
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
}
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
}
pub fn tidy(legacy: &Legacy) -> Vec<String> {
let mut out = Vec::new();
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"));
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"));
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}");
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}");
}
}