1use std::path::{Path, PathBuf};
34
35pub mod tracked;
36
37use crate::names::old;
39
40struct Move {
42 old: &'static str,
43 new: &'static str,
44 header: Option<(&'static str, &'static str)>,
45}
46
47use crate::names as n;
48
49const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum Direction {
111 Forward,
113 Reverse,
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Repo {
122 pub common: PathBuf,
123}
124
125impl Repo {
126 pub fn locate(start: &Path) -> Option<Repo> {
131 Repo::locate_with(start, std::env::var_os("GIT_DIR"))
132 }
133
134 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 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 pub fn git_dirs(&self) -> Vec<PathBuf> {
166 std::iter::once(self.common.clone())
167 .chain(self.worktrees())
168 .collect()
169 }
170
171 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
185fn 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
202pub 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#[derive(Debug, Clone, PartialEq, Eq)]
212pub enum MigrateError {
213 HeldStore { path: PathBuf },
216 PendingDetached { path: PathBuf },
219 PendingForDowngrade { path: PathBuf },
222 PendingUnreadable { path: PathBuf, why: String },
225 BothCommitted { source: PathBuf, target: PathBuf },
228 BothExist { source: PathBuf, target: PathBuf },
230 Locked { path: PathBuf },
232 Io {
234 op: &'static str,
235 path: PathBuf,
236 why: String,
237 },
238 Git { args: String, why: String },
240}
241
242impl std::error::Error for MigrateError {}
243
244impl MigrateError {
245 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
341const LOCK_DEADLINE: std::time::Duration = std::time::Duration::from_secs(10);
344
345#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
347pub struct Moved {
348 pub state: usize,
350 pub keys: usize,
352}
353
354pub 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
365pub 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
377pub 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 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 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 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 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 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
472fn 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
495fn 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
512pub 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
541fn 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
587fn 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#[derive(Debug, Clone)]
616pub enum Scope {
617 Local(PathBuf),
619 Global,
621}
622
623pub 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
640fn 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
649pub 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 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
711fn 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 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 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
759pub 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
771fn 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
803fn 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
825pub fn reverse_global(git: &GitFn<'_>) -> Result<Moved, MigrateError> {
828 let mut _lock = None;
831 if let Some(dir) = config_dir() {
832 std::fs::create_dir_all(&dir).map_err(io("make", &dir))?;
833 _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
845pub 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
855pub 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 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
965fn old_kubeconfig(path: &str) -> bool {
967 let folder = format!("/.config/{}/", old::STATE_DIR);
968 path.replace('\\', "/").contains(&folder)
969}
970
971pub 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 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); std::fs::create_dir_all(&scratch_dir).unwrap();
1005 scratch_dir
1006 }
1007
1008 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 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 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 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 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 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 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 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 ["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 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 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 ["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 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 migrate_repo(&repo, Direction::Forward, &git, NOW + 7 * 86_400).unwrap();
1350 assert!(gd.join("greengate/cluster-pending").is_file());
1351 }
1352
1353 #[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 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 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 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 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}