Skip to main content

greengate_runtime/
land.rs

1//! `amont land` — push the current branch, then prove the remote ref moved.
2//!
3//! A push that exits 0 says the remote ACCEPTED something. It does not say the
4//! branch now points where you pushed it: a forge that loses an accepted ref
5//! update, a replica that has not caught up, and a `| tail` that threw the
6//! exit status away all end the same way, a green terminal and a stale
7//! branch. The proof is one question asked of the remote afterwards, and this
8//! verb asks it every time, so nobody has to remember to.
9//!
10//! Before every push attempt it runs a pre-stage (ADR-0018): the heavy gates
11//! the push owes run in a child `amont rehearse --wait`, told the push's real
12//! ref line, with no connection open; the push's own hook then finds them
13//! stamped and runs only the unscoped checks. The stamps, the attestation and
14//! those checks stay in the pre-push hook; `land` neither re-implements nor
15//! skips them.
16//!
17//! Exit codes (`2` stays the binary-wide usage error):
18//!
19//! | code | status         | meaning                                              |
20//! |------|----------------|------------------------------------------------------|
21//! | 0    | `landed`       | the remote ref equals the pushed sha                 |
22//! | 1    | `refused`      | a gate, a hook, the server, or a precondition said no |
23//! | 2    | `usage`        | wrong invocation                                     |
24//! | 3    | `unreachable`  | the remote could not be reached, or the push was    |
25//! |      | / `unverified` | accepted but could not be checked                    |
26//! | 4    | `not-observed` | accepted, but the expected tip was not observed      |
27//! | 128+n| `interrupted`  | killed by signal n                                   |
28//! | 0    | `detached`     | `--detach`: a worker was started; the receipt says  |
29//! |      |                | how it ended (`--wait` reads it)                     |
30//!
31//! `--wait <receipt>` exits with the code of the status the receipt ended in,
32//! and with 1 (a refusal; its `worker <pid> died` lines tell it apart) when
33//! the worker died without finalizing it.
34//!
35//! `4` is deliberately worded as "not observed". Equality proves the tip was
36//! seen; inequality does not prove an update was lost, because another writer
37//! may have advanced or replaced the ref in between. The observed sha is
38//! reported so the person can tell which.
39
40use crate::names::BIN;
41use std::ffi::OsString;
42use std::io::{IsTerminal, Read, Write};
43use std::ops::ControlFlow;
44use std::path::PathBuf;
45use std::process::{Command, Stdio};
46use std::time::{Duration, SystemTime, UNIX_EPOCH};
47
48use crate::attest::{classify_push_stderr, PushFailure};
49use crate::git::{self, Probe};
50use crate::hooks::pull_rebase::PUSH_AGAIN;
51use crate::json;
52use crate::rehearsal::signal_of;
53
54/// The line the hook of land's own push prints, first, when the pushed
55/// range's remote side is not the one land's pre-stage ran against: the
56/// remote moved under land (ADR-0018). Matched in the push's output, never
57/// the prose after it.
58pub const LAND_REMOTE_MOVED: &str = "greengate-land: remote-moved";
59/// The line that hook prints, first, when the range is the pre-stage's but a
60/// gate it owes carries no evidence: a defect, named with the gates.
61pub const LAND_EVIDENCE_MISSING: &str = "greengate-land: evidence-missing";
62
63/// Re-reads of the remote after a mismatch, and the pause between them.
64/// Spent only when the first read disagrees: at most 6 s.
65const REREADS: u32 = 3;
66const REREAD_PAUSE: Duration = Duration::from_secs(2);
67
68/// A landing receipt older than this is deleted by the next land.
69const RECEIPT_KEEP: Duration = Duration::from_secs(7 * 24 * 60 * 60);
70
71/// Whether a non-fast-forward may replace the remote ref.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Mode {
74    /// A plain push: the server refuses anything but a fast-forward.
75    Plain,
76    /// `--force`: replace the ref, but only if it still holds the tip that
77    /// was read (`--force-with-lease` on that exact sha).
78    Force,
79}
80
81/// How the run ended. One value per exit code family.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Status {
84    Landed,
85    Refused,
86    Usage,
87    Unreachable,
88    Unverified,
89    NotObserved,
90    /// Killed by this signal number.
91    Interrupted(i32),
92}
93
94impl Status {
95    pub fn code(self) -> i32 {
96        match self {
97            Status::Landed => 0,
98            Status::Refused => 1,
99            Status::Usage => 2,
100            Status::Unreachable | Status::Unverified => 3,
101            Status::NotObserved => 4,
102            Status::Interrupted(sig) => 128 + sig,
103        }
104    }
105
106    pub fn as_str(self) -> &'static str {
107        match self {
108            Status::Landed => "landed",
109            Status::Refused => "refused",
110            Status::Usage => "usage",
111            Status::Unreachable => "unreachable",
112            Status::Unverified => "unverified",
113            Status::NotObserved => "not-observed",
114            Status::Interrupted(_) => "interrupted",
115        }
116    }
117}
118
119/// Everything the output is made of. Filled in as the run learns things, so
120/// a run that stops early still prints what it knew.
121#[derive(Debug, Clone)]
122pub struct Report {
123    pub branch: String,
124    pub remote: String,
125    pub push_url: String,
126    pub pushed: String,
127    /// `refs/heads/<rb>`, the ref the push writes; empty until known.
128    pub dst: String,
129    pub remote_before: String,
130    pub remote_after: String,
131    pub retried: bool,
132    pub status: Status,
133    /// Commands the person can run next, printed whole, one per line.
134    pub next: Vec<String>,
135    /// The push gates the pushed range owes (ADR-0018), and what the
136    /// pre-stage did about them.
137    pub gates_owed: Vec<String>,
138    pub prestage: PrestageState,
139}
140
141/// What land's pre-stage did (ADR-0018), as `--json` reports it.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum PrestageState {
144    /// It did not get that far.
145    NotRun,
146    /// Every owed gate already had its evidence: nothing ran.
147    Stamped,
148    /// It ran the owed gates, and they passed.
149    Ran,
150    /// A gate failed: nothing was pushed.
151    Failed,
152    /// It could not run, or was not allowed to: nothing was pushed.
153    Refused,
154    /// A signal stopped it: nothing was pushed.
155    Interrupted,
156}
157
158impl PrestageState {
159    pub fn as_str(self) -> &'static str {
160        match self {
161            PrestageState::NotRun => "",
162            PrestageState::Stamped => "stamped",
163            PrestageState::Ran => "ran",
164            PrestageState::Failed => "failed",
165            PrestageState::Refused => "refused",
166            PrestageState::Interrupted => "interrupted",
167        }
168    }
169}
170
171impl Report {
172    pub(crate) fn new(status: Status) -> Self {
173        Report {
174            branch: String::new(),
175            remote: String::new(),
176            push_url: String::new(),
177            pushed: String::new(),
178            dst: String::new(),
179            remote_before: String::new(),
180            remote_after: String::new(),
181            retried: false,
182            status,
183            next: Vec::new(),
184            gates_owed: Vec::new(),
185            prestage: PrestageState::NotRun,
186        }
187    }
188
189    pub(crate) fn json(&self) -> String {
190        json::object(&[
191            json::string_field("branch", &self.branch),
192            json::string_field("remote", &self.remote),
193            json::string_field("push_url", &self.push_url),
194            json::string_field("pushed", &self.pushed),
195            json::string_field("ref", &self.dst),
196            json::string_field("remote_before", &self.remote_before),
197            json::string_field("remote_after", &self.remote_after),
198            json::bool_field("retried", self.retried),
199            json::string_field("status", self.status.as_str()),
200            format!(
201                "\"gates\":{}",
202                json::object(&[
203                    json::string_array_field("owed", &self.gates_owed),
204                    json::string_field("prestage", self.prestage.as_str()),
205                ])
206            ),
207        ])
208    }
209}
210
211/// The widest the closing verdict line may be.
212const VERDICT_WIDTH: usize = 80;
213
214/// `…` in the middle of `s` so it fits `max` columns. Counts chars, which is
215/// right for branch names (ASCII in practice, and a wide glyph only makes the
216/// line shorter than the budget, never longer).
217pub fn truncate_middle(s: &str, max: usize) -> String {
218    let n = s.chars().count();
219    if n <= max {
220        return s.to_string();
221    }
222    if max <= 1 {
223        return "…".chars().take(max).collect();
224    }
225    let keep = max - 1;
226    let head = keep.div_ceil(2);
227    let tail = keep - head;
228    let front: String = s.chars().take(head).collect();
229    let back: String = s.chars().skip(n - tail).collect();
230    format!("{front}…{back}")
231}
232
233pub(crate) fn short(sha: &str) -> String {
234    if sha.is_empty() {
235        "-------".to_string()
236    } else {
237        sha.chars().take(7).collect()
238    }
239}
240
241/// The last line printed: plain text, no colour, no glyphs, at most 80
242/// columns whatever the branch is called. Outcome word, the two shas, then
243/// the branch in whatever room is left.
244pub fn verdict(status: Status, before: &str, after: &str, branch: &str) -> String {
245    verdict_word(status.as_str(), before, after, branch)
246}
247
248pub(crate) fn verdict_word(word: &str, before: &str, after: &str, branch: &str) -> String {
249    let head = format!("{word} {}..{}", short(before), short(after));
250    let room = VERDICT_WIDTH.saturating_sub(head.chars().count() + 1);
251    if branch.is_empty() || room == 0 {
252        return head;
253    }
254    format!("{head} {}", truncate_middle(branch, room))
255}
256
257/// The tip `ls-remote <url> <ref>` printed; empty when it printed nothing
258/// (the ref does not exist).
259pub fn parse_tip(ls_remote: &str) -> String {
260    ls_remote
261        .lines()
262        .find_map(|l| l.split_whitespace().next())
263        .unwrap_or("")
264        .to_string()
265}
266
267/// What a read of the remote ref came to.
268enum Seen {
269    Tip(String),
270    Unreachable,
271}
272
273fn read_tip(url: &str, rb: &str, budget: u64) -> Seen {
274    read_ref(url, &format!("refs/heads/{rb}"), budget)
275}
276
277/// Where `refname` stands on `url`: empty when absent.
278fn read_ref(url: &str, refname: &str, budget: u64) -> Seen {
279    match git::probe_remote_stdout(&["ls-remote", url, refname], budget) {
280        (Probe::Exit(0), out) => Seen::Tip(parse_tip(&out)),
281        _ => Seen::Unreachable,
282    }
283}
284
285/// What the command line of `land` said.
286#[derive(Default)]
287pub(crate) struct Options {
288    pub(crate) force: bool,
289    pub(crate) json: bool,
290    pub(crate) dry_run: bool,
291    pub(crate) detach: bool,
292    pub(crate) worker: bool,
293    pub(crate) tag: Option<String>,
294    pub(crate) receipt: Option<String>,
295    pub(crate) lock_fd: Option<i32>,
296    pub(crate) wait: Option<String>,
297}
298
299impl Options {
300    pub(crate) fn mode(&self) -> Mode {
301        if self.force {
302            Mode::Force
303        } else {
304            Mode::Plain
305        }
306    }
307
308    /// The flags a rerun of this land keeps, as typed. Only the unix-only
309    /// detached land reruns a land, so other targets do not build it.
310    #[cfg(unix)]
311    pub(crate) fn rerun_flags(&self) -> Vec<String> {
312        let mut flags = Vec::new();
313        if self.force {
314            flags.push("--force".to_string());
315        }
316        if self.json {
317            flags.push("--json".to_string());
318        }
319        if let Some(tag) = &self.tag {
320            flags.push("--tag".to_string());
321            flags.push(tag.clone());
322        }
323        flags
324    }
325}
326
327fn parse_options(args: &[OsString]) -> Result<Options, String> {
328    let mut options = Options::default();
329    let mut it = args.iter().map(|a| a.to_string_lossy().into_owned());
330    let tag_needs_name = || "--tag needs a tag name".to_string();
331    let value_of = |flag: &str, it: &mut dyn Iterator<Item = String>| match it.next() {
332        Some(v) if !v.is_empty() && !v.starts_with('-') => Ok(v),
333        _ => Err(format!("{flag} needs a value")),
334    };
335    let mut others = 0usize;
336    while let Some(a) = it.next() {
337        match a.as_str() {
338            "--force" => {
339                options.force = true;
340                others += 1;
341            }
342            "--json" => {
343                options.json = true;
344                others += 1;
345            }
346            "--dry-run" => {
347                options.dry_run = true;
348                others += 1;
349            }
350            "--detach" => {
351                options.detach = true;
352                others += 1;
353            }
354            "--worker" => {
355                options.worker = true;
356                others += 1;
357            }
358            "--tag" => {
359                match it.next() {
360                    Some(name) if !name.is_empty() && !name.starts_with('-') => {
361                        options.tag = Some(name)
362                    }
363                    _ => return Err(tag_needs_name()),
364                }
365                others += 1;
366            }
367            "--receipt" => {
368                options.receipt = Some(value_of("--receipt", &mut it)?);
369                others += 1;
370            }
371            "--lock-fd" => {
372                let raw = value_of("--lock-fd", &mut it)?;
373                options.lock_fd = Some(
374                    raw.parse::<i32>()
375                        .map_err(|_| "--lock-fd needs a descriptor number".to_string())?,
376                );
377                others += 1;
378            }
379            "--wait" => options.wait = Some(value_of("--wait", &mut it)?),
380            other if other.starts_with("--tag=") => match &other["--tag=".len()..] {
381                "" => return Err(tag_needs_name()),
382                name => {
383                    options.tag = Some(name.to_string());
384                    others += 1;
385                }
386            },
387            other if other.starts_with("--wait=") => match &other["--wait=".len()..] {
388                "" => return Err("--wait needs a receipt path".to_string()),
389                path => options.wait = Some(path.to_string()),
390            },
391            other => {
392                return Err(format!(
393                    "unknown argument `{other}`; takes only [--force] [--json] [--dry-run] \
394                     [--tag <name>] [--detach], or --wait <receipt> alone"
395                ))
396            }
397        }
398    }
399    if options.wait.is_some() && others > 0 {
400        return Err("--wait takes a receipt and no other flag".to_string());
401    }
402    if options.detach && options.dry_run {
403        return Err("--detach cannot be combined with --dry-run".to_string());
404    }
405    if options.tag.is_some() && options.mode() == Mode::Force {
406        return Err("a tag is never forced; --tag takes no --force".to_string());
407    }
408    if options.worker && (options.receipt.is_none() || options.lock_fd.is_none()) {
409        return Err("--worker is internal: it needs --receipt and --lock-fd".to_string());
410    }
411    Ok(options)
412}
413
414/// `amont land [--force] [--json] [--dry-run] [--detach]`,
415/// `amont land --tag <name> [--json] [--dry-run] [--detach]`, or
416/// `amont land --wait <receipt>`.
417pub fn command(args: &[OsString]) -> i32 {
418    let json_out = args.iter().any(|a| a == "--json");
419    let options = match parse_options(args) {
420        Ok(options) => options,
421        Err(why) => {
422            eprintln!("{BIN}: land: {why}");
423            return finish(&Report::new(Status::Usage), json_out);
424        }
425    };
426    let (dry_run, mode) = (options.dry_run, options.mode());
427    if let Some(receipt) = &options.wait {
428        return wait_on(receipt);
429    }
430    if options.worker {
431        return worker_of(&options);
432    }
433    if options.detach {
434        return launch_of(&options);
435    }
436    if let Some(name) = options.tag.clone() {
437        // `parse_options` already refused --tag with --force (usage, exit 2).
438        if dry_run {
439            let (report, verdict) = dry_run_tag(&name);
440            say_dry_run(&report, verdict);
441            if json_out {
442                println!("{}", dry_run_json(&report, verdict, mode));
443            }
444            return i32::from(verdict != "would-land");
445        }
446        let started = now_nanos();
447        let report = land_tag(&name, None);
448        write_receipt(&report, started, now_nanos());
449        return finish(&report, json_out);
450    }
451    if dry_run {
452        let (report, verdict) = dry_run_branch();
453        say_dry_run(&report, verdict);
454        if json_out {
455            println!("{}", dry_run_json(&report, verdict, mode));
456        }
457        return i32::from(verdict != "would-land");
458    }
459    let started = now_nanos();
460    let report = land(mode, None);
461    write_receipt(&report, started, now_nanos());
462    finish(&report, json_out)
463}
464
465#[cfg(unix)]
466fn launch_of(options: &Options) -> i32 {
467    crate::land_detach::launch(options)
468}
469
470#[cfg(not(unix))]
471fn launch_of(options: &Options) -> i32 {
472    eprintln!("{BIN}: land: --detach needs a unix host");
473    finish(&Report::new(Status::Usage), options.json)
474}
475
476#[cfg(unix)]
477fn worker_of(options: &Options) -> i32 {
478    crate::land_detach::worker(options)
479}
480
481#[cfg(not(unix))]
482fn worker_of(options: &Options) -> i32 {
483    eprintln!("{BIN}: land: --worker needs a unix host");
484    finish(&Report::new(Status::Usage), options.json)
485}
486
487#[cfg(unix)]
488fn wait_on(receipt: &str) -> i32 {
489    crate::land_detach::wait(receipt)
490}
491
492#[cfg(not(unix))]
493fn wait_on(_receipt: &str) -> i32 {
494    eprintln!("{BIN}: land: --wait needs a unix host");
495    finish(&Report::new(Status::Usage), false)
496}
497
498/// The JSON document a usage error prints under `--json`, so a script that
499/// parses stdout never has to special-case exit 2.
500pub fn usage_json() -> String {
501    Report::new(Status::Usage).json()
502}
503
504pub(crate) fn finish(report: &Report, json_out: bool) -> i32 {
505    for line in &report.next {
506        eprintln!("    {line}");
507    }
508    eprintln!(
509        "{}",
510        verdict(
511            report.status,
512            &report.remote_before,
513            &report.remote_after,
514            shown_ref(report)
515        )
516    );
517    if json_out {
518        println!("{}", report.json());
519    }
520    report.status.code()
521}
522
523/// What the verdict line names: the branch, or for a tag land (which has none)
524/// the tag.
525pub(crate) fn shown_ref(report: &Report) -> &str {
526    if report.branch.is_empty() {
527        report.dst.strip_prefix("refs/tags/").unwrap_or(&report.dst)
528    } else {
529        &report.branch
530    }
531}
532
533pub(crate) fn refuse(mut report: Report, why: &str, next: &[&str]) -> Report {
534    eprintln!("{BIN}: land: {why}");
535    report.status = Status::Refused;
536    report.next = next.iter().map(|s| s.to_string()).collect();
537    report
538}
539
540/// What steps 1 and 2 learned: where the push goes and what it is called there.
541pub(crate) struct Resolved {
542    remote: String,
543    rb: String,
544    url: String,
545    has_upstream: bool,
546}
547
548/// The one push URL of `remote`, or the refusal saying why there is not one.
549fn one_push_url(remote: &str, mut report: Report) -> Result<(String, Report), Box<Report>> {
550    let Some(urls) = git::stdout(&["remote", "get-url", "--push", "--all", remote]) else {
551        return Err(Box::new(refuse(
552            report,
553            &format!("no remote named {remote:?}"),
554            &["git remote -v"],
555        )));
556    };
557    let urls: Vec<&str> = urls.lines().filter(|l| !l.is_empty()).collect();
558    if urls.len() != 1 {
559        return Err(Box::new(refuse(
560            report,
561            &format!(
562                "{remote:?} has {} push destinations; land verifies exactly one",
563                urls.len()
564            ),
565            &[&format!("git remote get-url --push --all {remote}")],
566        )));
567    }
568    let url = urls[0].to_string();
569    report.push_url = redact_url(&url);
570    Ok((url, report))
571}
572
573/// `url` as a report may print it: a password, or any user part of an
574/// http(s) URL (a token rides there), becomes `***`. The push itself uses
575/// the URL unchanged.
576fn redact_url(url: &str) -> String {
577    let Some((scheme, rest)) = url.split_once("://") else {
578        return url.to_string(); // scp-like `git@host:path` or a path: no secret
579    };
580    let authority_end = rest.find('/').unwrap_or(rest.len());
581    let (authority, path) = rest.split_at(authority_end);
582    let Some((user, host)) = authority.rsplit_once('@') else {
583        return url.to_string();
584    };
585    let user = if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
586        "***".to_string()
587    } else {
588        match user.split_once(':') {
589            Some((name, _)) => format!("{name}:***"),
590            None => user.to_string(),
591        }
592    };
593    format!("{scheme}://{user}@{host}{path}")
594}
595
596/// Steps 1 and 2: the branch, its upstream, the refusals, and the one push
597/// URL. Reads local git state only: no network, nothing written. `Err` is the
598/// refused report, already explained on stderr.
599pub(crate) fn resolve() -> Result<(Resolved, Report), Box<Report>> {
600    let mut report = Report::new(Status::Refused);
601
602    // 1. What are we pushing, and where to.
603    let Some(branch) = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"]) else {
604        return Err(Box::new(refuse(
605            report,
606            "HEAD is detached; there is no branch to land",
607            &[],
608        )));
609    };
610    report.branch = branch.clone();
611    let upstream_remote = git::stdout(&["config", "--get", &format!("branch.{branch}.remote")]);
612    let upstream_merge = git::stdout(&["config", "--get", &format!("branch.{branch}.merge")]);
613    // `.` is a branch tracking another LOCAL branch (`branch.autoSetupMerge`
614    // does that for `git switch -c`): not a remote upstream, so it names
615    // neither where to push nor what to call the branch there.
616    let (upstream_remote, upstream_merge) = match upstream_remote.as_deref() {
617        Some(".") => (None, None),
618        _ => (upstream_remote, upstream_merge),
619    };
620    // A branch cut from `main` tracks `main` (`git worktree add -b <b>
621    // origin/main` does that): its base, not where it publishes. Following
622    // it would refuse every such branch as a push to `main`; plain `git
623    // push` refuses the name mismatch too. So it lands under its own name on
624    // that remote, and the upstream is set to it afterwards, as `git push -u`
625    // would. A renamed upstream that is not `main` or `master` still decides.
626    let upstream_merge = upstream_merge.filter(|m| {
627        let tracked = m.strip_prefix("refs/heads/").unwrap_or(m);
628        !is_protected(tracked) || is_protected(&branch)
629    });
630    let has_upstream = upstream_remote.is_some() && upstream_merge.is_some();
631    let remote = upstream_remote.unwrap_or_else(|| "origin".to_string());
632    let rb = upstream_merge
633        .as_deref()
634        .and_then(|m| m.strip_prefix("refs/heads/"))
635        .unwrap_or(&branch)
636        .to_string();
637    report.remote = remote.clone();
638    report.dst = format!("refs/heads/{rb}");
639
640    if is_protected(&branch) || is_protected(&rb) {
641        return Err(Box::new(refuse(
642            report,
643            "main and master change by pull request, never by a push",
644            &["git switch -c <name>"],
645        )));
646    }
647    if git::stdout(&["status", "--porcelain", "--untracked-files=no"])
648        .is_some_and(|s| !s.is_empty())
649    {
650        return Err(Box::new(refuse(
651            report,
652            "tracked files have uncommitted changes; the push would not include them",
653            &["git status", "git stash"],
654        )));
655    }
656
657    // 2. The endpoint the push will really use.
658    let (url, report) = one_push_url(&remote, report)?;
659    Ok((
660        Resolved {
661            remote,
662            rb,
663            url,
664            has_upstream,
665        },
666        report,
667    ))
668}
669
670/// `pin` is the sha a detached land judged at launch: it pushes that sha and
671/// nothing else, and never takes the retry after a hook that moved HEAD.
672pub(crate) fn land(mode: Mode, pin: Option<&str>) -> Report {
673    let settings = crate::config::Settings::default();
674    let budget = crate::hooks::common::network_probe_budget(&settings);
675    let (
676        Resolved {
677            remote,
678            rb,
679            url,
680            has_upstream,
681        },
682        mut report,
683    ) = match resolve() {
684        Ok(r) => r,
685        Err(refused) => return *refused,
686    };
687
688    // Where the ref stands.
689    let mut expected_old = match read_tip(&url, &rb, budget) {
690        Seen::Tip(t) => t,
691        Seen::Unreachable => {
692            report.status = Status::Unreachable;
693            eprintln!("{BIN}: land: could not read {rb} from {remote}");
694            report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
695            return report;
696        }
697    };
698    report.remote_before = expected_old.clone();
699
700    // 3. Push, once, and once more only if the hook moved HEAD for us.
701    let mut attempt = 0;
702    let pushed = loop {
703        let Some(sha) = git::stdout(&["rev-parse", "HEAD"]) else {
704            return refuse(report, "cannot resolve HEAD", &[]);
705        };
706        if let Some(judged) = pin {
707            if let Some(refusal) = head_moved(&report, judged, &sha) {
708                return refusal;
709            }
710        }
711        report.pushed = sha.clone();
712        let lease = match mode {
713            Mode::Force => Some(expected_old.as_str()),
714            Mode::Plain => None,
715        };
716        // ADR-0018: every heavy gate this push owes runs HERE, before git
717        // connects — on every attempt, so a hook that moved HEAD gets its new
718        // sha pre-staged too.
719        let local_ref = format!("refs/heads/{}", report.branch);
720        let dst = format!("refs/heads/{rb}");
721        report = match prestage(&local_ref, &sha, &dst, &expected_old, (&remote, &url))
722            .into_report(report)
723        {
724            ControlFlow::Continue(report) => report,
725            ControlFlow::Break(stopped) => return *stopped,
726        };
727        if let Some(judged) = pin {
728            let now = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
729            if let Some(refusal) = head_moved(&report, judged, &now) {
730                return refusal;
731            }
732        }
733        let land_env = format!("{sha} {}", or_zeros(&expected_old));
734        let run = push(&url, &sha, &dst, lease, &land_env);
735        match run.outcome {
736            PushOutcome::Done => break sha,
737            PushOutcome::Signal(sig) => {
738                report.status = Status::Interrupted(sig);
739                return report;
740            }
741            PushOutcome::Failed => {}
742        }
743        let head_now = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
744        let hook_moved_head = run.seen.contains(PUSH_AGAIN)
745            && head_now != sha
746            && (expected_old.is_empty()
747                || git::succeeds(&["merge-base", "--is-ancestor", &expected_old, &head_now]));
748        if pin.is_some() && hook_moved_head {
749            eprintln!(
750                "{BIN}: land: the pre-push hook moved HEAD {} -> {}; a detached land never \
751                 pushes a sha it did not judge",
752                short(&sha),
753                short(&head_now)
754            );
755            report.status = Status::Refused;
756            report.next = vec![format!("{BIN} land --detach")];
757            return report;
758        }
759        if attempt == 0 && hook_moved_head {
760            attempt = 1;
761            report.retried = true;
762            eprintln!(
763                "{BIN}: land: retrying once: pre-push hook fast-forwarded HEAD {} -> {}",
764                short(&sha),
765                short(&head_now)
766            );
767            match read_tip(&url, &rb, budget) {
768                Seen::Tip(t) => {
769                    expected_old = t;
770                    report.remote_before = expected_old.clone();
771                }
772                Seen::Unreachable => {
773                    report.status = Status::Unreachable;
774                    report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
775                    return report;
776                }
777            }
778            continue;
779        }
780        // The hook of land's own push refused (ADR-0018): matched on its
781        // sentinel lines, never on the prose.
782        if run.seen.contains(crate::land::LAND_REMOTE_MOVED) {
783            report.status = Status::Refused;
784            report.next = vec![format!("{BIN} land")];
785            return report;
786        }
787        if run.seen.contains(crate::land::LAND_EVIDENCE_MISSING) {
788            report.status = Status::Refused;
789            report.next = vec![format!("{BIN} rehearse --wait"), format!("{BIN} land")];
790            return report;
791        }
792        report.status = status_of_failed_push(&run.stderr);
793        return report;
794    };
795
796    // 4. The proof.
797    let mut observed = Seen::Unreachable;
798    for i in 0..=REREADS {
799        if i > 0 {
800            std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
801        }
802        observed = read_tip(&url, &rb, budget);
803        if matches!(&observed, Seen::Tip(t) if *t == pushed) {
804            break;
805        }
806    }
807    match observed {
808        Seen::Tip(t) if t == pushed => {
809            report.remote_after = t;
810            report.status = Status::Landed;
811            move_tracking_ref(&remote, &rb, &pushed);
812            if !has_upstream {
813                set_upstream(&remote, &rb);
814            }
815        }
816        Seen::Tip(t) => {
817            report.remote_after = t;
818            report.status = Status::NotObserved;
819            eprintln!(
820                "{BIN}: land: the remote accepted the push but {rb} reads {}, not {}",
821                short(&report.remote_after),
822                short(&pushed)
823            );
824            report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
825        }
826        Seen::Unreachable => {
827            report.status = Status::Unverified;
828            eprintln!("{BIN}: land: the push was accepted but {rb} could not be read back");
829            report.next = vec![format!("git ls-remote {remote} refs/heads/{rb}")];
830        }
831    }
832    report
833}
834
835/// The refusal of a detached land whose HEAD is no longer the sha it judged.
836fn head_moved(report: &Report, judged: &str, now: &str) -> Option<Report> {
837    if now == judged {
838        return None;
839    }
840    Some(refuse(
841        report.clone(),
842        &format!(
843            "HEAD moved from {} to {} since the launch; nothing was pushed",
844            short(judged),
845            short(now)
846        ),
847        &[&format!("{BIN} land --detach")],
848    ))
849}
850
851/// An absent remote tip, as git's ref lines spell it.
852const ZEROS: &str = "0000000000000000000000000000000000000000";
853
854fn or_zeros(tip: &str) -> &str {
855    if tip.is_empty() {
856        ZEROS
857    } else {
858        tip
859    }
860}
861
862/// What land's pre-stage ended in.
863enum Prestage {
864    /// Every gate the push owes has its evidence: push.
865    Ready,
866    /// Do not push; why, for the person, and what to run next.
867    Refused(String, Vec<String>),
868    /// The pre-stage was stopped by this signal; nothing was pushed.
869    Interrupted(i32),
870}
871
872/// The pre-stage's result: what the push owed, what was done about it, and
873/// whether to go on.
874struct Staged {
875    owed: Vec<String>,
876    state: PrestageState,
877    end: Prestage,
878}
879
880impl Staged {
881    fn ended(owed: Vec<String>, state: PrestageState, end: Prestage) -> Staged {
882        Staged { owed, state, end }
883    }
884
885    fn refused(owed: Vec<String>, state: PrestageState, why: String) -> Staged {
886        Staged::ended(owed, state, Prestage::Refused(why, Vec::new()))
887    }
888
889    /// `report` with this folded in: `Continue` when land may push, `Break`
890    /// with the finished report when it must stop.
891    fn into_report(self, mut report: Report) -> ControlFlow<Box<Report>, Report> {
892        report.gates_owed = self.owed;
893        report.prestage = self.state;
894        match self.end {
895            Prestage::Ready => ControlFlow::Continue(report),
896            Prestage::Refused(why, next) => {
897                eprintln!("{BIN}: land: {why}");
898                report.status = Status::Refused;
899                report.next = next;
900                ControlFlow::Break(Box::new(report))
901            }
902            Prestage::Interrupted(sig) => {
903                report.status = Status::Interrupted(sig);
904                ControlFlow::Break(Box::new(report))
905            }
906        }
907    }
908}
909
910/// A push git refused, as land reports it.
911fn status_of_failed_push(stderr: &str) -> Status {
912    match classify_push_stderr(stderr) {
913        PushFailure::Unreachable => Status::Unreachable,
914        PushFailure::Raced | PushFailure::Refused => Status::Refused,
915        // `PushFailure` is another crate's `#[non_exhaustive]` enum: a kind
916        // it adds later is a refusal until land learns it.
917        _ => Status::Refused,
918    }
919}
920
921/// The rehearsal this worktree recorded last: `(pid, started, running)`.
922/// What tells whether gates ran during the pre-stage: one started by it, or
923/// one already running that it followed.
924fn last_rehearsal() -> Option<(u32, u64, bool)> {
925    crate::rehearsal::read().map(|s| (s.pid, s.started, s.alive()))
926}
927
928/// Run every heavy gate the push of `sha` onto `dst` (whose remote tip is
929/// `remote_tip`, empty when the ref is new) will owe, before git opens a
930/// connection (ADR-0018). In a child `amont rehearse --wait`, told the real
931/// ref line, whose stdout goes to this process's stderr so a `--json` report
932/// stays the only thing on stdout.
933/// `remote` is the remote's name, for what land tells the person: its URL
934/// may carry credentials, and is only ever handed to git.
935fn prestage(
936    local_ref: &str,
937    sha: &str,
938    dst: &str,
939    remote_tip: &str,
940    (remote, url): (&str, &str),
941) -> Staged {
942    // What to run again after a refusal: the same land.
943    let again = match dst.strip_prefix("refs/tags/") {
944        Some(tag) => format!("{BIN} land --tag {tag}"),
945        None => format!("{BIN} land"),
946    };
947    let root = match crate::hooks::common::repo_root_checked() {
948        Ok(root) => root,
949        Err(e) => return Staged::refused(Vec::new(), PrestageState::Refused, e),
950    };
951    let (manifest, settings) = crate::manifest::load_resolved(std::path::Path::new(&root));
952    // The range starts at the remote's tip: a tip this clone never fetched
953    // (a force push elsewhere) would make it unwalkable. Fetch it, or refuse.
954    // A fetch moves objects, so it gets the check budget (`greengate.timeout`),
955    // not the few seconds a reachability probe gets.
956    if !remote_tip.is_empty() && !has_commit(remote_tip) {
957        eprintln!(
958            "{BIN}: land: fetching {} ({dst}) from the remote",
959            short(remote_tip)
960        );
961        let budget = crate::hooks::common::check_timeout(&settings);
962        let (probe, _) = git::probe_remote_stdout(&["fetch", "-q", "--no-tags", url, dst], budget);
963        if !has_commit(remote_tip) {
964            let how = match probe {
965                Probe::Exit(0) => "it fetched, but not that commit".to_string(),
966                Probe::Exit(code) => format!("git fetch exited {code}"),
967                Probe::TimedOut(secs) => format!("git fetch did not finish within {secs}s"),
968                Probe::Failed => "git fetch did not run".to_string(),
969            };
970            return Staged::ended(
971                Vec::new(),
972                PrestageState::Refused,
973                Prestage::Refused(
974                    format!(
975                        "the remote's {dst} is at {}, a commit this clone does not have ({how})",
976                        short(remote_tip)
977                    ),
978                    // git's own words, which the bounded fetch could not keep
979                    vec![format!("git fetch --no-tags {remote} {dst}"), again],
980                ),
981            );
982        }
983    }
984    let line = crate::pushrefs::PushRef {
985        local_ref: local_ref.to_string(),
986        local_oid: sha.to_string(),
987        remote_ref: dst.to_string(),
988        remote_oid: or_zeros(remote_tip).to_string(),
989    };
990    let changed = crate::pushrefs::changed_files(std::slice::from_ref(&line));
991    let mut owed = crate::dispatch::scoped_push_gates(&settings, &manifest, &changed);
992    let audits = crate::hooks::audit::Ledger::default();
993    for audit in
994        crate::dispatch::owed_audits(&settings, &manifest, &audits, std::slice::from_ref(&line))
995    {
996        if !owed.contains(&audit) {
997            owed.push(audit);
998        }
999    }
1000    if owed.is_empty() {
1001        return Staged::ended(owed, PrestageState::Stamped, Prestage::Ready);
1002    }
1003    if !crate::gate_stamp::push_stamps_enabled(&settings) {
1004        return Staged::ended(
1005            owed,
1006            PrestageState::Refused,
1007            Prestage::Refused(
1008                "stamp reuse is off (greengate.pushStamps false), so the gates land runs \
1009                 cannot count at the push"
1010                    .to_string(),
1011                vec!["git config greengate.pushStamps true".to_string(), again],
1012            ),
1013        );
1014    }
1015    let exe = match std::env::current_exe() {
1016        Ok(exe) => exe,
1017        Err(e) => {
1018            return Staged::refused(
1019                owed,
1020                PrestageState::Refused,
1021                format!("cannot locate the {BIN} binary for the pre-stage: {e}"),
1022            )
1023        }
1024    };
1025    // Before the pre-stage: stamps this binary makes do not count at a hook
1026    // that runs another greengate version (f06).
1027    if let Some(split) = crate::land_hook::split() {
1028        let next = split.next(&exe, &again);
1029        return Staged::ended(
1030            owed,
1031            PrestageState::Refused,
1032            Prestage::Refused(split.why(), next),
1033        );
1034    }
1035    let names: Vec<&str> = owed.iter().map(String::as_str).collect();
1036    eprintln!(
1037        "{BIN}: land: {} push gate{} to check before git connects:",
1038        owed.len(),
1039        if owed.len() == 1 { "" } else { "s" }
1040    );
1041    for wrapped in crate::dispatch::wrap_names(&names) {
1042        eprintln!("{wrapped}");
1043    }
1044    let before = last_rehearsal();
1045    let status = Command::new(exe)
1046        .args(["rehearse", "--wait"])
1047        .env(
1048            crate::rehearsal::PRESTAGE_ENV,
1049            format!(
1050                "{} {} {} {}",
1051                line.local_ref, line.local_oid, line.remote_ref, line.remote_oid
1052            ),
1053        )
1054        .stdin(Stdio::null())
1055        .stdout(Stdio::from(std::io::stderr()))
1056        .status();
1057    let status = match status {
1058        Ok(status) => status,
1059        Err(e) => {
1060            return Staged::refused(
1061                owed,
1062                PrestageState::Refused,
1063                format!("could not start the pre-stage: {e}"),
1064            )
1065        }
1066    };
1067    if let Some(sig) = signal_of(&status) {
1068        return Staged::ended(owed, PrestageState::Interrupted, Prestage::Interrupted(sig));
1069    }
1070    match status.code() {
1071        Some(0) => {
1072            // `ran` when gates ran meanwhile: a rehearsal this pre-stage
1073            // started, or one already running that it followed. `stamped`
1074            // when every gate already had its evidence.
1075            let followed = before.is_some_and(|(_, _, running)| running);
1076            let state = if followed
1077                || last_rehearsal().map(|(p, t, _)| (p, t)) != before.map(|(p, t, _)| (p, t))
1078            {
1079                PrestageState::Ran
1080            } else {
1081                PrestageState::Stamped
1082            };
1083            Staged::ended(owed, state, Prestage::Ready)
1084        }
1085        Some(1) => Staged::ended(
1086            owed,
1087            PrestageState::Failed,
1088            Prestage::Refused(
1089                "a push gate failed before the push (named above); nothing was pushed".to_string(),
1090                vec![format!("{BIN} rehearse --status"), again],
1091            ),
1092        ),
1093        // `rehearse` reports a gate stopped by signal n as 128+n.
1094        Some(code) if code > 128 => Staged::ended(
1095            owed,
1096            PrestageState::Interrupted,
1097            Prestage::Interrupted(code - 128),
1098        ),
1099        code => Staged::refused(
1100            owed,
1101            PrestageState::Refused,
1102            format!(
1103                "the pre-stage could not run (exit {}); nothing was pushed",
1104                code.map_or("by signal".to_string(), |c| c.to_string())
1105            ),
1106        ),
1107    }
1108}
1109
1110fn has_commit(oid: &str) -> bool {
1111    git::succeeds(&["cat-file", "-e", &format!("{oid}^{{commit}}")])
1112}
1113
1114/// `amont land --tag <name>` (ADR-0018): pre-stage the push of one existing
1115/// local tag (release-mode audits for a `v*` tag, on a snapshot of the tagged
1116/// commit), push it, and read it back. A tag already on the remote is refused:
1117/// a tag is never moved.
1118/// Steps 1 and 2 of a tag land: the local tag and the one push URL. The
1119/// report so far, the URL and the tag's oid, or the finished refusal.
1120pub(crate) fn resolve_tag(name: &str) -> Result<(Report, String, String), Box<Report>> {
1121    let mut report = Report::new(Status::Refused);
1122    let dst = format!("refs/tags/{name}");
1123    report.dst = dst.clone();
1124    let Some(oid) = git::stdout(&["rev-parse", "--verify", "-q", &dst]) else {
1125        return Err(Box::new(refuse(
1126            report,
1127            &format!("there is no local tag {name:?}"),
1128            &["git tag --list"],
1129        )));
1130    };
1131    report.pushed = oid.clone();
1132    let remote = git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"])
1133        .and_then(|b| git::stdout(&["config", &format!("branch.{b}.remote")]))
1134        .filter(|r| r != ".")
1135        .unwrap_or_else(|| "origin".to_string());
1136    report.remote = remote.clone();
1137    let (url, report) = one_push_url(&remote, report)?;
1138    Ok((report, url, oid))
1139}
1140
1141/// `amont land --tag <name> --dry-run`: steps 1 and 2 only. Nothing is read
1142/// from the network and nothing is pushed, so the verdict is `would-land`.
1143fn dry_run_tag(name: &str) -> (Report, &'static str) {
1144    match resolve_tag(name) {
1145        Ok((report, _, _)) => (report, "would-land"),
1146        Err(refused) => (*refused, "refused"),
1147    }
1148}
1149
1150pub(crate) fn land_tag(name: &str, pin: Option<&str>) -> Report {
1151    let settings = crate::config::Settings::default();
1152    let budget = crate::hooks::common::network_probe_budget(&settings);
1153    let (mut report, url, oid) = match resolve_tag(name) {
1154        Ok(resolved) => resolved,
1155        Err(refused) => return *refused,
1156    };
1157    let (dst, remote) = (report.dst.clone(), report.remote.clone());
1158    if let Some(judged) = pin {
1159        if let Some(refusal) = head_moved(&report, judged, &oid) {
1160            return refusal;
1161        }
1162    }
1163    match read_ref(&url, &dst, budget) {
1164        Seen::Tip(t) if t.is_empty() => {}
1165        Seen::Tip(t) => {
1166            report.remote_before = t.clone();
1167            return refuse(
1168                report,
1169                &format!("{dst} already exists on {remote}; a tag is never moved"),
1170                &[&format!("git ls-remote {remote} {dst}")],
1171            );
1172        }
1173        Seen::Unreachable => {
1174            report.status = Status::Unreachable;
1175            eprintln!("{BIN}: land: could not read {dst} from {remote}");
1176            report.next = vec![format!("git ls-remote {remote} {dst}")];
1177            return report;
1178        }
1179    }
1180    report = match prestage(&dst, &oid, &dst, "", (&remote, &url)).into_report(report) {
1181        ControlFlow::Continue(report) => report,
1182        ControlFlow::Break(stopped) => return *stopped,
1183    };
1184    let land_env = format!("{oid} {ZEROS}");
1185    let run = push(&url, &dst, &dst, None, &land_env);
1186    match run.outcome {
1187        PushOutcome::Done => {}
1188        PushOutcome::Signal(sig) => {
1189            report.status = Status::Interrupted(sig);
1190            return report;
1191        }
1192        PushOutcome::Failed => {
1193            report.status = status_of_failed_push(&run.stderr);
1194            if run.seen.contains(LAND_EVIDENCE_MISSING) {
1195                // A rehearsal tests HEAD, never the tagged commit's release
1196                // audits: land the tag again, which runs them first.
1197                report.next = vec![format!("{BIN} land --tag {name}")];
1198            }
1199            return report;
1200        }
1201    }
1202    let mut observed = Seen::Unreachable;
1203    for i in 0..=REREADS {
1204        if i > 0 {
1205            std::thread::sleep(crate::clock::scaled(REREAD_PAUSE));
1206        }
1207        observed = read_ref(&url, &dst, budget);
1208        if matches!(&observed, Seen::Tip(t) if *t == oid) {
1209            break;
1210        }
1211    }
1212    match observed {
1213        Seen::Tip(t) if t == oid => {
1214            report.remote_after = t;
1215            report.status = Status::Landed;
1216        }
1217        Seen::Tip(t) => {
1218            report.remote_after = t;
1219            report.status = Status::NotObserved;
1220            report.next = vec![format!("git ls-remote {remote} {dst}")];
1221        }
1222        Seen::Unreachable => {
1223            report.status = Status::Unverified;
1224            report.next = vec![format!("git ls-remote {remote} {dst}")];
1225        }
1226    }
1227    report
1228}
1229
1230/// `--dry-run`: steps 1 and 2 of a land and nothing else. No network, no push,
1231/// no ref written, no receipt.
1232fn dry_run_branch() -> (Report, &'static str) {
1233    match resolve() {
1234        Ok((_, mut report)) => {
1235            report.pushed = git::stdout(&["rev-parse", "HEAD"]).unwrap_or_default();
1236            (report, "would-land")
1237        }
1238        Err(refused) => (*refused, "refused"),
1239    }
1240}
1241
1242/// A dry run's talk, branch or tag alike: `next`, then the headline.
1243fn say_dry_run(report: &Report, verdict: &str) {
1244    for line in &report.next {
1245        eprintln!("    {line}");
1246    }
1247    eprintln!(
1248        "{}",
1249        verdict_word(verdict, "", &report.pushed, shown_ref(report))
1250    );
1251}
1252
1253/// A dry run's document: the same fields for a branch and a tag.
1254fn dry_run_json(report: &Report, verdict: &str, mode: Mode) -> String {
1255    let dir = receipt_dir()
1256        .map(|d| d.to_string_lossy().into_owned())
1257        .unwrap_or_default();
1258    json::object(&[
1259        json::string_field("branch", &report.branch),
1260        json::string_field("remote", &report.remote),
1261        json::string_field("push_url", &report.push_url),
1262        json::string_field("pushed", &report.pushed),
1263        json::string_field("dst", &report.dst),
1264        json::string_field("ref", &report.dst),
1265        json::bool_field("retried", false),
1266        json::string_field("status", verdict),
1267        json::string_field("receipt_dir", &dir),
1268        json::bool_field("lease", mode == Mode::Force),
1269    ])
1270}
1271
1272pub(crate) fn now_nanos() -> i64 {
1273    SystemTime::now()
1274        .duration_since(UNIX_EPOCH)
1275        .ok()
1276        .and_then(|d| i64::try_from(d.as_nanos()).ok())
1277        .unwrap_or(0)
1278}
1279
1280/// `<git-dir>/amont/land`, absolute and per worktree.
1281pub(crate) fn receipt_dir() -> Option<PathBuf> {
1282    git::stdout(&["rev-parse", "--absolute-git-dir"])
1283        .map(|d| PathBuf::from(d).join(crate::names::STATE_DIR).join("land"))
1284}
1285
1286/// What a detached land adds to its receipt.
1287#[derive(Debug, Clone)]
1288pub(crate) struct Meta {
1289    /// The sha the launcher judged, the only one the worker pushes.
1290    pub(crate) judged: String,
1291    pub(crate) log: String,
1292    pub(crate) worker_pid: Option<u32>,
1293    /// The flags the land was launched with, for a rerun.
1294    pub(crate) flags: Vec<String>,
1295}
1296
1297/// The receipt's JSON: `word` is its status (`running` while a worker has it).
1298pub(crate) fn receipt_body(
1299    report: &Report,
1300    word: &str,
1301    exit: Option<i32>,
1302    (started, ended): (i64, Option<i64>),
1303    meta: Option<&Meta>,
1304) -> String {
1305    let mut fields = vec![json::int_field("started", started)];
1306    if let Some(ended) = ended {
1307        fields.push(json::int_field("ended", ended));
1308    }
1309    fields.extend([
1310        json::string_field("branch", &report.branch),
1311        json::string_field("remote", &report.remote),
1312        json::string_field("push_url", &report.push_url),
1313        json::string_field("dst", &report.dst),
1314        json::string_field("pushed", &report.pushed),
1315        json::bool_field("retried", report.retried),
1316        json::string_field("status", word),
1317        json::string_field("remote_before", &report.remote_before),
1318        json::string_field("remote_after", &report.remote_after),
1319        format!(
1320            "\"gates\":{}",
1321            json::object(&[
1322                json::string_array_field("owed", &report.gates_owed),
1323                json::string_field("prestage", report.prestage.as_str()),
1324            ])
1325        ),
1326    ]);
1327    if let Some(code) = exit {
1328        fields.push(json::int_field("exit", i64::from(code)));
1329    }
1330    if let Some(meta) = meta {
1331        fields.push(json::string_field("judged", &meta.judged));
1332        fields.push(json::string_field("log", &meta.log));
1333        if let Some(pid) = meta.worker_pid {
1334            fields.push(json::int_field("worker_pid", i64::from(pid)));
1335        }
1336        fields.push(json::string_array_field("flags", &meta.flags));
1337    }
1338    json::object(&fields)
1339}
1340
1341/// Write `body` to `<path>.tmp`, then rename it over `path`: a reader sees the
1342/// old receipt or the new one, never half of either.
1343pub(crate) fn write_atomic(path: &std::path::Path, body: &str) -> std::io::Result<()> {
1344    let mut tmp = path.as_os_str().to_owned();
1345    tmp.push(".tmp");
1346    let tmp = PathBuf::from(tmp);
1347    std::fs::write(&tmp, format!("{body}\n"))?;
1348    std::fs::rename(&tmp, path)
1349}
1350
1351/// The receipt is the evidence of what a land pushed, independent of the
1352/// tracking ref. One per land that got past resolving the branch, written with
1353/// the final status. A receipt that cannot be written is a warning, never a
1354/// change of exit code.
1355fn write_receipt(report: &Report, started: i64, ended: i64) {
1356    if report.branch.is_empty() && report.dst.is_empty() {
1357        return;
1358    }
1359    let Some(dir) = receipt_dir() else {
1360        eprintln!("{BIN}: land: could not find the git directory; no landing receipt written");
1361        return;
1362    };
1363    if let Err(e) = std::fs::create_dir_all(&dir) {
1364        eprintln!(
1365            "{BIN}: land: could not write a landing receipt in {}: {e}",
1366            dir.display()
1367        );
1368        return;
1369    }
1370    prune_receipts(&dir);
1371    let path = dir.join(format!("{started}-{}.json", std::process::id()));
1372    let body = receipt_body(
1373        report,
1374        report.status.as_str(),
1375        Some(report.status.code()),
1376        (started, Some(ended)),
1377        None,
1378    );
1379    if let Err(e) = write_atomic(&path, &body) {
1380        eprintln!(
1381            "{BIN}: land: could not write the landing receipt {}: {e}",
1382            path.display()
1383        );
1384    }
1385}
1386
1387/// Whether a worker still holds `receipt`'s lock.
1388pub(crate) fn lock_held(receipt: &std::path::Path) -> bool {
1389    #[cfg(unix)]
1390    {
1391        let mut lock = receipt.as_os_str().to_owned();
1392        lock.push(".lock");
1393        match std::fs::File::open(&lock) {
1394            Ok(file) => !crate::fdlock::try_exclusive(&file),
1395            Err(_) => false,
1396        }
1397    }
1398    #[cfg(not(unix))]
1399    {
1400        let _ = receipt;
1401        false
1402    }
1403}
1404
1405/// Deletes receipts older than [`RECEIPT_KEEP`], each with its log, lock and
1406/// leftover temp file. A receipt whose lock is held belongs to a live worker
1407/// and is never pruned.
1408pub(crate) fn prune_receipts(dir: &std::path::Path) {
1409    let Ok(entries) = std::fs::read_dir(dir) else {
1410        return;
1411    };
1412    for entry in entries.flatten() {
1413        let path = entry.path();
1414        if path.extension().map_or(true, |e| e != "json") {
1415            continue;
1416        }
1417        let old = entry
1418            .metadata()
1419            .and_then(|m| m.modified())
1420            .ok()
1421            .and_then(|t| t.elapsed().ok())
1422            .is_some_and(|age| age > RECEIPT_KEEP);
1423        if !old || lock_held(&path) {
1424            continue;
1425        }
1426        let mut lock = path.as_os_str().to_owned();
1427        lock.push(".lock");
1428        let mut tmp = path.as_os_str().to_owned();
1429        tmp.push(".tmp");
1430        for doomed in [
1431            path.clone(),
1432            path.with_extension("log"),
1433            PathBuf::from(lock),
1434            PathBuf::from(tmp),
1435        ] {
1436            match std::fs::remove_file(&doomed) {
1437                Ok(()) => {}
1438                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1439                Err(e) => eprintln!(
1440                    "{BIN}: land: could not delete the old receipt file {}: {e}",
1441                    doomed.display()
1442                ),
1443            }
1444        }
1445    }
1446}
1447
1448fn is_protected(branch: &str) -> bool {
1449    matches!(branch, "main" | "master")
1450}
1451
1452/// A push to a URL updates no tracking ref, so after a verified landing the
1453/// local view of the remote is moved to what was just proven. The landing
1454/// already happened, so a failure here is a warning, not an exit code.
1455fn move_tracking_ref(remote: &str, rb: &str, sha: &str) {
1456    let tracking = format!("refs/remotes/{remote}/{rb}");
1457    if !git::succeeds(&["update-ref", &tracking, sha]) {
1458        eprintln!(
1459            "{BIN}: land: landed, but could not move {tracking} to {}",
1460            short(sha)
1461        );
1462    }
1463}
1464
1465/// The first landing of a branch with no upstream sets one.
1466fn set_upstream(remote: &str, rb: &str) {
1467    let upstream = format!("{remote}/{rb}");
1468    if !git::succeeds(&["branch", "--set-upstream-to", &upstream]) {
1469        eprintln!("{BIN}: land: landed, but could not set the upstream to {upstream}");
1470    }
1471}
1472
1473enum PushOutcome {
1474    Done,
1475    Failed,
1476    Signal(i32),
1477}
1478
1479struct PushRun {
1480    outcome: PushOutcome,
1481    /// stderr alone, for classification.
1482    stderr: String,
1483    /// stdout and stderr, for finding the hook's `push again`.
1484    seen: String,
1485}
1486
1487/// `git push <url> <sha>:refs/heads/<rb>` with the pre-push hooks running.
1488///
1489/// An explicit sha, so the commit that is verified is the commit that was
1490/// pushed even if HEAD moves underneath. Both of the child's streams are
1491/// copied to OUR stderr as they arrive, in chunks rather than lines so git's
1492/// `\r` progress still moves, and a copy is kept for classification; stdout
1493/// of the process stays free for `--json`. No overall deadline: the
1494/// pre-push hook runs the whole gate, which takes minutes. Without a
1495/// terminal the push gets the no-prompt environment, which bounds the
1496/// network legs only: a custom ssh command, a credential helper or an
1497/// established session can still stall, and Ctrl-C is the answer.
1498fn push(url: &str, src: &str, dst: &str, lease: Option<&str>, land_env: &str) -> PushRun {
1499    let mut cmd = Command::new("git");
1500    // What the pre-stage ran against, for the hook of THIS push (ADR-0018).
1501    cmd.env(crate::rehearsal::LAND_ENV, land_env);
1502    if !std::io::stdin().is_terminal() {
1503        let (pre, env) = git::remote_env(git::configured_ssh());
1504        cmd.args(pre).envs(env);
1505    }
1506    cmd.arg("push");
1507    if let Some(old) = lease {
1508        cmd.arg(format!("--force-with-lease={dst}:{old}"));
1509    }
1510    cmd.arg(url)
1511        .arg(format!("{src}:{dst}"))
1512        .stdin(Stdio::inherit())
1513        .stdout(Stdio::piped())
1514        .stderr(Stdio::piped());
1515    let mut child = match cmd.spawn() {
1516        Ok(c) => c,
1517        Err(e) => {
1518            let why = format!("could not run git push: {e}\n");
1519            eprint!("{BIN}: land: {why}");
1520            return PushRun {
1521                outcome: PushOutcome::Failed,
1522                stderr: why.clone(),
1523                seen: why,
1524            };
1525        }
1526    };
1527    let tee = |mut from: Box<dyn Read + Send>| {
1528        std::thread::spawn(move || {
1529            let mut kept = Vec::new();
1530            let mut buf = [0u8; 4096];
1531            let mut err = std::io::stderr();
1532            while let Ok(n) = from.read(&mut buf) {
1533                if n == 0 {
1534                    break;
1535                }
1536                let _ = err.write_all(&buf[..n]);
1537                let _ = err.flush();
1538                kept.extend_from_slice(&buf[..n]);
1539            }
1540            String::from_utf8_lossy(&kept).into_owned()
1541        })
1542    };
1543    let out_thread = child.stdout.take().map(|s| tee(Box::new(s)));
1544    let err_thread = child.stderr.take().map(|s| tee(Box::new(s)));
1545    let status = child.wait();
1546    let out = out_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1547    let err = err_thread.and_then(|t| t.join().ok()).unwrap_or_default();
1548    let outcome = match status {
1549        Ok(s) if s.success() => PushOutcome::Done,
1550        Ok(s) => match signal_of(&s) {
1551            Some(sig) => PushOutcome::Signal(sig),
1552            None => PushOutcome::Failed,
1553        },
1554        Err(_) => PushOutcome::Failed,
1555    };
1556    PushRun {
1557        outcome,
1558        seen: format!("{out}{err}"),
1559        stderr: err,
1560    }
1561}
1562
1563#[cfg(test)]
1564mod tests {
1565
1566    /// A credential in the push URL never reaches `land --json`.
1567    #[test]
1568    fn a_push_url_is_reported_without_its_credentials() {
1569        let r = super::redact_url;
1570        assert_eq!(
1571            r("https://x:tok@github.com/o/r.git"),
1572            "https://***@github.com/o/r.git"
1573        );
1574        assert_eq!(
1575            r("https://tok@github.com/o/r.git"),
1576            "https://***@github.com/o/r.git"
1577        );
1578        assert_eq!(r("ssh://git:pw@host/o/r"), "ssh://git:***@host/o/r");
1579        assert_eq!(
1580            r("ssh://git@github.com/o/r.git"),
1581            "ssh://git@github.com/o/r.git"
1582        );
1583        assert_eq!(r("git@github.com:o/r.git"), "git@github.com:o/r.git");
1584        assert_eq!(
1585            r("https://github.com/o/r.git"),
1586            "https://github.com/o/r.git"
1587        );
1588        assert_eq!(r("/tmp/bare.git"), "/tmp/bare.git");
1589    }
1590    use super::*;
1591
1592    #[test]
1593    fn exit_codes_keep_usage_apart_from_the_lost_ref() {
1594        assert_eq!(Status::Landed.code(), 0);
1595        assert_eq!(Status::Refused.code(), 1);
1596        assert_eq!(Status::Usage.code(), 2);
1597        assert_eq!(Status::Unreachable.code(), 3);
1598        assert_eq!(Status::Unverified.code(), 3);
1599        assert_eq!(Status::NotObserved.code(), 4);
1600        assert_eq!(Status::Interrupted(2).code(), 130);
1601    }
1602
1603    #[test]
1604    fn every_status_has_its_own_word() {
1605        let all = [
1606            Status::Landed,
1607            Status::Refused,
1608            Status::Usage,
1609            Status::Unreachable,
1610            Status::Unverified,
1611            Status::NotObserved,
1612            Status::Interrupted(15),
1613        ];
1614        let words: std::collections::HashSet<_> = all.iter().map(|s| s.as_str()).collect();
1615        assert_eq!(words.len(), all.len());
1616    }
1617
1618    #[test]
1619    fn the_verdict_fits_eighty_columns_for_any_branch() {
1620        let long = "feature/".to_string() + &"x".repeat(120);
1621        for status in [Status::Landed, Status::NotObserved, Status::Unverified] {
1622            let line = verdict(status, "0123456789abcdef", "fedcba9876543210", &long);
1623            assert!(line.chars().count() <= 80, "{line}");
1624            assert!(line.contains('…'), "{line}");
1625            assert!(line.starts_with(status.as_str()));
1626        }
1627    }
1628
1629    #[test]
1630    fn a_short_branch_is_shown_whole_and_a_new_ref_has_a_placeholder() {
1631        let line = verdict(Status::Landed, "", "fedcba9876543210", "feat/x");
1632        assert_eq!(line, "landed -------..fedcba9 feat/x");
1633    }
1634
1635    #[test]
1636    fn the_verdict_is_plain_text() {
1637        let line = verdict(Status::Refused, "a", "b", "feat/ünï");
1638        assert!(!line.contains('\u{1b}'));
1639    }
1640
1641    #[test]
1642    fn truncation_keeps_both_ends() {
1643        assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
1644        assert_eq!(truncate_middle("abc", 5), "abc");
1645        assert_eq!(truncate_middle("abcdefghij", 1), "…");
1646    }
1647
1648    #[test]
1649    fn the_tip_is_the_first_field_and_absence_is_empty() {
1650        assert_eq!(parse_tip("abc123\trefs/heads/x\n"), "abc123");
1651        assert_eq!(parse_tip(""), "");
1652    }
1653
1654    #[test]
1655    fn json_carries_every_field_the_contract_names() {
1656        let mut r = Report::new(Status::NotObserved);
1657        r.branch = "feat/x".into();
1658        r.retried = true;
1659        let j = r.json();
1660        for key in [
1661            "branch",
1662            "remote",
1663            "push_url",
1664            "pushed",
1665            "remote_before",
1666            "remote_after",
1667            "retried",
1668            "status",
1669        ] {
1670            assert!(j.contains(&format!("\"{key}\"")), "{key} missing in {j}");
1671        }
1672        assert!(j.contains("\"status\":\"not-observed\""), "{j}");
1673        assert!(j.contains("\"retried\":true"), "{j}");
1674        assert!(usage_json().contains("\"status\":\"usage\""));
1675    }
1676}