1use crate::names::BIN;
51use std::ffi::OsString;
52use std::io::Write;
53use std::path::{Path, PathBuf};
54use std::process::{Command, Stdio};
55use std::time::{Duration, SystemTime, UNIX_EPOCH};
56
57use crate::hooks::common::{human_secs, warn};
58use crate::ui::{highlight, valid_sign, warning_sign};
59
60const ON_COMMIT: &str = "amont.rehearseOnCommit";
62
63const WAIT_BUDGET: &str = "amont.rehearsalWait";
80
81pub fn wait_budget(settings: &crate::config::Settings) -> Option<Duration> {
82 match crate::config::integer_or(settings, WAIT_BUDGET, 300, 0..=86_400) {
83 0 => None,
84 secs => Some(Duration::from_secs(secs as u64)),
85 }
86}
87
88const STATE: &str = "amont-rehearsal";
90const LOG: &str = "amont-rehearsal.log";
92const FORMAT: &str = "amont-rehearsal-v1";
95
96pub const ENV: &str = "AMONT_REHEARSAL";
102
103pub fn on_commit_enabled(settings: &crate::config::Settings) -> bool {
105 crate::config::boolean_or(settings, ON_COMMIT, false)
106}
107
108const UNSTAMPED_PUSH: &str = "amont.unstampedPush";
121
122pub fn refuse_unstamped(settings: &crate::config::Settings) -> bool {
124 crate::config::enumerated_or(settings, UNSTAMPED_PUSH, &["run", "refuse"], "run") == "refuse"
125}
126
127pub fn in_snapshot() -> bool {
144 snapshot_env().is_some()
145}
146
147const DETACHED_PREFIX: &str = "detached=";
150
151struct SnapshotEnv {
154 detached: Vec<String>,
155 prestage: bool,
158}
159
160const PRESTAGE_PREFIX: &str = "prestage;";
164
165fn parse_snapshot_env(raw: &str) -> SnapshotEnv {
168 let (prestage, rest) = match raw.strip_prefix(PRESTAGE_PREFIX) {
169 Some(rest) => (true, rest),
170 None => (false, raw),
171 };
172 let detached = rest
173 .strip_prefix(DETACHED_PREFIX)
174 .map(|ids| ids.split(',').map(str::to_string).collect())
175 .unwrap_or_default();
176 SnapshotEnv { detached, prestage }
177}
178
179fn snapshot_env() -> &'static Option<SnapshotEnv> {
182 static IN: std::sync::OnceLock<Option<SnapshotEnv>> = std::sync::OnceLock::new();
183 IN.get_or_init(|| {
184 let raw = std::env::var_os(ENV).map(|v| v.to_string_lossy().into_owned())?;
185 std::env::remove_var(ENV);
186 Some(parse_snapshot_env(&raw))
187 })
188}
189
190pub fn in_prestage() -> bool {
193 snapshot_env().as_ref().is_some_and(|env| env.prestage)
194}
195
196pub fn handed_to_cluster() -> &'static [String] {
201 snapshot_env()
202 .as_ref()
203 .map_or(&[], |env| env.detached.as_slice())
204}
205
206pub const LAND_ENV: &str = "AMONT_LAND";
211
212#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct LandLine {
216 pub sha: String,
217 pub remote_tip: String,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
222pub enum LandEnv {
223 Absent,
225 Valid(LandLine),
226 Malformed(String),
228}
229
230fn is_oid(s: &str) -> bool {
232 matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
233}
234
235impl LandEnv {
236 pub fn parse(raw: &str) -> LandEnv {
237 let fields: Vec<&str> = raw.split_whitespace().collect();
238 match fields.as_slice() {
239 [sha, remote_tip] if is_oid(sha) && is_oid(remote_tip) => LandEnv::Valid(LandLine {
240 sha: sha.to_string(),
241 remote_tip: remote_tip.to_string(),
242 }),
243 _ => LandEnv::Malformed(raw.to_string()),
244 }
245 }
246}
247
248pub fn land_env() -> &'static LandEnv {
251 static IN: std::sync::OnceLock<LandEnv> = std::sync::OnceLock::new();
252 IN.get_or_init(|| match std::env::var_os(LAND_ENV) {
253 None => LandEnv::Absent,
254 Some(raw) => {
255 std::env::remove_var(LAND_ENV);
256 LandEnv::parse(&raw.to_string_lossy())
257 }
258 })
259}
260
261pub const PRESTAGE_ENV: &str = "AMONT_LAND_PRESTAGE";
268
269#[derive(Debug, Clone, PartialEq, Eq)]
271pub enum Prestage {
272 Absent,
274 Of(crate::pushrefs::PushRef),
276 Malformed(String),
279}
280
281impl Prestage {
282 pub fn parse(raw: &str) -> Prestage {
283 let fields: Vec<&str> = raw.split_whitespace().collect();
284 match fields.as_slice() {
285 [local_ref, local_oid, remote_ref, remote_oid]
286 if is_oid(local_oid) && is_oid(remote_oid) =>
287 {
288 Prestage::Of(crate::pushrefs::PushRef {
289 local_ref: local_ref.to_string(),
290 local_oid: local_oid.to_string(),
291 remote_ref: remote_ref.to_string(),
292 remote_oid: remote_oid.to_string(),
293 })
294 }
295 _ => Prestage::Malformed(raw.to_string()),
296 }
297 }
298
299 fn line(&self) -> Option<&crate::pushrefs::PushRef> {
300 match self {
301 Prestage::Of(line) => Some(line),
302 Prestage::Absent | Prestage::Malformed(_) => None,
303 }
304 }
305}
306
307pub fn source_worktree() -> Option<&'static std::path::Path> {
311 static IN: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
312 IN.get_or_init(|| {
313 let raw = std::env::var_os(crate::pushed_tree::SOURCE_WORKTREE_ENV)?;
314 std::env::remove_var(crate::pushed_tree::SOURCE_WORKTREE_ENV);
315 Some(std::path::PathBuf::from(raw))
316 })
317 .as_deref()
318}
319
320pub fn prestage() -> &'static Prestage {
323 static IN: std::sync::OnceLock<Prestage> = std::sync::OnceLock::new();
324 IN.get_or_init(|| match std::env::var_os(PRESTAGE_ENV) {
325 None => Prestage::Absent,
326 Some(raw) => {
327 std::env::remove_var(PRESTAGE_ENV);
328 Prestage::parse(&raw.to_string_lossy())
329 }
330 })
331}
332
333const PUSH_GATES: &str = "amont.pushGates";
340
341pub fn refuse_push_gates(settings: &crate::config::Settings) -> bool {
343 crate::config::enumerated_or(settings, PUSH_GATES, &["refuse", "inline"], "refuse") == "refuse"
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347pub enum Phase {
348 Running,
349 Passed,
350 Failed,
351}
352
353impl Phase {
354 fn as_str(self) -> &'static str {
355 match self {
356 Phase::Running => "running",
357 Phase::Passed => "passed",
358 Phase::Failed => "failed",
359 }
360 }
361
362 fn parse(s: &str) -> Option<Phase> {
363 match s {
364 "running" => Some(Phase::Running),
365 "passed" => Some(Phase::Passed),
366 "failed" => Some(Phase::Failed),
367 _ => None,
368 }
369 }
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct State {
375 pub pid: u32,
376 pub commit: String,
377 pub tree: String,
378 pub started: u64,
379 pub snapshot: PathBuf,
380 pub phase: Phase,
381 pub step: Option<String>,
386 pub reason: Option<String>,
388 pub prestage: bool,
391 pub signal: Option<i32>,
394}
395
396impl State {
397 fn render(&self) -> String {
398 format!(
399 "{FORMAT}\npid={}\ncommit={}\ntree={}\nstarted={}\nsnapshot={}\nphase={}\n",
400 self.pid,
401 self.commit,
402 self.tree,
403 self.started,
404 self.snapshot.display(),
405 self.phase.as_str(),
406 ) + &[("step", &self.step), ("reason", &self.reason)]
407 .iter()
408 .filter_map(|(k, v)| v.as_ref().map(|v| format!("{k}={}\n", one_line(v))))
409 .collect::<String>()
410 + if self.prestage { "kind=prestage\n" } else { "" }
411 + &self
412 .signal
413 .map(|n| format!("signal={n}\n"))
414 .unwrap_or_default()
415 }
416
417 pub fn parse(body: &str) -> Option<State> {
420 let mut lines = body.lines();
421 if lines.next()? != FORMAT {
422 return None;
423 }
424 let (mut pid, mut commit, mut tree, mut started, mut snapshot, mut phase) =
425 (None, None, None, None, None, None);
426 let (mut step, mut reason, mut prestage, mut signal) = (None, None, false, None);
427 for line in lines {
428 let (k, v) = line.split_once('=')?;
429 match k {
430 "pid" => pid = v.parse().ok(),
431 "commit" => commit = Some(v.to_string()),
432 "tree" => tree = Some(v.to_string()),
433 "started" => started = v.parse().ok(),
434 "snapshot" => snapshot = Some(PathBuf::from(v)),
435 "phase" => phase = Phase::parse(v),
436 "step" => step = Some(v.to_string()),
437 "reason" => reason = Some(v.to_string()),
438 "kind" => prestage = v == "prestage",
439 "signal" => signal = v.parse().ok(),
440 _ => {}
441 }
442 }
443 Some(State {
444 pid: pid?,
445 commit: commit?,
446 tree: tree?,
447 started: started?,
448 snapshot: snapshot?,
449 phase: phase?,
450 step,
451 reason,
452 prestage,
453 signal,
454 })
455 }
456
457 pub fn alive(&self) -> bool {
461 self.phase == Phase::Running && process_alive(self.pid)
462 }
463
464 pub fn age_secs(&self) -> u64 {
465 now().saturating_sub(self.started)
466 }
467
468 fn short(&self) -> &str {
469 self.commit.get(..8).unwrap_or(&self.commit)
470 }
471}
472
473fn one_line(v: &str) -> String {
475 v.replace(['\n', '\r'], " ")
476}
477
478fn now() -> u64 {
479 SystemTime::now()
480 .duration_since(UNIX_EPOCH)
481 .unwrap_or_default()
482 .as_secs()
483}
484
485fn git_dir() -> Option<PathBuf> {
488 crate::git::stdout(&["rev-parse", "--absolute-git-dir"]).map(PathBuf::from)
489}
490
491fn state_path() -> Option<PathBuf> {
492 git_dir().map(|d| d.join(STATE))
493}
494
495pub fn log_path() -> Option<PathBuf> {
498 git_dir().map(|d| d.join(LOG))
499}
500
501pub fn read() -> Option<State> {
503 let body = std::fs::read_to_string(state_path()?).ok()?;
504 State::parse(&body)
505}
506
507fn write(state: &State) {
508 if let Some(path) = state_path() {
509 let _ = std::fs::write(path, state.render());
513 }
514}
515
516fn clear() {
517 if let Some(path) = state_path() {
518 let _ = std::fs::remove_file(path);
519 }
520}
521
522pub fn process_alive(pid: u32) -> bool {
526 #[cfg(unix)]
527 {
528 Command::new("kill")
529 .args(["-0", &pid.to_string()])
530 .stdin(Stdio::null())
531 .stdout(Stdio::null())
532 .stderr(Stdio::null())
533 .status()
534 .map(|s| s.success())
535 .unwrap_or(false)
536 }
537 #[cfg(not(unix))]
538 {
539 Command::new("tasklist")
540 .args(["/FI", &format!("PID eq {pid}"), "/NH"])
541 .stdin(Stdio::null())
542 .stderr(Stdio::null())
543 .output()
544 .map(|o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string()))
545 .unwrap_or(false)
546 }
547}
548
549fn kill_group(pid: u32) {
553 #[cfg(unix)]
554 {
555 let _ = Command::new("kill")
556 .args(["-TERM", "--", &format!("-{pid}")])
557 .stdin(Stdio::null())
558 .stdout(Stdio::null())
559 .stderr(Stdio::null())
560 .status();
561 }
562 #[cfg(not(unix))]
563 {
564 let _ = Command::new("taskkill")
565 .args(["/PID", &pid.to_string(), "/T", "/F"])
566 .stdin(Stdio::null())
567 .stdout(Stdio::null())
568 .stderr(Stdio::null())
569 .status();
570 }
571}
572
573fn cancel(state: &State, repo: &Path) {
577 if state.alive() {
578 kill_group(state.pid);
579 for _ in 0..20 {
582 if !process_alive(state.pid) {
583 break;
584 }
585 std::thread::sleep(Duration::from_millis(100));
586 }
587 }
588 remove_snapshot(repo, &state.snapshot);
589}
590
591fn remove_snapshot(repo: &Path, path: &Path) {
592 if path.as_os_str().is_empty() || !path.exists() {
593 let _ = crate::git::succeeds_in(repo, &["worktree", "prune"]);
594 return;
595 }
596 let _ = crate::git::succeeds_in(
597 repo,
598 &[
599 "worktree",
600 "remove",
601 "--force",
602 path.to_str().unwrap_or_default(),
603 ],
604 );
605 let _ = std::fs::remove_dir_all(path);
606 let _ = crate::git::succeeds_in(repo, &["worktree", "prune"]);
607}
608
609fn strip_repo_env(cmd: &mut Command) {
616 for key in [
617 "GIT_DIR",
618 "GIT_WORK_TREE",
619 "GIT_INDEX_FILE",
620 "GIT_COMMON_DIR",
621 "GIT_PREFIX",
622 "GIT_OBJECT_DIRECTORY",
623 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
624 "GIT_NAMESPACE",
625 "GIT_REFLOG_ACTION",
626 "GIT_EXEC_PATH",
627 crate::hooks::common::INDEX_ENV,
630 crate::hooks::common::INDEX_GIT_DIR_ENV,
631 ] {
632 cmd.env_remove(key);
633 }
634}
635
636#[cfg(not(unix))]
651pub fn spawn_detached() -> Result<u32, String> {
652 Err(format!(
653 "background rehearsal is not available on Windows yet — \
654 `{BIN} rehearse --wait` runs it in the foreground"
655 ))
656}
657
658#[cfg(unix)]
659pub fn spawn_detached() -> Result<u32, String> {
660 let log = log_path().ok_or("not inside a git repository")?;
661 spawn_amont(&["rehearse", "--worker"], &log)
662}
663
664#[cfg(unix)]
669pub fn spawn_amont(args: &[&str], log: &std::path::Path) -> Result<u32, String> {
670 use std::os::unix::process::CommandExt;
671 let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
672 let file =
673 std::fs::File::create(log).map_err(|e| format!("cannot open {}: {e}", log.display()))?;
674 let err = file
675 .try_clone()
676 .map_err(|e| format!("cannot open {}: {e}", log.display()))?;
677 let mut cmd = Command::new(exe);
678 cmd.args(args)
679 .stdin(Stdio::null())
680 .stdout(Stdio::from(file))
681 .stderr(Stdio::from(err));
682 strip_repo_env(&mut cmd);
683 cmd.process_group(0);
684 let child = cmd
685 .spawn()
686 .map_err(|e| format!("cannot start {BIN} {}: {e}", args.join(" ")))?;
687 Ok(child.id())
688}
689
690#[derive(Debug, Clone, PartialEq, Eq)]
692pub enum Outcome {
693 NothingToDo,
695 AlreadyStamped,
697 AlreadyRunning(u32),
699 Detached,
702 Passed,
703 Failed,
704 Interrupted(i32),
706}
707
708pub(crate) fn signal_of(status: &std::process::ExitStatus) -> Option<i32> {
710 #[cfg(unix)]
711 {
712 std::os::unix::process::ExitStatusExt::signal(status)
713 }
714 #[cfg(not(unix))]
715 {
716 let _ = status;
717 None
718 }
719}
720
721fn still_running(state: &State) -> bool {
723 read().is_some_and(|now| now.alive() && now.pid == state.pid && now.started == state.started)
724}
725
726const PRESTAGE_WAIT: Duration = Duration::from_secs(3 * 60 * 60);
730
731struct Plan {
733 root: String,
734 head: String,
735 tree: String,
736 push_ref: crate::pushrefs::PushRef,
737 manifest: crate::manifest::Manifest,
738 settings: crate::config::Settings,
739 gates: Vec<String>,
741 tree_todo: Vec<crate::manifest::TreeGate>,
743 audits: crate::hooks::audit::Ledger,
745}
746
747fn plan(prestage: Option<&crate::pushrefs::PushRef>) -> Result<Plan, String> {
748 let root = crate::hooks::common::repo_root_checked()?;
749 let repo = Path::new(&root);
750 let head = match prestage {
753 Some(line) => crate::git::stdout(&["rev-parse", &format!("{}^{{commit}}", line.local_oid)])
754 .ok_or("could not resolve the commit to pre-stage")?,
755 None => crate::git::stdout(&["rev-parse", "HEAD"]).ok_or("could not resolve HEAD")?,
756 };
757 let tree = crate::git::stdout(&["rev-parse", &format!("{head}^{{tree}}")])
758 .ok_or("could not resolve the tree to rehearse")?;
759 let push_ref = match prestage {
762 Some(line) => line.clone(),
763 None => crate::pushrefs::synthetic_from_upstream()?,
764 };
765 let (manifest, settings) = crate::manifest::load_resolved(repo);
766 let changed = crate::pushrefs::changed_files(std::slice::from_ref(&push_ref));
767 let mut gates = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
768 let audits = crate::hooks::audit::Ledger::default();
771 for audit in crate::dispatch::owed_audits(
772 &settings,
773 &manifest,
774 &audits,
775 std::slice::from_ref(&push_ref),
776 ) {
777 if !gates.contains(&audit) {
778 gates.push(audit);
779 }
780 }
781 let proven_here = crate::gate_stamp::tree_tokens(&tree);
785 let tree_todo: Vec<crate::manifest::TreeGate> = if crate::tree_lint::enabled(&settings) {
786 manifest
787 .tree
788 .iter()
789 .filter(|g| !proven_here.contains(&g.stamp_key()))
790 .cloned()
791 .collect()
792 } else {
793 Vec::new()
794 };
795 Ok(Plan {
796 root,
797 head,
798 tree,
799 push_ref,
800 manifest,
801 settings,
802 gates,
803 tree_todo,
804 audits,
805 })
806}
807
808impl Plan {
809 fn vouched(&self, gate: &str) -> bool {
812 if crate::hooks::audit::is_audit(gate) {
813 return !crate::hooks::audit::owed(
814 &self.settings,
815 &self.audits,
816 gate,
817 std::slice::from_ref(&self.push_ref),
818 );
819 }
820 vouched_by(&self.settings, &self.manifest, &self.head, gate)
821 }
822
823 fn detach(&self, ask: crate::cluster::Ask) -> Vec<String> {
826 let unstamped: Vec<String> = self
827 .gates
828 .iter()
829 .filter(|gate| !self.vouched(gate))
830 .cloned()
831 .collect();
832 crate::cluster::detach(&self.settings, &self.manifest, &unstamped, ask).gates
833 }
834}
835
836#[derive(Debug, Clone, Copy, PartialEq, Eq)]
838enum Origin {
839 Push,
841 Prestage,
843}
844
845impl Origin {
846 fn of(prestage: Option<&crate::pushrefs::PushRef>) -> Origin {
849 match prestage {
850 Some(_) => Origin::Prestage,
851 None => Origin::Push,
852 }
853 }
854}
855
856fn snapshot_env_value(on_cluster: &[String], origin: Origin) -> String {
859 let marker = match origin {
860 Origin::Push => "",
861 Origin::Prestage => PRESTAGE_PREFIX,
862 };
863 if on_cluster.is_empty() {
864 format!("{marker}1")
865 } else {
866 format!("{marker}{DETACHED_PREFIX}{}", on_cluster.join(","))
867 }
868}
869
870fn vouched_by(
872 settings: &crate::config::Settings,
873 manifest: &crate::manifest::Manifest,
874 head: &str,
875 gate: &str,
876) -> bool {
877 let tips = [head.to_string()];
878 let stamped = crate::gate_stamp::stamps_for(&tips);
879 let local = crate::gate_identity::token(&manifest.externals, gate)
880 .is_some_and(|t| stamped.get(head).is_some_and(|s| s.contains(&t)));
881 local
882 || manifest
883 .externals
884 .iter()
885 .find(|e| e.id == gate)
886 .is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
887}
888
889pub fn worker(
893 ask: crate::cluster::Ask,
894 prestage: Option<&crate::pushrefs::PushRef>,
895) -> Result<Outcome, String> {
896 let planned = plan(prestage)?;
897 let repo = Path::new(&planned.root);
898 let (head, tree) = (planned.head.clone(), planned.tree.clone());
899 let short = head.get(..8).unwrap_or(&head);
900 if planned.gates.is_empty() && planned.tree_todo.is_empty() {
901 println!("nothing to rehearse: no test gate has work to do for what {short} would push");
902 return Ok(Outcome::NothingToDo);
903 }
904 if planned.gates.iter().all(|gate| planned.vouched(gate)) && planned.tree_todo.is_empty() {
905 println!(
906 "{} {} already stamped on this tree — nothing to rehearse",
907 valid_sign(),
908 highlight(&planned.gates.join(" "))
909 );
910 return Ok(Outcome::AlreadyStamped);
911 }
912 let mut settled = false;
918 for _ in 0..3 {
919 let Some(prev) = read() else {
920 settled = true;
921 break;
922 };
923 if !prev.alive() {
924 if prev.phase == Phase::Running {
925 remove_snapshot(repo, &prev.snapshot);
927 }
928 settled = true;
929 break;
930 }
931 if prev.tree == tree {
932 println!(
933 "a rehearsal of this tree is already running (pid {}, started {} ago)",
934 prev.pid,
935 human_secs(prev.age_secs())
936 );
937 return Ok(Outcome::AlreadyRunning(prev.pid));
938 }
939 if prestage.is_some() || prev.prestage {
940 eprintln!(
941 "waiting for the rehearsal of {} (pid {}) before rehearsing {short}",
942 prev.short(),
943 prev.pid,
944 );
945 if follow(&prev, Some(PRESTAGE_WAIT)).is_none() && still_running(&prev) {
946 return Err(format!(
947 "the rehearsal of {} (pid {}) is still running after {}; \
948 not starting another beside it",
949 prev.short(),
950 prev.pid,
951 human_secs(PRESTAGE_WAIT.as_secs())
952 ));
953 }
954 continue;
955 }
956 eprintln!(
957 "cancelling the rehearsal of {} (pid {}) — {} is the tree that matters now",
958 prev.short(),
959 prev.pid,
960 short
961 );
962 cancel(&prev, repo);
963 settled = true;
964 break;
965 }
966 if !settled {
967 return Err("other rehearsals kept starting in this worktree; try again".to_string());
968 }
969 let on_cluster = planned.detach(ask);
972 let Plan {
973 push_ref,
974 manifest,
975 settings,
976 gates,
977 tree_todo,
978 ..
979 } = planned;
980 let local_work = gates
981 .iter()
982 .any(|gate| !on_cluster.contains(gate) && !vouched_by(&settings, &manifest, &head, gate));
983 if !local_work && tree_todo.is_empty() {
984 eprintln!(
985 "{} every gate left to rehearse went to the cluster ({}) — the next commit or push collects the result",
986 valid_sign(),
987 highlight(&on_cluster.join(" "))
988 );
989 return Ok(Outcome::Detached);
990 }
991 let snapshot = crate::pushed_tree::PushedTree::checkout(repo, &head)
992 .ok_or("could not check out HEAD into a snapshot worktree")?;
993 let mut me = State {
997 pid: std::process::id(),
998 commit: head.clone(),
999 tree,
1000 started: now(),
1001 snapshot: snapshot.path().to_path_buf(),
1002 phase: Phase::Running,
1003 step: Some("preparing".to_string()),
1004 reason: None,
1005 prestage: prestage.is_some(),
1006 signal: None,
1007 };
1008 if let Some(other) = read().filter(|s| s.alive() && s.pid != me.pid) {
1011 if prestage.is_some() || other.prestage {
1012 drop(snapshot);
1013 return Err(format!(
1014 "the rehearsal of {} (pid {}) started meanwhile; try again",
1015 other.short(),
1016 other.pid
1017 ));
1018 }
1019 cancel(&other, repo);
1020 }
1021 write(&me);
1022 if let Err(why) = snapshot.prepare(&settings) {
1023 write(&State {
1024 phase: Phase::Failed,
1025 step: None,
1026 reason: Some(format!("could not prepare the snapshot: {why}")),
1027 ..me
1028 });
1029 drop(snapshot);
1030 return Err(format!("could not prepare the snapshot: {why}"));
1031 }
1032 if !tree_todo.is_empty() {
1033 me.step = Some("tree lint".to_string());
1034 write(&me);
1035 crate::tree_lint::rehearse(&settings, snapshot.path(), &me.tree, &tree_todo);
1036 }
1037 if gates.is_empty() {
1038 write(&State {
1040 phase: Phase::Passed,
1041 step: None,
1042 ..me
1043 });
1044 drop(snapshot);
1045 println!(
1046 "{} rehearsal of {short} done (tree lint only)",
1047 valid_sign()
1048 );
1049 return Ok(Outcome::Passed);
1050 }
1051 me.step = Some("testing".to_string());
1052 write(&me);
1053 println!(
1054 "rehearsing {} for {} in {}",
1055 highlight(&gates.join(" ")),
1056 short,
1057 snapshot.path().display()
1058 );
1059 let hooks_dir = crate::git::stdout(&["rev-parse", "--git-path", "hooks"])
1060 .map(PathBuf::from)
1061 .map(|p| if p.is_absolute() { p } else { repo.join(p) })
1062 .ok_or("could not locate the hooks directory")?;
1063 let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
1064 let mut cmd = Command::new(exe);
1065 cmd.arg("--hooks-dir")
1066 .arg(&hooks_dir)
1067 .arg("pre-push")
1068 .current_dir(snapshot.path())
1069 .env(ENV, snapshot_env_value(&on_cluster, Origin::of(prestage)))
1070 .env(crate::host_slots::ON_BUSY_ENV, "wait")
1074 .env(crate::pushed_tree::SOURCE_WORKTREE_ENV, repo)
1077 .stdin(Stdio::piped());
1078 strip_repo_env(&mut cmd);
1079 let line = format!(
1080 "{} {} {} {}\n",
1081 push_ref.local_ref, push_ref.local_oid, push_ref.remote_ref, push_ref.remote_oid
1082 );
1083 let status = (|| -> std::io::Result<std::process::ExitStatus> {
1084 let mut child = cmd.spawn()?;
1085 if let Some(mut stdin) = child.stdin.take() {
1086 stdin.write_all(line.as_bytes())?;
1087 }
1088 child.wait()
1089 })()
1090 .map_err(|e| format!("could not run the push gate in the snapshot: {e}"))?;
1091 let passed = status.success();
1092 let done = State {
1093 phase: if passed { Phase::Passed } else { Phase::Failed },
1094 step: None,
1095 reason: signal_of(&status).map(|n| format!("the push gate was stopped by signal {n}")),
1096 signal: signal_of(&status),
1097 ..me
1098 };
1099 write(&done);
1100 drop(snapshot);
1101 if let Some(n) = signal_of(&status) {
1102 eprintln!(
1103 "{} rehearsal of {short} stopped by signal {n}",
1104 warning_sign()
1105 );
1106 return Ok(Outcome::Interrupted(n));
1107 }
1108 if passed {
1109 println!("{} rehearsal of {short} passed", valid_sign());
1110 Ok(Outcome::Passed)
1111 } else {
1112 println!("{} rehearsal of {short} FAILED", warning_sign());
1113 Ok(Outcome::Failed)
1114 }
1115}
1116
1117pub fn await_for(settings: &crate::config::Settings, tips: &[String]) -> Option<Phase> {
1126 if in_snapshot() {
1127 return None;
1128 }
1129 let state = read()?;
1130 let on_a_tip = tips.iter().any(|t| {
1131 let spec = format!("{t}^{{tree}}");
1132 crate::git::stdout(&["rev-parse", &spec]).as_deref() == Some(state.tree.as_str())
1133 });
1134 if !on_a_tip {
1135 return None;
1136 }
1137 let log = log_path()
1138 .map(|p| format!(" (log: {})", p.display()))
1139 .unwrap_or_default();
1140 let then = if refuse_unstamped(settings) {
1143 format!("fix it and rehearse again (`{BIN} rehearse --wait`)")
1144 } else {
1145 "running the gate here".to_string()
1146 };
1147 match state.phase {
1148 Phase::Passed => None, Phase::Failed => {
1150 crate::say!(
1151 "{} the background rehearsal of this tree failed {} ago{}{log} — {then}",
1152 warning_sign(),
1153 human_secs(state.age_secs()),
1154 state
1155 .reason
1156 .as_deref()
1157 .map(|r| format!(" ({r})"))
1158 .unwrap_or_default(),
1159 );
1160 None
1161 }
1162 Phase::Running if !process_alive(state.pid) => {
1163 crate::say!(
1164 "{} a background rehearsal of this tree died without a verdict{log} — {then}",
1165 warning_sign(),
1166 );
1167 None
1168 }
1169 Phase::Running => {
1170 let budget = wait_budget(settings);
1171 crate::say!(
1172 "{} a background rehearsal of this tree started {} ago is still running — \
1173 waiting{} for it rather than starting the suite over{log}",
1174 warning_sign(),
1175 human_secs(state.age_secs()),
1176 match budget {
1177 Some(b) => format!(" up to {}", human_secs(b.as_secs())),
1178 None => String::new(),
1179 },
1180 );
1181 let followed = follow(&state, budget).map(|(phase, _)| phase);
1182 if followed.is_none() && still_running(&state) {
1183 warn(&format!(
1187 "the rehearsal is still running after {} — running the gate here \
1188 rather than holding the push open (`git config \
1189 amont.rehearsalWait <secs>`, or 0 to wait indefinitely)",
1190 human_secs(state.age_secs())
1191 ));
1192 }
1193 followed
1194 }
1195 }
1196}
1197
1198fn follow(state: &State, budget: Option<Duration>) -> Option<(Phase, State)> {
1205 let mut last_word = std::time::Instant::now();
1206 let deadline = budget.map(|b| std::time::Instant::now() + b);
1207 loop {
1208 std::thread::sleep(Duration::from_secs(1));
1209 let now_state = read()?;
1210 if now_state.tree != state.tree || now_state.started != state.started {
1211 return None;
1212 }
1213 match now_state.phase {
1214 Phase::Running => {
1215 if !process_alive(now_state.pid) {
1216 warn("the rehearsal died without a verdict");
1217 return None;
1218 }
1219 if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
1220 return None;
1222 }
1223 if last_word.elapsed() >= Duration::from_secs(60) {
1224 eprintln!(
1225 " still rehearsing ({} so far)",
1226 human_secs(now_state.age_secs())
1227 );
1228 last_word = std::time::Instant::now();
1229 }
1230 }
1231 phase => {
1232 let verb = if phase == Phase::Passed {
1233 format!("{} rehearsal passed", valid_sign())
1234 } else {
1235 format!(
1236 "{} rehearsal failed{}",
1237 warning_sign(),
1238 now_state
1239 .reason
1240 .as_deref()
1241 .map(|r| format!(" ({r})"))
1242 .unwrap_or_default()
1243 )
1244 };
1245 crate::say!("{verb} after {}", human_secs(now_state.age_secs()));
1246 return Some((phase, now_state));
1247 }
1248 }
1249 }
1250}
1251
1252pub fn command(args: &[OsString], prestage: &Prestage) -> i32 {
1254 let flag = |f: &str| args.iter().any(|a| a == f);
1255 let ask = if flag("--cluster") {
1256 crate::cluster::Ask::Flag
1257 } else {
1258 crate::cluster::Ask::Setting
1259 };
1260 let prestage = match prestage {
1261 Prestage::Malformed(raw) => {
1262 eprintln!("{BIN}: {PRESTAGE_ENV} is not a push line ({raw:?}); nothing was rehearsed");
1263 return 2;
1264 }
1265 line => line.line(),
1266 };
1267 if flag("--worker") {
1268 return match worker(ask, prestage) {
1269 Ok(Outcome::Failed) => 1,
1270 Ok(Outcome::Interrupted(n)) => 128 + n,
1271 Ok(_) => 0,
1272 Err(e) => {
1273 eprintln!("{BIN}: {e}");
1274 2
1275 }
1276 };
1277 }
1278 let root = match crate::hooks::common::repo_root_checked() {
1279 Ok(r) => r,
1280 Err(e) => {
1281 eprintln!("{BIN}: {e}");
1282 return 2;
1283 }
1284 };
1285 if flag("--status") {
1286 return status();
1287 }
1288 if flag("--stop") {
1289 let terminated = crate::cluster::stop_pending();
1291 for line in terminated.done.iter().chain(&terminated.failed) {
1292 eprintln!("{line}");
1293 }
1294 match read() {
1295 Some(s) if s.alive() => {
1296 cancel(&s, Path::new(&root));
1297 clear();
1298 println!("stopped the rehearsal of {} (pid {})", s.short(), s.pid);
1299 }
1300 _ if terminated.done.is_empty() && terminated.failed.is_empty() => {
1301 println!("no rehearsal is running in this worktree");
1302 }
1303 _ => {}
1304 }
1305 return i32::from(!terminated.failed.is_empty());
1307 }
1308 if flag("--cluster") && !flag("--wait") {
1309 match plan(prestage) {
1312 Ok(planned) => {
1313 let on_cluster = planned.detach(crate::cluster::Ask::Flag);
1314 let left = planned
1315 .gates
1316 .iter()
1317 .any(|gate| !on_cluster.contains(gate) && !planned.vouched(gate));
1318 if !left && planned.tree_todo.is_empty() && !on_cluster.is_empty() {
1319 return 0;
1320 }
1321 }
1322 Err(e) => {
1323 eprintln!("{BIN}: {e}");
1325 return 1;
1326 }
1327 }
1328 }
1329 let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1330 let running_here = read().filter(|s| s.alive() && Some(s.tree.as_str()) == head.as_deref());
1331 if flag("--wait") {
1332 let target = match prestage {
1346 Some(line) => format!("{}^{{tree}}", line.local_oid),
1347 None => "HEAD^{tree}".to_string(),
1348 };
1349 for _ in 0..3 {
1350 let running = read().filter(|s| {
1351 s.alive()
1352 && Some(s.tree.as_str())
1353 == crate::git::stdout(&["rev-parse", &target]).as_deref()
1354 });
1355 let Some(state) = running else {
1356 match worker(ask, prestage) {
1358 Ok(Outcome::Failed) => return 1,
1359 Ok(Outcome::Interrupted(n)) => return 128 + n,
1360 Ok(Outcome::AlreadyRunning(_)) => continue,
1361 Ok(_) => return 0,
1362 Err(e) => {
1363 eprintln!("{BIN}: {e}");
1364 return 2;
1365 }
1366 }
1367 };
1368 eprintln!(
1369 "following the rehearsal of {} (pid {}, started {} ago)",
1370 state.short(),
1371 state.pid,
1372 human_secs(state.age_secs())
1373 );
1374 match follow(&state, None) {
1375 Some((Phase::Passed, _)) => continue,
1379 Some((
1381 _,
1382 State {
1383 signal: Some(n), ..
1384 },
1385 )) => return 128 + n,
1386 Some(_) => {
1387 show_log_tail();
1388 return 1;
1389 }
1390 None => {
1391 eprintln!("{BIN}: the rehearsal ended without a verdict");
1392 return 2;
1393 }
1394 }
1395 }
1396 eprintln!("{BIN}: another rehearsal keeps claiming this tree — run the gate yourself");
1397 return 2;
1398 }
1399 if let Some(state) = running_here {
1400 println!(
1401 "a rehearsal of this tree is already running (pid {}, started {} ago) — \
1402 `{BIN} rehearse --wait` follows it",
1403 state.pid,
1404 human_secs(state.age_secs())
1405 );
1406 return 0;
1407 }
1408 match spawn_detached() {
1409 Ok(pid) => {
1410 println!(
1411 "rehearsing the push gate for HEAD in the background (pid {pid}) — \
1412 `{BIN} rehearse --wait` follows it, `--status` reports{}",
1413 log_path()
1414 .map(|p| format!("; log: {}", p.display()))
1415 .unwrap_or_default()
1416 );
1417 0
1418 }
1419 Err(e) => {
1420 eprintln!("{BIN}: {e}");
1421 2
1422 }
1423 }
1424}
1425
1426fn status() -> i32 {
1427 let collected = crate::cluster::collect();
1430 let mut detached = crate::cluster::settled_lines(&collected.settled);
1431 detached.extend(crate::cluster::status_lines());
1432 for line in &detached {
1433 println!("{line}");
1434 }
1435 if let Some(trouble) = &collected.trouble {
1436 eprintln!("cluster runs not refreshed — {trouble}");
1437 }
1438 let Some(state) = read() else {
1439 if detached.is_empty() {
1440 println!("no rehearsal recorded in this worktree");
1441 }
1442 return 0;
1443 };
1444 let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1445 let which = if head.as_deref() == Some(state.tree.as_str()) {
1446 "HEAD's tree".to_string()
1447 } else {
1448 format!("{} (not HEAD's tree)", state.short())
1449 };
1450 let age = human_secs(state.age_secs());
1451 let line = match state.phase {
1452 Phase::Running if state.alive() => {
1453 format!(
1454 "rehearsal of {which}: running for {age} (pid {}{})",
1455 state.pid,
1456 state
1457 .step
1458 .as_deref()
1459 .map(|s| format!(", {s}"))
1460 .unwrap_or_default()
1461 )
1462 }
1463 Phase::Running => {
1464 format!("rehearsal of {which}: died without a verdict, started {age} ago")
1465 }
1466 Phase::Passed => format!("rehearsal of {which}: passed, started {age} ago"),
1467 Phase::Failed => format!(
1468 "rehearsal of {which}: FAILED, started {age} ago{}",
1469 state
1470 .reason
1471 .as_deref()
1472 .map(|r| format!(" — {r}"))
1473 .unwrap_or_default()
1474 ),
1475 };
1476 println!("{line}");
1477 if let Some(log) = log_path().filter(|p| p.exists()) {
1478 println!("log: {}", log.display());
1479 }
1480 0
1481}
1482
1483fn show_log_tail() {
1486 let Some(log) = log_path() else { return };
1487 let Ok(body) = std::fs::read_to_string(&log) else {
1488 return;
1489 };
1490 let lines: Vec<&str> = body.lines().collect();
1491 let start = lines.len().saturating_sub(40);
1492 eprintln!(
1493 "--- {} (last {} lines) ---",
1494 log.display(),
1495 lines.len() - start
1496 );
1497 for l in &lines[start..] {
1498 eprintln!("{l}");
1499 }
1500}
1501
1502#[cfg(test)]
1503mod tests {
1504 use super::*;
1505
1506 fn sample() -> State {
1507 State {
1508 pid: 4242,
1509 commit: "a".repeat(40),
1510 tree: "b".repeat(40),
1511 started: 1_700_000_000,
1512 snapshot: PathBuf::from("/tmp/amont-push-1-2"),
1513 phase: Phase::Running,
1514 step: Some("preparing".to_string()),
1515 reason: None,
1516 prestage: false,
1517 signal: None,
1518 }
1519 }
1520
1521 #[test]
1522 fn the_prestage_marker_leaves_the_detached_gates_intact() {
1523 let marked = parse_snapshot_env("prestage;detached=a,b");
1524 assert!(marked.prestage);
1525 assert_eq!(marked.detached, ["a", "b"]);
1526 let plain = parse_snapshot_env("detached=a,b");
1527 assert!(!plain.prestage);
1528 assert_eq!(plain.detached, ["a", "b"]);
1529 let bare = parse_snapshot_env("1");
1530 assert!(!bare.prestage);
1531 assert!(bare.detached.is_empty());
1532 let marked_bare = parse_snapshot_env("prestage;1");
1533 assert!(marked_bare.prestage);
1534 assert!(marked_bare.detached.is_empty());
1535 }
1536
1537 #[test]
1540 fn a_prestage_survives_the_state_file() {
1541 let staged = State {
1542 prestage: true,
1543 signal: Some(9),
1544 ..sample()
1545 };
1546 assert_eq!(State::parse(&staged.render()), Some(staged));
1547 assert_eq!(State::parse(&sample().render()), Some(sample()));
1548 }
1549
1550 #[test]
1553 fn the_land_variables_take_object_names_only() {
1554 let (a, b) = ("a".repeat(40), "0".repeat(40));
1555 assert_eq!(
1556 LandEnv::parse(&format!("{a} {b}")),
1557 LandEnv::Valid(LandLine {
1558 sha: a.clone(),
1559 remote_tip: b.clone()
1560 })
1561 );
1562 for bad in [
1563 "",
1564 "abc",
1565 a.as_str(),
1566 &format!("{a} {b} extra"),
1567 &format!("{a} xyz"),
1568 ] {
1569 assert!(
1570 matches!(LandEnv::parse(bad), LandEnv::Malformed(_)),
1571 "{bad:?}"
1572 );
1573 }
1574 assert!(matches!(
1575 Prestage::parse(&format!("refs/heads/x {a} refs/heads/x {b}")),
1576 Prestage::Of(_)
1577 ));
1578 for bad in [
1579 format!("refs/heads/x {a} refs/heads/x"),
1580 "x y z w".to_string(),
1581 ] {
1582 assert!(
1583 matches!(Prestage::parse(&bad), Prestage::Malformed(_)),
1584 "{bad:?}"
1585 );
1586 }
1587 }
1588
1589 #[test]
1590 fn a_state_survives_the_round_trip() {
1591 let s = sample();
1592 assert_eq!(State::parse(&s.render()), Some(s));
1593 let done = State {
1594 phase: Phase::Failed,
1595 step: None,
1596 reason: Some("could not prepare the snapshot: npm ci failed\nin web/".to_string()),
1597 ..sample()
1598 };
1599 let back = State::parse(&done.render()).expect("parses");
1600 assert_eq!(
1601 back.reason.as_deref(),
1602 Some("could not prepare the snapshot: npm ci failed in web/"),
1603 "a reason is kept on one line"
1604 );
1605 assert_eq!(back.phase, Phase::Failed);
1606 }
1607
1608 #[test]
1611 fn a_foreign_or_partial_file_is_no_rehearsal() {
1612 assert_eq!(State::parse(""), None);
1613 assert_eq!(State::parse("amont-rehearsal-v2\npid=1\n"), None);
1614 assert_eq!(State::parse("amont-rehearsal-v1\npid=1\n"), None);
1615 assert_eq!(
1616 State::parse("amont-rehearsal-v1\npid=x\ncommit=a\ntree=b\nstarted=1\nsnapshot=/s\nphase=running\n"),
1617 None
1618 );
1619 }
1620
1621 #[test]
1624 fn a_dead_pid_is_not_alive() {
1625 let s = State {
1626 pid: u32::MAX - 7,
1627 ..sample()
1628 };
1629 assert!(!s.alive());
1630 let done = State {
1631 phase: Phase::Passed,
1632 pid: std::process::id(),
1633 ..sample()
1634 };
1635 assert!(
1636 !done.alive(),
1637 "a finished rehearsal is not running whoever's pid it names"
1638 );
1639 }
1640}