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    if direction == Direction::Forward {
439        drop_old_audit_ref(repo, git)?;
440    }
441    // A config file that names no section of the namespace being moved
442    // holds no key of it: skip git. This keeps the first run of a
443    // repository without 3.x keys free of any extra process.
444    let local_files = [
445        repo.common.join("config"),
446        repo.common.join("config.worktree"),
447    ];
448    match may_hold(&local_files, direction) {
449        Some(true) => moved.keys += move_keys(&Scope::Local(repo.common.clone()), direction, git)?,
450        Some(false) => {}
451        // A config git cannot read either: going forward, the command that
452        // follows says so in its own words, the keys wait, and no marker is
453        // written, so the next run tries again. A reverse asked for by name
454        // must not report success over keys it never read.
455        None if direction == Direction::Forward => return Ok(moved),
456        None => {
457            return Err(MigrateError::Io {
458                op: "read",
459                path: repo.common.join("config"),
460                why: "the repository's config cannot be read".into(),
461            })
462        }
463    }
464    if direction == Direction::Forward {
465        let text = format!("{}-v1\n{}\n", n::MIGRATED_MARKER, env!("CARGO_PKG_VERSION"));
466        std::fs::write(repo.marker(), text).map_err(io("write", &repo.marker()))?;
467        remove_if_present(&reversed)?;
468    }
469    Ok(moved)
470}
471
472/// Deletes `refs/notes/amont-audit`, the release audit's 24-hour local cache
473/// (never pushed; the new one is `refs/notes/greengate-audit`), so the next
474/// tag push audits once. Absent is no error, and no process is spawned unless
475/// the ref is there: it is looked for as a loose file and in `packed-refs`.
476fn drop_old_audit_ref(repo: &Repo, git: &GitFn<'_>) -> Result<(), MigrateError> {
477    let name = format!("refs/notes/{}", old::AUDIT_REF);
478    let present = repo.common.join(&name).exists()
479        || std::fs::read_to_string(repo.common.join("packed-refs"))
480            .is_ok_and(|t| t.lines().any(|l| l.ends_with(&format!(" {name}"))));
481    if present {
482        run_git(git, Some(&repo.common), &["update-ref", "-d", &name])?;
483        eprintln!("removed the old audit cache; the next tag push audits once");
484    }
485    Ok(())
486}
487
488fn remove_if_present(path: &Path) -> Result<(), MigrateError> {
489    match std::fs::remove_file(path) {
490        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(io("remove", path)(e)),
491        _ => Ok(()),
492    }
493}
494
495/// The migration lock, waited for at most [`LOCK_DEADLINE`], saying so
496/// once when another process holds it (a silent wait in a hook reads as a
497/// hang).
498fn lock(path: &Path) -> Result<std::fs::File, MigrateError> {
499    if let Some(file) = greenharness_slots::lock_within(path, std::time::Duration::ZERO)
500        .map_err(io("lock", path))?
501    {
502        return Ok(file);
503    }
504    eprintln!("{}: waiting for {}", n::BIN, path.display());
505    greenharness_slots::lock_within(path, LOCK_DEADLINE)
506        .map_err(io("lock", path))?
507        .ok_or_else(|| MigrateError::Locked {
508            path: path.to_path_buf(),
509        })
510}
511
512/// Move every name of [`MOVES`] in `dir`, in `direction`; how many moved.
513pub fn move_state(dir: &Path, direction: Direction) -> Result<usize, MigrateError> {
514    let mut moved = 0;
515    for m in MOVES {
516        let (from, to, header) = match direction {
517            Direction::Forward => (m.old, m.new, m.header),
518            Direction::Reverse => (m.new, m.old, m.header.map(|(o, n)| (n, o))),
519        };
520        let source = dir.join(from);
521        let target = dir.join(to);
522        if !source.exists() {
523            continue;
524        }
525        moved += 1;
526        if source.is_dir() && target.is_dir() {
527            merge_dirs(&source, &target)?;
528            continue;
529        }
530        if target.exists() {
531            return Err(MigrateError::BothExist { source, target });
532        }
533        if let Some((old_header, new_header)) = header {
534            rewrite_header(&source, old_header, new_header)?;
535        }
536        std::fs::rename(&source, &target).map_err(io("move", &source))?;
537    }
538    Ok(moved)
539}
540
541/// Move what `source` holds into `target`, which already exists (a tool or
542/// a test of the other version wrote there first): a child only in
543/// `source` is moved; a `.log` in both becomes `source`'s lines then
544/// `target`'s, written whole and renamed into place before `source`'s copy
545/// is removed (a crash between the two repeats those lines once); any other
546/// clash is refused before anything moves. `source` is removed once empty.
547fn merge_dirs(source: &Path, target: &Path) -> Result<(), MigrateError> {
548    let read = |dir: &Path| -> Result<Vec<PathBuf>, MigrateError> {
549        let mut out: Vec<PathBuf> = std::fs::read_dir(dir)
550            .map_err(io("read", dir))?
551            .filter_map(Result::ok)
552            .map(|e| e.path())
553            .collect();
554        out.sort();
555        Ok(out)
556    };
557    let children = read(source)?;
558    for child in &children {
559        let there = target.join(child.file_name().unwrap_or_default());
560        let log = child.extension().is_some_and(|e| e == "log");
561        let both_dirs = child.is_dir() && there.is_dir();
562        if there.exists() && !log && !both_dirs {
563            return Err(MigrateError::BothExist {
564                source: child.clone(),
565                target: there,
566            });
567        }
568    }
569    for child in children {
570        let there = target.join(child.file_name().unwrap_or_default());
571        if child.is_dir() && there.is_dir() {
572            merge_dirs(&child, &there)?;
573        } else if there.exists() {
574            let mut joined = std::fs::read(&child).map_err(io("read", &child))?;
575            joined.extend(std::fs::read(&there).map_err(io("read", &there))?);
576            let staged = there.with_extension("log.greengate-merge");
577            std::fs::write(&staged, joined).map_err(io("write", &staged))?;
578            std::fs::rename(&staged, &there).map_err(io("replace", &there))?;
579            std::fs::remove_file(&child).map_err(io("remove", &child))?;
580        } else {
581            std::fs::rename(&child, &there).map_err(io("move", &child))?;
582        }
583    }
584    std::fs::remove_dir(source).map_err(io("remove", source))
585}
586
587/// Replace every line of `file` that is exactly `old` with `new`, through a
588/// temporary file and a rename, so a crash leaves one whole version.
589fn rewrite_header(file: &Path, old: &str, new: &str) -> Result<(), MigrateError> {
590    if !file.is_file() {
591        return Ok(());
592    }
593    let text = std::fs::read(file).map_err(io("read", file))?;
594    let Ok(text) = String::from_utf8(text) else {
595        return Ok(());
596    };
597    if !text.lines().any(|l| l == old) {
598        return Ok(());
599    }
600    let mut out = String::with_capacity(text.len() + 8);
601    for line in text.split_inclusive('\n') {
602        let (body, end) = match line.strip_suffix('\n') {
603            Some(body) => (body, "\n"),
604            None => (line, ""),
605        };
606        out.push_str(if body == old { new } else { body });
607        out.push_str(end);
608    }
609    let staged = file.with_extension("greengate-migrate.tmp");
610    std::fs::write(&staged, out).map_err(io("write", &staged))?;
611    std::fs::rename(&staged, file).map_err(io("replace", file))
612}
613
614/// Where config keys are moved.
615#[derive(Debug, Clone)]
616pub enum Scope {
617    /// The repository's own config (`--local`), the common dir given.
618    Local(PathBuf),
619    /// The person's global config (`--global`).
620    Global,
621}
622
623/// A git command for [`move_keys`]: `(GIT_DIR or None, args)` →
624/// `Ok(Some(stdout))` on exit 0, `Ok(None)` on exit 1 (git's "nothing
625/// matched"), `Err` on any other end. A seam, so the tests drive a scratch
626/// repository and `main` composes the real one.
627pub type GitFn<'a> = dyn Fn(Option<&Path>, &[&str]) -> Result<Option<String>, String> + 'a;
628
629fn run_git(
630    git: &GitFn<'_>,
631    dir: Option<&Path>,
632    args: &[&str],
633) -> Result<Option<String>, MigrateError> {
634    git(dir, args).map_err(|why| MigrateError::Git {
635        args: args.join(" "),
636        why,
637    })
638}
639
640/// The values `git config -z --get-all` prints for one key, each ended by
641/// a NUL: an empty value (`git config amont.x ""`) is a value too.
642fn values(raw: &str) -> Vec<String> {
643    match raw.strip_suffix('\0') {
644        Some(body) => body.split('\0').map(str::to_string).collect(),
645        None => Vec::new(),
646    }
647}
648
649/// Move the `amont.*` keys of `scope` to `greengate.*` (or back); how many
650/// keys moved. Each value the old key holds is added to the new one unless
651/// already there (a migration interrupted between two `--add`s resumes
652/// without losing one), and the old key goes only once every value is
653/// present. A new key that holds a value of its own was set by the person:
654/// the new name wins, and the old values are dropped. `amont.agent.*` is
655/// greenpiste's, never moved. A `cluster.namespace` of `amont-gates` is
656/// dropped on the way forward: 4.0's default namespace is `greengate-gates`.
657pub fn move_keys(
658    scope: &Scope,
659    direction: Direction,
660    git: &GitFn<'_>,
661) -> Result<usize, MigrateError> {
662    let (from, to) = match direction {
663        Direction::Forward => (old::CONFIG_PREFIX, n::CONFIG_PREFIX),
664        Direction::Reverse => (n::CONFIG_PREFIX, old::CONFIG_PREFIX),
665    };
666    let (dir, flag) = match scope {
667        Scope::Local(common) => (Some(common.as_path()), "--local"),
668        Scope::Global => (None, "--global"),
669    };
670    let pattern = format!("^{}", from.replace('.', r"\."));
671    let listed = run_git(
672        git,
673        dir,
674        &["config", flag, "--name-only", "--get-regexp", &pattern],
675    )?
676    .unwrap_or_default();
677    // One line per VALUE, in file order: a key whose values another key
678    // separates is listed twice, apart.
679    let keys: std::collections::BTreeSet<&str> = listed
680        .lines()
681        .filter(|k| !k.is_empty() && !k.starts_with(old::FOREIGN_PREFIX))
682        .collect();
683    let mut moved = 0;
684    for key in keys {
685        let rest = &key[from.len()..];
686        let target = format!("{to}{rest}");
687        let old_values = values(
688            &run_git(git, dir, &["config", flag, "-z", "--get-all", key])?.unwrap_or_default(),
689        );
690        let new_values = values(
691            &run_git(git, dir, &["config", flag, "-z", "--get-all", &target])?.unwrap_or_default(),
692        );
693        let owned_by_person = new_values.iter().any(|v| !old_values.contains(v));
694        if !owned_by_person {
695            for value in &old_values {
696                let dropped = direction == Direction::Forward
697                    && rest.eq_ignore_ascii_case("cluster.namespace")
698                    && value == old::CLUSTER_NAMESPACE;
699                if dropped || new_values.contains(value) {
700                    continue;
701                }
702                run_git(git, dir, &["config", flag, "--add", &target, value])?;
703            }
704        }
705        run_git(git, dir, &["config", flag, "--unset-all", key])?;
706        moved += 1;
707    }
708    Ok(moved)
709}
710
711/// The machine's global keys, once: a marker in greengate's config folder,
712/// written under a lock there. A config that names no `[amont` section
713/// needs no git, and then a config folder that cannot be made (a read-only
714/// HOME in a container) is no reason to refuse; the files are read again
715/// on the next run, which costs no process either. A held
716/// `~/.gitconfig.lock` (another git writing) is retried for a few seconds.
717fn ensure_global(git: &GitFn<'_>) -> Result<Moved, MigrateError> {
718    let Some(dir) = config_dir() else {
719        return Ok(Moved::default());
720    };
721    let marker = dir.join(n::MIGRATED_MARKER);
722    if marker.exists() || dir.join(n::REVERSED_MARKER).exists() {
723        return Ok(Moved::default());
724    }
725    let Some(holds) = may_hold(&global_config_files(), Direction::Forward) else {
726        // An unreadable global config: git cannot read it either. The keys
727        // wait for a run that can.
728        return Ok(Moved::default());
729    };
730    if std::fs::create_dir_all(&dir).is_err() && !holds {
731        return Ok(Moved::default());
732    }
733    std::fs::create_dir_all(&dir).map_err(io("make", &dir))?;
734    let _lock = lock(&dir.join(n::MIGRATE_LOCK))?;
735    if marker.exists() || dir.join(n::REVERSED_MARKER).exists() {
736        return Ok(Moved::default());
737    }
738    let mut moved = Moved::default();
739    if holds {
740        // Another git writing `~/.gitconfig` holds its `.lock` for a moment:
741        // retried for up to five seconds. Any other failure is reported at
742        // once.
743        let mut attempts = 0;
744        moved.keys = loop {
745            match move_keys(&Scope::Global, Direction::Forward, git) {
746                Err(MigrateError::Git { why, .. }) if why.contains(".lock") && attempts < 50 => {
747                    attempts += 1;
748                    std::thread::sleep(std::time::Duration::from_millis(100));
749                }
750                done => break done?,
751            }
752        };
753    }
754    std::fs::write(&marker, format!("{}-v1\n", n::MIGRATED_MARKER))
755        .map_err(io("write", &marker))?;
756    Ok(moved)
757}
758
759/// Forget that the global keys were moved or reversed, so the next
760/// [`ensure`] reads the global config again: `greengate migrate --global`.
761pub fn forget_global() -> Result<(), MigrateError> {
762    match config_dir() {
763        Some(dir) => {
764            remove_if_present(&dir.join(n::MIGRATED_MARKER))?;
765            remove_if_present(&dir.join(n::REVERSED_MARKER))
766        }
767        None => Ok(()),
768    }
769}
770
771/// Whether any of `files` names a section of the namespace `direction`
772/// moves from: `[amont]`, `[amont "…"]` (forward) or the greengate ones
773/// (reverse), in any case: `None` when a file exists but cannot be read.
774/// An `include.path` is read by git and not here: a key reached only
775/// through an include is left for `greengate doctor` to name.
776fn may_hold(files: &[PathBuf], direction: Direction) -> Option<bool> {
777    let section = match direction {
778        Direction::Forward => "[amont",
779        Direction::Reverse => "[greengate",
780    };
781    let mut holds = false;
782    for file in files {
783        let found = match std::fs::read(file) {
784            Ok(bytes) => String::from_utf8_lossy(&bytes)
785                .to_ascii_lowercase()
786                .lines()
787                .any(|line| {
788                    let line = line.trim_start();
789                    line.starts_with(section)
790                        && matches!(
791                            line[section.len()..].chars().next(),
792                            Some(']' | ' ' | '"' | '.')
793                        )
794                }),
795            Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
796            Err(_) => return None,
797        };
798        holds |= found;
799    }
800    Some(holds)
801}
802
803/// The files `git config --global` reads: `$GIT_CONFIG_GLOBAL` when set,
804/// else `$XDG_CONFIG_HOME/git/config` (or `~/.config/git/config`) and
805/// `~/.gitconfig`.
806fn global_config_files() -> Vec<PathBuf> {
807    if let Some(f) = std::env::var_os("GIT_CONFIG_GLOBAL").filter(|f| !f.is_empty()) {
808        return vec![PathBuf::from(f)];
809    }
810    let home = std::env::var_os("HOME").map(PathBuf::from);
811    let xdg = std::env::var_os("XDG_CONFIG_HOME")
812        .filter(|d| !d.is_empty())
813        .map(PathBuf::from)
814        .or_else(|| home.as_ref().map(|h| h.join(".config")));
815    let mut files = Vec::new();
816    if let Some(x) = xdg {
817        files.push(x.join("git").join("config"));
818    }
819    if let Some(h) = home {
820        files.push(h.join(".gitconfig"));
821    }
822    files
823}
824
825/// Move the machine's global keys back: `greengate migrate --reverse
826/// --global`.
827pub fn reverse_global(git: &GitFn<'_>) -> Result<Moved, MigrateError> {
828    // The reversed marker first, as for a repository: until `migrate
829    // --global`, 4.0 leaves the machine's keys under 3.x's names.
830    let mut _lock = None;
831    if let Some(dir) = config_dir() {
832        std::fs::create_dir_all(&dir).map_err(io("make", &dir))?;
833        // Under the machine lock, so a first run that passed its check
834        // before this started cannot move the keys forward again.
835        _lock = Some(lock(&dir.join(n::MIGRATE_LOCK))?);
836        let reversed = dir.join(n::REVERSED_MARKER);
837        std::fs::write(&reversed, format!("{}-v1\n", n::REVERSED_MARKER))
838            .map_err(io("write", &reversed))?;
839        remove_if_present(&dir.join(n::MIGRATED_MARKER))?;
840    }
841    let keys = move_keys(&Scope::Global, Direction::Reverse, git)?;
842    Ok(Moved { state: 0, keys })
843}
844
845/// greengate's folder of machine state: `$XDG_CONFIG_HOME/greengate`, else
846/// `~/.config/greengate`.
847pub fn config_dir() -> Option<PathBuf> {
848    if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|d| !d.is_empty()) {
849        return Some(PathBuf::from(x).join(n::STATE_DIR));
850    }
851    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
852    Some(PathBuf::from(home).join(".config").join(n::STATE_DIR))
853}
854
855/// What `greengate doctor` reports: the 3.x names still visible from here,
856/// one line each, with the command that moves them. `Err` when git could
857/// not answer: a failure never reads as "nothing left".
858pub fn leftovers(cwd: &Path, git: &GitFn<'_>) -> Result<Vec<String>, MigrateError> {
859    let mut out = Vec::new();
860    let mut env: Vec<String> = std::env::vars_os()
861        .filter_map(|(k, _)| k.into_string().ok())
862        .filter(|k| k.starts_with(old::ENV_PREFIX) && !k.starts_with(old::FOREIGN_ENV_PREFIX))
863        .collect();
864    env.sort();
865    for k in env {
866        let rest = &k[old::ENV_PREFIX.len()..];
867        let new = match rest {
868            "HOST_SLOT" => greenharness_slots::HELD_ENV.to_string(),
869            "SLOT_DIR" => greenharness_slots::DIR_ENV.to_string(),
870            _ => format!("{}_{rest}", n::ENV_PREFIX),
871        };
872        out.push(format!(
873            "environment: {k} is ignored by greengate 4.0; set {new} instead"
874        ));
875    }
876    let pattern = r"^amont\.";
877    let listed = |dir: Option<&Path>, flag: &str| -> Result<Vec<String>, MigrateError> {
878        let names = run_git(
879            git,
880            dir,
881            &["config", flag, "--name-only", "--get-regexp", pattern],
882        )?
883        .unwrap_or_default();
884        Ok(names
885            .lines()
886            .filter(|k| !k.starts_with(old::FOREIGN_PREFIX))
887            .collect::<std::collections::BTreeSet<_>>()
888            .into_iter()
889            .map(str::to_string)
890            .collect())
891    };
892    if config_dir().is_some_and(|dir| dir.join(n::REVERSED_MARKER).exists()) {
893        out.push(format!(
894            "reversed: the global keys were moved back to greengate 3.x's names; \
895             greengate 4.0 leaves them until `{} migrate --global`",
896            n::BIN
897        ));
898    }
899    for key in listed(None, "--global")? {
900        out.push(format!(
901            "global config: {key} is ignored by greengate 4.0; `{} migrate --global` moves it",
902            n::BIN
903        ));
904    }
905    // The migration copies the kubeconfig path as it is, and 3.x's logs in as
906    // the runner of the namespace 4.0 no longer uses: every cluster gate
907    // would be refused, and quietly run here instead.
908    let kubeconfig = run_git(
909        git,
910        None,
911        &[
912            "config",
913            "--global",
914            "--get",
915            "greengate.cluster.kubeconfig",
916        ],
917    )?
918    .unwrap_or_default();
919    if old_kubeconfig(kubeconfig.trim()) {
920        out.push(format!(
921            "cluster: greengate.cluster.kubeconfig is greengate 3.x's ({}), which logs in \
922             as the old namespace's runner; run homelab's \
923             scripts/greengate-gates-kubeconfig.sh, then \
924             `git config --global greengate.cluster.kubeconfig ~/.config/{}/kube/homelab.yaml`",
925            kubeconfig.trim(),
926            n::STATE_DIR
927        ));
928    }
929    if let Some(repo) = Repo::locate(cwd) {
930        if repo.common.join(n::REVERSED_MARKER).exists() {
931            out.push(format!(
932                "reversed: this repository was moved back to greengate 3.x's names; \
933                 greengate 4.0 leaves it until `{} migrate`",
934                n::BIN
935            ));
936        }
937        for key in listed(Some(&repo.common), "--local")? {
938            out.push(format!(
939                "local config: {key} is ignored by greengate 4.0; `{} migrate` moves it",
940                n::BIN
941            ));
942        }
943        for dir in repo.git_dirs() {
944            for m in MOVES {
945                if dir.join(m.old).exists() {
946                    out.push(format!(
947                        "state: {} was left by greengate 3.x; `{} migrate` moves it",
948                        dir.join(m.old).display(),
949                        n::BIN
950                    ));
951                }
952            }
953            if let Some(store) = old_held_store(&dir) {
954                out.push(format!(
955                    "state: {} holds parked changes; `{} restore` puts them back",
956                    store.display(),
957                    n::BIN
958                ));
959            }
960        }
961    }
962    Ok(out)
963}
964
965/// Is `path` a kubeconfig under greengate 3.x's config folder?
966fn old_kubeconfig(path: &str) -> bool {
967    let folder = format!("/.config/{}/", old::STATE_DIR);
968    path.replace('\\', "/").contains(&folder)
969}
970
971/// git, with `GIT_DIR` set to `dir` when one is given, as [`GitFn`] says.
972pub fn system_git(dir: Option<&Path>, args: &[&str]) -> Result<Option<String>, String> {
973    let mut cmd = std::process::Command::new("git");
974    if let Some(dir) = dir {
975        cmd.env("GIT_DIR", dir);
976    }
977    let out = cmd
978        .args(args)
979        .stdin(std::process::Stdio::null())
980        .output()
981        .map_err(|e| e.to_string())?;
982    match out.status.code() {
983        Some(0) => Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned())),
984        Some(1) => Ok(None),
985        code => Err(format!(
986            "exit {}: {}",
987            code.map_or("signal".to_string(), |c| c.to_string()),
988            String::from_utf8_lossy(&out.stderr).trim()
989        )),
990    }
991}
992
993#[cfg(test)]
994mod tests {
995    use super::*;
996
997    /// A fixed clock: no test here depends on the date.
998    const NOW: u64 = 1_800_000_000;
999
1000    fn scratch(name: &str) -> PathBuf {
1001        let scratch_dir =
1002            std::env::temp_dir().join(format!("greengate-migrate-{name}-{}", std::process::id()));
1003        let _ = std::fs::remove_dir_all(&scratch_dir); // a fresh dir; absent is fine
1004        std::fs::create_dir_all(&scratch_dir).unwrap();
1005        scratch_dir
1006    }
1007
1008    /// git in `repo`, its global config a file of its own, as [`GitFn`].
1009    fn git_in(
1010        repo: &Path,
1011    ) -> impl Fn(Option<&Path>, &[&str]) -> Result<Option<String>, String> + '_ {
1012        move |_dir, args| {
1013            let out = std::process::Command::new("git")
1014                .current_dir(repo)
1015                .env("GIT_CONFIG_GLOBAL", repo.join("global-config"))
1016                .env("GIT_CONFIG_NOSYSTEM", "1")
1017                .args(args)
1018                .output()
1019                .map_err(|e| e.to_string())?;
1020            match out.status.code() {
1021                Some(0) => Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned())),
1022                Some(1) => Ok(None),
1023                code => Err(format!("{code:?}")),
1024            }
1025        }
1026    }
1027
1028    /// The values of `key`, newline-joined; empty when unset.
1029    fn get(git: &GitFn<'_>, key: &str) -> String {
1030        git(None, &["config", "--get-all", key])
1031            .unwrap()
1032            .unwrap_or_default()
1033    }
1034
1035    fn init(dir: &Path) {
1036        let ok = std::process::Command::new("git")
1037            .args(["init", "-q"])
1038            .arg(dir)
1039            .status()
1040            .unwrap()
1041            .success();
1042        assert!(ok);
1043    }
1044
1045    #[test]
1046    fn three_x_state_moves_with_its_headers_and_a_second_run_is_a_no_op() {
1047        let root = scratch("state");
1048        init(&root);
1049        let gd = root.join(".git");
1050        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n1 abc gate\n").unwrap();
1051        std::fs::write(
1052            gd.join("amont-waves"),
1053            "amont-waves-v1\n1 2\namont-waves-v1\n3 4\n",
1054        )
1055        .unwrap();
1056        std::fs::create_dir_all(gd.join("amont/logs")).unwrap();
1057        std::fs::write(gd.join("amont/logs/x.log"), "log").unwrap();
1058        std::fs::create_dir_all(gd.join("amont-cache/cargo-test")).unwrap();
1059
1060        let repo = Repo::locate_with(&root, None).unwrap();
1061        let git = git_in(&root);
1062        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1063
1064        assert_eq!(
1065            std::fs::read_to_string(gd.join(n::BYPASS_LEDGER)).unwrap(),
1066            "greengate-bypass-v1\n1 abc gate\n"
1067        );
1068        assert_eq!(
1069            std::fs::read_to_string(gd.join(n::WAVES_LEDGER)).unwrap(),
1070            "greengate-waves-v1\n1 2\ngreengate-waves-v1\n3 4\n"
1071        );
1072        assert!(gd.join("greengate/logs/x.log").is_file());
1073        assert!(gd.join(n::TREE_CACHE).join("cargo-test").is_dir());
1074        for old in ["amont-bypasses", "amont-waves", "amont", "amont-cache"] {
1075            assert!(!gd.join(old).exists(), "{old} left behind");
1076        }
1077        assert!(repo.marker().is_file());
1078        // A second run, marker or not, changes nothing.
1079        std::fs::remove_file(repo.marker()).unwrap();
1080        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1081        assert!(gd.join(n::BYPASS_LEDGER).is_file());
1082    }
1083
1084    #[test]
1085    fn an_interrupted_move_resumes_and_both_names_are_refused() {
1086        let root = scratch("resume");
1087        init(&root);
1088        let gd = root.join(".git");
1089        // A crash after the header rewrite, before the rename.
1090        std::fs::write(
1091            gd.join("amont-downgrades"),
1092            "greengate-downgrade-v1\n1 a b c\n",
1093        )
1094        .unwrap();
1095        move_state(&gd, Direction::Forward).unwrap();
1096        assert_eq!(
1097            std::fs::read_to_string(gd.join(n::DOWNGRADE_LEDGER)).unwrap(),
1098            "greengate-downgrade-v1\n1 a b c\n"
1099        );
1100        // Both names: refused, nothing moved.
1101        std::fs::write(gd.join("amont-downgrades"), "amont-downgrade-v1\n").unwrap();
1102        let err = move_state(&gd, Direction::Forward).unwrap_err();
1103        assert!(matches!(err, MigrateError::BothExist { .. }), "{err}");
1104        assert!(gd.join("amont-downgrades").is_file());
1105    }
1106
1107    #[test]
1108    fn linked_worktrees_are_walked_and_a_held_store_refuses() {
1109        let root = scratch("worktrees");
1110        init(&root);
1111        let wt = root.join(".git/worktrees/side");
1112        std::fs::create_dir_all(&wt).unwrap();
1113        std::fs::write(wt.join("amont-skew"), "amont-skew-v1\n3.0.0\n").unwrap();
1114        let repo = Repo::locate_with(&root, None).unwrap();
1115        assert_eq!(repo.worktrees(), vec![wt.clone()]);
1116        std::fs::create_dir_all(wt.join("amont-held")).unwrap();
1117        let git = git_in(&root);
1118        let err = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err();
1119        assert_eq!(
1120            err,
1121            MigrateError::HeldStore {
1122                path: wt.join("amont-held")
1123            }
1124        );
1125        assert!(err.to_string().contains("restore"), "{err}");
1126        assert!(
1127            wt.join("amont-skew").is_file(),
1128            "nothing moved while refused"
1129        );
1130        assert!(!repo.marker().exists());
1131        std::fs::remove_dir(wt.join("amont-held")).unwrap();
1132        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1133        assert_eq!(
1134            std::fs::read_to_string(wt.join(n::SKEW_MARKER)).unwrap(),
1135            "greengate-skew-v1\n3.0.0\n"
1136        );
1137    }
1138
1139    #[test]
1140    fn the_old_audit_cache_ref_is_deleted_and_an_absent_one_is_no_error() {
1141        let root = scratch("auditref");
1142        init(&root);
1143        let git = git_in(&root);
1144        let repo = Repo::locate_with(&root, None).unwrap();
1145        // Absent: no error, no ref.
1146        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1147        for args in [
1148            vec![
1149                "-c",
1150                "user.name=t",
1151                "-c",
1152                "user.email=t@t",
1153                "commit",
1154                "--allow-empty",
1155                "-qm",
1156                "x",
1157            ],
1158            vec![
1159                "-c",
1160                "user.name=t",
1161                "-c",
1162                "user.email=t@t",
1163                "notes",
1164                "--ref",
1165                "amont-audit",
1166                "add",
1167                "-m",
1168                "n",
1169                "HEAD",
1170            ],
1171            vec![
1172                "-c",
1173                "user.name=t",
1174                "-c",
1175                "user.email=t@t",
1176                "notes",
1177                "--ref",
1178                "greengate-audit",
1179                "add",
1180                "-m",
1181                "n",
1182                "HEAD",
1183            ],
1184        ] {
1185            git(None, &args).unwrap();
1186        }
1187        // `greengate migrate` clears the done-marker first; so does this.
1188        std::fs::remove_file(repo.marker()).unwrap();
1189        let refs = || {
1190            git(None, &["for-each-ref", "refs/notes"])
1191                .unwrap()
1192                .unwrap_or_default()
1193        };
1194        assert!(refs().contains("refs/notes/amont-audit"), "{}", refs());
1195        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1196        assert!(!refs().contains("amont-audit"), "{}", refs());
1197        assert!(
1198            refs().contains("refs/notes/greengate-audit"),
1199            "the new one stays"
1200        );
1201        // And again, with it packed: still deleted.
1202        git(
1203            None,
1204            &[
1205                "-c",
1206                "user.name=t",
1207                "-c",
1208                "user.email=t@t",
1209                "notes",
1210                "--ref",
1211                "amont-audit",
1212                "add",
1213                "-fm",
1214                "n",
1215                "HEAD",
1216            ],
1217        )
1218        .unwrap();
1219        git(None, &["pack-refs", "--all"]).unwrap();
1220        std::fs::remove_file(repo.marker()).unwrap();
1221        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1222        assert!(!refs().contains("amont-audit"), "{}", refs());
1223    }
1224
1225    #[test]
1226    fn local_keys_move_with_every_value_and_the_new_name_wins() {
1227        let root = scratch("keys");
1228        init(&root);
1229        let git = git_in(&root);
1230        for args in [
1231            ["config", "--add", "amont.trusted", "aaa"],
1232            ["config", "--add", "amont.timeout", "600"],
1233            // Another key between two values: listed twice, apart.
1234            ["config", "--add", "amont.trusted", "bbb"],
1235            ["config", "--add", "greengate.timeout", "900"],
1236            ["config", "--add", "amont.cluster.namespace", "amont-gates"],
1237            ["config", "--add", "amont.agent.suppressions", "allow"],
1238        ] {
1239            git(None, &args).unwrap();
1240        }
1241        let repo = Repo::locate_with(&root, None).unwrap();
1242        let moved = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1243        assert_eq!(moved.keys, 3, "trusted, timeout, cluster.namespace");
1244        assert_eq!(get(&git, "greengate.trusted"), "aaa\nbbb\n");
1245        assert_eq!(get(&git, "greengate.timeout"), "900\n", "the new name wins");
1246        assert_eq!(get(&git, "greengate.cluster.namespace"), "");
1247        assert_eq!(get(&git, "amont.trusted"), "");
1248        assert_eq!(get(&git, "amont.timeout"), "");
1249        assert_eq!(get(&git, "amont.agent.suppressions"), "allow\n");
1250
1251        // And back: the reverse restores the 3.x names, and 4.0 then leaves
1252        // the repository alone until asked.
1253        migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap();
1254        assert_eq!(get(&git, "amont.trusted"), "aaa\nbbb\n");
1255        assert_eq!(get(&git, "greengate.trusted"), "");
1256        assert!(!repo.marker().exists());
1257        assert!(repo.common.join(n::REVERSED_MARKER).is_file());
1258        // The repository half only: the global half reads this machine's
1259        // config home, which a unit test must not touch.
1260        ensure_repo(&root, &git, NOW).unwrap();
1261        assert_eq!(
1262            get(&git, "amont.trusted"),
1263            "aaa\nbbb\n",
1264            "a reverse is not undone"
1265        );
1266    }
1267
1268    #[test]
1269    fn a_copy_cut_off_between_two_values_resumes_without_losing_one() {
1270        let root = scratch("partial");
1271        init(&root);
1272        let git = git_in(&root);
1273        for args in [
1274            ["config", "--add", "amont.trusted", "aaa"],
1275            ["config", "--add", "amont.trusted", "bbb"],
1276            ["config", "--add", "amont.trusted", "ccc"],
1277            // The first run stopped after one `--add`.
1278            ["config", "--add", "greengate.trusted", "aaa"],
1279        ] {
1280            git(None, &args).unwrap();
1281        }
1282        move_keys(&Scope::Local(root.join(".git")), Direction::Forward, &git).unwrap();
1283        assert_eq!(get(&git, "greengate.trusted"), "aaa\nbbb\nccc\n");
1284        assert_eq!(get(&git, "amont.trusted"), "");
1285    }
1286
1287    #[test]
1288    fn a_git_that_fails_stops_the_move_and_keeps_the_old_key() {
1289        let root = scratch("git-fails");
1290        init(&root);
1291        let real = git_in(&root);
1292        real(None, &["config", "--add", "amont.trusted", "aaa"]).unwrap();
1293        let failing = |dir: Option<&Path>, args: &[&str]| -> Result<Option<String>, String> {
1294            if args.contains(&"--add") {
1295                return Err("exit 255: could not lock config file".into());
1296            }
1297            real(dir, args)
1298        };
1299        let err = move_keys(
1300            &Scope::Local(root.join(".git")),
1301            Direction::Forward,
1302            &failing,
1303        )
1304        .unwrap_err();
1305        assert!(matches!(err, MigrateError::Git { .. }), "{err}");
1306        assert_eq!(get(&real, "amont.trusted"), "aaa\n", "the old key stays");
1307    }
1308
1309    #[test]
1310    fn a_3x_pending_file_this_version_cannot_read_refuses_the_move() {
1311        // The TTL rule itself is tested beside the file's owner
1312        // (`cluster::detached::collect`, `lists_live`).
1313        let root = scratch("pending");
1314        init(&root);
1315        let gd = root.join(".git");
1316        std::fs::create_dir_all(gd.join("amont")).unwrap();
1317        let pending = gd.join("amont/cluster-pending");
1318        std::fs::write(&pending, "{\"format\":1,\"records\":[{\"name\":\"x\"}]}\n").unwrap();
1319        let repo = Repo::locate_with(&root, None).unwrap();
1320        let git = git_in(&root);
1321        let err = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err();
1322        assert!(
1323            matches!(err, MigrateError::PendingUnreadable { .. }),
1324            "{err}"
1325        );
1326        assert!(err.to_string().contains("rm "), "{err}");
1327        std::fs::write(&pending, "{\"format\":1,\"records\":[]}\n").unwrap();
1328        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1329        assert!(gd.join("greengate/cluster-pending").is_file());
1330    }
1331
1332    #[test]
1333    fn a_live_3x_run_refuses_the_move_and_an_expired_one_lets_it_through() {
1334        let root = scratch("pending-live");
1335        init(&root);
1336        let gd = root.join(".git");
1337        std::fs::create_dir_all(gd.join("amont")).unwrap();
1338        let pending = gd.join("amont/cluster-pending");
1339        std::fs::write(&pending, crate::cluster::sample_pending_file(NOW)).unwrap();
1340        let repo = Repo::locate_with(&root, None).unwrap();
1341        let git = git_in(&root);
1342        assert_eq!(
1343            migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err(),
1344            MigrateError::PendingDetached {
1345                path: pending.clone()
1346            }
1347        );
1348        // The same file, a week later: the run is past its Workflow's TTL.
1349        migrate_repo(&repo, Direction::Forward, &git, NOW + 7 * 86_400).unwrap();
1350        assert!(gd.join("greengate/cluster-pending").is_file());
1351    }
1352
1353    /// The other way round: 3.x cannot collect a run 4.0 submitted, so a
1354    /// reverse waits for it, and moves nothing meanwhile.
1355    #[test]
1356    fn a_live_4_0_run_refuses_a_reverse() {
1357        let root = scratch("pending-reverse");
1358        init(&root);
1359        let gd = root.join(".git");
1360        std::fs::create_dir_all(gd.join(n::STATE_DIR)).unwrap();
1361        let pending = gd.join(n::STATE_DIR).join(crate::cluster::PENDING_FILE);
1362        std::fs::write(&pending, crate::cluster::sample_pending_file(NOW)).unwrap();
1363        let repo = Repo::locate_with(&root, None).unwrap();
1364        let git = git_in(&root);
1365        let err = migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap_err();
1366        assert_eq!(
1367            err,
1368            MigrateError::PendingForDowngrade {
1369                path: pending.clone()
1370            }
1371        );
1372        assert!(err.to_string().contains("cluster collect"), "{err}");
1373        assert!(pending.is_file() && !gd.join(n::REVERSED_MARKER).exists());
1374        migrate_repo(&repo, Direction::Reverse, &git, NOW + 7 * 86_400).unwrap();
1375        assert!(gd
1376            .join(old::STATE_DIR)
1377            .join(crate::cluster::PENDING_FILE)
1378            .is_file());
1379    }
1380
1381    #[test]
1382    fn a_first_run_stands_down_while_a_reverse_is_marked() {
1383        let root = scratch("stand-down");
1384        init(&root);
1385        let gd = root.join(".git");
1386        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n").unwrap();
1387        let repo = Repo::locate_with(&root, None).unwrap();
1388        // The state a reverse leaves: its marker, no done-marker, 3.x names.
1389        std::fs::write(repo.common.join(n::REVERSED_MARKER), "").unwrap();
1390        let git = git_in(&root);
1391        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1392        assert!(gd.join("amont-bypasses").is_file(), "the reverse holds");
1393    }
1394
1395    #[test]
1396    fn a_reverse_that_stops_half_way_is_moved_forward_again() {
1397        let root = scratch("half-reverse");
1398        init(&root);
1399        let gd = root.join(".git");
1400        let git = git_in(&root);
1401        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n").unwrap();
1402        git(None, &["config", "amont.timeout", "700"]).unwrap();
1403        let repo = Repo::locate_with(&root, None).unwrap();
1404        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1405        // A reverse whose key move fails, after the state went back.
1406        let failing = |dir: Option<&Path>, args: &[&str]| -> Result<Option<String>, String> {
1407            if args.contains(&"--add") {
1408                return Err("exit 255: could not lock config file".into());
1409            }
1410            git(dir, args)
1411        };
1412        assert!(migrate_repo(&repo, Direction::Reverse, &failing, NOW).is_err());
1413        assert!(gd.join("amont-bypasses").is_file(), "the state went back");
1414        assert!(!repo.marker().exists(), "no done-marker over 3.x state");
1415        // Asked forward again: everything is under greengate's names.
1416        std::fs::remove_file(repo.common.join(n::REVERSED_MARKER)).unwrap();
1417        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1418        assert!(gd.join(n::BYPASS_LEDGER).is_file());
1419        assert_eq!(get(&git, "greengate.timeout"), "700\n");
1420    }
1421
1422    #[test]
1423    fn a_reverse_refuses_while_4_0_holds_parked_changes() {
1424        let root = scratch("reverse-held");
1425        init(&root);
1426        let gd = root.join(".git");
1427        std::fs::create_dir_all(gd.join(n::HELD_STORE)).unwrap();
1428        let repo = Repo::locate_with(&root, None).unwrap();
1429        let git = git_in(&root);
1430        assert!(matches!(
1431            migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap_err(),
1432            MigrateError::HeldStore { .. }
1433        ));
1434    }
1435
1436    #[test]
1437    fn only_a_file_naming_the_namespace_may_hold_its_keys() {
1438        let root = scratch("may-hold");
1439        let config_file = root.join("config");
1440        std::fs::write(&config_file, "[core]\n\tbare = false\n[amontx]\n\ta = 1\n").unwrap();
1441        assert_eq!(
1442            may_hold(std::slice::from_ref(&config_file), Direction::Forward),
1443            Some(false)
1444        );
1445        for section in ["[amont]", "[Amont \"severity\"]", "  [amont.cluster]"] {
1446            std::fs::write(&config_file, format!("[core]\n{section}\n\tx = 1\n")).unwrap();
1447            assert_eq!(
1448                may_hold(std::slice::from_ref(&config_file), Direction::Forward),
1449                Some(true),
1450                "{section}"
1451            );
1452        }
1453        assert_eq!(
1454            may_hold(std::slice::from_ref(&config_file), Direction::Reverse),
1455            Some(false)
1456        );
1457        assert_eq!(
1458            may_hold(&[root.join("absent")], Direction::Forward),
1459            Some(false)
1460        );
1461    }
1462
1463    #[test]
1464    fn a_state_folder_both_versions_wrote_is_merged() {
1465        let root = scratch("merge");
1466        init(&root);
1467        let gd = root.join(".git");
1468        std::fs::create_dir_all(gd.join("amont/land")).unwrap();
1469        std::fs::create_dir_all(gd.join("greengate/logs")).unwrap();
1470        std::fs::write(gd.join("amont/cluster.log"), "1 old\n").unwrap();
1471        std::fs::write(gd.join("amont/land/r.json"), "{}").unwrap();
1472        std::fs::write(gd.join("greengate/cluster.log"), "2 new\n").unwrap();
1473        move_state(&gd, Direction::Forward).unwrap();
1474        assert!(!gd.join("amont").exists());
1475        assert_eq!(
1476            std::fs::read_to_string(gd.join("greengate/cluster.log")).unwrap(),
1477            "1 old\n2 new\n"
1478        );
1479        assert!(gd.join("greengate/land/r.json").is_file());
1480        assert!(gd.join("greengate/logs").is_dir());
1481        // A clash that is not a log is refused, nothing moved.
1482        std::fs::create_dir_all(gd.join("amont")).unwrap();
1483        std::fs::write(gd.join("amont/cluster-pending"), "a").unwrap();
1484        std::fs::write(gd.join("greengate/cluster-pending"), "b").unwrap();
1485        assert!(matches!(
1486            move_state(&gd, Direction::Forward).unwrap_err(),
1487            MigrateError::BothExist { .. }
1488        ));
1489        assert!(gd.join("amont/cluster-pending").is_file());
1490    }
1491
1492    #[test]
1493    fn the_reverse_puts_state_back_under_3x_names() {
1494        let root = scratch("reverse");
1495        init(&root);
1496        let gd = root.join(".git");
1497        std::fs::write(
1498            gd.join(n::REHEARSAL_STATE),
1499            "greengate-rehearsal-v1\npid=1\n",
1500        )
1501        .unwrap();
1502        move_state(&gd, Direction::Reverse).unwrap();
1503        assert_eq!(
1504            std::fs::read_to_string(gd.join("amont-rehearsal")).unwrap(),
1505            "amont-rehearsal-v1\npid=1\n"
1506        );
1507    }
1508
1509    #[test]
1510    fn a_gitdir_file_is_followed_to_its_common_dir() {
1511        let root = scratch("pointer");
1512        init(&root);
1513        let wt_git = root.join(".git/worktrees/w");
1514        std::fs::create_dir_all(&wt_git).unwrap();
1515        std::fs::write(wt_git.join("commondir"), "../..\n").unwrap();
1516        let checkout = root.join("w");
1517        std::fs::create_dir_all(checkout.join("src")).unwrap();
1518        std::fs::write(
1519            checkout.join(".git"),
1520            format!("gitdir: {}\n", wt_git.display()),
1521        )
1522        .unwrap();
1523        let repo = Repo::locate_with(&checkout.join("src"), None).unwrap();
1524        assert_eq!(
1525            repo.common.canonicalize().unwrap(),
1526            root.join(".git").canonicalize().unwrap()
1527        );
1528    }
1529}