Skip to main content

greengate_runtime/
migrate.rs

1//! The one-time move of greengate 3.x's local state to greengate 4.0's names
2//! (plan "greengate 4.0 renames its data names", a hard rename: 4.0 reads
3//! and writes only the new names, so what 3.x left on this machine is moved
4//! once instead of being read twice forever).
5//!
6//! Per repository, the first 4.0 command moves, under a `flock` on
7//! `$GIT_COMMON_DIR/greengate-migrate.lock`:
8//!
9//! - every `amont-*` file and the `amont/` folder in the common dir and in
10//!   each linked worktree's private git dir (`$GIT_COMMON_DIR/worktrees/*`),
11//!   a ledger's header line rewritten to its `greengate-…` spelling first;
12//! - the repository's local `amont.*` config keys to `greengate.*`, each
13//!   value copied (`--get-all`, then `--add`), then the old key removed.
14//!
15//! then writes `$GIT_COMMON_DIR/greengate-migrated`, which every later
16//! command only `stat`s. The machine's global `amont.*` keys move the same
17//! way, once, under a lock in greengate's config folder.
18//!
19//! Every step is idempotent and ordered so an interrupted migration resumes:
20//! a header is rewritten before its file is renamed, and a key is removed
21//! only after all its values were copied. A migration that cannot finish
22//! leaves what it has not reached under the old names and refuses the
23//! command, naming what to fix.
24//!
25//! One store is never moved: `amont-held` holds unstaged changes a 3.x
26//! check parked, and 3.x records no owner, so a live 3.x may still be about
27//! to put them back. The command is refused until `greengate restore` (which
28//! reads the old store, [`old_held_store`]) has put them back.
29//!
30//! The old spellings live in `names::old` and here; the names test exempts
31//! both files.
32
33use std::path::{Path, PathBuf};
34
35pub mod tracked;
36
37/// greengate 3.x's names, kept beside the new ones in [`crate::names`].
38use crate::names::old;
39
40/// One name in a git dir, its 4.0 spelling, and the header line it carries.
41struct Move {
42    old: &'static str,
43    new: &'static str,
44    header: Option<(&'static str, &'static str)>,
45}
46
47use crate::names as n;
48
49/// Everything 3.x kept in a git dir, in the order it is moved.
50const MOVES: &[Move] = &[
51    Move {
52        old: "amont-bypasses",
53        new: n::BYPASS_LEDGER,
54        header: Some(("amont-bypass-v1", n::BYPASS_FORMAT)),
55    },
56    Move {
57        old: "amont-downgrades",
58        new: n::DOWNGRADE_LEDGER,
59        header: Some(("amont-downgrade-v1", n::DOWNGRADE_FORMAT)),
60    },
61    Move {
62        old: "amont-waves",
63        new: n::WAVES_LEDGER,
64        header: Some(("amont-waves-v1", n::WAVES_FORMAT)),
65    },
66    Move {
67        old: "amont-rehearsal",
68        new: n::REHEARSAL_STATE,
69        header: Some(("amont-rehearsal-v1", n::REHEARSAL_FORMAT)),
70    },
71    Move {
72        old: "amont-rehearsal.log",
73        new: n::REHEARSAL_LOG,
74        header: None,
75    },
76    Move {
77        old: "amont-skew",
78        new: n::SKEW_MARKER,
79        header: Some(("amont-skew-v1", n::SKEW_FORMAT)),
80    },
81    Move {
82        old: "amont-gate",
83        new: n::GATE_MARKER,
84        header: None,
85    },
86    Move {
87        old: "amont-warm.log",
88        new: n::WARM_LOG,
89        header: None,
90    },
91    Move {
92        old: "amont-cache",
93        new: n::TREE_CACHE,
94        header: None,
95    },
96    Move {
97        old: "amont-preserved",
98        new: n::PRESERVED_STORE,
99        header: None,
100    },
101    Move {
102        old: "amont",
103        new: n::STATE_DIR,
104        header: None,
105    },
106];
107
108/// Which way a migration goes.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum Direction {
111    /// 3.x names to 4.0 names: what every 4.0 command does once.
112    Forward,
113    /// 4.0 names back to 3.x names: `greengate migrate --reverse`, before a
114    /// downgrade to 3.x.
115    Reverse,
116}
117
118/// The git dirs of one repository: the common dir, then each linked
119/// worktree's private one.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Repo {
122    pub common: PathBuf,
123}
124
125impl Repo {
126    /// The repository `start` stands in, found from the filesystem alone:
127    /// `$GIT_DIR` when set, else the nearest `.git` above `start` (a folder,
128    /// or a `gitdir:` file), its `commondir` followed. No process is spawned:
129    /// this runs before every command.
130    pub fn locate(start: &Path) -> Option<Repo> {
131        Repo::locate_with(start, std::env::var_os("GIT_DIR"))
132    }
133
134    /// As [`Repo::locate`], with `$GIT_DIR` given rather than read.
135    pub fn locate_with(start: &Path, git_dir: Option<std::ffi::OsString>) -> Option<Repo> {
136        let private = match git_dir.filter(|d| !d.is_empty()) {
137            Some(dir) => absolute(start, Path::new(&dir)),
138            None => find_git_dir(start)?,
139        };
140        let common = match std::fs::read_to_string(private.join("commondir")) {
141            Ok(text) => absolute(&private, Path::new(text.trim())),
142            Err(_) => private.clone(),
143        };
144        Some(Repo { common })
145    }
146
147    /// Each linked worktree's private git dir, listed when asked: the hot
148    /// path checks the done-marker first and never lists them.
149    pub fn worktrees(&self) -> Vec<PathBuf> {
150        match std::fs::read_dir(self.common.join("worktrees")) {
151            Ok(entries) => {
152                let mut dirs: Vec<PathBuf> = entries
153                    .filter_map(Result::ok)
154                    .map(|e| e.path())
155                    .filter(|p| p.is_dir())
156                    .collect();
157                dirs.sort();
158                dirs
159            }
160            Err(_) => Vec::new(),
161        }
162    }
163
164    /// The common dir, then each linked worktree's private one.
165    pub fn git_dirs(&self) -> Vec<PathBuf> {
166        std::iter::once(self.common.clone())
167            .chain(self.worktrees())
168            .collect()
169    }
170
171    /// The done-marker: present once this repository was migrated.
172    pub fn marker(&self) -> PathBuf {
173        self.common.join(n::MIGRATED_MARKER)
174    }
175}
176
177fn absolute(base: &Path, path: &Path) -> PathBuf {
178    if path.is_absolute() {
179        path.to_path_buf()
180    } else {
181        base.join(path)
182    }
183}
184
185/// The nearest git dir above `start`.
186fn find_git_dir(start: &Path) -> Option<PathBuf> {
187    let mut here = Some(start);
188    while let Some(dir) = here {
189        let dotgit = dir.join(".git");
190        if dotgit.is_dir() {
191            return Some(dotgit);
192        }
193        if let Ok(text) = std::fs::read_to_string(&dotgit) {
194            let pointer = text.lines().find_map(|l| l.strip_prefix("gitdir:"))?;
195            return Some(absolute(dir, Path::new(pointer.trim())));
196        }
197        here = dir.parent();
198    }
199    None
200}
201
202/// The held store greengate 3.x left in this worktree, for `greengate
203/// restore`: `$GIT_DIR/amont-held`, when it exists.
204pub fn old_held_store(git_dir: &Path) -> Option<PathBuf> {
205    let store = git_dir.join(old::HELD_STORE);
206    store.is_dir().then_some(store)
207}
208
209/// Why a migration stopped. Its `Display` is the line a refused command
210/// prints; the variants are what a caller or a test tells apart.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub enum MigrateError {
213    /// A 3.x check parked unstaged changes here (forward), or a 4.0 one did
214    /// (reverse): they are put back first, never moved.
215    HeldStore { path: PathBuf },
216    /// A detached cluster run 3.x submitted is still pending: its Workflow
217    /// carries 3.x's label, which 4.0 cannot collect.
218    PendingDetached { path: PathBuf },
219    /// A reverse, while a detached cluster run 4.0 submitted is pending:
220    /// 3.x cannot collect it.
221    PendingForDowngrade { path: PathBuf },
222    /// The pending file of the version being left exists but cannot be
223    /// read: its runs would be lost all the same, so the move waits.
224    PendingUnreadable { path: PathBuf, why: String },
225    /// Both spellings of a committed file are in the work tree
226    /// (`migrate --tracked`): which one is meant is the repository's call.
227    BothCommitted { source: PathBuf, target: PathBuf },
228    /// Both spellings of one name exist and are not a log to merge.
229    BothExist { source: PathBuf, target: PathBuf },
230    /// Another process held the migration lock past its deadline.
231    Locked { path: PathBuf },
232    /// A file operation failed.
233    Io {
234        op: &'static str,
235        path: PathBuf,
236        why: String,
237    },
238    /// git refused or could not run.
239    Git { args: String, why: String },
240}
241
242impl std::error::Error for MigrateError {}
243
244impl MigrateError {
245    /// Refused before anything moved, so nothing is staged or renamed: the
246    /// order of the checks lives here, beside the code that sets it.
247    /// Exhaustive on purpose: a new variant decides here which side it is on.
248    pub fn staged_nothing(&self) -> bool {
249        match self {
250            MigrateError::BothCommitted { .. } => true,
251            MigrateError::HeldStore { .. }
252            | MigrateError::PendingDetached { .. }
253            | MigrateError::PendingForDowngrade { .. }
254            | MigrateError::PendingUnreadable { .. }
255            | MigrateError::BothExist { .. }
256            | MigrateError::Locked { .. }
257            | MigrateError::Io { .. }
258            | MigrateError::Git { .. } => false,
259        }
260    }
261}
262
263impl std::fmt::Display for MigrateError {
264    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        match self {
266            MigrateError::HeldStore { path } => write!(
267                out,
268                "{} holds unstaged changes a check parked; put them back with `{} restore` \
269                 in that worktree, then run the command again",
270                path.display(),
271                n::BIN
272            ),
273            MigrateError::PendingDetached { path } => write!(
274                out,
275                "{} lists a detached cluster run greengate 3.x submitted,\n  \
276                 which 4.0 cannot collect. Once `kubectl get workflows -n {}`\n  \
277                 no longer shows it (or its verdict no longer matters),\n  \
278                 remove the file:\n  rm {}\n  then run the command again",
279                path.display(),
280                old::CLUSTER_NAMESPACE,
281                path.display()
282            ),
283            MigrateError::PendingForDowngrade { path } => write!(
284                out,
285                "{} lists a detached cluster run greengate 4.0 submitted,\n  \
286                 which 3.x cannot collect. Collect it first (`{} cluster collect`),\n  \
287                 or, if its verdict no longer matters, remove the file:\n  rm {}\n  \
288                 then run the command again",
289                path.display(),
290                n::BIN,
291                path.display()
292            ),
293            MigrateError::PendingUnreadable { path, why } => write!(
294                out,
295                "{} (detached cluster runs)\n  cannot be read: \
296                 {why}.\n  If no run in it matters any more, remove it:\n  rm {}\n  \
297                 then run the command again",
298                path.display(),
299                path.display()
300            ),
301            MigrateError::BothExist { source, target } => write!(
302                out,
303                "both {} and {} exist; remove the one you do not need (`rm -r {}` or \
304                 `rm -r {}`), then run `{} migrate`",
305                source.display(),
306                target.display(),
307                source.display(),
308                target.display(),
309                n::BIN
310            ),
311            MigrateError::BothCommitted { source, target } => write!(
312                out,
313                "both {} and {} are here; keep the one that is meant, remove the \
314                 other (`git rm` it) and commit, then run `{} migrate --tracked` again",
315                source.display(),
316                target.display(),
317                n::BIN
318            ),
319            MigrateError::Locked { path } => write!(
320                out,
321                "another {} is migrating this repository ({} is held); run the command again",
322                n::BIN,
323                path.display()
324            ),
325            MigrateError::Io { op, path, why } => {
326                write!(out, "could not {op} {}: {why}", path.display())
327            }
328            MigrateError::Git { args, why } => write!(out, "git {args} failed: {why}"),
329        }
330    }
331}
332
333fn io<'a>(op: &'static str, path: &'a Path) -> impl FnOnce(std::io::Error) -> MigrateError + 'a {
334    move |e| MigrateError::Io {
335        op,
336        path: path.to_path_buf(),
337        why: e.to_string(),
338    }
339}
340
341/// How long a migration waits for another process that holds its lock: a
342/// migration takes well under a second, so a longer hold is a stuck peer.
343const LOCK_DEADLINE: std::time::Duration = std::time::Duration::from_secs(10);
344
345/// What the first-run migration did, for `greengate migrate` to say.
346#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
347pub struct Moved {
348    /// Names moved in the git dirs.
349    pub state: usize,
350    /// Config keys moved.
351    pub keys: usize,
352}
353
354/// Before any command but `--help`, `--version`, `restore`, `uninstall`,
355/// `migrate`, `doctor` and a `--dry-run`: migrate the repository the
356/// process stands in, once, then the machine's global keys, once.
357pub fn ensure(cwd: &Path, git: &GitFn<'_>, now: u64) -> Result<Moved, MigrateError> {
358    let mut moved = ensure_global(git)?;
359    let here = ensure_repo(cwd, git, now)?;
360    moved.state += here.state;
361    moved.keys += here.keys;
362    Ok(moved)
363}
364
365/// The repository half of [`ensure`]: the one `cwd` stands in, once, unless
366/// a reverse asked 4.0 to leave it alone.
367pub fn ensure_repo(cwd: &Path, git: &GitFn<'_>, now: u64) -> Result<Moved, MigrateError> {
368    let Some(repo) = Repo::locate(cwd) else {
369        return Ok(Moved::default());
370    };
371    if repo.marker().exists() || repo.common.join(n::REVERSED_MARKER).exists() {
372        return Ok(Moved::default());
373    }
374    migrate_repo(&repo, Direction::Forward, git, now)
375}
376
377/// Migrate `repo` in `direction`, under its lock. Forward writes the
378/// done-marker and clears a reverse; reverse removes the done-marker and
379/// leaves the reversed one, so a 4.0 hook does not move it forward again.
380pub fn migrate_repo(
381    repo: &Repo,
382    direction: Direction,
383    git: &GitFn<'_>,
384    now: u64,
385) -> Result<Moved, MigrateError> {
386    let _lock = lock(&repo.common.join(n::MIGRATE_LOCK))?;
387    let reversed = repo.common.join(n::REVERSED_MARKER);
388    // Checked again under the lock: a first run that passed `ensure_repo`'s
389    // check before a reverse took the lock must not undo it. A reverse
390    // writes its marker before it moves anything, so a reverse that stopped
391    // half-way also stands the first run down; `greengate migrate` clears
392    // both markers first, so asked by name it moves everything forward.
393    if direction == Direction::Forward && (repo.marker().exists() || reversed.exists()) {
394        return Ok(Moved::default());
395    }
396    let dirs = repo.git_dirs();
397    for dir in &dirs {
398        let held = match direction {
399            Direction::Forward => old_held_store(dir),
400            Direction::Reverse => Some(dir.join(n::HELD_STORE)).filter(|p| p.is_dir()),
401        };
402        if let Some(path) = held {
403            return Err(MigrateError::HeldStore { path });
404        }
405    }
406    // A detached run is collected only by the version that submitted it
407    // (its Workflow carries that version's label): forward, 3.x's pending
408    // runs wait; reverse, 4.0's. A run that has outlived its Workflow is
409    // past collecting; a file this version cannot read is refused too, with
410    // its reason.
411    let state_dir = match direction {
412        Direction::Forward => old::STATE_DIR,
413        Direction::Reverse => n::STATE_DIR,
414    };
415    let pending = repo
416        .common
417        .join(state_dir)
418        .join(crate::cluster::PENDING_FILE);
419    match crate::cluster::lists_live(&pending, now) {
420        Ok(false) => {}
421        Ok(true) if direction == Direction::Forward => {
422            return Err(MigrateError::PendingDetached { path: pending })
423        }
424        Ok(true) => return Err(MigrateError::PendingForDowngrade { path: pending }),
425        Err(why) => return Err(MigrateError::PendingUnreadable { path: pending, why }),
426    }
427    if direction == Direction::Reverse {
428        // The markers first: a reverse that stops half-way must not leave
429        // a done-marker over state already under 3.x names.
430        std::fs::write(&reversed, format!("{}-v1\n", n::REVERSED_MARKER))
431            .map_err(io("write", &reversed))?;
432        remove_if_present(&repo.marker())?;
433    }
434    let mut moved = Moved::default();
435    for dir in &dirs {
436        moved.state += move_state(dir, direction)?;
437    }
438    // A config file that names no section of the namespace being moved
439    // holds no key of it: skip git. This keeps the first run of a
440    // repository without 3.x keys free of any extra process.
441    let local_files = [
442        repo.common.join("config"),
443        repo.common.join("config.worktree"),
444    ];
445    match may_hold(&local_files, direction) {
446        Some(true) => moved.keys += move_keys(&Scope::Local(repo.common.clone()), direction, git)?,
447        Some(false) => {}
448        // A config git cannot read either: going forward, the command that
449        // follows says so in its own words, the keys wait, and no marker is
450        // written, so the next run tries again. A reverse asked for by name
451        // must not report success over keys it never read.
452        None if direction == Direction::Forward => return Ok(moved),
453        None => {
454            return Err(MigrateError::Io {
455                op: "read",
456                path: repo.common.join("config"),
457                why: "the repository's config cannot be read".into(),
458            })
459        }
460    }
461    if direction == Direction::Forward {
462        let text = format!("{}-v1\n{}\n", n::MIGRATED_MARKER, env!("CARGO_PKG_VERSION"));
463        std::fs::write(repo.marker(), text).map_err(io("write", &repo.marker()))?;
464        remove_if_present(&reversed)?;
465    }
466    Ok(moved)
467}
468
469fn remove_if_present(path: &Path) -> Result<(), MigrateError> {
470    match std::fs::remove_file(path) {
471        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(io("remove", path)(e)),
472        _ => Ok(()),
473    }
474}
475
476/// The migration lock, waited for at most [`LOCK_DEADLINE`], saying so
477/// once when another process holds it (a silent wait in a hook reads as a
478/// hang).
479fn lock(path: &Path) -> Result<std::fs::File, MigrateError> {
480    if let Some(file) = greenharness_slots::lock_within(path, std::time::Duration::ZERO)
481        .map_err(io("lock", path))?
482    {
483        return Ok(file);
484    }
485    eprintln!("{}: waiting for {}", n::BIN, path.display());
486    greenharness_slots::lock_within(path, LOCK_DEADLINE)
487        .map_err(io("lock", path))?
488        .ok_or_else(|| MigrateError::Locked {
489            path: path.to_path_buf(),
490        })
491}
492
493/// Move every name of [`MOVES`] in `dir`, in `direction`; how many moved.
494pub fn move_state(dir: &Path, direction: Direction) -> Result<usize, MigrateError> {
495    let mut moved = 0;
496    for m in MOVES {
497        let (from, to, header) = match direction {
498            Direction::Forward => (m.old, m.new, m.header),
499            Direction::Reverse => (m.new, m.old, m.header.map(|(o, n)| (n, o))),
500        };
501        let source = dir.join(from);
502        let target = dir.join(to);
503        if !source.exists() {
504            continue;
505        }
506        moved += 1;
507        if source.is_dir() && target.is_dir() {
508            merge_dirs(&source, &target)?;
509            continue;
510        }
511        if target.exists() {
512            return Err(MigrateError::BothExist { source, target });
513        }
514        if let Some((old_header, new_header)) = header {
515            rewrite_header(&source, old_header, new_header)?;
516        }
517        std::fs::rename(&source, &target).map_err(io("move", &source))?;
518    }
519    Ok(moved)
520}
521
522/// Move what `source` holds into `target`, which already exists (a tool or
523/// a test of the other version wrote there first): a child only in
524/// `source` is moved; a `.log` in both becomes `source`'s lines then
525/// `target`'s, written whole and renamed into place before `source`'s copy
526/// is removed (a crash between the two repeats those lines once); any other
527/// clash is refused before anything moves. `source` is removed once empty.
528fn merge_dirs(source: &Path, target: &Path) -> Result<(), MigrateError> {
529    let read = |dir: &Path| -> Result<Vec<PathBuf>, MigrateError> {
530        let mut out: Vec<PathBuf> = std::fs::read_dir(dir)
531            .map_err(io("read", dir))?
532            .filter_map(Result::ok)
533            .map(|e| e.path())
534            .collect();
535        out.sort();
536        Ok(out)
537    };
538    let children = read(source)?;
539    for child in &children {
540        let there = target.join(child.file_name().unwrap_or_default());
541        let log = child.extension().is_some_and(|e| e == "log");
542        let both_dirs = child.is_dir() && there.is_dir();
543        if there.exists() && !log && !both_dirs {
544            return Err(MigrateError::BothExist {
545                source: child.clone(),
546                target: there,
547            });
548        }
549    }
550    for child in children {
551        let there = target.join(child.file_name().unwrap_or_default());
552        if child.is_dir() && there.is_dir() {
553            merge_dirs(&child, &there)?;
554        } else if there.exists() {
555            let mut joined = std::fs::read(&child).map_err(io("read", &child))?;
556            joined.extend(std::fs::read(&there).map_err(io("read", &there))?);
557            let staged = there.with_extension("log.greengate-merge");
558            std::fs::write(&staged, joined).map_err(io("write", &staged))?;
559            std::fs::rename(&staged, &there).map_err(io("replace", &there))?;
560            std::fs::remove_file(&child).map_err(io("remove", &child))?;
561        } else {
562            std::fs::rename(&child, &there).map_err(io("move", &child))?;
563        }
564    }
565    std::fs::remove_dir(source).map_err(io("remove", source))
566}
567
568/// Replace every line of `file` that is exactly `old` with `new`, through a
569/// temporary file and a rename, so a crash leaves one whole version.
570fn rewrite_header(file: &Path, old: &str, new: &str) -> Result<(), MigrateError> {
571    if !file.is_file() {
572        return Ok(());
573    }
574    let text = std::fs::read(file).map_err(io("read", file))?;
575    let Ok(text) = String::from_utf8(text) else {
576        return Ok(());
577    };
578    if !text.lines().any(|l| l == old) {
579        return Ok(());
580    }
581    let mut out = String::with_capacity(text.len() + 8);
582    for line in text.split_inclusive('\n') {
583        let (body, end) = match line.strip_suffix('\n') {
584            Some(body) => (body, "\n"),
585            None => (line, ""),
586        };
587        out.push_str(if body == old { new } else { body });
588        out.push_str(end);
589    }
590    let staged = file.with_extension("greengate-migrate.tmp");
591    std::fs::write(&staged, out).map_err(io("write", &staged))?;
592    std::fs::rename(&staged, file).map_err(io("replace", file))
593}
594
595/// Where config keys are moved.
596#[derive(Debug, Clone)]
597pub enum Scope {
598    /// The repository's own config (`--local`), the common dir given.
599    Local(PathBuf),
600    /// The person's global config (`--global`).
601    Global,
602}
603
604/// A git command for [`move_keys`]: `(GIT_DIR or None, args)` →
605/// `Ok(Some(stdout))` on exit 0, `Ok(None)` on exit 1 (git's "nothing
606/// matched"), `Err` on any other end. A seam, so the tests drive a scratch
607/// repository and `main` composes the real one.
608pub type GitFn<'a> = dyn Fn(Option<&Path>, &[&str]) -> Result<Option<String>, String> + 'a;
609
610fn run_git(
611    git: &GitFn<'_>,
612    dir: Option<&Path>,
613    args: &[&str],
614) -> Result<Option<String>, MigrateError> {
615    git(dir, args).map_err(|why| MigrateError::Git {
616        args: args.join(" "),
617        why,
618    })
619}
620
621/// The values `git config -z --get-all` prints for one key, each ended by
622/// a NUL: an empty value (`git config amont.x ""`) is a value too.
623fn values(raw: &str) -> Vec<String> {
624    match raw.strip_suffix('\0') {
625        Some(body) => body.split('\0').map(str::to_string).collect(),
626        None => Vec::new(),
627    }
628}
629
630/// Move the `amont.*` keys of `scope` to `greengate.*` (or back); how many
631/// keys moved. Each value the old key holds is added to the new one unless
632/// already there (a migration interrupted between two `--add`s resumes
633/// without losing one), and the old key goes only once every value is
634/// present. A new key that holds a value of its own was set by the person:
635/// the new name wins, and the old values are dropped. `amont.agent.*` is
636/// greenpiste's, never moved. A `cluster.namespace` of `amont-gates` is
637/// dropped on the way forward: 4.0's default namespace is `greengate-gates`.
638pub fn move_keys(
639    scope: &Scope,
640    direction: Direction,
641    git: &GitFn<'_>,
642) -> Result<usize, MigrateError> {
643    let (from, to) = match direction {
644        Direction::Forward => (old::CONFIG_PREFIX, n::CONFIG_PREFIX),
645        Direction::Reverse => (n::CONFIG_PREFIX, old::CONFIG_PREFIX),
646    };
647    let (dir, flag) = match scope {
648        Scope::Local(common) => (Some(common.as_path()), "--local"),
649        Scope::Global => (None, "--global"),
650    };
651    let pattern = format!("^{}", from.replace('.', r"\."));
652    let listed = run_git(
653        git,
654        dir,
655        &["config", flag, "--name-only", "--get-regexp", &pattern],
656    )?
657    .unwrap_or_default();
658    // One line per VALUE, in file order: a key whose values another key
659    // separates is listed twice, apart.
660    let keys: std::collections::BTreeSet<&str> = listed
661        .lines()
662        .filter(|k| !k.is_empty() && !k.starts_with(old::FOREIGN_PREFIX))
663        .collect();
664    let mut moved = 0;
665    for key in keys {
666        let rest = &key[from.len()..];
667        let target = format!("{to}{rest}");
668        let old_values = values(
669            &run_git(git, dir, &["config", flag, "-z", "--get-all", key])?.unwrap_or_default(),
670        );
671        let new_values = values(
672            &run_git(git, dir, &["config", flag, "-z", "--get-all", &target])?.unwrap_or_default(),
673        );
674        let owned_by_person = new_values.iter().any(|v| !old_values.contains(v));
675        if !owned_by_person {
676            for value in &old_values {
677                let dropped = direction == Direction::Forward
678                    && rest.eq_ignore_ascii_case("cluster.namespace")
679                    && value == old::CLUSTER_NAMESPACE;
680                if dropped || new_values.contains(value) {
681                    continue;
682                }
683                run_git(git, dir, &["config", flag, "--add", &target, value])?;
684            }
685        }
686        run_git(git, dir, &["config", flag, "--unset-all", key])?;
687        moved += 1;
688    }
689    Ok(moved)
690}
691
692/// The machine's global keys, once: a marker in greengate's config folder,
693/// written under a lock there. A config that names no `[amont` section
694/// needs no git, and then a config folder that cannot be made (a read-only
695/// HOME in a container) is no reason to refuse; the files are read again
696/// on the next run, which costs no process either. A held
697/// `~/.gitconfig.lock` (another git writing) is retried for a few seconds.
698fn ensure_global(git: &GitFn<'_>) -> Result<Moved, MigrateError> {
699    let Some(dir) = config_dir() else {
700        return Ok(Moved::default());
701    };
702    let marker = dir.join(n::MIGRATED_MARKER);
703    if marker.exists() || dir.join(n::REVERSED_MARKER).exists() {
704        return Ok(Moved::default());
705    }
706    let Some(holds) = may_hold(&global_config_files(), Direction::Forward) else {
707        // An unreadable global config: git cannot read it either. The keys
708        // wait for a run that can.
709        return Ok(Moved::default());
710    };
711    if std::fs::create_dir_all(&dir).is_err() && !holds {
712        return Ok(Moved::default());
713    }
714    std::fs::create_dir_all(&dir).map_err(io("make", &dir))?;
715    let _lock = lock(&dir.join(n::MIGRATE_LOCK))?;
716    if marker.exists() || dir.join(n::REVERSED_MARKER).exists() {
717        return Ok(Moved::default());
718    }
719    let mut moved = Moved::default();
720    if holds {
721        // Another git writing `~/.gitconfig` holds its `.lock` for a moment:
722        // retried for up to five seconds. Any other failure is reported at
723        // once.
724        let mut attempts = 0;
725        moved.keys = loop {
726            match move_keys(&Scope::Global, Direction::Forward, git) {
727                Err(MigrateError::Git { why, .. }) if why.contains(".lock") && attempts < 50 => {
728                    attempts += 1;
729                    std::thread::sleep(std::time::Duration::from_millis(100));
730                }
731                done => break done?,
732            }
733        };
734    }
735    std::fs::write(&marker, format!("{}-v1\n", n::MIGRATED_MARKER))
736        .map_err(io("write", &marker))?;
737    Ok(moved)
738}
739
740/// Forget that the global keys were moved or reversed, so the next
741/// [`ensure`] reads the global config again: `greengate migrate --global`.
742pub fn forget_global() -> Result<(), MigrateError> {
743    match config_dir() {
744        Some(dir) => {
745            remove_if_present(&dir.join(n::MIGRATED_MARKER))?;
746            remove_if_present(&dir.join(n::REVERSED_MARKER))
747        }
748        None => Ok(()),
749    }
750}
751
752/// Whether any of `files` names a section of the namespace `direction`
753/// moves from: `[amont]`, `[amont "…"]` (forward) or the greengate ones
754/// (reverse), in any case: `None` when a file exists but cannot be read.
755/// An `include.path` is read by git and not here: a key reached only
756/// through an include is left for `greengate doctor` to name.
757fn may_hold(files: &[PathBuf], direction: Direction) -> Option<bool> {
758    let section = match direction {
759        Direction::Forward => "[amont",
760        Direction::Reverse => "[greengate",
761    };
762    let mut holds = false;
763    for file in files {
764        let found = match std::fs::read(file) {
765            Ok(bytes) => String::from_utf8_lossy(&bytes)
766                .to_ascii_lowercase()
767                .lines()
768                .any(|line| {
769                    let line = line.trim_start();
770                    line.starts_with(section)
771                        && matches!(
772                            line[section.len()..].chars().next(),
773                            Some(']' | ' ' | '"' | '.')
774                        )
775                }),
776            Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
777            Err(_) => return None,
778        };
779        holds |= found;
780    }
781    Some(holds)
782}
783
784/// The files `git config --global` reads: `$GIT_CONFIG_GLOBAL` when set,
785/// else `$XDG_CONFIG_HOME/git/config` (or `~/.config/git/config`) and
786/// `~/.gitconfig`.
787fn global_config_files() -> Vec<PathBuf> {
788    if let Some(f) = std::env::var_os("GIT_CONFIG_GLOBAL").filter(|f| !f.is_empty()) {
789        return vec![PathBuf::from(f)];
790    }
791    let home = std::env::var_os("HOME").map(PathBuf::from);
792    let xdg = std::env::var_os("XDG_CONFIG_HOME")
793        .filter(|d| !d.is_empty())
794        .map(PathBuf::from)
795        .or_else(|| home.as_ref().map(|h| h.join(".config")));
796    let mut files = Vec::new();
797    if let Some(x) = xdg {
798        files.push(x.join("git").join("config"));
799    }
800    if let Some(h) = home {
801        files.push(h.join(".gitconfig"));
802    }
803    files
804}
805
806/// Move the machine's global keys back: `greengate migrate --reverse
807/// --global`.
808pub fn reverse_global(git: &GitFn<'_>) -> Result<Moved, MigrateError> {
809    // The reversed marker first, as for a repository: until `migrate
810    // --global`, 4.0 leaves the machine's keys under 3.x's names.
811    let mut _lock = None;
812    if let Some(dir) = config_dir() {
813        std::fs::create_dir_all(&dir).map_err(io("make", &dir))?;
814        // Under the machine lock, so a first run that passed its check
815        // before this started cannot move the keys forward again.
816        _lock = Some(lock(&dir.join(n::MIGRATE_LOCK))?);
817        let reversed = dir.join(n::REVERSED_MARKER);
818        std::fs::write(&reversed, format!("{}-v1\n", n::REVERSED_MARKER))
819            .map_err(io("write", &reversed))?;
820        remove_if_present(&dir.join(n::MIGRATED_MARKER))?;
821    }
822    let keys = move_keys(&Scope::Global, Direction::Reverse, git)?;
823    Ok(Moved { state: 0, keys })
824}
825
826/// greengate's folder of machine state: `$XDG_CONFIG_HOME/greengate`, else
827/// `~/.config/greengate`.
828pub fn config_dir() -> Option<PathBuf> {
829    if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|d| !d.is_empty()) {
830        return Some(PathBuf::from(x).join(n::STATE_DIR));
831    }
832    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
833    Some(PathBuf::from(home).join(".config").join(n::STATE_DIR))
834}
835
836/// What `greengate doctor` reports: the 3.x names still visible from here,
837/// one line each, with the command that moves them. `Err` when git could
838/// not answer: a failure never reads as "nothing left".
839pub fn leftovers(cwd: &Path, git: &GitFn<'_>) -> Result<Vec<String>, MigrateError> {
840    let mut out = Vec::new();
841    let mut env: Vec<String> = std::env::vars_os()
842        .filter_map(|(k, _)| k.into_string().ok())
843        .filter(|k| k.starts_with(old::ENV_PREFIX) && !k.starts_with(old::FOREIGN_ENV_PREFIX))
844        .collect();
845    env.sort();
846    for k in env {
847        let rest = &k[old::ENV_PREFIX.len()..];
848        let new = match rest {
849            "HOST_SLOT" => greenharness_slots::HELD_ENV.to_string(),
850            "SLOT_DIR" => greenharness_slots::DIR_ENV.to_string(),
851            _ => format!("{}_{rest}", n::ENV_PREFIX),
852        };
853        out.push(format!(
854            "environment: {k} is ignored by greengate 4.0; set {new} instead"
855        ));
856    }
857    let pattern = r"^amont\.";
858    let listed = |dir: Option<&Path>, flag: &str| -> Result<Vec<String>, MigrateError> {
859        let names = run_git(
860            git,
861            dir,
862            &["config", flag, "--name-only", "--get-regexp", pattern],
863        )?
864        .unwrap_or_default();
865        Ok(names
866            .lines()
867            .filter(|k| !k.starts_with(old::FOREIGN_PREFIX))
868            .collect::<std::collections::BTreeSet<_>>()
869            .into_iter()
870            .map(str::to_string)
871            .collect())
872    };
873    if config_dir().is_some_and(|dir| dir.join(n::REVERSED_MARKER).exists()) {
874        out.push(format!(
875            "reversed: the global keys were moved back to greengate 3.x's names; \
876             greengate 4.0 leaves them until `{} migrate --global`",
877            n::BIN
878        ));
879    }
880    for key in listed(None, "--global")? {
881        out.push(format!(
882            "global config: {key} is ignored by greengate 4.0; `{} migrate --global` moves it",
883            n::BIN
884        ));
885    }
886    // The migration copies the kubeconfig path as it is, and 3.x's logs in as
887    // the runner of the namespace 4.0 no longer uses: every cluster gate
888    // would be refused, and quietly run here instead.
889    let kubeconfig = run_git(
890        git,
891        None,
892        &[
893            "config",
894            "--global",
895            "--get",
896            "greengate.cluster.kubeconfig",
897        ],
898    )?
899    .unwrap_or_default();
900    if old_kubeconfig(kubeconfig.trim()) {
901        out.push(format!(
902            "cluster: greengate.cluster.kubeconfig is greengate 3.x's ({}), which logs in \
903             as the old namespace's runner; run homelab's \
904             scripts/greengate-gates-kubeconfig.sh, then \
905             `git config --global greengate.cluster.kubeconfig ~/.config/{}/kube/homelab.yaml`",
906            kubeconfig.trim(),
907            n::STATE_DIR
908        ));
909    }
910    if let Some(repo) = Repo::locate(cwd) {
911        if repo.common.join(n::REVERSED_MARKER).exists() {
912            out.push(format!(
913                "reversed: this repository was moved back to greengate 3.x's names; \
914                 greengate 4.0 leaves it until `{} migrate`",
915                n::BIN
916            ));
917        }
918        for key in listed(Some(&repo.common), "--local")? {
919            out.push(format!(
920                "local config: {key} is ignored by greengate 4.0; `{} migrate` moves it",
921                n::BIN
922            ));
923        }
924        for dir in repo.git_dirs() {
925            for m in MOVES {
926                if dir.join(m.old).exists() {
927                    out.push(format!(
928                        "state: {} was left by greengate 3.x; `{} migrate` moves it",
929                        dir.join(m.old).display(),
930                        n::BIN
931                    ));
932                }
933            }
934            if let Some(store) = old_held_store(&dir) {
935                out.push(format!(
936                    "state: {} holds parked changes; `{} restore` puts them back",
937                    store.display(),
938                    n::BIN
939                ));
940            }
941        }
942    }
943    Ok(out)
944}
945
946/// Is `path` a kubeconfig under greengate 3.x's config folder?
947fn old_kubeconfig(path: &str) -> bool {
948    let folder = format!("/.config/{}/", old::STATE_DIR);
949    path.replace('\\', "/").contains(&folder)
950}
951
952/// git, with `GIT_DIR` set to `dir` when one is given, as [`GitFn`] says.
953pub fn system_git(dir: Option<&Path>, args: &[&str]) -> Result<Option<String>, String> {
954    let mut cmd = std::process::Command::new("git");
955    if let Some(dir) = dir {
956        cmd.env("GIT_DIR", dir);
957    }
958    let out = cmd
959        .args(args)
960        .stdin(std::process::Stdio::null())
961        .output()
962        .map_err(|e| e.to_string())?;
963    match out.status.code() {
964        Some(0) => Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned())),
965        Some(1) => Ok(None),
966        code => Err(format!(
967            "exit {}: {}",
968            code.map_or("signal".to_string(), |c| c.to_string()),
969            String::from_utf8_lossy(&out.stderr).trim()
970        )),
971    }
972}
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977
978    /// A fixed clock: no test here depends on the date.
979    const NOW: u64 = 1_800_000_000;
980
981    fn scratch(name: &str) -> PathBuf {
982        let scratch_dir =
983            std::env::temp_dir().join(format!("greengate-migrate-{name}-{}", std::process::id()));
984        let _ = std::fs::remove_dir_all(&scratch_dir); // a fresh dir; absent is fine
985        std::fs::create_dir_all(&scratch_dir).unwrap();
986        scratch_dir
987    }
988
989    /// git in `repo`, its global config a file of its own, as [`GitFn`].
990    fn git_in(
991        repo: &Path,
992    ) -> impl Fn(Option<&Path>, &[&str]) -> Result<Option<String>, String> + '_ {
993        move |_dir, args| {
994            let out = std::process::Command::new("git")
995                .current_dir(repo)
996                .env("GIT_CONFIG_GLOBAL", repo.join("global-config"))
997                .env("GIT_CONFIG_NOSYSTEM", "1")
998                .args(args)
999                .output()
1000                .map_err(|e| e.to_string())?;
1001            match out.status.code() {
1002                Some(0) => Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned())),
1003                Some(1) => Ok(None),
1004                code => Err(format!("{code:?}")),
1005            }
1006        }
1007    }
1008
1009    /// The values of `key`, newline-joined; empty when unset.
1010    fn get(git: &GitFn<'_>, key: &str) -> String {
1011        git(None, &["config", "--get-all", key])
1012            .unwrap()
1013            .unwrap_or_default()
1014    }
1015
1016    fn init(dir: &Path) {
1017        let ok = std::process::Command::new("git")
1018            .args(["init", "-q"])
1019            .arg(dir)
1020            .status()
1021            .unwrap()
1022            .success();
1023        assert!(ok);
1024    }
1025
1026    #[test]
1027    fn three_x_state_moves_with_its_headers_and_a_second_run_is_a_no_op() {
1028        let root = scratch("state");
1029        init(&root);
1030        let gd = root.join(".git");
1031        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n1 abc gate\n").unwrap();
1032        std::fs::write(
1033            gd.join("amont-waves"),
1034            "amont-waves-v1\n1 2\namont-waves-v1\n3 4\n",
1035        )
1036        .unwrap();
1037        std::fs::create_dir_all(gd.join("amont/logs")).unwrap();
1038        std::fs::write(gd.join("amont/logs/x.log"), "log").unwrap();
1039        std::fs::create_dir_all(gd.join("amont-cache/cargo-test")).unwrap();
1040
1041        let repo = Repo::locate_with(&root, None).unwrap();
1042        let git = git_in(&root);
1043        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1044
1045        assert_eq!(
1046            std::fs::read_to_string(gd.join(n::BYPASS_LEDGER)).unwrap(),
1047            "greengate-bypass-v1\n1 abc gate\n"
1048        );
1049        assert_eq!(
1050            std::fs::read_to_string(gd.join(n::WAVES_LEDGER)).unwrap(),
1051            "greengate-waves-v1\n1 2\ngreengate-waves-v1\n3 4\n"
1052        );
1053        assert!(gd.join("greengate/logs/x.log").is_file());
1054        assert!(gd.join(n::TREE_CACHE).join("cargo-test").is_dir());
1055        for old in ["amont-bypasses", "amont-waves", "amont", "amont-cache"] {
1056            assert!(!gd.join(old).exists(), "{old} left behind");
1057        }
1058        assert!(repo.marker().is_file());
1059        // A second run, marker or not, changes nothing.
1060        std::fs::remove_file(repo.marker()).unwrap();
1061        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1062        assert!(gd.join(n::BYPASS_LEDGER).is_file());
1063    }
1064
1065    #[test]
1066    fn an_interrupted_move_resumes_and_both_names_are_refused() {
1067        let root = scratch("resume");
1068        init(&root);
1069        let gd = root.join(".git");
1070        // A crash after the header rewrite, before the rename.
1071        std::fs::write(
1072            gd.join("amont-downgrades"),
1073            "greengate-downgrade-v1\n1 a b c\n",
1074        )
1075        .unwrap();
1076        move_state(&gd, Direction::Forward).unwrap();
1077        assert_eq!(
1078            std::fs::read_to_string(gd.join(n::DOWNGRADE_LEDGER)).unwrap(),
1079            "greengate-downgrade-v1\n1 a b c\n"
1080        );
1081        // Both names: refused, nothing moved.
1082        std::fs::write(gd.join("amont-downgrades"), "amont-downgrade-v1\n").unwrap();
1083        let err = move_state(&gd, Direction::Forward).unwrap_err();
1084        assert!(matches!(err, MigrateError::BothExist { .. }), "{err}");
1085        assert!(gd.join("amont-downgrades").is_file());
1086    }
1087
1088    #[test]
1089    fn linked_worktrees_are_walked_and_a_held_store_refuses() {
1090        let root = scratch("worktrees");
1091        init(&root);
1092        let wt = root.join(".git/worktrees/side");
1093        std::fs::create_dir_all(&wt).unwrap();
1094        std::fs::write(wt.join("amont-skew"), "amont-skew-v1\n3.0.0\n").unwrap();
1095        let repo = Repo::locate_with(&root, None).unwrap();
1096        assert_eq!(repo.worktrees(), vec![wt.clone()]);
1097        std::fs::create_dir_all(wt.join("amont-held")).unwrap();
1098        let git = git_in(&root);
1099        let err = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err();
1100        assert_eq!(
1101            err,
1102            MigrateError::HeldStore {
1103                path: wt.join("amont-held")
1104            }
1105        );
1106        assert!(err.to_string().contains("restore"), "{err}");
1107        assert!(
1108            wt.join("amont-skew").is_file(),
1109            "nothing moved while refused"
1110        );
1111        assert!(!repo.marker().exists());
1112        std::fs::remove_dir(wt.join("amont-held")).unwrap();
1113        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1114        assert_eq!(
1115            std::fs::read_to_string(wt.join(n::SKEW_MARKER)).unwrap(),
1116            "greengate-skew-v1\n3.0.0\n"
1117        );
1118    }
1119
1120    #[test]
1121    fn local_keys_move_with_every_value_and_the_new_name_wins() {
1122        let root = scratch("keys");
1123        init(&root);
1124        let git = git_in(&root);
1125        for args in [
1126            ["config", "--add", "amont.trusted", "aaa"],
1127            ["config", "--add", "amont.timeout", "600"],
1128            // Another key between two values: listed twice, apart.
1129            ["config", "--add", "amont.trusted", "bbb"],
1130            ["config", "--add", "greengate.timeout", "900"],
1131            ["config", "--add", "amont.cluster.namespace", "amont-gates"],
1132            ["config", "--add", "amont.agent.suppressions", "allow"],
1133        ] {
1134            git(None, &args).unwrap();
1135        }
1136        let repo = Repo::locate_with(&root, None).unwrap();
1137        let moved = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1138        assert_eq!(moved.keys, 3, "trusted, timeout, cluster.namespace");
1139        assert_eq!(get(&git, "greengate.trusted"), "aaa\nbbb\n");
1140        assert_eq!(get(&git, "greengate.timeout"), "900\n", "the new name wins");
1141        assert_eq!(get(&git, "greengate.cluster.namespace"), "");
1142        assert_eq!(get(&git, "amont.trusted"), "");
1143        assert_eq!(get(&git, "amont.timeout"), "");
1144        assert_eq!(get(&git, "amont.agent.suppressions"), "allow\n");
1145
1146        // And back: the reverse restores the 3.x names, and 4.0 then leaves
1147        // the repository alone until asked.
1148        migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap();
1149        assert_eq!(get(&git, "amont.trusted"), "aaa\nbbb\n");
1150        assert_eq!(get(&git, "greengate.trusted"), "");
1151        assert!(!repo.marker().exists());
1152        assert!(repo.common.join(n::REVERSED_MARKER).is_file());
1153        // The repository half only: the global half reads this machine's
1154        // config home, which a unit test must not touch.
1155        ensure_repo(&root, &git, NOW).unwrap();
1156        assert_eq!(
1157            get(&git, "amont.trusted"),
1158            "aaa\nbbb\n",
1159            "a reverse is not undone"
1160        );
1161    }
1162
1163    #[test]
1164    fn a_copy_cut_off_between_two_values_resumes_without_losing_one() {
1165        let root = scratch("partial");
1166        init(&root);
1167        let git = git_in(&root);
1168        for args in [
1169            ["config", "--add", "amont.trusted", "aaa"],
1170            ["config", "--add", "amont.trusted", "bbb"],
1171            ["config", "--add", "amont.trusted", "ccc"],
1172            // The first run stopped after one `--add`.
1173            ["config", "--add", "greengate.trusted", "aaa"],
1174        ] {
1175            git(None, &args).unwrap();
1176        }
1177        move_keys(&Scope::Local(root.join(".git")), Direction::Forward, &git).unwrap();
1178        assert_eq!(get(&git, "greengate.trusted"), "aaa\nbbb\nccc\n");
1179        assert_eq!(get(&git, "amont.trusted"), "");
1180    }
1181
1182    #[test]
1183    fn a_git_that_fails_stops_the_move_and_keeps_the_old_key() {
1184        let root = scratch("git-fails");
1185        init(&root);
1186        let real = git_in(&root);
1187        real(None, &["config", "--add", "amont.trusted", "aaa"]).unwrap();
1188        let failing = |dir: Option<&Path>, args: &[&str]| -> Result<Option<String>, String> {
1189            if args.contains(&"--add") {
1190                return Err("exit 255: could not lock config file".into());
1191            }
1192            real(dir, args)
1193        };
1194        let err = move_keys(
1195            &Scope::Local(root.join(".git")),
1196            Direction::Forward,
1197            &failing,
1198        )
1199        .unwrap_err();
1200        assert!(matches!(err, MigrateError::Git { .. }), "{err}");
1201        assert_eq!(get(&real, "amont.trusted"), "aaa\n", "the old key stays");
1202    }
1203
1204    #[test]
1205    fn a_3x_pending_file_this_version_cannot_read_refuses_the_move() {
1206        // The TTL rule itself is tested beside the file's owner
1207        // (`cluster::detached::collect`, `lists_live`).
1208        let root = scratch("pending");
1209        init(&root);
1210        let gd = root.join(".git");
1211        std::fs::create_dir_all(gd.join("amont")).unwrap();
1212        let pending = gd.join("amont/cluster-pending");
1213        std::fs::write(&pending, "{\"format\":1,\"records\":[{\"name\":\"x\"}]}\n").unwrap();
1214        let repo = Repo::locate_with(&root, None).unwrap();
1215        let git = git_in(&root);
1216        let err = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err();
1217        assert!(
1218            matches!(err, MigrateError::PendingUnreadable { .. }),
1219            "{err}"
1220        );
1221        assert!(err.to_string().contains("rm "), "{err}");
1222        std::fs::write(&pending, "{\"format\":1,\"records\":[]}\n").unwrap();
1223        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1224        assert!(gd.join("greengate/cluster-pending").is_file());
1225    }
1226
1227    #[test]
1228    fn a_live_3x_run_refuses_the_move_and_an_expired_one_lets_it_through() {
1229        let root = scratch("pending-live");
1230        init(&root);
1231        let gd = root.join(".git");
1232        std::fs::create_dir_all(gd.join("amont")).unwrap();
1233        let pending = gd.join("amont/cluster-pending");
1234        std::fs::write(&pending, crate::cluster::sample_pending_file(NOW)).unwrap();
1235        let repo = Repo::locate_with(&root, None).unwrap();
1236        let git = git_in(&root);
1237        assert_eq!(
1238            migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err(),
1239            MigrateError::PendingDetached {
1240                path: pending.clone()
1241            }
1242        );
1243        // The same file, a week later: the run is past its Workflow's TTL.
1244        migrate_repo(&repo, Direction::Forward, &git, NOW + 7 * 86_400).unwrap();
1245        assert!(gd.join("greengate/cluster-pending").is_file());
1246    }
1247
1248    /// The other way round: 3.x cannot collect a run 4.0 submitted, so a
1249    /// reverse waits for it, and moves nothing meanwhile.
1250    #[test]
1251    fn a_live_4_0_run_refuses_a_reverse() {
1252        let root = scratch("pending-reverse");
1253        init(&root);
1254        let gd = root.join(".git");
1255        std::fs::create_dir_all(gd.join(n::STATE_DIR)).unwrap();
1256        let pending = gd.join(n::STATE_DIR).join(crate::cluster::PENDING_FILE);
1257        std::fs::write(&pending, crate::cluster::sample_pending_file(NOW)).unwrap();
1258        let repo = Repo::locate_with(&root, None).unwrap();
1259        let git = git_in(&root);
1260        let err = migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap_err();
1261        assert_eq!(
1262            err,
1263            MigrateError::PendingForDowngrade {
1264                path: pending.clone()
1265            }
1266        );
1267        assert!(err.to_string().contains("cluster collect"), "{err}");
1268        assert!(pending.is_file() && !gd.join(n::REVERSED_MARKER).exists());
1269        migrate_repo(&repo, Direction::Reverse, &git, NOW + 7 * 86_400).unwrap();
1270        assert!(gd
1271            .join(old::STATE_DIR)
1272            .join(crate::cluster::PENDING_FILE)
1273            .is_file());
1274    }
1275
1276    #[test]
1277    fn a_first_run_stands_down_while_a_reverse_is_marked() {
1278        let root = scratch("stand-down");
1279        init(&root);
1280        let gd = root.join(".git");
1281        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n").unwrap();
1282        let repo = Repo::locate_with(&root, None).unwrap();
1283        // The state a reverse leaves: its marker, no done-marker, 3.x names.
1284        std::fs::write(repo.common.join(n::REVERSED_MARKER), "").unwrap();
1285        let git = git_in(&root);
1286        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1287        assert!(gd.join("amont-bypasses").is_file(), "the reverse holds");
1288    }
1289
1290    #[test]
1291    fn a_reverse_that_stops_half_way_is_moved_forward_again() {
1292        let root = scratch("half-reverse");
1293        init(&root);
1294        let gd = root.join(".git");
1295        let git = git_in(&root);
1296        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n").unwrap();
1297        git(None, &["config", "amont.timeout", "700"]).unwrap();
1298        let repo = Repo::locate_with(&root, None).unwrap();
1299        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1300        // A reverse whose key move fails, after the state went back.
1301        let failing = |dir: Option<&Path>, args: &[&str]| -> Result<Option<String>, String> {
1302            if args.contains(&"--add") {
1303                return Err("exit 255: could not lock config file".into());
1304            }
1305            git(dir, args)
1306        };
1307        assert!(migrate_repo(&repo, Direction::Reverse, &failing, NOW).is_err());
1308        assert!(gd.join("amont-bypasses").is_file(), "the state went back");
1309        assert!(!repo.marker().exists(), "no done-marker over 3.x state");
1310        // Asked forward again: everything is under greengate's names.
1311        std::fs::remove_file(repo.common.join(n::REVERSED_MARKER)).unwrap();
1312        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1313        assert!(gd.join(n::BYPASS_LEDGER).is_file());
1314        assert_eq!(get(&git, "greengate.timeout"), "700\n");
1315    }
1316
1317    #[test]
1318    fn a_reverse_refuses_while_4_0_holds_parked_changes() {
1319        let root = scratch("reverse-held");
1320        init(&root);
1321        let gd = root.join(".git");
1322        std::fs::create_dir_all(gd.join(n::HELD_STORE)).unwrap();
1323        let repo = Repo::locate_with(&root, None).unwrap();
1324        let git = git_in(&root);
1325        assert!(matches!(
1326            migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap_err(),
1327            MigrateError::HeldStore { .. }
1328        ));
1329    }
1330
1331    #[test]
1332    fn only_a_file_naming_the_namespace_may_hold_its_keys() {
1333        let root = scratch("may-hold");
1334        let config_file = root.join("config");
1335        std::fs::write(&config_file, "[core]\n\tbare = false\n[amontx]\n\ta = 1\n").unwrap();
1336        assert_eq!(
1337            may_hold(std::slice::from_ref(&config_file), Direction::Forward),
1338            Some(false)
1339        );
1340        for section in ["[amont]", "[Amont \"severity\"]", "  [amont.cluster]"] {
1341            std::fs::write(&config_file, format!("[core]\n{section}\n\tx = 1\n")).unwrap();
1342            assert_eq!(
1343                may_hold(std::slice::from_ref(&config_file), Direction::Forward),
1344                Some(true),
1345                "{section}"
1346            );
1347        }
1348        assert_eq!(
1349            may_hold(std::slice::from_ref(&config_file), Direction::Reverse),
1350            Some(false)
1351        );
1352        assert_eq!(
1353            may_hold(&[root.join("absent")], Direction::Forward),
1354            Some(false)
1355        );
1356    }
1357
1358    #[test]
1359    fn a_state_folder_both_versions_wrote_is_merged() {
1360        let root = scratch("merge");
1361        init(&root);
1362        let gd = root.join(".git");
1363        std::fs::create_dir_all(gd.join("amont/land")).unwrap();
1364        std::fs::create_dir_all(gd.join("greengate/logs")).unwrap();
1365        std::fs::write(gd.join("amont/cluster.log"), "1 old\n").unwrap();
1366        std::fs::write(gd.join("amont/land/r.json"), "{}").unwrap();
1367        std::fs::write(gd.join("greengate/cluster.log"), "2 new\n").unwrap();
1368        move_state(&gd, Direction::Forward).unwrap();
1369        assert!(!gd.join("amont").exists());
1370        assert_eq!(
1371            std::fs::read_to_string(gd.join("greengate/cluster.log")).unwrap(),
1372            "1 old\n2 new\n"
1373        );
1374        assert!(gd.join("greengate/land/r.json").is_file());
1375        assert!(gd.join("greengate/logs").is_dir());
1376        // A clash that is not a log is refused, nothing moved.
1377        std::fs::create_dir_all(gd.join("amont")).unwrap();
1378        std::fs::write(gd.join("amont/cluster-pending"), "a").unwrap();
1379        std::fs::write(gd.join("greengate/cluster-pending"), "b").unwrap();
1380        assert!(matches!(
1381            move_state(&gd, Direction::Forward).unwrap_err(),
1382            MigrateError::BothExist { .. }
1383        ));
1384        assert!(gd.join("amont/cluster-pending").is_file());
1385    }
1386
1387    #[test]
1388    fn the_reverse_puts_state_back_under_3x_names() {
1389        let root = scratch("reverse");
1390        init(&root);
1391        let gd = root.join(".git");
1392        std::fs::write(
1393            gd.join(n::REHEARSAL_STATE),
1394            "greengate-rehearsal-v1\npid=1\n",
1395        )
1396        .unwrap();
1397        move_state(&gd, Direction::Reverse).unwrap();
1398        assert_eq!(
1399            std::fs::read_to_string(gd.join("amont-rehearsal")).unwrap(),
1400            "amont-rehearsal-v1\npid=1\n"
1401        );
1402    }
1403
1404    #[test]
1405    fn a_gitdir_file_is_followed_to_its_common_dir() {
1406        let root = scratch("pointer");
1407        init(&root);
1408        let wt_git = root.join(".git/worktrees/w");
1409        std::fs::create_dir_all(&wt_git).unwrap();
1410        std::fs::write(wt_git.join("commondir"), "../..\n").unwrap();
1411        let checkout = root.join("w");
1412        std::fs::create_dir_all(checkout.join("src")).unwrap();
1413        std::fs::write(
1414            checkout.join(".git"),
1415            format!("gitdir: {}\n", wt_git.display()),
1416        )
1417        .unwrap();
1418        let repo = Repo::locate_with(&checkout.join("src"), None).unwrap();
1419        assert_eq!(
1420            repo.common.canonicalize().unwrap(),
1421            root.join(".git").canonicalize().unwrap()
1422        );
1423    }
1424}