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 = "greengate.rehearseOnCommit";
62
63const WAIT_BUDGET: &str = "greengate.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 = crate::names::REHEARSAL_STATE;
90const LOG: &str = crate::names::REHEARSAL_LOG;
92const FORMAT: &str = crate::names::REHEARSAL_FORMAT;
95
96pub const ENV: &str = "GREENGATE_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 = "greengate.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 = "GREENGATE_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 = "GREENGATE_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 = "greengate.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, None)
662}
663
664#[cfg(unix)]
671pub fn spawn_amont(
672 args: &[&str],
673 log: &std::path::Path,
674 inherit: Option<i32>,
675) -> Result<u32, String> {
676 use std::os::unix::process::CommandExt;
677 let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
678 let file =
679 std::fs::File::create(log).map_err(|e| format!("cannot open {}: {e}", log.display()))?;
680 let err = file
681 .try_clone()
682 .map_err(|e| format!("cannot open {}: {e}", log.display()))?;
683 let mut cmd = Command::new(exe);
684 cmd.args(args)
685 .stdin(Stdio::null())
686 .stdout(Stdio::from(file))
687 .stderr(Stdio::from(err));
688 strip_repo_env(&mut cmd);
689 cmd.process_group(0);
690 if let Some(fd) = inherit {
691 unsafe {
694 cmd.pre_exec(move || {
695 if crate::fdlock::clear_cloexec(fd) {
696 Ok(())
697 } else {
698 Err(std::io::Error::last_os_error())
699 }
700 });
701 }
702 }
703 let child = cmd
704 .spawn()
705 .map_err(|e| format!("cannot start {BIN} {}: {e}", args.join(" ")))?;
706 Ok(child.id())
707}
708
709#[derive(Debug, Clone, PartialEq, Eq)]
711pub enum Outcome {
712 NothingToDo,
714 AlreadyStamped,
716 AlreadyRunning(u32),
718 Detached,
721 Passed,
722 Failed,
723 Interrupted(i32),
725}
726
727pub(crate) fn signal_of(status: &std::process::ExitStatus) -> Option<i32> {
729 #[cfg(unix)]
730 {
731 std::os::unix::process::ExitStatusExt::signal(status)
732 }
733 #[cfg(not(unix))]
734 {
735 let _ = status;
736 None
737 }
738}
739
740fn still_running(state: &State) -> bool {
742 read().is_some_and(|now| now.alive() && now.pid == state.pid && now.started == state.started)
743}
744
745const PRESTAGE_WAIT: Duration = Duration::from_secs(3 * 60 * 60);
749
750struct Plan {
752 root: String,
753 head: String,
754 tree: String,
755 push_ref: crate::pushrefs::PushRef,
756 manifest: crate::manifest::Manifest,
757 settings: crate::config::Settings,
758 gates: Vec<String>,
760 tree_todo: Vec<crate::manifest::TreeGate>,
762 audits: crate::hooks::audit::Ledger,
764}
765
766fn plan(prestage: Option<&crate::pushrefs::PushRef>) -> Result<Plan, String> {
767 let root = crate::hooks::common::repo_root_checked()?;
768 let repo = Path::new(&root);
769 let head = match prestage {
772 Some(line) => crate::git::stdout(&["rev-parse", &format!("{}^{{commit}}", line.local_oid)])
773 .ok_or("could not resolve the commit to pre-stage")?,
774 None => crate::git::stdout(&["rev-parse", "HEAD"]).ok_or("could not resolve HEAD")?,
775 };
776 let tree = crate::git::stdout(&["rev-parse", &format!("{head}^{{tree}}")])
777 .ok_or("could not resolve the tree to rehearse")?;
778 let push_ref = match prestage {
781 Some(line) => line.clone(),
782 None => crate::pushrefs::synthetic_from_upstream()?,
783 };
784 let (manifest, settings) = crate::manifest::load_resolved(repo);
785 let changed = crate::pushrefs::changed_files(std::slice::from_ref(&push_ref));
786 let mut gates = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
787 let audits = crate::hooks::audit::Ledger::default();
790 for audit in crate::dispatch::owed_audits(
791 &settings,
792 &manifest,
793 &audits,
794 std::slice::from_ref(&push_ref),
795 ) {
796 if !gates.contains(&audit) {
797 gates.push(audit);
798 }
799 }
800 let proven_here = crate::gate_stamp::tree_tokens(&tree);
804 let tree_todo: Vec<crate::manifest::TreeGate> = if crate::tree_lint::enabled(&settings) {
805 manifest
806 .tree
807 .iter()
808 .filter(|g| !proven_here.contains(&g.stamp_key()))
809 .cloned()
810 .collect()
811 } else {
812 Vec::new()
813 };
814 Ok(Plan {
815 root,
816 head,
817 tree,
818 push_ref,
819 manifest,
820 settings,
821 gates,
822 tree_todo,
823 audits,
824 })
825}
826
827impl Plan {
828 fn vouched(&self, gate: &str) -> bool {
831 if crate::hooks::audit::is_audit(gate) {
832 return !crate::hooks::audit::owed(
833 &self.settings,
834 &self.audits,
835 gate,
836 std::slice::from_ref(&self.push_ref),
837 );
838 }
839 vouched_by(&self.settings, &self.manifest, &self.head, gate)
840 }
841
842 fn detach(&self, ask: crate::cluster::Ask) -> Vec<String> {
845 let unstamped: Vec<String> = self
846 .gates
847 .iter()
848 .filter(|gate| !self.vouched(gate))
849 .cloned()
850 .collect();
851 crate::cluster::detach(&self.settings, &self.manifest, &unstamped, ask).gates
852 }
853}
854
855#[derive(Debug, Clone, Copy, PartialEq, Eq)]
857enum Origin {
858 Push,
860 Prestage,
862}
863
864impl Origin {
865 fn of(prestage: Option<&crate::pushrefs::PushRef>) -> Origin {
868 match prestage {
869 Some(_) => Origin::Prestage,
870 None => Origin::Push,
871 }
872 }
873}
874
875fn snapshot_env_value(on_cluster: &[String], origin: Origin) -> String {
878 let marker = match origin {
879 Origin::Push => "",
880 Origin::Prestage => PRESTAGE_PREFIX,
881 };
882 if on_cluster.is_empty() {
883 format!("{marker}1")
884 } else {
885 format!("{marker}{DETACHED_PREFIX}{}", on_cluster.join(","))
886 }
887}
888
889fn vouched_by(
891 settings: &crate::config::Settings,
892 manifest: &crate::manifest::Manifest,
893 head: &str,
894 gate: &str,
895) -> bool {
896 let tips = [head.to_string()];
897 let stamped = crate::gate_stamp::stamps_for(&tips);
898 let local = crate::gate_identity::token(&manifest.externals, gate)
899 .is_some_and(|t| stamped.get(head).is_some_and(|s| s.contains(&t)));
900 local
901 || manifest
902 .externals
903 .iter()
904 .find(|e| e.id == gate)
905 .is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
906}
907
908pub fn worker(
912 ask: crate::cluster::Ask,
913 prestage: Option<&crate::pushrefs::PushRef>,
914) -> Result<Outcome, String> {
915 let planned = plan(prestage)?;
916 let repo = Path::new(&planned.root);
917 let (head, tree) = (planned.head.clone(), planned.tree.clone());
918 let short = head.get(..8).unwrap_or(&head);
919 if planned.gates.is_empty() && planned.tree_todo.is_empty() {
920 println!("nothing to rehearse: no test gate has work to do for what {short} would push");
921 return Ok(Outcome::NothingToDo);
922 }
923 if planned.gates.iter().all(|gate| planned.vouched(gate)) && planned.tree_todo.is_empty() {
924 println!(
925 "{} {} already stamped on this tree — nothing to rehearse",
926 valid_sign(),
927 highlight(&planned.gates.join(" "))
928 );
929 return Ok(Outcome::AlreadyStamped);
930 }
931 let mut settled = false;
937 for _ in 0..3 {
938 let Some(prev) = read() else {
939 settled = true;
940 break;
941 };
942 if !prev.alive() {
943 if prev.phase == Phase::Running {
944 remove_snapshot(repo, &prev.snapshot);
946 }
947 settled = true;
948 break;
949 }
950 if prev.tree == tree {
951 println!(
952 "a rehearsal of this tree is already running (pid {}, started {} ago)",
953 prev.pid,
954 human_secs(prev.age_secs())
955 );
956 return Ok(Outcome::AlreadyRunning(prev.pid));
957 }
958 if prestage.is_some() || prev.prestage {
959 eprintln!(
960 "waiting for the rehearsal of {} (pid {}) before rehearsing {short}",
961 prev.short(),
962 prev.pid,
963 );
964 if follow(&prev, Some(PRESTAGE_WAIT)).is_none() && still_running(&prev) {
965 return Err(format!(
966 "the rehearsal of {} (pid {}) is still running after {}; \
967 not starting another beside it",
968 prev.short(),
969 prev.pid,
970 human_secs(PRESTAGE_WAIT.as_secs())
971 ));
972 }
973 continue;
974 }
975 eprintln!(
976 "cancelling the rehearsal of {} (pid {}) — {} is the tree that matters now",
977 prev.short(),
978 prev.pid,
979 short
980 );
981 cancel(&prev, repo);
982 settled = true;
983 break;
984 }
985 if !settled {
986 return Err("other rehearsals kept starting in this worktree; try again".to_string());
987 }
988 let on_cluster = planned.detach(ask);
991 let Plan {
992 push_ref,
993 manifest,
994 settings,
995 gates,
996 tree_todo,
997 ..
998 } = planned;
999 let local_work = gates
1000 .iter()
1001 .any(|gate| !on_cluster.contains(gate) && !vouched_by(&settings, &manifest, &head, gate));
1002 if !local_work && tree_todo.is_empty() {
1003 eprintln!(
1004 "{} every gate left to rehearse went to the cluster ({}) — the next commit or push collects the result",
1005 valid_sign(),
1006 highlight(&on_cluster.join(" "))
1007 );
1008 return Ok(Outcome::Detached);
1009 }
1010 let snapshot = crate::pushed_tree::PushedTree::checkout(repo, &head)
1011 .ok_or("could not check out HEAD into a snapshot worktree")?;
1012 let mut me = State {
1016 pid: std::process::id(),
1017 commit: head.clone(),
1018 tree,
1019 started: now(),
1020 snapshot: snapshot.path().to_path_buf(),
1021 phase: Phase::Running,
1022 step: Some("preparing".to_string()),
1023 reason: None,
1024 prestage: prestage.is_some(),
1025 signal: None,
1026 };
1027 if let Some(other) = read().filter(|s| s.alive() && s.pid != me.pid) {
1030 if prestage.is_some() || other.prestage {
1031 drop(snapshot);
1032 return Err(format!(
1033 "the rehearsal of {} (pid {}) started meanwhile; try again",
1034 other.short(),
1035 other.pid
1036 ));
1037 }
1038 cancel(&other, repo);
1039 }
1040 write(&me);
1041 if let Err(why) = snapshot.prepare(&settings) {
1042 write(&State {
1043 phase: Phase::Failed,
1044 step: None,
1045 reason: Some(format!("could not prepare the snapshot: {why}")),
1046 ..me
1047 });
1048 drop(snapshot);
1049 return Err(format!("could not prepare the snapshot: {why}"));
1050 }
1051 if !tree_todo.is_empty() {
1052 me.step = Some("tree lint".to_string());
1053 write(&me);
1054 crate::tree_lint::rehearse(&settings, snapshot.path(), &me.tree, &tree_todo);
1055 }
1056 if gates.is_empty() {
1057 write(&State {
1059 phase: Phase::Passed,
1060 step: None,
1061 ..me
1062 });
1063 drop(snapshot);
1064 println!(
1065 "{} rehearsal of {short} done (tree lint only)",
1066 valid_sign()
1067 );
1068 return Ok(Outcome::Passed);
1069 }
1070 me.step = Some("testing".to_string());
1071 write(&me);
1072 println!(
1073 "rehearsing {} for {} in {}",
1074 highlight(&gates.join(" ")),
1075 short,
1076 snapshot.path().display()
1077 );
1078 let hooks_dir = crate::git::stdout(&["rev-parse", "--git-path", "hooks"])
1079 .map(PathBuf::from)
1080 .map(|p| if p.is_absolute() { p } else { repo.join(p) })
1081 .ok_or("could not locate the hooks directory")?;
1082 let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
1083 let mut cmd = Command::new(exe);
1084 cmd.arg("--hooks-dir")
1085 .arg(&hooks_dir)
1086 .arg("pre-push")
1087 .current_dir(snapshot.path())
1088 .env(ENV, snapshot_env_value(&on_cluster, Origin::of(prestage)))
1089 .env(crate::host_slots::ON_BUSY_ENV, "wait")
1093 .env(crate::pushed_tree::SOURCE_WORKTREE_ENV, repo)
1096 .stdin(Stdio::piped());
1097 strip_repo_env(&mut cmd);
1098 let line = format!(
1099 "{} {} {} {}\n",
1100 push_ref.local_ref, push_ref.local_oid, push_ref.remote_ref, push_ref.remote_oid
1101 );
1102 let status = (|| -> std::io::Result<std::process::ExitStatus> {
1103 let mut child = cmd.spawn()?;
1104 if let Some(mut stdin) = child.stdin.take() {
1105 stdin.write_all(line.as_bytes())?;
1106 }
1107 child.wait()
1108 })()
1109 .map_err(|e| format!("could not run the push gate in the snapshot: {e}"))?;
1110 let passed = status.success();
1111 let done = State {
1112 phase: if passed { Phase::Passed } else { Phase::Failed },
1113 step: None,
1114 reason: signal_of(&status).map(|n| format!("the push gate was stopped by signal {n}")),
1115 signal: signal_of(&status),
1116 ..me
1117 };
1118 write(&done);
1119 drop(snapshot);
1120 if let Some(n) = signal_of(&status) {
1121 eprintln!(
1122 "{} rehearsal of {short} stopped by signal {n}",
1123 warning_sign()
1124 );
1125 return Ok(Outcome::Interrupted(n));
1126 }
1127 if passed {
1128 println!("{} rehearsal of {short} passed", valid_sign());
1129 Ok(Outcome::Passed)
1130 } else {
1131 println!("{} rehearsal of {short} FAILED", warning_sign());
1132 Ok(Outcome::Failed)
1133 }
1134}
1135
1136pub fn await_for(settings: &crate::config::Settings, tips: &[String]) -> Option<Phase> {
1145 if in_snapshot() {
1146 return None;
1147 }
1148 let state = read()?;
1149 let on_a_tip = tips.iter().any(|t| {
1150 let spec = format!("{t}^{{tree}}");
1151 crate::git::stdout(&["rev-parse", &spec]).as_deref() == Some(state.tree.as_str())
1152 });
1153 if !on_a_tip {
1154 return None;
1155 }
1156 let log = log_path()
1157 .map(|p| format!(" (log: {})", p.display()))
1158 .unwrap_or_default();
1159 let then = if refuse_unstamped(settings) {
1162 format!("fix it and rehearse again (`{BIN} rehearse --wait`)")
1163 } else {
1164 "running the gate here".to_string()
1165 };
1166 match state.phase {
1167 Phase::Passed => None, Phase::Failed => {
1169 crate::say!(
1170 "{} the background rehearsal of this tree failed {} ago{}{log} — {then}",
1171 warning_sign(),
1172 human_secs(state.age_secs()),
1173 state
1174 .reason
1175 .as_deref()
1176 .map(|r| format!(" ({r})"))
1177 .unwrap_or_default(),
1178 );
1179 None
1180 }
1181 Phase::Running if !process_alive(state.pid) => {
1182 crate::say!(
1183 "{} a background rehearsal of this tree died without a verdict{log} — {then}",
1184 warning_sign(),
1185 );
1186 None
1187 }
1188 Phase::Running => {
1189 let budget = wait_budget(settings);
1190 crate::say!(
1191 "{} a background rehearsal of this tree started {} ago is still running — \
1192 waiting{} for it rather than starting the suite over{log}",
1193 warning_sign(),
1194 human_secs(state.age_secs()),
1195 match budget {
1196 Some(b) => format!(" up to {}", human_secs(b.as_secs())),
1197 None => String::new(),
1198 },
1199 );
1200 let followed = follow(&state, budget).map(|(phase, _)| phase);
1201 if followed.is_none() && still_running(&state) {
1202 warn(&format!(
1206 "the rehearsal is still running after {} — running the gate here \
1207 rather than holding the push open (`git config \
1208 greengate.rehearsalWait <secs>`, or 0 to wait indefinitely)",
1209 human_secs(state.age_secs())
1210 ));
1211 }
1212 followed
1213 }
1214 }
1215}
1216
1217fn follow(state: &State, budget: Option<Duration>) -> Option<(Phase, State)> {
1224 let mut last_word = std::time::Instant::now();
1225 let deadline = budget.map(|b| std::time::Instant::now() + b);
1226 loop {
1227 std::thread::sleep(Duration::from_secs(1));
1228 let now_state = read()?;
1229 if now_state.tree != state.tree || now_state.started != state.started {
1230 return None;
1231 }
1232 match now_state.phase {
1233 Phase::Running => {
1234 if !process_alive(now_state.pid) {
1235 warn("the rehearsal died without a verdict");
1236 return None;
1237 }
1238 if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
1239 return None;
1241 }
1242 if last_word.elapsed() >= Duration::from_secs(60) {
1243 eprintln!(
1244 " still rehearsing ({} so far)",
1245 human_secs(now_state.age_secs())
1246 );
1247 last_word = std::time::Instant::now();
1248 }
1249 }
1250 phase => {
1251 let verb = if phase == Phase::Passed {
1252 format!("{} rehearsal passed", valid_sign())
1253 } else {
1254 format!(
1255 "{} rehearsal failed{}",
1256 warning_sign(),
1257 now_state
1258 .reason
1259 .as_deref()
1260 .map(|r| format!(" ({r})"))
1261 .unwrap_or_default()
1262 )
1263 };
1264 crate::say!("{verb} after {}", human_secs(now_state.age_secs()));
1265 return Some((phase, now_state));
1266 }
1267 }
1268 }
1269}
1270
1271pub fn command(args: &[OsString], prestage: &Prestage) -> i32 {
1273 let flag = |f: &str| args.iter().any(|a| a == f);
1274 let ask = if flag("--cluster") {
1275 crate::cluster::Ask::Flag
1276 } else {
1277 crate::cluster::Ask::Setting
1278 };
1279 let prestage = match prestage {
1280 Prestage::Malformed(raw) => {
1281 eprintln!("{BIN}: {PRESTAGE_ENV} is not a push line ({raw:?}); nothing was rehearsed");
1282 return 2;
1283 }
1284 line => line.line(),
1285 };
1286 if flag("--worker") {
1287 return match worker(ask, prestage) {
1288 Ok(Outcome::Failed) => 1,
1289 Ok(Outcome::Interrupted(n)) => 128 + n,
1290 Ok(_) => 0,
1291 Err(e) => {
1292 eprintln!("{BIN}: {e}");
1293 2
1294 }
1295 };
1296 }
1297 let root = match crate::hooks::common::repo_root_checked() {
1298 Ok(r) => r,
1299 Err(e) => {
1300 eprintln!("{BIN}: {e}");
1301 return 2;
1302 }
1303 };
1304 if flag("--status") {
1305 return status();
1306 }
1307 if flag("--stop") {
1308 let terminated = crate::cluster::stop_pending();
1310 for line in terminated.done.iter().chain(&terminated.failed) {
1311 eprintln!("{line}");
1312 }
1313 match read() {
1314 Some(s) if s.alive() => {
1315 cancel(&s, Path::new(&root));
1316 clear();
1317 println!("stopped the rehearsal of {} (pid {})", s.short(), s.pid);
1318 }
1319 _ if terminated.done.is_empty() && terminated.failed.is_empty() => {
1320 println!("no rehearsal is running in this worktree");
1321 }
1322 _ => {}
1323 }
1324 return i32::from(!terminated.failed.is_empty());
1326 }
1327 if flag("--cluster") && !flag("--wait") {
1328 match plan(prestage) {
1331 Ok(planned) => {
1332 let on_cluster = planned.detach(crate::cluster::Ask::Flag);
1333 let left = planned
1334 .gates
1335 .iter()
1336 .any(|gate| !on_cluster.contains(gate) && !planned.vouched(gate));
1337 if !left && planned.tree_todo.is_empty() && !on_cluster.is_empty() {
1338 return 0;
1339 }
1340 }
1341 Err(e) => {
1342 eprintln!("{BIN}: {e}");
1344 return 1;
1345 }
1346 }
1347 }
1348 let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1349 let running_here = read().filter(|s| s.alive() && Some(s.tree.as_str()) == head.as_deref());
1350 if flag("--wait") {
1351 let target = match prestage {
1365 Some(line) => format!("{}^{{tree}}", line.local_oid),
1366 None => "HEAD^{tree}".to_string(),
1367 };
1368 for _ in 0..3 {
1369 let running = read().filter(|s| {
1370 s.alive()
1371 && Some(s.tree.as_str())
1372 == crate::git::stdout(&["rev-parse", &target]).as_deref()
1373 });
1374 let Some(state) = running else {
1375 match worker(ask, prestage) {
1377 Ok(Outcome::Failed) => return 1,
1378 Ok(Outcome::Interrupted(n)) => return 128 + n,
1379 Ok(Outcome::AlreadyRunning(_)) => continue,
1380 Ok(_) => return 0,
1381 Err(e) => {
1382 eprintln!("{BIN}: {e}");
1383 return 2;
1384 }
1385 }
1386 };
1387 eprintln!(
1388 "following the rehearsal of {} (pid {}, started {} ago)",
1389 state.short(),
1390 state.pid,
1391 human_secs(state.age_secs())
1392 );
1393 match follow(&state, None) {
1394 Some((Phase::Passed, _)) => continue,
1398 Some((
1400 _,
1401 State {
1402 signal: Some(n), ..
1403 },
1404 )) => return 128 + n,
1405 Some(_) => {
1406 show_log_tail();
1407 return 1;
1408 }
1409 None => {
1410 eprintln!("{BIN}: the rehearsal ended without a verdict");
1411 return 2;
1412 }
1413 }
1414 }
1415 eprintln!("{BIN}: another rehearsal keeps claiming this tree — run the gate yourself");
1416 return 2;
1417 }
1418 if let Some(state) = running_here {
1419 println!(
1420 "a rehearsal of this tree is already running (pid {}, started {} ago) — \
1421 `{BIN} rehearse --wait` follows it",
1422 state.pid,
1423 human_secs(state.age_secs())
1424 );
1425 return 0;
1426 }
1427 match spawn_detached() {
1428 Ok(pid) => {
1429 println!(
1430 "rehearsing the push gate for HEAD in the background (pid {pid}) — \
1431 `{BIN} rehearse --wait` follows it, `--status` reports{}",
1432 log_path()
1433 .map(|p| format!("; log: {}", p.display()))
1434 .unwrap_or_default()
1435 );
1436 0
1437 }
1438 Err(e) => {
1439 eprintln!("{BIN}: {e}");
1440 2
1441 }
1442 }
1443}
1444
1445fn status() -> i32 {
1446 let collected = crate::cluster::collect();
1449 let mut detached = crate::cluster::settled_lines(&collected.settled);
1450 detached.extend(crate::cluster::status_lines());
1451 for line in &detached {
1452 println!("{line}");
1453 }
1454 if let Some(trouble) = &collected.trouble {
1455 eprintln!("cluster runs not refreshed — {trouble}");
1456 }
1457 let Some(state) = read() else {
1458 if detached.is_empty() {
1459 println!("no rehearsal recorded in this worktree");
1460 }
1461 return 0;
1462 };
1463 let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
1464 let which = if head.as_deref() == Some(state.tree.as_str()) {
1465 "HEAD's tree".to_string()
1466 } else {
1467 format!("{} (not HEAD's tree)", state.short())
1468 };
1469 let age = human_secs(state.age_secs());
1470 let line = match state.phase {
1471 Phase::Running if state.alive() => {
1472 format!(
1473 "rehearsal of {which}: running for {age} (pid {}{})",
1474 state.pid,
1475 state
1476 .step
1477 .as_deref()
1478 .map(|s| format!(", {s}"))
1479 .unwrap_or_default()
1480 )
1481 }
1482 Phase::Running => {
1483 format!("rehearsal of {which}: died without a verdict, started {age} ago")
1484 }
1485 Phase::Passed => format!("rehearsal of {which}: passed, started {age} ago"),
1486 Phase::Failed => format!(
1487 "rehearsal of {which}: FAILED, started {age} ago{}",
1488 state
1489 .reason
1490 .as_deref()
1491 .map(|r| format!(" — {r}"))
1492 .unwrap_or_default()
1493 ),
1494 };
1495 println!("{line}");
1496 if let Some(log) = log_path().filter(|p| p.exists()) {
1497 println!("log: {}", log.display());
1498 }
1499 0
1500}
1501
1502fn show_log_tail() {
1505 let Some(log) = log_path() else { return };
1506 let Ok(body) = std::fs::read_to_string(&log) else {
1507 return;
1508 };
1509 let lines: Vec<&str> = body.lines().collect();
1510 let start = lines.len().saturating_sub(40);
1511 eprintln!(
1512 "--- {} (last {} lines) ---",
1513 log.display(),
1514 lines.len() - start
1515 );
1516 for l in &lines[start..] {
1517 eprintln!("{l}");
1518 }
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523 use super::*;
1524
1525 fn sample() -> State {
1526 State {
1527 pid: 4242,
1528 commit: "a".repeat(40),
1529 tree: "b".repeat(40),
1530 started: 1_700_000_000,
1531 snapshot: PathBuf::from("/tmp/greengate-push-1-2"),
1532 phase: Phase::Running,
1533 step: Some("preparing".to_string()),
1534 reason: None,
1535 prestage: false,
1536 signal: None,
1537 }
1538 }
1539
1540 #[test]
1541 fn the_prestage_marker_leaves_the_detached_gates_intact() {
1542 let marked = parse_snapshot_env("prestage;detached=a,b");
1543 assert!(marked.prestage);
1544 assert_eq!(marked.detached, ["a", "b"]);
1545 let plain = parse_snapshot_env("detached=a,b");
1546 assert!(!plain.prestage);
1547 assert_eq!(plain.detached, ["a", "b"]);
1548 let bare = parse_snapshot_env("1");
1549 assert!(!bare.prestage);
1550 assert!(bare.detached.is_empty());
1551 let marked_bare = parse_snapshot_env("prestage;1");
1552 assert!(marked_bare.prestage);
1553 assert!(marked_bare.detached.is_empty());
1554 }
1555
1556 #[test]
1559 fn a_prestage_survives_the_state_file() {
1560 let staged = State {
1561 prestage: true,
1562 signal: Some(9),
1563 ..sample()
1564 };
1565 assert_eq!(State::parse(&staged.render()), Some(staged));
1566 assert_eq!(State::parse(&sample().render()), Some(sample()));
1567 }
1568
1569 #[test]
1572 fn the_land_variables_take_object_names_only() {
1573 let (a, b) = ("a".repeat(40), "0".repeat(40));
1574 assert_eq!(
1575 LandEnv::parse(&format!("{a} {b}")),
1576 LandEnv::Valid(LandLine {
1577 sha: a.clone(),
1578 remote_tip: b.clone()
1579 })
1580 );
1581 for bad in [
1582 "",
1583 "abc",
1584 a.as_str(),
1585 &format!("{a} {b} extra"),
1586 &format!("{a} xyz"),
1587 ] {
1588 assert!(
1589 matches!(LandEnv::parse(bad), LandEnv::Malformed(_)),
1590 "{bad:?}"
1591 );
1592 }
1593 assert!(matches!(
1594 Prestage::parse(&format!("refs/heads/x {a} refs/heads/x {b}")),
1595 Prestage::Of(_)
1596 ));
1597 for bad in [
1598 format!("refs/heads/x {a} refs/heads/x"),
1599 "x y z w".to_string(),
1600 ] {
1601 assert!(
1602 matches!(Prestage::parse(&bad), Prestage::Malformed(_)),
1603 "{bad:?}"
1604 );
1605 }
1606 }
1607
1608 #[test]
1609 fn a_state_survives_the_round_trip() {
1610 let s = sample();
1611 assert_eq!(State::parse(&s.render()), Some(s));
1612 let done = State {
1613 phase: Phase::Failed,
1614 step: None,
1615 reason: Some("could not prepare the snapshot: npm ci failed\nin web/".to_string()),
1616 ..sample()
1617 };
1618 let back = State::parse(&done.render()).expect("parses");
1619 assert_eq!(
1620 back.reason.as_deref(),
1621 Some("could not prepare the snapshot: npm ci failed in web/"),
1622 "a reason is kept on one line"
1623 );
1624 assert_eq!(back.phase, Phase::Failed);
1625 }
1626
1627 #[test]
1630 fn a_foreign_or_partial_file_is_no_rehearsal() {
1631 assert_eq!(State::parse(""), None);
1632 assert_eq!(State::parse("greengate-rehearsal-v2\npid=1\n"), None);
1633 assert_eq!(State::parse("greengate-rehearsal-v1\npid=1\n"), None);
1634 assert_eq!(
1635 State::parse("greengate-rehearsal-v1\npid=x\ncommit=a\ntree=b\nstarted=1\nsnapshot=/s\nphase=running\n"),
1636 None
1637 );
1638 }
1639
1640 #[test]
1643 fn a_dead_pid_is_not_alive() {
1644 let s = State {
1645 pid: u32::MAX - 7,
1646 ..sample()
1647 };
1648 assert!(!s.alive());
1649 let done = State {
1650 phase: Phase::Passed,
1651 pid: std::process::id(),
1652 ..sample()
1653 };
1654 assert!(
1655 !done.alive(),
1656 "a finished rehearsal is not running whoever's pid it names"
1657 );
1658 }
1659}