use crate::names::BIN;
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::hooks::common::{human_secs, warn};
use crate::ui::{highlight, valid_sign, warning_sign};
const ON_COMMIT: &str = "amont.rehearseOnCommit";
const WAIT_BUDGET: &str = "amont.rehearsalWait";
pub fn wait_budget(settings: &crate::config::Settings) -> Option<Duration> {
match crate::config::integer_or(settings, WAIT_BUDGET, 300, 0..=86_400) {
0 => None,
secs => Some(Duration::from_secs(secs as u64)),
}
}
const STATE: &str = "amont-rehearsal";
const LOG: &str = "amont-rehearsal.log";
const FORMAT: &str = "amont-rehearsal-v1";
pub const ENV: &str = "AMONT_REHEARSAL";
pub fn on_commit_enabled(settings: &crate::config::Settings) -> bool {
crate::config::boolean_or(settings, ON_COMMIT, false)
}
const UNSTAMPED_PUSH: &str = "amont.unstampedPush";
pub fn refuse_unstamped(settings: &crate::config::Settings) -> bool {
crate::config::enumerated_or(settings, UNSTAMPED_PUSH, &["run", "refuse"], "run") == "refuse"
}
pub fn in_snapshot() -> bool {
snapshot_env().is_some()
}
const DETACHED_PREFIX: &str = "detached=";
struct SnapshotEnv {
detached: Vec<String>,
prestage: bool,
}
const PRESTAGE_PREFIX: &str = "prestage;";
fn parse_snapshot_env(raw: &str) -> SnapshotEnv {
let (prestage, rest) = match raw.strip_prefix(PRESTAGE_PREFIX) {
Some(rest) => (true, rest),
None => (false, raw),
};
let detached = rest
.strip_prefix(DETACHED_PREFIX)
.map(|ids| ids.split(',').map(str::to_string).collect())
.unwrap_or_default();
SnapshotEnv { detached, prestage }
}
fn snapshot_env() -> &'static Option<SnapshotEnv> {
static IN: std::sync::OnceLock<Option<SnapshotEnv>> = std::sync::OnceLock::new();
IN.get_or_init(|| {
let raw = std::env::var_os(ENV).map(|v| v.to_string_lossy().into_owned())?;
std::env::remove_var(ENV);
Some(parse_snapshot_env(&raw))
})
}
pub fn in_prestage() -> bool {
snapshot_env().as_ref().is_some_and(|env| env.prestage)
}
pub fn handed_to_cluster() -> &'static [String] {
snapshot_env()
.as_ref()
.map_or(&[], |env| env.detached.as_slice())
}
pub const LAND_ENV: &str = "AMONT_LAND";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LandLine {
pub sha: String,
pub remote_tip: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LandEnv {
Absent,
Valid(LandLine),
Malformed(String),
}
fn is_oid(s: &str) -> bool {
matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
}
impl LandEnv {
pub fn parse(raw: &str) -> LandEnv {
let fields: Vec<&str> = raw.split_whitespace().collect();
match fields.as_slice() {
[sha, remote_tip] if is_oid(sha) && is_oid(remote_tip) => LandEnv::Valid(LandLine {
sha: sha.to_string(),
remote_tip: remote_tip.to_string(),
}),
_ => LandEnv::Malformed(raw.to_string()),
}
}
}
pub fn land_env() -> &'static LandEnv {
static IN: std::sync::OnceLock<LandEnv> = std::sync::OnceLock::new();
IN.get_or_init(|| match std::env::var_os(LAND_ENV) {
None => LandEnv::Absent,
Some(raw) => {
std::env::remove_var(LAND_ENV);
LandEnv::parse(&raw.to_string_lossy())
}
})
}
pub const PRESTAGE_ENV: &str = "AMONT_LAND_PRESTAGE";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Prestage {
Absent,
Of(crate::pushrefs::PushRef),
Malformed(String),
}
impl Prestage {
pub fn parse(raw: &str) -> Prestage {
let fields: Vec<&str> = raw.split_whitespace().collect();
match fields.as_slice() {
[local_ref, local_oid, remote_ref, remote_oid]
if is_oid(local_oid) && is_oid(remote_oid) =>
{
Prestage::Of(crate::pushrefs::PushRef {
local_ref: local_ref.to_string(),
local_oid: local_oid.to_string(),
remote_ref: remote_ref.to_string(),
remote_oid: remote_oid.to_string(),
})
}
_ => Prestage::Malformed(raw.to_string()),
}
}
fn line(&self) -> Option<&crate::pushrefs::PushRef> {
match self {
Prestage::Of(line) => Some(line),
Prestage::Absent | Prestage::Malformed(_) => None,
}
}
}
pub fn source_worktree() -> Option<&'static std::path::Path> {
static IN: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
IN.get_or_init(|| {
let raw = std::env::var_os(crate::pushed_tree::SOURCE_WORKTREE_ENV)?;
std::env::remove_var(crate::pushed_tree::SOURCE_WORKTREE_ENV);
Some(std::path::PathBuf::from(raw))
})
.as_deref()
}
pub fn prestage() -> &'static Prestage {
static IN: std::sync::OnceLock<Prestage> = std::sync::OnceLock::new();
IN.get_or_init(|| match std::env::var_os(PRESTAGE_ENV) {
None => Prestage::Absent,
Some(raw) => {
std::env::remove_var(PRESTAGE_ENV);
Prestage::parse(&raw.to_string_lossy())
}
})
}
const PUSH_GATES: &str = "amont.pushGates";
pub fn refuse_push_gates(settings: &crate::config::Settings) -> bool {
crate::config::enumerated_or(settings, PUSH_GATES, &["refuse", "inline"], "refuse") == "refuse"
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
Running,
Passed,
Failed,
}
impl Phase {
fn as_str(self) -> &'static str {
match self {
Phase::Running => "running",
Phase::Passed => "passed",
Phase::Failed => "failed",
}
}
fn parse(s: &str) -> Option<Phase> {
match s {
"running" => Some(Phase::Running),
"passed" => Some(Phase::Passed),
"failed" => Some(Phase::Failed),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct State {
pub pid: u32,
pub commit: String,
pub tree: String,
pub started: u64,
pub snapshot: PathBuf,
pub phase: Phase,
pub step: Option<String>,
pub reason: Option<String>,
pub prestage: bool,
pub signal: Option<i32>,
}
impl State {
fn render(&self) -> String {
format!(
"{FORMAT}\npid={}\ncommit={}\ntree={}\nstarted={}\nsnapshot={}\nphase={}\n",
self.pid,
self.commit,
self.tree,
self.started,
self.snapshot.display(),
self.phase.as_str(),
) + &[("step", &self.step), ("reason", &self.reason)]
.iter()
.filter_map(|(k, v)| v.as_ref().map(|v| format!("{k}={}\n", one_line(v))))
.collect::<String>()
+ if self.prestage { "kind=prestage\n" } else { "" }
+ &self
.signal
.map(|n| format!("signal={n}\n"))
.unwrap_or_default()
}
pub fn parse(body: &str) -> Option<State> {
let mut lines = body.lines();
if lines.next()? != FORMAT {
return None;
}
let (mut pid, mut commit, mut tree, mut started, mut snapshot, mut phase) =
(None, None, None, None, None, None);
let (mut step, mut reason, mut prestage, mut signal) = (None, None, false, None);
for line in lines {
let (k, v) = line.split_once('=')?;
match k {
"pid" => pid = v.parse().ok(),
"commit" => commit = Some(v.to_string()),
"tree" => tree = Some(v.to_string()),
"started" => started = v.parse().ok(),
"snapshot" => snapshot = Some(PathBuf::from(v)),
"phase" => phase = Phase::parse(v),
"step" => step = Some(v.to_string()),
"reason" => reason = Some(v.to_string()),
"kind" => prestage = v == "prestage",
"signal" => signal = v.parse().ok(),
_ => {}
}
}
Some(State {
pid: pid?,
commit: commit?,
tree: tree?,
started: started?,
snapshot: snapshot?,
phase: phase?,
step,
reason,
prestage,
signal,
})
}
pub fn alive(&self) -> bool {
self.phase == Phase::Running && process_alive(self.pid)
}
pub fn age_secs(&self) -> u64 {
now().saturating_sub(self.started)
}
fn short(&self) -> &str {
self.commit.get(..8).unwrap_or(&self.commit)
}
}
fn one_line(v: &str) -> String {
v.replace(['\n', '\r'], " ")
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn git_dir() -> Option<PathBuf> {
crate::git::stdout(&["rev-parse", "--absolute-git-dir"]).map(PathBuf::from)
}
fn state_path() -> Option<PathBuf> {
git_dir().map(|d| d.join(STATE))
}
pub fn log_path() -> Option<PathBuf> {
git_dir().map(|d| d.join(LOG))
}
pub fn read() -> Option<State> {
let body = std::fs::read_to_string(state_path()?).ok()?;
State::parse(&body)
}
fn write(state: &State) {
if let Some(path) = state_path() {
let _ = std::fs::write(path, state.render());
}
}
fn clear() {
if let Some(path) = state_path() {
let _ = std::fs::remove_file(path);
}
}
pub fn process_alive(pid: u32) -> bool {
#[cfg(unix)]
{
Command::new("kill")
.args(["-0", &pid.to_string()])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[cfg(not(unix))]
{
Command::new("tasklist")
.args(["/FI", &format!("PID eq {pid}"), "/NH"])
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string()))
.unwrap_or(false)
}
}
fn kill_group(pid: u32) {
#[cfg(unix)]
{
let _ = Command::new("kill")
.args(["-TERM", "--", &format!("-{pid}")])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
#[cfg(not(unix))]
{
let _ = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
}
fn cancel(state: &State, repo: &Path) {
if state.alive() {
kill_group(state.pid);
for _ in 0..20 {
if !process_alive(state.pid) {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
}
remove_snapshot(repo, &state.snapshot);
}
fn remove_snapshot(repo: &Path, path: &Path) {
if path.as_os_str().is_empty() || !path.exists() {
let _ = crate::git::succeeds_in(repo, &["worktree", "prune"]);
return;
}
let _ = crate::git::succeeds_in(
repo,
&[
"worktree",
"remove",
"--force",
path.to_str().unwrap_or_default(),
],
);
let _ = std::fs::remove_dir_all(path);
let _ = crate::git::succeeds_in(repo, &["worktree", "prune"]);
}
fn strip_repo_env(cmd: &mut Command) {
for key in [
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_PREFIX",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_NAMESPACE",
"GIT_REFLOG_ACTION",
"GIT_EXEC_PATH",
crate::hooks::common::INDEX_ENV,
crate::hooks::common::INDEX_GIT_DIR_ENV,
] {
cmd.env_remove(key);
}
}
#[cfg(not(unix))]
pub fn spawn_detached() -> Result<u32, String> {
Err(format!(
"background rehearsal is not available on Windows yet — \
`{BIN} rehearse --wait` runs it in the foreground"
))
}
#[cfg(unix)]
pub fn spawn_detached() -> Result<u32, String> {
let log = log_path().ok_or("not inside a git repository")?;
spawn_amont(&["rehearse", "--worker"], &log)
}
#[cfg(unix)]
pub fn spawn_amont(args: &[&str], log: &std::path::Path) -> Result<u32, String> {
use std::os::unix::process::CommandExt;
let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
let file =
std::fs::File::create(log).map_err(|e| format!("cannot open {}: {e}", log.display()))?;
let err = file
.try_clone()
.map_err(|e| format!("cannot open {}: {e}", log.display()))?;
let mut cmd = Command::new(exe);
cmd.args(args)
.stdin(Stdio::null())
.stdout(Stdio::from(file))
.stderr(Stdio::from(err));
strip_repo_env(&mut cmd);
cmd.process_group(0);
let child = cmd
.spawn()
.map_err(|e| format!("cannot start {BIN} {}: {e}", args.join(" ")))?;
Ok(child.id())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
NothingToDo,
AlreadyStamped,
AlreadyRunning(u32),
Detached,
Passed,
Failed,
Interrupted(i32),
}
pub(crate) fn signal_of(status: &std::process::ExitStatus) -> Option<i32> {
#[cfg(unix)]
{
std::os::unix::process::ExitStatusExt::signal(status)
}
#[cfg(not(unix))]
{
let _ = status;
None
}
}
fn still_running(state: &State) -> bool {
read().is_some_and(|now| now.alive() && now.pid == state.pid && now.started == state.started)
}
const PRESTAGE_WAIT: Duration = Duration::from_secs(3 * 60 * 60);
struct Plan {
root: String,
head: String,
tree: String,
push_ref: crate::pushrefs::PushRef,
manifest: crate::manifest::Manifest,
settings: crate::config::Settings,
gates: Vec<String>,
tree_todo: Vec<crate::manifest::TreeGate>,
audits: crate::hooks::audit::Ledger,
}
fn plan(prestage: Option<&crate::pushrefs::PushRef>) -> Result<Plan, String> {
let root = crate::hooks::common::repo_root_checked()?;
let repo = Path::new(&root);
let head = match prestage {
Some(line) => crate::git::stdout(&["rev-parse", &format!("{}^{{commit}}", line.local_oid)])
.ok_or("could not resolve the commit to pre-stage")?,
None => crate::git::stdout(&["rev-parse", "HEAD"]).ok_or("could not resolve HEAD")?,
};
let tree = crate::git::stdout(&["rev-parse", &format!("{head}^{{tree}}")])
.ok_or("could not resolve the tree to rehearse")?;
let push_ref = match prestage {
Some(line) => line.clone(),
None => crate::pushrefs::synthetic_from_upstream()?,
};
let manifest = crate::manifest::load(repo);
let settings = crate::config::Settings::new(manifest.policy.clone());
let changed = crate::pushrefs::changed_files(std::slice::from_ref(&push_ref));
let mut gates = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
let audits = crate::hooks::audit::Ledger::default();
for audit in crate::dispatch::owed_audits(
&settings,
&manifest,
&audits,
std::slice::from_ref(&push_ref),
) {
if !gates.contains(&audit) {
gates.push(audit);
}
}
let proven_here = crate::gate_stamp::tree_tokens(&tree);
let tree_todo: Vec<crate::manifest::TreeGate> = if crate::tree_lint::enabled(&settings) {
manifest
.tree
.iter()
.filter(|g| !proven_here.contains(&g.stamp_key()))
.cloned()
.collect()
} else {
Vec::new()
};
Ok(Plan {
root,
head,
tree,
push_ref,
manifest,
settings,
gates,
tree_todo,
audits,
})
}
impl Plan {
fn vouched(&self, gate: &str) -> bool {
if crate::hooks::audit::is_audit(gate) {
return !crate::hooks::audit::owed(
&self.settings,
&self.audits,
gate,
std::slice::from_ref(&self.push_ref),
);
}
vouched_by(&self.settings, &self.manifest, &self.head, gate)
}
fn detach(&self, ask: crate::cluster::Ask) -> Vec<String> {
let unstamped: Vec<String> = self
.gates
.iter()
.filter(|gate| !self.vouched(gate))
.cloned()
.collect();
crate::cluster::detach(&self.settings, &self.manifest, &unstamped, ask).gates
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
Push,
Prestage,
}
impl Origin {
fn of(prestage: Option<&crate::pushrefs::PushRef>) -> Origin {
match prestage {
Some(_) => Origin::Prestage,
None => Origin::Push,
}
}
}
fn snapshot_env_value(on_cluster: &[String], origin: Origin) -> String {
let marker = match origin {
Origin::Push => "",
Origin::Prestage => PRESTAGE_PREFIX,
};
if on_cluster.is_empty() {
format!("{marker}1")
} else {
format!("{marker}{DETACHED_PREFIX}{}", on_cluster.join(","))
}
}
fn vouched_by(
settings: &crate::config::Settings,
manifest: &crate::manifest::Manifest,
head: &str,
gate: &str,
) -> bool {
let tips = [head.to_string()];
let stamped = crate::gate_stamp::stamps_for(&tips);
let local = crate::gate_identity::token(&manifest.externals, gate)
.is_some_and(|t| stamped.get(head).is_some_and(|s| s.contains(&t)));
local
|| manifest
.externals
.iter()
.find(|e| e.id == gate)
.is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
}
pub fn worker(
ask: crate::cluster::Ask,
prestage: Option<&crate::pushrefs::PushRef>,
) -> Result<Outcome, String> {
let planned = plan(prestage)?;
let repo = Path::new(&planned.root);
let (head, tree) = (planned.head.clone(), planned.tree.clone());
let short = head.get(..8).unwrap_or(&head);
if planned.gates.is_empty() && planned.tree_todo.is_empty() {
println!("nothing to rehearse: no test gate has work to do for what {short} would push");
return Ok(Outcome::NothingToDo);
}
if planned.gates.iter().all(|gate| planned.vouched(gate)) && planned.tree_todo.is_empty() {
println!(
"{} {} already stamped on this tree — nothing to rehearse",
valid_sign(),
highlight(&planned.gates.join(" "))
);
return Ok(Outcome::AlreadyStamped);
}
let mut settled = false;
for _ in 0..3 {
let Some(prev) = read() else {
settled = true;
break;
};
if !prev.alive() {
if prev.phase == Phase::Running {
remove_snapshot(repo, &prev.snapshot);
}
settled = true;
break;
}
if prev.tree == tree {
println!(
"a rehearsal of this tree is already running (pid {}, started {} ago)",
prev.pid,
human_secs(prev.age_secs())
);
return Ok(Outcome::AlreadyRunning(prev.pid));
}
if prestage.is_some() || prev.prestage {
eprintln!(
"waiting for the rehearsal of {} (pid {}) before rehearsing {short}",
prev.short(),
prev.pid,
);
if follow(&prev, Some(PRESTAGE_WAIT)).is_none() && still_running(&prev) {
return Err(format!(
"the rehearsal of {} (pid {}) is still running after {}; \
not starting another beside it",
prev.short(),
prev.pid,
human_secs(PRESTAGE_WAIT.as_secs())
));
}
continue;
}
eprintln!(
"cancelling the rehearsal of {} (pid {}) — {} is the tree that matters now",
prev.short(),
prev.pid,
short
);
cancel(&prev, repo);
settled = true;
break;
}
if !settled {
return Err("other rehearsals kept starting in this worktree; try again".to_string());
}
let on_cluster = planned.detach(ask);
let Plan {
push_ref,
manifest,
settings,
gates,
tree_todo,
..
} = planned;
let local_work = gates
.iter()
.any(|gate| !on_cluster.contains(gate) && !vouched_by(&settings, &manifest, &head, gate));
if !local_work && tree_todo.is_empty() {
eprintln!(
"{} every gate left to rehearse went to the cluster ({}) — the next commit or push collects the result",
valid_sign(),
highlight(&on_cluster.join(" "))
);
return Ok(Outcome::Detached);
}
let snapshot = crate::pushed_tree::PushedTree::checkout(repo, &head)
.ok_or("could not check out HEAD into a snapshot worktree")?;
let mut me = State {
pid: std::process::id(),
commit: head.clone(),
tree,
started: now(),
snapshot: snapshot.path().to_path_buf(),
phase: Phase::Running,
step: Some("preparing".to_string()),
reason: None,
prestage: prestage.is_some(),
signal: None,
};
if let Some(other) = read().filter(|s| s.alive() && s.pid != me.pid) {
if prestage.is_some() || other.prestage {
drop(snapshot);
return Err(format!(
"the rehearsal of {} (pid {}) started meanwhile; try again",
other.short(),
other.pid
));
}
cancel(&other, repo);
}
write(&me);
if let Err(why) = snapshot.prepare(&settings) {
write(&State {
phase: Phase::Failed,
step: None,
reason: Some(format!("could not prepare the snapshot: {why}")),
..me
});
drop(snapshot);
return Err(format!("could not prepare the snapshot: {why}"));
}
if !tree_todo.is_empty() {
me.step = Some("tree lint".to_string());
write(&me);
crate::tree_lint::rehearse(&settings, snapshot.path(), &me.tree, &tree_todo);
}
if gates.is_empty() {
write(&State {
phase: Phase::Passed,
step: None,
..me
});
drop(snapshot);
println!(
"{} rehearsal of {short} done (tree lint only)",
valid_sign()
);
return Ok(Outcome::Passed);
}
me.step = Some("testing".to_string());
write(&me);
println!(
"rehearsing {} for {} in {}",
highlight(&gates.join(" ")),
short,
snapshot.path().display()
);
let hooks_dir = crate::git::stdout(&["rev-parse", "--git-path", "hooks"])
.map(PathBuf::from)
.map(|p| if p.is_absolute() { p } else { repo.join(p) })
.ok_or("could not locate the hooks directory")?;
let exe = std::env::current_exe().map_err(|e| format!("cannot locate {BIN}: {e}"))?;
let mut cmd = Command::new(exe);
cmd.arg("--hooks-dir")
.arg(&hooks_dir)
.arg("pre-push")
.current_dir(snapshot.path())
.env(ENV, snapshot_env_value(&on_cluster, Origin::of(prestage)))
.env(crate::host_slots::ON_BUSY_ENV, "wait")
.env(crate::pushed_tree::SOURCE_WORKTREE_ENV, repo)
.stdin(Stdio::piped());
strip_repo_env(&mut cmd);
let line = format!(
"{} {} {} {}\n",
push_ref.local_ref, push_ref.local_oid, push_ref.remote_ref, push_ref.remote_oid
);
let status = (|| -> std::io::Result<std::process::ExitStatus> {
let mut child = cmd.spawn()?;
if let Some(mut stdin) = child.stdin.take() {
stdin.write_all(line.as_bytes())?;
}
child.wait()
})()
.map_err(|e| format!("could not run the push gate in the snapshot: {e}"))?;
let passed = status.success();
let done = State {
phase: if passed { Phase::Passed } else { Phase::Failed },
step: None,
reason: signal_of(&status).map(|n| format!("the push gate was stopped by signal {n}")),
signal: signal_of(&status),
..me
};
write(&done);
drop(snapshot);
if let Some(n) = signal_of(&status) {
eprintln!(
"{} rehearsal of {short} stopped by signal {n}",
warning_sign()
);
return Ok(Outcome::Interrupted(n));
}
if passed {
println!("{} rehearsal of {short} passed", valid_sign());
Ok(Outcome::Passed)
} else {
println!("{} rehearsal of {short} FAILED", warning_sign());
Ok(Outcome::Failed)
}
}
pub fn await_for(settings: &crate::config::Settings, tips: &[String]) -> Option<Phase> {
if in_snapshot() {
return None;
}
let state = read()?;
let on_a_tip = tips.iter().any(|t| {
let spec = format!("{t}^{{tree}}");
crate::git::stdout(&["rev-parse", &spec]).as_deref() == Some(state.tree.as_str())
});
if !on_a_tip {
return None;
}
let log = log_path()
.map(|p| format!(" (log: {})", p.display()))
.unwrap_or_default();
let then = if refuse_unstamped(settings) {
format!("fix it and rehearse again (`{BIN} rehearse --wait`)")
} else {
"running the gate here".to_string()
};
match state.phase {
Phase::Passed => None, Phase::Failed => {
crate::say!(
"{} the background rehearsal of this tree failed {} ago{}{log} — {then}",
warning_sign(),
human_secs(state.age_secs()),
state
.reason
.as_deref()
.map(|r| format!(" ({r})"))
.unwrap_or_default(),
);
None
}
Phase::Running if !process_alive(state.pid) => {
crate::say!(
"{} a background rehearsal of this tree died without a verdict{log} — {then}",
warning_sign(),
);
None
}
Phase::Running => {
let budget = wait_budget(settings);
crate::say!(
"{} a background rehearsal of this tree started {} ago is still running — \
waiting{} for it rather than starting the suite over{log}",
warning_sign(),
human_secs(state.age_secs()),
match budget {
Some(b) => format!(" up to {}", human_secs(b.as_secs())),
None => String::new(),
},
);
let followed = follow(&state, budget).map(|(phase, _)| phase);
if followed.is_none() && still_running(&state) {
warn(&format!(
"the rehearsal is still running after {} — running the gate here \
rather than holding the push open (`git config \
amont.rehearsalWait <secs>`, or 0 to wait indefinitely)",
human_secs(state.age_secs())
));
}
followed
}
}
}
fn follow(state: &State, budget: Option<Duration>) -> Option<(Phase, State)> {
let mut last_word = std::time::Instant::now();
let deadline = budget.map(|b| std::time::Instant::now() + b);
loop {
std::thread::sleep(Duration::from_secs(1));
let now_state = read()?;
if now_state.tree != state.tree || now_state.started != state.started {
return None;
}
match now_state.phase {
Phase::Running => {
if !process_alive(now_state.pid) {
warn("the rehearsal died without a verdict");
return None;
}
if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
return None;
}
if last_word.elapsed() >= Duration::from_secs(60) {
eprintln!(
" still rehearsing ({} so far)",
human_secs(now_state.age_secs())
);
last_word = std::time::Instant::now();
}
}
phase => {
let verb = if phase == Phase::Passed {
format!("{} rehearsal passed", valid_sign())
} else {
format!(
"{} rehearsal failed{}",
warning_sign(),
now_state
.reason
.as_deref()
.map(|r| format!(" ({r})"))
.unwrap_or_default()
)
};
crate::say!("{verb} after {}", human_secs(now_state.age_secs()));
return Some((phase, now_state));
}
}
}
}
pub fn command(args: &[OsString], prestage: &Prestage) -> i32 {
let flag = |f: &str| args.iter().any(|a| a == f);
let ask = if flag("--cluster") {
crate::cluster::Ask::Flag
} else {
crate::cluster::Ask::Setting
};
let prestage = match prestage {
Prestage::Malformed(raw) => {
eprintln!("{BIN}: {PRESTAGE_ENV} is not a push line ({raw:?}); nothing was rehearsed");
return 2;
}
line => line.line(),
};
if flag("--worker") {
return match worker(ask, prestage) {
Ok(Outcome::Failed) => 1,
Ok(Outcome::Interrupted(n)) => 128 + n,
Ok(_) => 0,
Err(e) => {
eprintln!("{BIN}: {e}");
2
}
};
}
let root = match crate::hooks::common::repo_root_checked() {
Ok(r) => r,
Err(e) => {
eprintln!("{BIN}: {e}");
return 2;
}
};
if flag("--status") {
return status();
}
if flag("--stop") {
let terminated = crate::cluster::stop_pending();
for line in terminated.done.iter().chain(&terminated.failed) {
eprintln!("{line}");
}
match read() {
Some(s) if s.alive() => {
cancel(&s, Path::new(&root));
clear();
println!("stopped the rehearsal of {} (pid {})", s.short(), s.pid);
}
_ if terminated.done.is_empty() && terminated.failed.is_empty() => {
println!("no rehearsal is running in this worktree");
}
_ => {}
}
return i32::from(!terminated.failed.is_empty());
}
if flag("--cluster") && !flag("--wait") {
match plan(prestage) {
Ok(planned) => {
let on_cluster = planned.detach(crate::cluster::Ask::Flag);
let left = planned
.gates
.iter()
.any(|gate| !on_cluster.contains(gate) && !planned.vouched(gate));
if !left && planned.tree_todo.is_empty() && !on_cluster.is_empty() {
return 0;
}
}
Err(e) => {
eprintln!("{BIN}: {e}");
return 1;
}
}
}
let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
let running_here = read().filter(|s| s.alive() && Some(s.tree.as_str()) == head.as_deref());
if flag("--wait") {
let target = match prestage {
Some(line) => format!("{}^{{tree}}", line.local_oid),
None => "HEAD^{tree}".to_string(),
};
for _ in 0..3 {
let running = read().filter(|s| {
s.alive()
&& Some(s.tree.as_str())
== crate::git::stdout(&["rev-parse", &target]).as_deref()
});
let Some(state) = running else {
match worker(ask, prestage) {
Ok(Outcome::Failed) => return 1,
Ok(Outcome::Interrupted(n)) => return 128 + n,
Ok(Outcome::AlreadyRunning(_)) => continue,
Ok(_) => return 0,
Err(e) => {
eprintln!("{BIN}: {e}");
return 2;
}
}
};
eprintln!(
"following the rehearsal of {} (pid {}, started {} ago)",
state.short(),
state.pid,
human_secs(state.age_secs())
);
match follow(&state, None) {
Some((Phase::Passed, _)) => continue,
Some((
_,
State {
signal: Some(n), ..
},
)) => return 128 + n,
Some(_) => {
show_log_tail();
return 1;
}
None => {
eprintln!("{BIN}: the rehearsal ended without a verdict");
return 2;
}
}
}
eprintln!("{BIN}: another rehearsal keeps claiming this tree — run the gate yourself");
return 2;
}
if let Some(state) = running_here {
println!(
"a rehearsal of this tree is already running (pid {}, started {} ago) — \
`{BIN} rehearse --wait` follows it",
state.pid,
human_secs(state.age_secs())
);
return 0;
}
match spawn_detached() {
Ok(pid) => {
println!(
"rehearsing the push gate for HEAD in the background (pid {pid}) — \
`{BIN} rehearse --wait` follows it, `--status` reports{}",
log_path()
.map(|p| format!("; log: {}", p.display()))
.unwrap_or_default()
);
0
}
Err(e) => {
eprintln!("{BIN}: {e}");
2
}
}
}
fn status() -> i32 {
let collected = crate::cluster::collect();
let mut detached = crate::cluster::settled_lines(&collected.settled);
detached.extend(crate::cluster::status_lines());
for line in &detached {
println!("{line}");
}
if let Some(trouble) = &collected.trouble {
eprintln!("cluster runs not refreshed — {trouble}");
}
let Some(state) = read() else {
if detached.is_empty() {
println!("no rehearsal recorded in this worktree");
}
return 0;
};
let head = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
let which = if head.as_deref() == Some(state.tree.as_str()) {
"HEAD's tree".to_string()
} else {
format!("{} (not HEAD's tree)", state.short())
};
let age = human_secs(state.age_secs());
let line = match state.phase {
Phase::Running if state.alive() => {
format!(
"rehearsal of {which}: running for {age} (pid {}{})",
state.pid,
state
.step
.as_deref()
.map(|s| format!(", {s}"))
.unwrap_or_default()
)
}
Phase::Running => {
format!("rehearsal of {which}: died without a verdict, started {age} ago")
}
Phase::Passed => format!("rehearsal of {which}: passed, started {age} ago"),
Phase::Failed => format!(
"rehearsal of {which}: FAILED, started {age} ago{}",
state
.reason
.as_deref()
.map(|r| format!(" — {r}"))
.unwrap_or_default()
),
};
println!("{line}");
if let Some(log) = log_path().filter(|p| p.exists()) {
println!("log: {}", log.display());
}
0
}
fn show_log_tail() {
let Some(log) = log_path() else { return };
let Ok(body) = std::fs::read_to_string(&log) else {
return;
};
let lines: Vec<&str> = body.lines().collect();
let start = lines.len().saturating_sub(40);
eprintln!(
"--- {} (last {} lines) ---",
log.display(),
lines.len() - start
);
for l in &lines[start..] {
eprintln!("{l}");
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> State {
State {
pid: 4242,
commit: "a".repeat(40),
tree: "b".repeat(40),
started: 1_700_000_000,
snapshot: PathBuf::from("/tmp/amont-push-1-2"),
phase: Phase::Running,
step: Some("preparing".to_string()),
reason: None,
prestage: false,
signal: None,
}
}
#[test]
fn the_prestage_marker_leaves_the_detached_gates_intact() {
let marked = parse_snapshot_env("prestage;detached=a,b");
assert!(marked.prestage);
assert_eq!(marked.detached, ["a", "b"]);
let plain = parse_snapshot_env("detached=a,b");
assert!(!plain.prestage);
assert_eq!(plain.detached, ["a", "b"]);
let bare = parse_snapshot_env("1");
assert!(!bare.prestage);
assert!(bare.detached.is_empty());
let marked_bare = parse_snapshot_env("prestage;1");
assert!(marked_bare.prestage);
assert!(marked_bare.detached.is_empty());
}
#[test]
fn a_prestage_survives_the_state_file() {
let staged = State {
prestage: true,
signal: Some(9),
..sample()
};
assert_eq!(State::parse(&staged.render()), Some(staged));
assert_eq!(State::parse(&sample().render()), Some(sample()));
}
#[test]
fn the_land_variables_take_object_names_only() {
let (a, b) = ("a".repeat(40), "0".repeat(40));
assert_eq!(
LandEnv::parse(&format!("{a} {b}")),
LandEnv::Valid(LandLine {
sha: a.clone(),
remote_tip: b.clone()
})
);
for bad in [
"",
"abc",
a.as_str(),
&format!("{a} {b} extra"),
&format!("{a} xyz"),
] {
assert!(
matches!(LandEnv::parse(bad), LandEnv::Malformed(_)),
"{bad:?}"
);
}
assert!(matches!(
Prestage::parse(&format!("refs/heads/x {a} refs/heads/x {b}")),
Prestage::Of(_)
));
for bad in [
format!("refs/heads/x {a} refs/heads/x"),
"x y z w".to_string(),
] {
assert!(
matches!(Prestage::parse(&bad), Prestage::Malformed(_)),
"{bad:?}"
);
}
}
#[test]
fn a_state_survives_the_round_trip() {
let s = sample();
assert_eq!(State::parse(&s.render()), Some(s));
let done = State {
phase: Phase::Failed,
step: None,
reason: Some("could not prepare the snapshot: npm ci failed\nin web/".to_string()),
..sample()
};
let back = State::parse(&done.render()).expect("parses");
assert_eq!(
back.reason.as_deref(),
Some("could not prepare the snapshot: npm ci failed in web/"),
"a reason is kept on one line"
);
assert_eq!(back.phase, Phase::Failed);
}
#[test]
fn a_foreign_or_partial_file_is_no_rehearsal() {
assert_eq!(State::parse(""), None);
assert_eq!(State::parse("amont-rehearsal-v2\npid=1\n"), None);
assert_eq!(State::parse("amont-rehearsal-v1\npid=1\n"), None);
assert_eq!(
State::parse("amont-rehearsal-v1\npid=x\ncommit=a\ntree=b\nstarted=1\nsnapshot=/s\nphase=running\n"),
None
);
}
#[test]
fn a_dead_pid_is_not_alive() {
let s = State {
pid: u32::MAX - 7,
..sample()
};
assert!(!s.alive());
let done = State {
phase: Phase::Passed,
pid: std::process::id(),
..sample()
};
assert!(
!done.alive(),
"a finished rehearsal is not running whoever's pid it names"
);
}
}