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