Skip to main content

greengate_runtime/
run_stamp.rs

1//! `amont run --stamp` and `amont stamps` (ADR-0015): a runner other than the
2//! commit hook earns amont's verdict for a tree, and anyone can ask which
3//! gates a tree carries a verdict for.
4//!
5//! The commit hook stamps the tree it is about to seal and the push hook the
6//! tips it pushes. A tool that verifies a tree of its own (relais, in a clean
7//! candidate worktree) had no way to leave the same record, so the person's
8//! later commit and push of that exact tree ran the suite again. `run --stamp`
9//! runs the named gates on HEAD of a clean worktree and writes the same tokens
10//! the hooks write, through the same writers:
11//!
12//! - a commit-time declaration that blocks is stamped on the TREE note, under
13//!   its script name ([`crate::gate_stamp::stamp_tree`]), which is what the
14//!   pre-commit hook ([`crate::gate_stamp::vouched_for_staged_tree`]) and the
15//!   push twin's pairing read. Not the one-shot marker: that lives in the
16//!   worktree-private gitdir and dies with a throwaway worktree;
17//! - a push gate is stamped on the tree and the commit
18//!   ([`crate::gate_stamp::stamp_push`]), as a rehearsal does;
19//! - a built-in pre-commit check gets its built-in token on the tree note. The
20//!   commit hook reruns built-ins whatever the note says (they read the index);
21//!   the token is evidence for `amont stamps` and the tools that read it.
22//!
23//! Nothing here signs. Signing stays at push time, with the key the pre-push
24//! hook already uses, over the stamps it finds (decisions programme "one
25//! verdict per tree", t02).
26//!
27//! Every failure points the usual way: a gate that did not pass, was deferred,
28//! could not run or had nothing to judge writes no token, and no token means
29//! the hooks run it.
30
31use crate::check::{Check, Outcome, Severity, Stage};
32use crate::manifest::Manifest;
33use crate::names::BIN;
34use crate::pushrefs::PushRefs;
35use crate::registry::Ctx;
36use crate::ui::{highlight, valid_sign, warning_sign};
37
38/// Exit codes of `amont run --stamp`.
39pub const EXIT_STAMPED: i32 = 0;
40pub const EXIT_FAILED: i32 = 1;
41pub const EXIT_REFUSED: i32 = 2;
42/// A gate was deferred, could not run, had nothing to judge, or passed under
43/// `warn` (a warn pass is not stamped): no token was written for it, and
44/// nothing failed.
45pub const EXIT_UNSTAMPED: i32 = 4;
46
47/// What became of one gate in a `run --stamp`.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Ended {
50    Stamped,
51    /// A push gate whose commit-time twin passed in this run: its pairing at
52    /// push time reads the twin's tree token, so it is not run twice.
53    CoveredBy(String),
54    Failed,
55    /// Deferred by the busy policy (ADR-0013): never a token.
56    Deferred,
57    /// Could not run, warned, repaired files, not opted in, or judged nothing.
58    NotStamped(&'static str),
59}
60
61/// How `amont stamps` prints its answer.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum Output {
64    Json,
65    Text,
66}
67
68/// One gate's state on a tree, as `amont stamps` reports it.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum State {
71    Stamped,
72    Attested,
73    Deferred,
74    Absent,
75}
76
77impl State {
78    pub fn as_str(self) -> &'static str {
79        match self {
80            State::Stamped => "stamped",
81            State::Attested => "attested",
82            State::Deferred => "deferred",
83            State::Absent => "absent",
84        }
85    }
86}
87
88/// Resolve `names` to check ids. A short name that reaches more than one
89/// check (`cargo-test`: the commit-time declaration and the push built-in)
90/// selects all of them: the push one is then covered by its twin, not run
91/// twice. Empty `names`: the default set.
92fn resolve(
93    settings: &crate::config::Settings,
94    manifest: &Manifest,
95    names: &[String],
96) -> Result<Vec<String>, String> {
97    if names.is_empty() {
98        return Ok(default_gates(settings, manifest));
99    }
100    let mut out: Vec<String> = Vec::new();
101    for n in names {
102        let ids = match crate::dispatch::resolve_check_name(n, manifest) {
103            crate::dispatch::Named2::Resolved(id) => vec![id],
104            crate::dispatch::Named2::Ambiguous(ids) => ids,
105            crate::dispatch::Named2::Unknown => {
106                return Err(format!("unknown gate {n:?} — try `{BIN} list`"))
107            }
108        };
109        for id in ids {
110            if crate::registry::one_named(&id, manifest).is_none() {
111                return Err(format!("{n:?} is not a check `--stamp` can run"));
112            }
113            if !out.contains(&id) {
114                out.push(id);
115            }
116        }
117    }
118    Ok(out)
119}
120
121/// Every gate the hooks honour a stamp for: the blocking commit-time
122/// declarations, and the scoped push gates this repository opted into.
123/// `hook.skip` removes a gate here as it does from a stage.
124pub fn default_gates(settings: &crate::config::Settings, manifest: &Manifest) -> Vec<String> {
125    let skips = crate::configured_skips(settings);
126    let skipped = |id: &str| skips.iter().any(|s| crate::skip_suppresses(id, s));
127    let tracked = crate::tracked_paths();
128    let mut out: Vec<String> =
129        crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
130            .into_iter()
131            .map(|d| d.id)
132            .filter(|id| !skipped(id))
133            .collect();
134    for c in crate::registry::all_stage_checks(Stage::PrePush, manifest) {
135        let scope = c.scope();
136        if crate::dispatch::stamped_push_gate(c) && scope.opted_in(&tracked) && !skipped(c.name()) {
137            let id = c.name().to_string();
138            if !out.contains(&id) {
139                out.push(id);
140            }
141        }
142    }
143    out
144}
145
146/// The token a gate's verdict is stamped under, and whether it is a
147/// commit-time one (tree note) or a push one (tree and commit).
148fn token_for(
149    settings: &crate::config::Settings,
150    manifest: &Manifest,
151    check: &dyn Check,
152) -> Option<String> {
153    if check.stage() == Stage::PreCommit {
154        if let Some(d) =
155            crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
156                .into_iter()
157                .find(|d| d.id == check.name())
158        {
159            return manifest
160                .externals
161                .iter()
162                .find(|e| e.id == d.id)
163                .and_then(|e| crate::gate_identity::external_token(e, &d.script));
164        }
165    }
166    crate::gate_identity::token(&manifest.externals, check.name())
167}
168
169/// The commit-time declaration a push gate pairs with, if any.
170fn twin_of(
171    settings: &crate::config::Settings,
172    manifest: &Manifest,
173    check: &dyn Check,
174) -> Option<String> {
175    if check.stage() != Stage::PrePush {
176        return None;
177    }
178    let short = check.pairing_name();
179    crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
180        .into_iter()
181        .find(|d| d.script == short)
182        .map(|d| d.id)
183}
184
185/// Run one check by itself, keeping its outcome (a deferral wins, as in a
186/// stage).
187fn run_one(ctx: &Ctx, check: &dyn Check) -> Outcome {
188    let slot = crate::host_slots::enter_check(check.name(), check.weight());
189    let outcome = check.run(ctx);
190    if slot.deferred().is_some() {
191        Outcome::Deferred
192    } else {
193        outcome
194    }
195}
196
197/// `amont run --stamp [<gate>…]`.
198pub fn stamp(settings: &crate::config::Settings, manifest: &Manifest, names: &[String]) -> i32 {
199    // Captured before anything runs: what the gates are handed is what the
200    // stamp vouches for. Tracked changes only, as `stamp_tips` argues; the
201    // untracked artefacts a gate leaves behind do not count.
202    let dirty = crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]);
203    match dirty.as_deref() {
204        None => {
205            eprintln!("{BIN}: git would not say whether the worktree is clean — nothing stamped");
206            return EXIT_REFUSED;
207        }
208        Some(s) if !s.trim().is_empty() => {
209            eprintln!(
210                "{BIN}: run --stamp needs a clean worktree: tracked files differ from HEAD, so \
211                 the gates would judge content no tree holds — commit or stash them first"
212            );
213            return EXIT_REFUSED;
214        }
215        Some(_) => {}
216    }
217    let (Some(head), Some(tree)) = (
218        crate::git::stdout(&["rev-parse", "HEAD"]),
219        crate::git::stdout(&["rev-parse", "HEAD^{tree}"]),
220    ) else {
221        eprintln!("{BIN}: run --stamp needs a commit at HEAD to stamp");
222        return EXIT_REFUSED;
223    };
224    let ids = match resolve(settings, manifest, names) {
225        Ok(ids) => ids,
226        Err(e) => {
227            eprintln!("{BIN}: {e}");
228            return EXIT_REFUSED;
229        }
230    };
231    if ids.is_empty() {
232        println!("{} no gate to stamp here", warning_sign());
233        return EXIT_STAMPED;
234    }
235    let checks: Vec<&dyn Check> = ids
236        .iter()
237        .filter_map(|id| crate::registry::one_named(id, manifest))
238        .collect();
239    let tracked = crate::tracked_paths();
240    // Commit-time gates judge the whole tree, not an index nobody staged.
241    if checks.iter().any(|c| c.stage() == Stage::PreCommit) {
242        crate::dispatch::enter_all_files_mode();
243    }
244    let hooks_dir = std::path::PathBuf::from(".git/hooks");
245    let empty = PushRefs::preloaded(Vec::new());
246    let audits = crate::hooks::audit::Ledger::default();
247    // A push gate judges a push; standalone there is none, so the one ref a
248    // rehearsal would push is synthesised, as `amont run pre-push` does —
249    // only when a push gate actually has to run (one covered by its twin
250    // needs no ref, and a repository with no remote then says nothing).
251    let push: std::cell::OnceCell<Option<(PushRefs, Vec<String>)>> = std::cell::OnceCell::new();
252    let push_for = || {
253        push.get_or_init(|| match crate::pushrefs::synthetic_from_upstream() {
254            Ok(r) => {
255                let refs = PushRefs::preloaded(vec![r]);
256                let changed = crate::pushrefs::changed_files(refs.get());
257                Some((refs, changed))
258            }
259            Err(e) => {
260                eprintln!("{BIN}: push gates cannot run here: {e}");
261                None
262            }
263        })
264        .as_ref()
265    };
266    let mut ended: Vec<(String, Ended)> = Vec::new();
267    // Commit-time first, so a push gate can be covered by its twin.
268    let mut ordered = checks.clone();
269    ordered.sort_by_key(|c| u8::from(c.stage() != Stage::PreCommit));
270    for check in ordered {
271        let name = check.name().to_string();
272        let scope = check.scope();
273        if !scope.opted_in(&tracked) {
274            ended.push((name, Ended::NotStamped("not opted in here")));
275            continue;
276        }
277        let end = match check.stage() {
278            Stage::PreCommit => {
279                if !scope.is_unscoped() && !scope.touches(&tracked) {
280                    Ended::NotStamped("no tracked file in its scope")
281                } else {
282                    let ctx = Ctx {
283                        name: check.name(),
284                        args: &[],
285                        hooks_dir: &hooks_dir,
286                        push: &empty,
287                        manifest,
288                        settings,
289                        handed_to_cluster: &[],
290                        land: &crate::rehearsal::LandEnv::Absent,
291                        audits: &audits,
292                        source_worktree: None,
293                    };
294                    finish(
295                        settings,
296                        manifest,
297                        check,
298                        &tree,
299                        run_one(&ctx, check),
300                        |tok| crate::gate_stamp::stamp_tree(&tree, &[tok]),
301                    )
302                }
303            }
304            Stage::PrePush => {
305                let twin = twin_of(settings, manifest, check);
306                if let Some(t) =
307                    twin.filter(|t| ended.iter().any(|(n, e)| n == t && *e == Ended::Stamped))
308                {
309                    Ended::CoveredBy(t)
310                } else {
311                    match push_for() {
312                        None => Ended::NotStamped("no push ref to judge"),
313                        Some((_, changed)) if !scope.is_unscoped() && !scope.touches(changed) => {
314                            Ended::NotStamped("nothing it judges changed since the base")
315                        }
316                        Some((refs, _)) => {
317                            let ctx = Ctx {
318                                name: check.name(),
319                                args: &[],
320                                hooks_dir: &hooks_dir,
321                                push: refs,
322                                manifest,
323                                settings,
324                                handed_to_cluster: &[],
325                                land: &crate::rehearsal::LandEnv::Absent,
326                                audits: &audits,
327                                source_worktree: None,
328                            };
329                            finish(
330                                settings,
331                                manifest,
332                                check,
333                                &tree,
334                                run_one(&ctx, check),
335                                |tok| crate::gate_stamp::stamp_push(&head, &tree, &[tok]),
336                            )
337                        }
338                    }
339                }
340            }
341        };
342        ended.push((name, end));
343    }
344    report(&tree, &ended)
345}
346
347/// Turn one outcome into what is recorded, writing the token on a pass.
348fn finish(
349    settings: &crate::config::Settings,
350    manifest: &Manifest,
351    check: &dyn Check,
352    tree: &str,
353    outcome: Outcome,
354    write: impl FnOnce(String) -> bool,
355) -> Ended {
356    match outcome {
357        // Not a stamp (f129): a warn gate's verdict is advisory and may read
358        // more than the tree, so a pass keyed by tree could go stale.
359        Outcome::Passed
360            if check.stage() == Stage::PrePush
361                && crate::registry::severity_of(settings, check) == Severity::Warn =>
362        {
363            // The same one-hour word the push hook writes, so a land within
364            // the hour skips the gate.
365            match token_for(settings, manifest, check).map(|tok| {
366                crate::gate_stamp::record_done(
367                    tree,
368                    &[tok],
369                    crate::gate_stamp::Completion::PassedUnderWarn,
370                )
371            }) {
372                Some(Ok(())) => Ended::NotStamped("passed under warn"),
373                Some(Err(why)) => {
374                    eprintln!("{BIN}: {why}");
375                    Ended::NotStamped("passed under warn; completion not recorded")
376                }
377                None => Ended::NotStamped("passed under warn; its identity cannot be worked out"),
378            }
379        }
380        // The cluster recorded it in its own ref (ADR-0016); a local token
381        // here would claim a run this machine never made.
382        Outcome::Passed if crate::cluster::proved(check.name(), tree) => Ended::Stamped,
383        Outcome::Passed => match token_for(settings, manifest, check) {
384            Some(tok) => {
385                if write(tok) {
386                    Ended::Stamped
387                } else {
388                    Ended::NotStamped("git refused the note")
389                }
390            }
391            None => Ended::NotStamped("its identity cannot be worked out"),
392        },
393        Outcome::Failed => match crate::registry::severity_of(settings, check) {
394            Severity::Block => Ended::Failed,
395            Severity::Warn => Ended::NotStamped("failed, set to warn"),
396        },
397        Outcome::Deferred => Ended::Deferred,
398        Outcome::Fixed => Ended::NotStamped("repaired files"),
399        Outcome::Warned => Ended::NotStamped("warned"),
400        Outcome::Unavailable => Ended::NotStamped("could not run"),
401        Outcome::Inert => Ended::NotStamped("judged nothing"),
402        Outcome::Skipped => Ended::NotStamped("skipped, an earlier gate failed"),
403    }
404}
405
406fn report(tree: &str, ended: &[(String, Ended)]) -> i32 {
407    let short = tree.get(..12).unwrap_or(tree);
408    let mut code = EXIT_STAMPED;
409    for (name, end) in ended {
410        match end {
411            Ended::Stamped => println!(
412                "{} stamped {} on tree {short}",
413                valid_sign(),
414                highlight(name)
415            ),
416            Ended::CoveredBy(t) => println!(
417                "{} {} covered by its commit-time twin {}",
418                valid_sign(),
419                highlight(name),
420                highlight(t)
421            ),
422            Ended::Failed => {
423                println!(
424                    "{} {} failed — not stamped",
425                    warning_sign(),
426                    highlight(name)
427                );
428                code = EXIT_FAILED;
429            }
430            Ended::Deferred => {
431                println!(
432                    "{} {} deferred, no host slot freed — not stamped",
433                    warning_sign(),
434                    highlight(name)
435                );
436                if code == EXIT_STAMPED {
437                    code = EXIT_UNSTAMPED;
438                }
439            }
440            Ended::NotStamped(why) => {
441                println!("{} {} not stamped: {why}", warning_sign(), highlight(name));
442                if code == EXIT_STAMPED {
443                    code = EXIT_UNSTAMPED;
444                }
445            }
446        }
447    }
448    code
449}
450
451/// The ids that carry a gate's verdict: itself, and its twin at the other
452/// stage. A commit-time declaration and the push gate it pairs with run the
453/// same command on the same tree, so a token or a signed attestation for
454/// either is the verdict of both (the push hook skips on the first, CI on
455/// the second).
456fn verdict_ids(
457    settings: &crate::config::Settings,
458    manifest: &Manifest,
459    check: &dyn Check,
460) -> Vec<String> {
461    let mut ids = vec![check.name().to_string()];
462    match check.stage() {
463        Stage::PrePush => ids.extend(twin_of(settings, manifest, check)),
464        Stage::PreCommit => {
465            let declared =
466                crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
467                    .into_iter()
468                    .any(|d| d.id == check.name());
469            if declared {
470                ids.extend(
471                    crate::registry::all_stage_checks(Stage::PrePush, manifest)
472                        .into_iter()
473                        .filter(|c| c.pairing_name() == check.pairing_name())
474                        .map(|c| c.name().to_string()),
475                );
476            }
477        }
478    }
479    ids
480}
481
482/// A detached checkout of a commit with no files, removed on drop: the
483/// verifier judges the tree checked out where it is pointed.
484struct Detached {
485    dir: std::path::PathBuf,
486}
487
488impl Detached {
489    fn at(commit: &str) -> Option<Detached> {
490        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
491        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
492        let dir = std::env::temp_dir().join(format!("greengate-stamps-{}-{n}", std::process::id()));
493        let path = dir.to_str()?;
494        crate::git::succeeds(&[
495            "worktree",
496            "add",
497            "--detach",
498            "--no-checkout",
499            "-q",
500            path,
501            commit,
502        ])
503        .then_some(Detached { dir })
504    }
505}
506
507impl Drop for Detached {
508    fn drop(&mut self) {
509        if let Some(path) = self.dir.to_str() {
510            let remove = ["worktree", "remove", "--force", path];
511            let _ = crate::git::succeeds(&remove); // best-effort: scratch, swept below
512        }
513        let _ = std::fs::remove_dir_all(&self.dir); // best-effort: scratch left by a failed remove
514    }
515}
516
517/// A commit holding `tree`, for a caller that was given a bare tree id. Fixed
518/// identity and date, so the same tree is the same commit; nothing refers to
519/// it and gc takes it.
520fn commit_of_tree(tree: &str) -> Option<String> {
521    commit_of_tree_in(tree, None)
522}
523
524/// [`commit_of_tree`] in `dir` (the current directory when `None`).
525fn commit_of_tree_in(tree: &str, dir: Option<&std::path::Path>) -> Option<String> {
526    use crate::names::{GIT_AUTHOR, GIT_EMAIL};
527    let mut cmd = std::process::Command::new("git");
528    cmd.args(["commit-tree", tree, "-m", crate::names::STAMP_MESSAGE])
529        .env("GIT_AUTHOR_NAME", GIT_AUTHOR)
530        .env("GIT_AUTHOR_EMAIL", GIT_EMAIL)
531        .env("GIT_COMMITTER_NAME", GIT_AUTHOR)
532        .env("GIT_COMMITTER_EMAIL", GIT_EMAIL)
533        .env("GIT_AUTHOR_DATE", "@0 +0000")
534        .env("GIT_COMMITTER_DATE", "@0 +0000");
535    if let Some(dir) = dir {
536        cmd.current_dir(dir);
537    }
538    let out = cmd.output().ok()?;
539    out.status
540        .success()
541        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
542        .filter(|c| !c.is_empty())
543}
544
545/// The gate ids a signed attestation covers for `tree` on this platform.
546///
547/// The verifier syncs the notes from origin before it judges (up to 15 s, 45
548/// if origin is dead), so [`states`] asks only when some gate is not already
549/// stamped. For a tree other than the one checked out, a throwaway checkout of
550/// `commit` (or of a commit made for the tree) is what it is pointed at.
551///
552/// `anywhere` are the trusted `platform=any` gate ids: a linux block the
553/// cluster's pass earned covers them on this platform too.
554fn attested_for(tree: &str, commit: Option<&str>, anywhere: &[String]) -> Vec<String> {
555    let Some(signers) = crate::attest::default_signers() else {
556        return Vec::new();
557    };
558    let platform = crate::attest::platform();
559    let checked_out = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
560    let gates = if checked_out.as_deref() == Some(tree) {
561        crate::attest::covered(&signers, None, Some(&platform), anywhere)
562    } else {
563        let Some(commit) = commit.map(str::to_string).or_else(|| commit_of_tree(tree)) else {
564            return Vec::new();
565        };
566        let Some(checkout) = Detached::at(&commit) else {
567            return Vec::new();
568        };
569        crate::attest::covered_in(&checkout.dir, &signers, None, Some(&platform), anywhere)
570    };
571    gates
572        .map(|g| g.split_whitespace().map(str::to_string).collect())
573        .unwrap_or_default()
574}
575
576/// Each gate's state on `tree`: a valid local token (its own or its twin's),
577/// else a signed attestation for it on this platform, else a recorded
578/// deferral, else nothing. `commit` is the commit `tree` was asked for by, if
579/// it was asked for by one.
580pub fn states(
581    settings: &crate::config::Settings,
582    manifest: &Manifest,
583    tree: &str,
584    commit: Option<&str>,
585    ids: &[String],
586) -> Vec<(String, State)> {
587    let tokens = crate::gate_stamp::tree_tokens(tree);
588    let deferred = crate::gate_stamp::deferred_on(tree);
589    let attested: std::cell::OnceCell<Vec<String>> = std::cell::OnceCell::new();
590    let anywhere = crate::cluster::platform_any_ids(manifest);
591    ids.iter()
592        .filter_map(|id| crate::registry::one_named(id, manifest).map(|c| (id, c)))
593        .map(|(id, check)| {
594            let verdict = verdict_ids(settings, manifest, check);
595            let stamped = verdict
596                .iter()
597                .filter_map(|v| crate::registry::one_named(v, manifest))
598                .filter_map(|c| token_for(settings, manifest, c))
599                .any(|t| tokens.contains(&t))
600                || crate::cluster::stamped_on_tree(settings, &manifest.externals, &verdict, tree);
601            let state = if stamped {
602                State::Stamped
603            } else if attested
604                .get_or_init(|| attested_for(tree, commit, &anywhere))
605                .iter()
606                .any(|g| verdict.contains(g))
607            {
608                State::Attested
609            } else if deferred
610                .iter()
611                .any(|d| *d == crate::short_name(id) || *d == check.pairing_name())
612            {
613                State::Deferred
614            } else {
615                State::Absent
616            };
617            (id.clone(), state)
618        })
619        .collect()
620}
621
622/// `amont stamps [--json] [--tree <rev>] [<gate>…]`. Exit 0 with an answer,
623/// 2 on usage (an unknown gate, a rev that names no tree).
624pub fn stamps_command(
625    settings: &crate::config::Settings,
626    manifest: &Manifest,
627    output: Output,
628    tree: Option<&str>,
629    names: &[String],
630) -> i32 {
631    // A detached rehearsal's passes are tokens before the question is asked
632    // (ADR-0017).
633    crate::cluster::collect_if_declared(manifest);
634    let rev = tree.unwrap_or("HEAD");
635    let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{rev}^{{tree}}")]) else {
636        eprintln!("{BIN}: {rev:?} names no tree here");
637        return EXIT_REFUSED;
638    };
639    // The commit the tree was asked for by, when it was asked for by one.
640    let commit = crate::git::stdout(&[
641        "rev-parse",
642        "--verify",
643        "--quiet",
644        &format!("{rev}^{{commit}}"),
645    ]);
646    let ids = match resolve(settings, manifest, names) {
647        Ok(ids) => ids,
648        Err(e) => {
649            eprintln!("{BIN}: {e}");
650            return EXIT_REFUSED;
651        }
652    };
653    let states = states(settings, manifest, &tree, commit.as_deref(), &ids);
654    if output == Output::Json {
655        let gates: Vec<String> = states
656            .iter()
657            .map(|(id, s)| crate::json::string_field(id, s.as_str()))
658            .collect();
659        println!(
660            "{}",
661            crate::json::object(&[
662                crate::json::string_field("tree", &tree),
663                crate::json::string_field("platform", &crate::attest::platform()),
664                format!("\"gates\":{}", crate::json::object(&gates)),
665            ])
666        );
667    } else {
668        println!("tree {tree} ({})", crate::attest::platform());
669        for (id, s) in &states {
670            println!("  {:<9} {id}", s.as_str());
671        }
672    }
673    0
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679
680    /// The throwaway commit made for a bare tree id is authored by greengate.
681    #[test]
682    fn a_stamp_commit_is_authored_by_greengate() {
683        let dir = std::env::temp_dir().join(format!(
684            "{}-stamp-author-{}",
685            crate::names::BIN,
686            std::process::id()
687        ));
688        let _ = std::fs::remove_dir_all(&dir); // a stale scratch dir from an earlier run may not exist
689        std::fs::create_dir_all(&dir).unwrap();
690        let git = |args: &[&str]| {
691            let out = std::process::Command::new("git")
692                .args(args)
693                .current_dir(&dir)
694                .output()
695                .unwrap();
696            assert!(out.status.success(), "{args:?}: {out:?}");
697            String::from_utf8_lossy(&out.stdout).trim().to_string()
698        };
699        git(&["init", "-q"]);
700        let tree = git(&["write-tree"]);
701        let commit = commit_of_tree_in(&tree, Some(&dir)).expect("a commit");
702        assert_eq!(
703            git(&["log", "-1", "--format=%an <%ae> %s", &commit]),
704            "greengate <greengate@localhost> greengate stamps"
705        );
706        assert_eq!(
707            git(&["log", "-1", "--format=%cn <%ce>", &commit]),
708            "greengate <greengate@localhost>"
709        );
710        let _ = std::fs::remove_dir_all(&dir); // best-effort: scratch in the temp dir
711    }
712}