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/// greenbelay'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 (and, since 4.4, the
857/// signing key's rename when only the `amont-attest` key exists). `Err` when git could
858/// not answer: a failure never reads as "nothing left".
859pub fn leftovers(cwd: &Path, git: &GitFn<'_>) -> Result<Vec<String>, MigrateError> {
860    let mut out = Vec::new();
861    let mut env: Vec<String> = std::env::vars_os()
862        .filter_map(|(k, _)| k.into_string().ok())
863        .filter(|k| k.starts_with(old::ENV_PREFIX) && !k.starts_with(old::FOREIGN_ENV_PREFIX))
864        .collect();
865    env.sort();
866    for k in env {
867        let rest = &k[old::ENV_PREFIX.len()..];
868        let new = match rest {
869            "HOST_SLOT" => greenharness_slots::HELD_ENV.to_string(),
870            "SLOT_DIR" => greenharness_slots::DIR_ENV.to_string(),
871            _ => format!("{}_{rest}", n::ENV_PREFIX),
872        };
873        out.push(format!(
874            "environment: {k} is ignored by greengate 4.0; set {new} instead"
875        ));
876    }
877    let pattern = r"^amont\.";
878    let listed = |dir: Option<&Path>, flag: &str| -> Result<Vec<String>, MigrateError> {
879        let names = run_git(
880            git,
881            dir,
882            &["config", flag, "--name-only", "--get-regexp", pattern],
883        )?
884        .unwrap_or_default();
885        Ok(names
886            .lines()
887            .filter(|k| !k.starts_with(old::FOREIGN_PREFIX))
888            .collect::<std::collections::BTreeSet<_>>()
889            .into_iter()
890            .map(str::to_string)
891            .collect())
892    };
893    if config_dir().is_some_and(|dir| dir.join(n::REVERSED_MARKER).exists()) {
894        out.push(format!(
895            "reversed: the global keys were moved back to greengate 3.x's names; \
896             greengate 4.0 leaves them until `{} migrate --global`",
897            n::BIN
898        ));
899    }
900    for key in listed(None, "--global")? {
901        out.push(format!(
902            "global config: {key} is ignored by greengate 4.0; `{} migrate --global` moves it",
903            n::BIN
904        ));
905    }
906    // The migration copies the kubeconfig path as it is, and 3.x's logs in as
907    // the runner of the namespace 4.0 no longer uses: every cluster gate
908    // would be refused, and quietly run here instead.
909    let kubeconfig = run_git(
910        git,
911        None,
912        &[
913            "config",
914            "--global",
915            "--get",
916            "greengate.cluster.kubeconfig",
917        ],
918    )?
919    .unwrap_or_default();
920    if old_kubeconfig(kubeconfig.trim()) {
921        out.push(format!(
922            "cluster: greengate.cluster.kubeconfig is greengate 3.x's ({}), which logs in \
923             as the old namespace's runner; run homelab's \
924             scripts/greengate-gates-kubeconfig.sh, then \
925             `git config --global greengate.cluster.kubeconfig ~/.config/{}/kube/homelab.yaml`",
926            kubeconfig.trim(),
927            n::STATE_DIR
928        ));
929    }
930    // The signing key moved names with the notes (greengate 4.4). Signing
931    // never fails because of the old name: the old path is used while the
932    // new one is absent. But doctor exits 1 on this line like any leftover
933    // until the key is renamed. Not said when a key path is configured; the
934    // config is read in the repository when there is one.
935    let located = Repo::locate(cwd);
936    let configured = run_git(
937        git,
938        located.as_ref().map(|r| r.common.as_path()),
939        &["config", "--get", crate::attest::KEY_CONFIG],
940    )?
941    .is_some_and(|k| !k.trim().is_empty());
942    if !configured {
943        if let Some(line) = std::env::var_os("HOME")
944            .or_else(|| std::env::var_os("USERPROFILE"))
945            .and_then(|home| crate::attest::key_move_hint_in(Path::new(&home)))
946        {
947            out.push(format!("signing key: {line}"));
948        }
949    }
950    if let Some(repo) = located {
951        // Signer blocks an older greengate filed locally under the old notes
952        // name: nothing reads them any more (the census removes them).
953        let old_refs = run_git(
954            git,
955            Some(&repo.common),
956            &[
957                "for-each-ref",
958                "--format=%(refname)",
959                "refs/notes/attest-local/amont-*",
960            ],
961        )?
962        .unwrap_or_default();
963        for name in old_refs.lines().filter(|l| !l.trim().is_empty()) {
964            out.push(format!(
965                "local notes: {name} was left by an older greengate and is no longer read; `git update-ref -d {name}` removes it"
966            ));
967        }
968        if repo.common.join(n::REVERSED_MARKER).exists() {
969            out.push(format!(
970                "reversed: this repository was moved back to greengate 3.x's names; \
971                 greengate 4.0 leaves it until `{} migrate`",
972                n::BIN
973            ));
974        }
975        for key in listed(Some(&repo.common), "--local")? {
976            out.push(format!(
977                "local config: {key} is ignored by greengate 4.0; `{} migrate` moves it",
978                n::BIN
979            ));
980        }
981        for dir in repo.git_dirs() {
982            for m in MOVES {
983                if dir.join(m.old).exists() {
984                    out.push(format!(
985                        "state: {} was left by greengate 3.x; `{} migrate` moves it",
986                        dir.join(m.old).display(),
987                        n::BIN
988                    ));
989                }
990            }
991            if let Some(store) = old_held_store(&dir) {
992                out.push(format!(
993                    "state: {} holds parked changes; `{} restore` puts them back",
994                    store.display(),
995                    n::BIN
996                ));
997            }
998        }
999    }
1000    Ok(out)
1001}
1002
1003/// Is `path` a kubeconfig under greengate 3.x's config folder?
1004fn old_kubeconfig(path: &str) -> bool {
1005    let folder = format!("/.config/{}/", old::STATE_DIR);
1006    path.replace('\\', "/").contains(&folder)
1007}
1008
1009/// git, with `GIT_DIR` set to `dir` when one is given, as [`GitFn`] says.
1010pub fn system_git(dir: Option<&Path>, args: &[&str]) -> Result<Option<String>, String> {
1011    let mut cmd = std::process::Command::new("git");
1012    if let Some(dir) = dir {
1013        cmd.env("GIT_DIR", dir);
1014    }
1015    let out = cmd
1016        .args(args)
1017        .stdin(std::process::Stdio::null())
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!(
1024            "exit {}: {}",
1025            code.map_or("signal".to_string(), |c| c.to_string()),
1026            String::from_utf8_lossy(&out.stderr).trim()
1027        )),
1028    }
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033    use super::*;
1034
1035    /// A fixed clock: no test here depends on the date.
1036    const NOW: u64 = 1_800_000_000;
1037
1038    fn scratch(name: &str) -> PathBuf {
1039        let scratch_dir =
1040            std::env::temp_dir().join(format!("greengate-migrate-{name}-{}", std::process::id()));
1041        let _ = std::fs::remove_dir_all(&scratch_dir); // a fresh dir; absent is fine
1042        std::fs::create_dir_all(&scratch_dir).unwrap();
1043        scratch_dir
1044    }
1045
1046    /// git in `repo`, its global config a file of its own, as [`GitFn`].
1047    fn git_in(
1048        repo: &Path,
1049    ) -> impl Fn(Option<&Path>, &[&str]) -> Result<Option<String>, String> + '_ {
1050        move |_dir, args| {
1051            let out = std::process::Command::new("git")
1052                .current_dir(repo)
1053                .env("GIT_CONFIG_GLOBAL", repo.join("global-config"))
1054                .env("GIT_CONFIG_NOSYSTEM", "1")
1055                .args(args)
1056                .output()
1057                .map_err(|e| e.to_string())?;
1058            match out.status.code() {
1059                Some(0) => Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned())),
1060                Some(1) => Ok(None),
1061                code => Err(format!("{code:?}")),
1062            }
1063        }
1064    }
1065
1066    /// The values of `key`, newline-joined; empty when unset.
1067    fn get(git: &GitFn<'_>, key: &str) -> String {
1068        git(None, &["config", "--get-all", key])
1069            .unwrap()
1070            .unwrap_or_default()
1071    }
1072
1073    fn init(dir: &Path) {
1074        let ok = std::process::Command::new("git")
1075            .args(["init", "-q"])
1076            .arg(dir)
1077            .status()
1078            .unwrap()
1079            .success();
1080        assert!(ok);
1081    }
1082
1083    #[test]
1084    fn three_x_state_moves_with_its_headers_and_a_second_run_is_a_no_op() {
1085        let root = scratch("state");
1086        init(&root);
1087        let gd = root.join(".git");
1088        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n1 abc gate\n").unwrap();
1089        std::fs::write(
1090            gd.join("amont-waves"),
1091            "amont-waves-v1\n1 2\namont-waves-v1\n3 4\n",
1092        )
1093        .unwrap();
1094        std::fs::create_dir_all(gd.join("amont/logs")).unwrap();
1095        std::fs::write(gd.join("amont/logs/x.log"), "log").unwrap();
1096        std::fs::create_dir_all(gd.join("amont-cache/cargo-test")).unwrap();
1097
1098        let repo = Repo::locate_with(&root, None).unwrap();
1099        let git = git_in(&root);
1100        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1101
1102        assert_eq!(
1103            std::fs::read_to_string(gd.join(n::BYPASS_LEDGER)).unwrap(),
1104            "greengate-bypass-v1\n1 abc gate\n"
1105        );
1106        assert_eq!(
1107            std::fs::read_to_string(gd.join(n::WAVES_LEDGER)).unwrap(),
1108            "greengate-waves-v1\n1 2\ngreengate-waves-v1\n3 4\n"
1109        );
1110        assert!(gd.join("greengate/logs/x.log").is_file());
1111        assert!(gd.join(n::TREE_CACHE).join("cargo-test").is_dir());
1112        for old in ["amont-bypasses", "amont-waves", "amont", "amont-cache"] {
1113            assert!(!gd.join(old).exists(), "{old} left behind");
1114        }
1115        assert!(repo.marker().is_file());
1116        // A second run, marker or not, changes nothing.
1117        std::fs::remove_file(repo.marker()).unwrap();
1118        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1119        assert!(gd.join(n::BYPASS_LEDGER).is_file());
1120    }
1121
1122    #[test]
1123    fn an_interrupted_move_resumes_and_both_names_are_refused() {
1124        let root = scratch("resume");
1125        init(&root);
1126        let gd = root.join(".git");
1127        // A crash after the header rewrite, before the rename.
1128        std::fs::write(
1129            gd.join("amont-downgrades"),
1130            "greengate-downgrade-v1\n1 a b c\n",
1131        )
1132        .unwrap();
1133        move_state(&gd, Direction::Forward).unwrap();
1134        assert_eq!(
1135            std::fs::read_to_string(gd.join(n::DOWNGRADE_LEDGER)).unwrap(),
1136            "greengate-downgrade-v1\n1 a b c\n"
1137        );
1138        // Both names: refused, nothing moved.
1139        std::fs::write(gd.join("amont-downgrades"), "amont-downgrade-v1\n").unwrap();
1140        let err = move_state(&gd, Direction::Forward).unwrap_err();
1141        assert!(matches!(err, MigrateError::BothExist { .. }), "{err}");
1142        assert!(gd.join("amont-downgrades").is_file());
1143    }
1144
1145    #[test]
1146    fn linked_worktrees_are_walked_and_a_held_store_refuses() {
1147        let root = scratch("worktrees");
1148        init(&root);
1149        let wt = root.join(".git/worktrees/side");
1150        std::fs::create_dir_all(&wt).unwrap();
1151        std::fs::write(wt.join("amont-skew"), "amont-skew-v1\n3.0.0\n").unwrap();
1152        let repo = Repo::locate_with(&root, None).unwrap();
1153        assert_eq!(repo.worktrees(), vec![wt.clone()]);
1154        std::fs::create_dir_all(wt.join("amont-held")).unwrap();
1155        let git = git_in(&root);
1156        let err = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err();
1157        assert_eq!(
1158            err,
1159            MigrateError::HeldStore {
1160                path: wt.join("amont-held")
1161            }
1162        );
1163        assert!(err.to_string().contains("restore"), "{err}");
1164        assert!(
1165            wt.join("amont-skew").is_file(),
1166            "nothing moved while refused"
1167        );
1168        assert!(!repo.marker().exists());
1169        std::fs::remove_dir(wt.join("amont-held")).unwrap();
1170        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1171        assert_eq!(
1172            std::fs::read_to_string(wt.join(n::SKEW_MARKER)).unwrap(),
1173            "greengate-skew-v1\n3.0.0\n"
1174        );
1175    }
1176
1177    #[test]
1178    fn the_old_audit_cache_ref_is_deleted_and_an_absent_one_is_no_error() {
1179        let root = scratch("auditref");
1180        init(&root);
1181        let git = git_in(&root);
1182        let repo = Repo::locate_with(&root, None).unwrap();
1183        // Absent: no error, no ref.
1184        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1185        for args in [
1186            vec![
1187                "-c",
1188                "user.name=t",
1189                "-c",
1190                "user.email=t@t",
1191                "commit",
1192                "--allow-empty",
1193                "-qm",
1194                "x",
1195            ],
1196            vec![
1197                "-c",
1198                "user.name=t",
1199                "-c",
1200                "user.email=t@t",
1201                "notes",
1202                "--ref",
1203                "amont-audit",
1204                "add",
1205                "-m",
1206                "n",
1207                "HEAD",
1208            ],
1209            vec![
1210                "-c",
1211                "user.name=t",
1212                "-c",
1213                "user.email=t@t",
1214                "notes",
1215                "--ref",
1216                "greengate-audit",
1217                "add",
1218                "-m",
1219                "n",
1220                "HEAD",
1221            ],
1222        ] {
1223            git(None, &args).unwrap();
1224        }
1225        // `greengate migrate` clears the done-marker first; so does this.
1226        std::fs::remove_file(repo.marker()).unwrap();
1227        let refs = || {
1228            git(None, &["for-each-ref", "refs/notes"])
1229                .unwrap()
1230                .unwrap_or_default()
1231        };
1232        assert!(refs().contains("refs/notes/amont-audit"), "{}", refs());
1233        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1234        assert!(!refs().contains("amont-audit"), "{}", refs());
1235        assert!(
1236            refs().contains("refs/notes/greengate-audit"),
1237            "the new one stays"
1238        );
1239        // And again, with it packed: still deleted.
1240        git(
1241            None,
1242            &[
1243                "-c",
1244                "user.name=t",
1245                "-c",
1246                "user.email=t@t",
1247                "notes",
1248                "--ref",
1249                "amont-audit",
1250                "add",
1251                "-fm",
1252                "n",
1253                "HEAD",
1254            ],
1255        )
1256        .unwrap();
1257        git(None, &["pack-refs", "--all"]).unwrap();
1258        std::fs::remove_file(repo.marker()).unwrap();
1259        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1260        assert!(!refs().contains("amont-audit"), "{}", refs());
1261    }
1262
1263    #[test]
1264    fn local_keys_move_with_every_value_and_the_new_name_wins() {
1265        let root = scratch("keys");
1266        init(&root);
1267        let git = git_in(&root);
1268        for args in [
1269            ["config", "--add", "amont.trusted", "aaa"],
1270            ["config", "--add", "amont.timeout", "600"],
1271            // Another key between two values: listed twice, apart.
1272            ["config", "--add", "amont.trusted", "bbb"],
1273            ["config", "--add", "greengate.timeout", "900"],
1274            ["config", "--add", "amont.cluster.namespace", "amont-gates"],
1275            ["config", "--add", "amont.agent.suppressions", "allow"],
1276        ] {
1277            git(None, &args).unwrap();
1278        }
1279        let repo = Repo::locate_with(&root, None).unwrap();
1280        let moved = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1281        assert_eq!(moved.keys, 3, "trusted, timeout, cluster.namespace");
1282        assert_eq!(get(&git, "greengate.trusted"), "aaa\nbbb\n");
1283        assert_eq!(get(&git, "greengate.timeout"), "900\n", "the new name wins");
1284        assert_eq!(get(&git, "greengate.cluster.namespace"), "");
1285        assert_eq!(get(&git, "amont.trusted"), "");
1286        assert_eq!(get(&git, "amont.timeout"), "");
1287        assert_eq!(get(&git, "amont.agent.suppressions"), "allow\n");
1288
1289        // And back: the reverse restores the 3.x names, and 4.0 then leaves
1290        // the repository alone until asked.
1291        migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap();
1292        assert_eq!(get(&git, "amont.trusted"), "aaa\nbbb\n");
1293        assert_eq!(get(&git, "greengate.trusted"), "");
1294        assert!(!repo.marker().exists());
1295        assert!(repo.common.join(n::REVERSED_MARKER).is_file());
1296        // The repository half only: the global half reads this machine's
1297        // config home, which a unit test must not touch.
1298        ensure_repo(&root, &git, NOW).unwrap();
1299        assert_eq!(
1300            get(&git, "amont.trusted"),
1301            "aaa\nbbb\n",
1302            "a reverse is not undone"
1303        );
1304    }
1305
1306    #[test]
1307    fn a_copy_cut_off_between_two_values_resumes_without_losing_one() {
1308        let root = scratch("partial");
1309        init(&root);
1310        let git = git_in(&root);
1311        for args in [
1312            ["config", "--add", "amont.trusted", "aaa"],
1313            ["config", "--add", "amont.trusted", "bbb"],
1314            ["config", "--add", "amont.trusted", "ccc"],
1315            // The first run stopped after one `--add`.
1316            ["config", "--add", "greengate.trusted", "aaa"],
1317        ] {
1318            git(None, &args).unwrap();
1319        }
1320        move_keys(&Scope::Local(root.join(".git")), Direction::Forward, &git).unwrap();
1321        assert_eq!(get(&git, "greengate.trusted"), "aaa\nbbb\nccc\n");
1322        assert_eq!(get(&git, "amont.trusted"), "");
1323    }
1324
1325    #[test]
1326    fn a_git_that_fails_stops_the_move_and_keeps_the_old_key() {
1327        let root = scratch("git-fails");
1328        init(&root);
1329        let real = git_in(&root);
1330        real(None, &["config", "--add", "amont.trusted", "aaa"]).unwrap();
1331        let failing = |dir: Option<&Path>, args: &[&str]| -> Result<Option<String>, String> {
1332            if args.contains(&"--add") {
1333                return Err("exit 255: could not lock config file".into());
1334            }
1335            real(dir, args)
1336        };
1337        let err = move_keys(
1338            &Scope::Local(root.join(".git")),
1339            Direction::Forward,
1340            &failing,
1341        )
1342        .unwrap_err();
1343        assert!(matches!(err, MigrateError::Git { .. }), "{err}");
1344        assert_eq!(get(&real, "amont.trusted"), "aaa\n", "the old key stays");
1345    }
1346
1347    #[test]
1348    fn a_3x_pending_file_this_version_cannot_read_refuses_the_move() {
1349        // The TTL rule itself is tested beside the file's owner
1350        // (`cluster::detached::collect`, `lists_live`).
1351        let root = scratch("pending");
1352        init(&root);
1353        let gd = root.join(".git");
1354        std::fs::create_dir_all(gd.join("amont")).unwrap();
1355        let pending = gd.join("amont/cluster-pending");
1356        std::fs::write(&pending, "{\"format\":1,\"records\":[{\"name\":\"x\"}]}\n").unwrap();
1357        let repo = Repo::locate_with(&root, None).unwrap();
1358        let git = git_in(&root);
1359        let err = migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err();
1360        assert!(
1361            matches!(err, MigrateError::PendingUnreadable { .. }),
1362            "{err}"
1363        );
1364        assert!(err.to_string().contains("rm "), "{err}");
1365        std::fs::write(&pending, "{\"format\":1,\"records\":[]}\n").unwrap();
1366        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1367        assert!(gd.join("greengate/cluster-pending").is_file());
1368    }
1369
1370    #[test]
1371    fn a_live_3x_run_refuses_the_move_and_an_expired_one_lets_it_through() {
1372        let root = scratch("pending-live");
1373        init(&root);
1374        let gd = root.join(".git");
1375        std::fs::create_dir_all(gd.join("amont")).unwrap();
1376        let pending = gd.join("amont/cluster-pending");
1377        std::fs::write(&pending, crate::cluster::sample_pending_file(NOW)).unwrap();
1378        let repo = Repo::locate_with(&root, None).unwrap();
1379        let git = git_in(&root);
1380        assert_eq!(
1381            migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap_err(),
1382            MigrateError::PendingDetached {
1383                path: pending.clone()
1384            }
1385        );
1386        // The same file, a week later: the run is past its Workflow's TTL.
1387        migrate_repo(&repo, Direction::Forward, &git, NOW + 7 * 86_400).unwrap();
1388        assert!(gd.join("greengate/cluster-pending").is_file());
1389    }
1390
1391    /// The other way round: 3.x cannot collect a run 4.0 submitted, so a
1392    /// reverse waits for it, and moves nothing meanwhile.
1393    #[test]
1394    fn a_live_4_0_run_refuses_a_reverse() {
1395        let root = scratch("pending-reverse");
1396        init(&root);
1397        let gd = root.join(".git");
1398        std::fs::create_dir_all(gd.join(n::STATE_DIR)).unwrap();
1399        let pending = gd.join(n::STATE_DIR).join(crate::cluster::PENDING_FILE);
1400        std::fs::write(&pending, crate::cluster::sample_pending_file(NOW)).unwrap();
1401        let repo = Repo::locate_with(&root, None).unwrap();
1402        let git = git_in(&root);
1403        let err = migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap_err();
1404        assert_eq!(
1405            err,
1406            MigrateError::PendingForDowngrade {
1407                path: pending.clone()
1408            }
1409        );
1410        assert!(err.to_string().contains("cluster collect"), "{err}");
1411        assert!(pending.is_file() && !gd.join(n::REVERSED_MARKER).exists());
1412        migrate_repo(&repo, Direction::Reverse, &git, NOW + 7 * 86_400).unwrap();
1413        assert!(gd
1414            .join(old::STATE_DIR)
1415            .join(crate::cluster::PENDING_FILE)
1416            .is_file());
1417    }
1418
1419    #[test]
1420    fn a_first_run_stands_down_while_a_reverse_is_marked() {
1421        let root = scratch("stand-down");
1422        init(&root);
1423        let gd = root.join(".git");
1424        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n").unwrap();
1425        let repo = Repo::locate_with(&root, None).unwrap();
1426        // The state a reverse leaves: its marker, no done-marker, 3.x names.
1427        std::fs::write(repo.common.join(n::REVERSED_MARKER), "").unwrap();
1428        let git = git_in(&root);
1429        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1430        assert!(gd.join("amont-bypasses").is_file(), "the reverse holds");
1431    }
1432
1433    #[test]
1434    fn a_reverse_that_stops_half_way_is_moved_forward_again() {
1435        let root = scratch("half-reverse");
1436        init(&root);
1437        let gd = root.join(".git");
1438        let git = git_in(&root);
1439        std::fs::write(gd.join("amont-bypasses"), "amont-bypass-v1\n").unwrap();
1440        git(None, &["config", "amont.timeout", "700"]).unwrap();
1441        let repo = Repo::locate_with(&root, None).unwrap();
1442        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1443        // A reverse whose key move fails, after the state went back.
1444        let failing = |dir: Option<&Path>, args: &[&str]| -> Result<Option<String>, String> {
1445            if args.contains(&"--add") {
1446                return Err("exit 255: could not lock config file".into());
1447            }
1448            git(dir, args)
1449        };
1450        assert!(migrate_repo(&repo, Direction::Reverse, &failing, NOW).is_err());
1451        assert!(gd.join("amont-bypasses").is_file(), "the state went back");
1452        assert!(!repo.marker().exists(), "no done-marker over 3.x state");
1453        // Asked forward again: everything is under greengate's names.
1454        std::fs::remove_file(repo.common.join(n::REVERSED_MARKER)).unwrap();
1455        migrate_repo(&repo, Direction::Forward, &git, NOW).unwrap();
1456        assert!(gd.join(n::BYPASS_LEDGER).is_file());
1457        assert_eq!(get(&git, "greengate.timeout"), "700\n");
1458    }
1459
1460    #[test]
1461    fn a_reverse_refuses_while_4_0_holds_parked_changes() {
1462        let root = scratch("reverse-held");
1463        init(&root);
1464        let gd = root.join(".git");
1465        std::fs::create_dir_all(gd.join(n::HELD_STORE)).unwrap();
1466        let repo = Repo::locate_with(&root, None).unwrap();
1467        let git = git_in(&root);
1468        assert!(matches!(
1469            migrate_repo(&repo, Direction::Reverse, &git, NOW).unwrap_err(),
1470            MigrateError::HeldStore { .. }
1471        ));
1472    }
1473
1474    #[test]
1475    fn only_a_file_naming_the_namespace_may_hold_its_keys() {
1476        let root = scratch("may-hold");
1477        let config_file = root.join("config");
1478        std::fs::write(&config_file, "[core]\n\tbare = false\n[amontx]\n\ta = 1\n").unwrap();
1479        assert_eq!(
1480            may_hold(std::slice::from_ref(&config_file), Direction::Forward),
1481            Some(false)
1482        );
1483        for section in ["[amont]", "[Amont \"severity\"]", "  [amont.cluster]"] {
1484            std::fs::write(&config_file, format!("[core]\n{section}\n\tx = 1\n")).unwrap();
1485            assert_eq!(
1486                may_hold(std::slice::from_ref(&config_file), Direction::Forward),
1487                Some(true),
1488                "{section}"
1489            );
1490        }
1491        assert_eq!(
1492            may_hold(std::slice::from_ref(&config_file), Direction::Reverse),
1493            Some(false)
1494        );
1495        assert_eq!(
1496            may_hold(&[root.join("absent")], Direction::Forward),
1497            Some(false)
1498        );
1499    }
1500
1501    #[test]
1502    fn a_state_folder_both_versions_wrote_is_merged() {
1503        let root = scratch("merge");
1504        init(&root);
1505        let gd = root.join(".git");
1506        std::fs::create_dir_all(gd.join("amont/land")).unwrap();
1507        std::fs::create_dir_all(gd.join("greengate/logs")).unwrap();
1508        std::fs::write(gd.join("amont/cluster.log"), "1 old\n").unwrap();
1509        std::fs::write(gd.join("amont/land/r.json"), "{}").unwrap();
1510        std::fs::write(gd.join("greengate/cluster.log"), "2 new\n").unwrap();
1511        move_state(&gd, Direction::Forward).unwrap();
1512        assert!(!gd.join("amont").exists());
1513        assert_eq!(
1514            std::fs::read_to_string(gd.join("greengate/cluster.log")).unwrap(),
1515            "1 old\n2 new\n"
1516        );
1517        assert!(gd.join("greengate/land/r.json").is_file());
1518        assert!(gd.join("greengate/logs").is_dir());
1519        // A clash that is not a log is refused, nothing moved.
1520        std::fs::create_dir_all(gd.join("amont")).unwrap();
1521        std::fs::write(gd.join("amont/cluster-pending"), "a").unwrap();
1522        std::fs::write(gd.join("greengate/cluster-pending"), "b").unwrap();
1523        assert!(matches!(
1524            move_state(&gd, Direction::Forward).unwrap_err(),
1525            MigrateError::BothExist { .. }
1526        ));
1527        assert!(gd.join("amont/cluster-pending").is_file());
1528    }
1529
1530    #[test]
1531    fn the_reverse_puts_state_back_under_3x_names() {
1532        let root = scratch("reverse");
1533        init(&root);
1534        let gd = root.join(".git");
1535        std::fs::write(
1536            gd.join(n::REHEARSAL_STATE),
1537            "greengate-rehearsal-v1\npid=1\n",
1538        )
1539        .unwrap();
1540        move_state(&gd, Direction::Reverse).unwrap();
1541        assert_eq!(
1542            std::fs::read_to_string(gd.join("amont-rehearsal")).unwrap(),
1543            "amont-rehearsal-v1\npid=1\n"
1544        );
1545    }
1546
1547    #[test]
1548    fn a_gitdir_file_is_followed_to_its_common_dir() {
1549        let root = scratch("pointer");
1550        init(&root);
1551        let wt_git = root.join(".git/worktrees/w");
1552        std::fs::create_dir_all(&wt_git).unwrap();
1553        std::fs::write(wt_git.join("commondir"), "../..\n").unwrap();
1554        let checkout = root.join("w");
1555        std::fs::create_dir_all(checkout.join("src")).unwrap();
1556        std::fs::write(
1557            checkout.join(".git"),
1558            format!("gitdir: {}\n", wt_git.display()),
1559        )
1560        .unwrap();
1561        let repo = Repo::locate_with(&checkout.join("src"), None).unwrap();
1562        assert_eq!(
1563            repo.common.canonicalize().unwrap(),
1564            root.join(".git").canonicalize().unwrap()
1565        );
1566    }
1567}