Skip to main content

onevcs/
host.rs

1//! The remote-host side of the seam.
2//!
3//! Host-neutral vocabulary: the review unit is a [`ChangeRequest`]. GitHub maps it
4//! to a pull request; a later host maps it to whatever it calls the same thing.
5
6use std::collections::{BTreeMap, BTreeSet};
7
8use serde::{Deserialize, Serialize};
9use url::Url;
10
11use crate::error::{invalid, Error, Result};
12use crate::event::ArtifactId;
13use crate::publish::DraftReason;
14use crate::rules::MergePolicy;
15use crate::{gh, git, stream};
16
17/// What `gh pr checks` exits with when a check it has just reported has not
18/// settled. The rollup it printed is still the answer, so this status is read
19/// alongside `0` rather than as a failure.
20const CHECKS_PENDING: i32 = 8;
21
22/// How `gh pr checks --required` opens its stderr when the repository declares no
23/// required check at all — a repository with no branch protection genuinely has
24/// none. The rest of that line names the branch, so only the prefix is fixed.
25const NO_REQUIRED_CHECKS: &str = "no required checks reported on the ";
26
27/// Whether a `gh pr checks` answer is one to read.
28fn usable(answer: &gh::Answer) -> bool {
29    matches!(answer.code, Some(0) | Some(CHECKS_PENDING))
30}
31
32/// How `gh pr checks` opens its stderr when the head carries no check **at all** —
33/// which is every head for the first seconds after it is pushed. The rest of that
34/// line names the branch, so only the prefix is fixed.
35const NO_CHECKS_YET: &str = "no checks reported on the ";
36
37/// Whether a failing `gh pr checks --required` failed by *answering* "none".
38///
39/// The whole shape, not a substring anywhere in the output: `gh` exits `1`, writes
40/// nothing to stdout, and opens stderr with [`NO_REQUIRED_CHECKS`]. Measured against
41/// real GitHub — a repository with no branch protection answers exactly that. It is
42/// held to all three because this is the one place a *failed* `gh` call is read as a
43/// meaningful answer, and a looser test would swallow an unrelated failure whose
44/// message happened to contain the phrase, reporting "nothing blocks the merge"
45/// about a host that never said so.
46fn no_required_checks(answer: &gh::Answer) -> bool {
47    answer.code == Some(1)
48        && answer.stdout.trim().is_empty()
49        && answer.stderr.trim_start().starts_with(NO_REQUIRED_CHECKS)
50}
51
52/// Whether a failing `gh pr checks` failed by reporting **no check at all** on the
53/// head, which is not an answer about what blocks the merge.
54///
55/// Held to the same three facts as [`no_required_checks`], and one word of `gh`'s own
56/// wording apart from it. Reading this one as that one would wave a merge through on
57/// a head no verification has begun on.
58fn no_checks_yet(answer: &gh::Answer) -> bool {
59    answer.code == Some(1)
60        && answer.stdout.trim().is_empty()
61        && answer.stderr.trim_start().starts_with(NO_CHECKS_YET)
62}
63
64/// How `gh api` reports a branch that has no classic protection at all — GitHub's
65/// own message, which is an answer (the source names nothing) and not a refusal.
66const NOT_PROTECTED: &str = "Branch not protected";
67
68/// Which of the host's check sources a call may consult.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70enum Consult {
71    /// The rollup, and Actions when the credential is not allowed to read it.
72    Either,
73    /// The complete status-check rollup only.
74    StatusChecks,
75    /// Actions jobs together with the branch rules that say which ones block.
76    Actions,
77}
78
79/// What [`gh::CHECK_SOURCE_ENV`] narrows a call to, or [`Consult::Either`].
80///
81/// The knob exists because the fallback is not free: a credential that will never
82/// be allowed to read check runs is refused *every* time the rollup is asked,
83/// which for a publication polling a change request is one failed call every few
84/// seconds. An operator who knows their token is a fine-grained one says so once.
85/// The value is checked here rather than acted on loosely — a misspelling that
86/// silently meant "auto" would look like the fallback working.
87fn consult() -> Result<Consult> {
88    let Some(raw) = std::env::var_os(gh::CHECK_SOURCE_ENV) else {
89        return Ok(Consult::Either);
90    };
91    match raw.to_string_lossy().trim().to_ascii_lowercase().as_str() {
92        "" | "auto" => Ok(Consult::Either),
93        "status-checks" => Ok(Consult::StatusChecks),
94        "actions" => Ok(Consult::Actions),
95        other => Err(invalid(format!(
96            "{} names {other:?}, which is not a check source this build can read: it must be \
97             \"auto\", \"status-checks\", or \"actions\"",
98            gh::CHECK_SOURCE_ENV
99        ))),
100    }
101}
102
103/// Read the operator's check-source knob and answer whether it names a source.
104///
105/// Exposed so a publication can refuse a misspelling of it **before** it pushes: the
106/// knob is input, and input is rejected at its boundary.
107pub(crate) fn check_source_names_a_source() -> Result<()> {
108    consult().map(|_| ())
109}
110
111/// How many entries an Actions listing is asked for at once, which is the most
112/// GitHub will return in one page.
113const PAGE: u32 = 100;
114
115/// How GitHub declines something the credential is not allowed to reach, in both
116/// the shapes it declines it in: a GraphQL error naming the node it would not
117/// produce, and a REST 403. The wording is GitHub's, and it is the whole of the
118/// test because it is the whole of what distinguishes the two cases below.
119const CHECK_RUN_REFUSAL: &str = "GraphQL: Resource not accessible by personal access token";
120
121/// Whether a refusal is one this credential will *always* get.
122///
123/// The one distinction the fallback turns on. A credential that may not read check
124/// runs will never read them, so asking a narrower source instead is the only way
125/// to answer at all — but a rollup that came back garbled, or a host that would not
126/// say which of its checks block, is a *complete* answer having gone wrong, and
127/// quietly answering from GitHub Actions alone would drop whatever a third-party
128/// integration posted. A required check nobody looked at is how a merge that was
129/// never gated ends up looking like one that was.
130fn check_rollup_refused_for_pat(error: &Error) -> bool {
131    let Error::Invalid { reason } = error else {
132        return false;
133    };
134    reason.contains(CHECK_RUN_REFUSAL) && reason.contains("statusCheckRollup")
135}
136
137/// Everything `onevcs` asks of a repository's remote host.
138pub trait RemoteHost {
139    /// Who the host believes is calling.
140    fn authenticated_user(&self) -> Result<String>;
141
142    /// Open a change request.
143    fn open_change(&self, req: ChangeSpec) -> Result<ChangeRequest>;
144
145    /// Every open change request from `head` into `base`.
146    fn find_changes(&self, head: &str, base: &str) -> Result<Vec<ChangeRequest>>;
147
148    /// The checks the host is reporting on a change request, and which of its
149    /// sources that answer was read from.
150    fn change_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks>;
151
152    /// Store one check's log as an artifact and return its id.
153    fn check_log(&self, cr: &ChangeRequest, check: &Check) -> Result<ArtifactId>;
154
155    /// Merge a change request under a policy.
156    fn merge(&self, cr: &ChangeRequest, policy: MergePolicy) -> Result<MergeOutcome>;
157
158    /// The commit a change request reached its base at, or `None` while the host
159    /// has not merged it.
160    ///
161    /// What a publication under `change-auto` watches. The host performs that merge
162    /// on its own clock — `merge` arms it and answers
163    /// [`MergeOutcome::Queued`] — so the only way to learn that it happened, and at
164    /// which commit, is to ask again. `None` is "not yet" and never "somewhere
165    /// else": an implementation that cannot say must refuse rather than answer it.
166    ///
167    /// Defaulted so that an implementation written against the earlier surface
168    /// still compiles, and defaulted to the refusal this crate reserves for a seam
169    /// with no body rather than to `None` — a host that was never taught to answer
170    /// this has not said a change is unmerged, and a publication that read it that
171    /// way would watch until its bound and then report checks that were never the
172    /// reason.
173    fn merged_at(&self, _cr: &ChangeRequest) -> Result<Option<Sha>> {
174        Err(Error::NotImplemented {
175            operation: "RemoteHost::merged_at",
176        })
177    }
178
179    /// Take a change request out of its draft state, so the host will let it land.
180    ///
181    /// What lifts a draft. A publication that carries no
182    /// [`DraftReason`](crate::DraftReason) is a caller saying the reason no longer
183    /// holds, and this is the call that says so to the host.
184    ///
185    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
186    /// stays additive — and to the same refusal: a host that was never taught to
187    /// lift a draft has not lifted one, and answering `Ok(())` would report a change
188    /// as ready for review while the host goes on holding it.
189    fn ready_for_review(&self, _cr: &ChangeRequest) -> Result<()> {
190        Err(Error::NotImplemented {
191            operation: "RemoteHost::ready_for_review",
192        })
193    }
194
195    /// Whether the host is holding this change request as a draft.
196    ///
197    /// Asked on both sides of a draft's life: after one is opened, because a host
198    /// that ignored the request would otherwise leave a landable change reported as
199    /// held back; and before one is lifted, so a change nobody drafted is asked for
200    /// nothing and a second lift changes nothing.
201    ///
202    /// Defaulted to the refusal, never to `false`: "this host was never taught to
203    /// answer" and "this change is not a draft" are different facts, and only the
204    /// second is a reason to go on and merge — which is what the `Result` around the
205    /// answer carries, rather than a third value inside it.
206    ///
207    /// The answer is a `bool` because the approved amendment in `docs/contract.md`
208    /// declares this seam verbatim as `-> Result<bool>`: a named domain type here would
209    /// be a public item the contract does not name, which this repository reports rather
210    /// than takes. Nothing is lost to the shape — the *third* state a caller must not
211    /// confuse with "not a draft" is "this host would not say", and that is the `Err`
212    /// arm rather than a value inside the `Ok`. Both call sites read it as one of three,
213    /// and they are `hold_as_draft` and `lift_any_draft` in `publish.rs`.
214    // llmlint: ignore[invalid_states_unrepresentable] the doc above: the contract fixes this seam.
215    fn is_draft(&self, _cr: &ChangeRequest) -> Result<bool> {
216        Err(Error::NotImplemented {
217            operation: "RemoteHost::is_draft",
218        })
219    }
220
221    /// The checks the repository requires before anything merges into `base`, asked
222    /// of the branch itself rather than of a change request targeting it.
223    ///
224    /// What `onevcs repos --audit-gates` names per identity. Which checks a
225    /// repository requires is a setting on that repository, and a consumer that
226    /// sequences its own work behind another repository's merge path had to keep a
227    /// copy of that list — which drifted the day the repository renamed a check, and
228    /// cost a whole gate to discover. The host holds the list; this is how it is
229    /// read.
230    ///
231    /// The answer says which protection source it could not consult, because "this
232    /// source found nothing" and "this merge path requires nothing" are opposite
233    /// facts and only the second is safe to act on: an answer with a source in
234    /// [`RequiredChecks::unconsulted`] is incomplete, and an empty one is *unknown*
235    /// rather than none. A host that could read no source at all must refuse rather
236    /// than answer, for the reason [`change_checks`](RemoteHost::change_checks) may
237    /// not answer with an empty source list.
238    ///
239    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
240    /// stays additive — and to the same refusal, which the audit reports as the list
241    /// being unreadable rather than as no check being required.
242    fn required_checks_on(&self, _base: &str) -> Result<RequiredChecks> {
243        Err(Error::NotImplemented {
244            operation: "RemoteHost::required_checks_on",
245        })
246    }
247
248    /// Replace a change request's description: its body, and its title when one is
249    /// given.
250    ///
251    /// The one write to a change request's prose after it exists. It writes exactly
252    /// the caller's bytes — nothing is composed around the body and nothing of a
253    /// draft's reason is rendered into it — because a body is what a reviewer reads
254    /// and what a drafting caller may rewrite, and `onevcs change describe` is where
255    /// a session's own evidence reaches it.
256    ///
257    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
258    /// stays additive — and to the same refusal: a host that was never taught to
259    /// describe a change has not described one.
260    fn describe_change(
261        &self,
262        _cr: &ChangeRequest,
263        _title: Option<&str>,
264        _body: &str,
265    ) -> Result<()> {
266        Err(Error::NotImplemented {
267            operation: "RemoteHost::describe_change",
268        })
269    }
270
271    /// What a change request's description is now: its title and its body, as the
272    /// host holds them.
273    ///
274    /// The read beside [`describe_change`](RemoteHost::describe_change), and what
275    /// `onevcs change show` answers with: a caller that wrote a description needs to
276    /// see what it wrote, and a caller finishing one off needs to see what it starts
277    /// from.
278    ///
279    /// Defaulted to the refusal for the reason every other added method is.
280    fn change_description(&self, _cr: &ChangeRequest) -> Result<Description> {
281        Err(Error::NotImplemented {
282            operation: "RemoteHost::change_description",
283        })
284    }
285}
286
287/// A change request's description as the host holds it.
288///
289/// What [`RemoteHost::change_description`] answers, and the other half of
290/// [`ChangeDescription`](crate::ChangeDescription): a caller writes a body and
291/// optionally a title, and reads back both. Both are plain strings, because both are
292/// prose a host places no shape on — a title *this crate lands* is a
293/// [`Subject`](crate::Subject), but a title a host already holds was composed by
294/// whoever opened the change request, and is reported as it is rather than refused.
295// llmlint: ignore[invalid_states_unrepresentable] the doc above: what a host answers,
296// reported rather than judged.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298pub struct Description {
299    /// The title, which under squash-merge becomes the commit subject.
300    pub title: String,
301    /// The body, verbatim. Empty where the change request carries none.
302    pub body: String,
303}
304
305/// One of the ways a host protects a branch, each of which may name required checks.
306#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
307#[serde(rename_all = "kebab-case")]
308pub enum ProtectionSource {
309    /// The repository's rulesets, which every credential that can read the
310    /// repository can read.
311    Rulesets,
312    /// Classic branch protection, which only a credential with administration
313    /// rights can read — so it is the source an audit is most often refused.
314    BranchProtection,
315}
316
317impl ProtectionSource {
318    /// Every source, in the order a report names them.
319    pub fn every() -> impl Iterator<Item = ProtectionSource> {
320        [
321            ProtectionSource::Rulesets,
322            ProtectionSource::BranchProtection,
323        ]
324        .into_iter()
325    }
326
327    /// How a report names it.
328    pub fn describe(self) -> &'static str {
329        match self {
330            ProtectionSource::Rulesets => "the repository's rulesets",
331            ProtectionSource::BranchProtection => "classic branch protection",
332        }
333    }
334}
335
336/// What a host requires before a merge into a branch, and how much of the host
337/// that answer covers.
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
339pub struct RequiredChecks {
340    /// The names, from every source that answered.
341    pub checks: BTreeSet<String>,
342    /// Each protection source the host holds that could not be read, with the
343    /// host's reason. Empty means every source answered and `checks` is the whole
344    /// list; otherwise `checks` is what the sources that did answer require, and an
345    /// empty `checks` is not "nothing is required".
346    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
347    pub unconsulted: BTreeMap<ProtectionSource, String>,
348}
349
350impl RequiredChecks {
351    /// Whether every protection source answered, so `checks` is the whole list.
352    pub fn complete(&self) -> bool {
353        self.unconsulted.is_empty()
354    }
355}
356
357/// Where a [`RemoteHost`] for one repository comes from.
358///
359/// A host is addressed at a repository rather than at an installation — every
360/// call `gh` makes carries a slug — so the seam a caller supplies is the factory
361/// rather than one host object. This is what makes the interface reachable: a
362/// publication asks the factory it was handed for the repository it is publishing
363/// to, and never names an implementation.
364pub trait Hosting {
365    /// The host that answers for the repository named `owner/name`.
366    // llmlint: ignore[invalid_states_unrepresentable] a validated slug newtype would be a
367    // public item beyond the one this seam is specified as, and it would have exactly one
368    // constructor — the check below. That check is where the value is decided: `GitHub::new`
369    // refuses anything that does not name one repository as `owner/name`, before the slug is
370    // interpolated into a single `gh --repo`. A caller cannot reach a host any other way.
371    fn for_repo(&self, slug: &str) -> Result<Box<dyn RemoteHost>>;
372}
373
374/// The factory that produces [`GitHub`] hosts, which is what a real run uses.
375///
376/// Private: the way to hold one is [`crate::Providers::real`], because a caller
377/// mixing a real GitHub into a run whose repository side is not git is asking for
378/// a combination neither half was written for.
379#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
380pub(crate) struct GitHubHosting;
381
382impl Hosting for GitHubHosting {
383    fn for_repo(&self, slug: &str) -> Result<Box<dyn RemoteHost>> {
384        Ok(Box::new(GitHub::new(slug)?))
385    }
386}
387
388/// What to open a change request for.
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390pub struct ChangeSpec {
391    /// The branch carrying the change.
392    // llmlint: ignore[invalid_states_unrepresentable] a validated branch-ref newtype is
393    // exactly what the publication path carries internally, and it cannot surface here:
394    // the contract fixes the matching `ChangeRequest.base` as `String` and names no ref
395    // type, so spelling one on this side of the same trait would add a public item the
396    // contract does not name and disagree with the type it does. Both names are handed to
397    // git before they reach a host, which is where the parser that decides them lives.
398    pub head: String,
399    /// The branch it targets, which for a stacked change is the branch below it.
400    pub base: String,
401    /// The title, which under squash-merge becomes the commit subject.
402    pub title: String,
403    /// The body. Absent means the host's default from the repository template.
404    pub body: Option<String>,
405    /// Open it as a **draft**, and why it is not ready. Absent opens an ordinary
406    /// change request, which is every publication that came before this field.
407    ///
408    /// The host is handed the whole reason and asked for one thing with it: open the
409    /// change as a draft. Nothing here renders the reason into the change request —
410    /// see [`DraftReason`] for the ruling that keeps it out of the body — so a host
411    /// implementation that reads past this field's presence is reading further than
412    /// the contract asks it to.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub draft: Option<DraftReason>,
415}
416
417/// An open change request on the host.
418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419pub struct ChangeRequest {
420    /// The host's identifier for it.
421    pub id: ChangeId,
422    /// Where a human reads it.
423    pub url: Url,
424    /// The commit its checks are reported against.
425    pub head_sha: Sha,
426    /// The branch it targets.
427    // llmlint: ignore[invalid_states_unrepresentable] the contract declares this field
428    // verbatim as `pub base: String` and names no ref type to narrow it to; changing it
429    // is changing the interface, which is reported rather than done. Every one this crate
430    // constructs is read out of a host response naming a branch the host already has.
431    pub base: String,
432}
433
434/// A host's identifier for a change request.
435// llmlint: ignore[invalid_states_unrepresentable] the contract declares this as
436// `id: ChangeId` and fixes nothing about its content — GitHub numbers its pull
437// requests, and another host may not. Every one this crate constructs is read out of
438// a host response that is required to carry it: `find_changes` rejects an entry with
439// no number, and `open_change` rejects output that printed no URL to take one from.
440#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
441#[serde(transparent)]
442pub struct ChangeId(pub String);
443
444/// A commit hash.
445// llmlint: ignore[invalid_states_unrepresentable] the contract declares this field as
446// `head_sha: Sha` and fixes nothing about its content, and a hash's shape is the host's
447// to state — a SHA-1 hex string today, something else on a repository that has moved.
448// Every one this crate constructs is validated where it enters: `head_sha` and
449// `merged_sha` below both reject a response that names no commit rather than
450// constructing an empty one, so no code path here can produce a blank `Sha`.
451#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
452#[serde(transparent)]
453pub struct Sha(pub String);
454
455/// One check the host reports on a change request.
456#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
457pub struct Check {
458    /// The check's name, as branch protection lists it.
459    pub name: String,
460    /// Where the check is: the host's own status vocabulary, passed through.
461    // llmlint: ignore[invalid_states_unrepresentable] the contract fixes this field name
462    // and enumerates no value set for it, and the vocabulary differs per host — which is
463    // the thing this crate exists to abstract. Inventing an enum here would add a public
464    // item the contract does not name. The one word this build reads out of it —
465    // `completed` — is read in `settled` below and nowhere else, so a host that spells
466    // its states differently is understood by a second implementation of that predicate
467    // rather than by a new variant here. Recorded as open question 1 in
468    // docs/inferred-surface.md for the planner to settle across the three repositories.
469    pub status: String,
470    /// How it ended, once it has. Absent while it is still running.
471    // llmlint: ignore[invalid_states_unrepresentable] `conclusion` is the other half of the
472    // same open question as `status` above, for the same reason: the contract names the
473    // field and enumerates no conclusion vocabulary, and each host spells its own. The
474    // three this build treats as not blocking a merge are read in `green` below, which is
475    // the one place a second host's vocabulary would be taught.
476    pub conclusion: Option<String>,
477    /// Whether it blocks the merge.
478    pub required: bool,
479    /// The commit the host attached this check to, or `None` where the host did not
480    /// say which one it is about.
481    ///
482    /// What makes a check's verdict addressable to a commit rather than to a change
483    /// request. A change request is a moving target — every push gives it a new head,
484    /// and the host attaches the new head's checks seconds to minutes later — so a
485    /// caller reading "the checks on this change request" moments after a push reads
486    /// the *previous* head's answer and cannot tell. `None` is the host declining to
487    /// say and never a commit inferred from the change request: a caller that must
488    /// distinguish them has to be able to, and one that cannot is told nothing rather
489    /// than told wrongly.
490    ///
491    /// Defaulted, so a check some earlier build serialized still reads — as one whose
492    /// commit that build never recorded, which is what it is.
493    #[serde(default, skip_serializing_if = "Option::is_none")]
494    pub head: Option<Sha>,
495    /// Where this check is on the host, so whoever is handed its refusal can go and
496    /// look at it. `None` where the host reported no address for it.
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub url: Option<Url>,
499}
500
501impl Check {
502    /// Whether this check has reached a terminal state.
503    pub fn settled(&self) -> bool {
504        self.status.eq_ignore_ascii_case("completed")
505    }
506
507    /// Whether a settled check ended in a way that does not block a merge.
508    pub fn green(&self) -> bool {
509        self.settled()
510            && self.conclusion.as_deref().is_some_and(|value| {
511                matches!(
512                    value.to_ascii_lowercase().as_str(),
513                    "success" | "skipped" | "neutral"
514                )
515            })
516    }
517
518    /// Whether the host ended this run without a verdict either way.
519    pub(crate) fn no_verdict(&self) -> bool {
520        self.settled()
521            && self.conclusion.as_deref().is_some_and(|value| {
522                matches!(value.to_ascii_lowercase().as_str(), "cancelled" | "stale")
523            })
524    }
525
526    /// Whether a settled check ended in a way that blocks a merge.
527    pub fn red(&self) -> bool {
528        self.settled() && !self.green() && !self.no_verdict()
529    }
530}
531
532/// One place a host's answer about a change request's checks was read from.
533///
534/// A credential decides which of these can be reached, so which were consulted is
535/// part of the answer rather than a property of the build: a fine-grained personal
536/// access token cannot read check runs *at all* — GitHub offers no `Checks`
537/// permission for one, and the permission it briefly had was withdrawn — so for
538/// such a token the rollup is unreadable and Actions is everything it can see.
539#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
540#[serde(rename_all = "kebab-case")]
541pub enum CheckSource {
542    /// The host's own rollup of every check on the change request: workflow jobs,
543    /// check runs a third-party integration posted, and commit statuses alike,
544    /// each carrying whether it blocks the merge. Complete, and the one source a
545    /// fine-grained token cannot read.
546    StatusChecks,
547    /// GitHub Actions' own view of the head commit: the jobs of the workflow runs
548    /// on it and nothing else. A check that ran no workflow — anything a
549    /// third-party integration posted as a check run or a commit status — is not
550    /// in it and cannot be seen from it.
551    Actions,
552    /// The repository's rulesets, for which checks block a merge into the base.
553    /// Narrower than the rollup's own answer: it reports rulesets and not classic
554    /// branch protection, so a repository protected the classic way reports
555    /// nothing blocking here — which the publication path fails closed on, waiting
556    /// for a required check that never arrives rather than merging without one.
557    BranchRules,
558}
559
560/// What a host reports about a change request's checks, and where it looked.
561///
562/// The sources travel with the checks because a caller deciding whether a change
563/// may merge has to be able to tell "these are all the checks" from "these are the
564/// workflow checks, and anything a third-party integration posted is invisible to
565/// this credential". Reporting the second as the first is how a merge gets waved
566/// through by a check nobody could see.
567#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
568pub struct ChangeChecks {
569    /// The checks themselves.
570    pub checks: Vec<Check>,
571    /// Every source consulted to produce them. Never empty: a host that could read
572    /// none of its sources is a refusal rather than an answer.
573    // llmlint: ignore[invalid_states_unrepresentable] the approved contract fixes
574    // this as a public BTreeSet; implementations refuse an empty answer.
575    pub sources: BTreeSet<CheckSource>,
576}
577
578impl ChangeChecks {
579    /// Whether this answer covers every check the host reports.
580    ///
581    /// False means the checks above are GitHub Actions' and only those.
582    pub fn complete(&self) -> bool {
583        self.sources.contains(&CheckSource::StatusChecks)
584    }
585}
586
587/// What merging a change request did.
588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
589#[serde(rename_all = "kebab-case")]
590pub enum MergeOutcome {
591    /// It merged, at this commit.
592    Merged(Sha),
593    /// The host queued it and will merge it once its checks pass.
594    Queued,
595    /// It was left open for review, which the policy asked for.
596    Open,
597}
598
599/// The GitHub implementation of [`RemoteHost`], driven through `gh`.
600///
601/// Every method is one `gh` invocation, and the program that answers as `gh` is the
602/// seam a journey substitutes: GitHub's decisioning is what a test replaces, never
603/// the git underneath it.
604#[derive(Debug, Clone, PartialEq, Eq)]
605pub struct GitHub {
606    /// The `owner/name` slug every call is addressed to. Private, so the only way
607    /// to hold one is to have had it accepted by [`GitHub::new`] — every `gh`
608    /// invocation below trusts it as the repository it addresses.
609    repo: String,
610}
611
612impl GitHub {
613    /// Address this host at one repository, named `owner/name`.
614    ///
615    /// Checked here rather than at each call: the slug is interpolated into every
616    /// `gh --repo` invocation, and a value that is not one repository is a value
617    /// that addresses something nobody asked for.
618    pub fn new(repo: impl Into<String>) -> Result<Self> {
619        let repo = repo.into();
620        let mut parts = repo.split('/');
621        let named = matches!(
622            (parts.next(), parts.next(), parts.next()),
623            (Some(owner), Some(name), None)
624                if !owner.is_empty()
625                    && !name.is_empty()
626                    && !repo.starts_with('-')
627                    && !repo.contains(char::is_whitespace)
628        );
629        if !named {
630            return Err(invalid(format!(
631                "{repo:?} does not name one repository as owner/name"
632            )));
633        }
634        Ok(Self { repo })
635    }
636
637    /// The names of the checks the host says block the merge.
638    ///
639    /// A second call, and it has to be one: `gh pr view`'s `statusCheckRollup`
640    /// carries a check's name, status, and conclusion and *nothing* about whether it
641    /// blocks anything. This build asked it for `isRequired` anyway and read the
642    /// field's absence as a host answering partially, so every `change_checks`
643    /// against real GitHub failed — a field `gh pr view` has never returned, checked
644    /// only ever against a stand-in that returned it. `gh pr checks --required` is
645    /// where `gh` reports it.
646    fn required_checks(&self, cr: &ChangeRequest) -> Result<BTreeSet<String>> {
647        addressable(&cr.id.0, "change request id")?;
648        let answer = gh::attempt(&[
649            "pr",
650            "checks",
651            &cr.id.0,
652            "--repo",
653            &self.repo,
654            "--required",
655            "--json",
656            "name",
657        ])?;
658        if !usable(&answer) {
659            // A repository that declares no required check at all is answering, not
660            // failing: refusing here would make every unprotected repository
661            // unreadable, and "nothing blocks the merge" is what the publication
662            // path already knows how to act on.
663            if no_required_checks(&answer) {
664                return Ok(BTreeSet::new());
665            }
666            if no_checks_yet(&answer) {
667                return Err(unregistered(&cr.url, answer.stderr.trim()));
668            }
669            return Err(unsaid(&cr.url, &answer.detail()));
670        }
671        let value = gh::json(&answer.stdout)?;
672        let entries = value
673            .as_array()
674            .ok_or_else(|| unsaid(&cr.url, &value.to_string()))?;
675        let mut names = BTreeSet::new();
676        for entry in entries {
677            let name = entry
678                .get("name")
679                .and_then(|value| value.as_str())
680                .filter(|value| !value.is_empty())
681                .ok_or_else(|| unsaid(&cr.url, &entry.to_string()))?;
682            names.insert(name.to_owned());
683        }
684        Ok(names)
685    }
686
687    /// The log of the job one check ran in.
688    ///
689    /// Two calls, because `gh` addresses a job's log by the job's *id* and a check's
690    /// name is not one. This build passed the name to `gh run view --job`, which has
691    /// never accepted anything but a number — so the artifact every settled check
692    /// carried held a refusal to produce a log rather than the log, and no offline
693    /// journey could tell, because the program standing in for `gh` answered to the
694    /// name. The id is the last segment of the details URL `gh pr checks` reports.
695    fn job_log(&self, cr: &ChangeRequest, name: &str) -> Result<String> {
696        addressable(&cr.id.0, "change request id")?;
697        let answer = gh::attempt(&[
698            "pr",
699            "checks",
700            &cr.id.0,
701            "--repo",
702            &self.repo,
703            "--json",
704            "name,link",
705        ])?;
706        if !usable(&answer) {
707            return Err(invalid(format!(
708                "gh pr checks would not say where check {name:?} on {} ran: {}",
709                cr.url,
710                answer.detail()
711            )));
712        }
713        let value = gh::json(&answer.stdout)?;
714        // Rejected here rather than searched through: a host that answered with
715        // something other than a list of checks has not said this check has no job,
716        // and reporting it as though it had would put the wrong reason in the
717        // artifact an operator reads to find out why there is no log.
718        let entries = value.as_array().ok_or_else(|| {
719            invalid(format!(
720                "gh pr checks returned a non-list of checks on {}, so where check {name:?} ran \
721                 cannot be read from it: {value}",
722                cr.url
723            ))
724        })?;
725        let link = entries
726            .iter()
727            .find(|entry| entry.get("name").and_then(|value| value.as_str()) == Some(name))
728            .and_then(|entry| entry.get("link"))
729            .and_then(|value| value.as_str())
730            .ok_or_else(|| {
731                invalid(format!(
732                    "the host reports no job for check {name:?} on {}",
733                    cr.url
734                ))
735            })?;
736        let job = link
737            .rsplit_once("/job/")
738            .map(|(_, id)| id)
739            .filter(|id| !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()))
740            .ok_or_else(|| {
741                invalid(format!(
742                    "the host says check {name:?} ran at {link:?}, which names no job this build \
743                     can ask for a log"
744                ))
745            })?;
746        gh::invoke_content(&["run", "view", "--repo", &self.repo, "--log", "--job", job])
747    }
748
749    /// One check's log, from whichever source this credential can read.
750    ///
751    /// The same order [`RemoteHost::change_checks`] consults them in, for the same
752    /// reason: `gh pr checks` reports where *every* check ran, including one no
753    /// workflow produced, and the Actions API answers for the ones it owns when the
754    /// credential may not read the rollup at all.
755    fn log_of(&self, cr: &ChangeRequest, name: &str) -> Result<String> {
756        match consult()? {
757            Consult::StatusChecks => self.job_log(cr, name),
758            Consult::Actions => self.actions_log(cr, name),
759            // As above, and for the same reason: where a check ran is a question
760            // `gh pr checks` can answer about every check, and only a credential
761            // that may not ask it at all has cause to ask a narrower source.
762            Consult::Either => self.job_log(cr, name).or_else(|reported| {
763                if !check_rollup_refused_for_pat(&reported) {
764                    return Err(reported);
765                }
766                self.actions_log(cr, name).map_err(|actions| {
767                    invalid(format!(
768                        "neither of GitHub's check sources would produce the log of check \
769                         {name:?} on {}: gh pr checks answered {reported}, and the Actions API \
770                         answered {actions}",
771                        cr.url
772                    ))
773                })
774            }),
775        }
776    }
777
778    /// Every check the host's own rollup reports on a change request.
779    ///
780    /// Complete — a workflow job, a check run some integration posted, and a commit
781    /// status all appear here — and readable only by a credential the repository
782    /// allows to read its check runs. A fine-grained personal access token is not
783    /// one and cannot become one, which is what [`GitHub::actions_checks`] answers
784    /// instead.
785    fn rollup_checks(&self, cr: &ChangeRequest) -> Result<Vec<Check>> {
786        // `headRefOid` in the same call, because the rollup GitHub renders is the
787        // rollup of the change request's *last commit* as that one response saw it —
788        // and which commit that was is the whole of what makes the answer
789        // addressable. Asked together rather than in a second call for the same
790        // reason a second call could not answer it: the head moves, so a commit read
791        // afterwards is not necessarily the one those checks were about. It costs
792        // this call nothing, because the field needs no more than the read access
793        // that found the change request while `statusCheckRollup` needs far more —
794        // a credential refused for one of them was already refused for the call.
795        let value = self.view(&cr.id.0, "headRefOid,statusCheckRollup")?;
796        let head = reported_sha(&value, "headRefOid")?;
797        let reported = value.get("statusCheckRollup").ok_or_else(|| {
798            invalid(format!(
799                "gh pr view reported no checks at all on {}",
800                cr.url
801            ))
802        })?;
803        if reported.is_null() {
804            return Ok(Vec::new());
805        }
806        let rollup = reported
807            .as_array()
808            .ok_or_else(|| invalid(format!("gh pr view returned a non-list rollup: {reported}")))?;
809        if rollup.is_empty() {
810            return Ok(Vec::new());
811        }
812        let required = self.required_checks(cr)?;
813        rollup
814            .iter()
815            .map(|entry| check(entry, cr, &required, head.as_ref()))
816            .collect()
817    }
818
819    /// The checks GitHub Actions reports for the change request's head commit.
820    ///
821    /// One workflow job is one check, which is the same unit the rollup reports
822    /// them in — GitHub posts a check run per job — so what a caller waits for is
823    /// unchanged. What it cannot see is anything that ran no workflow, which is why
824    /// the answer says which sources it came from rather than passing itself off as
825    /// the whole picture.
826    fn actions_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks> {
827        let jobs = self.actions_jobs(cr)?;
828        if jobs.is_empty() {
829            // Nothing has run yet, which is the first seconds of every change
830            // request. There is no check to ask the rulesets about, so they are not
831            // asked and the answer does not claim they were.
832            return Ok(ChangeChecks {
833                checks: Vec::new(),
834                sources: [CheckSource::Actions].into_iter().collect(),
835            });
836        }
837        let required = self.ruled_checks(cr)?;
838        Ok(ChangeChecks {
839            checks: jobs
840                .into_iter()
841                .map(|job| Check {
842                    required: required.contains(&job.name),
843                    name: job.name,
844                    status: job.status,
845                    conclusion: job.conclusion,
846                    head: job.head,
847                    url: job.url,
848                })
849                .collect(),
850            sources: [CheckSource::Actions, CheckSource::BranchRules]
851                .into_iter()
852                .collect(),
853        })
854    }
855
856    /// Every job of every workflow run on the change request's head commit.
857    ///
858    /// Two calls per run, because the Actions API reports a *run*'s status at the
859    /// run and a job's at the job, and a run that is still going says nothing about
860    /// which of its jobs have finished — and one before them, for which commit that
861    /// head is *now*. Asked rather than taken off the [`ChangeRequest`] the caller
862    /// holds, because that one was read when the change request was found: a
863    /// publication finds it moments after pushing, when the host may not have
864    /// processed the push, and a build that kept asking about the head it first saw
865    /// would go on asking about a commit this run replaced for as long as it
866    /// watched. The rollup source re-reads the same field on every call for the same
867    /// reason; this is that, on the source a fine-grained token is left with.
868    fn actions_jobs(&self, cr: &ChangeRequest) -> Result<Vec<Job>> {
869        let current = head_sha(&self.view(&cr.id.0, "headRefOid")?)?;
870        let sha = commit(&current)?;
871        let runs = self.api(&format!(
872            "repos/{}/actions/runs?head_sha={sha}&per_page={PAGE}",
873            self.repo
874        ))?;
875        let mut jobs = Vec::new();
876        for run in listed(&runs, "workflow_runs", &format!("the commit {sha}"))? {
877            let id = run
878                .get("id")
879                .and_then(serde_json::Value::as_u64)
880                .ok_or_else(|| {
881                    invalid(format!(
882                        "the Actions API reported a workflow run on {} with no id: {run}",
883                        cr.url
884                    ))
885                })?;
886            // The commit off the run's own record rather than the one this query
887            // filtered on: what the host says it ran against is the host's answer,
888            // and a build that stamped the question onto the answer could not tell a
889            // host that disagreed.
890            let head = reported_sha(run, "head_sha")?;
891            let listing = self.api(&format!(
892                "repos/{}/actions/runs/{id}/jobs?per_page={PAGE}",
893                self.repo
894            ))?;
895            for entry in listed(&listing, "jobs", &format!("workflow run {id}"))? {
896                jobs.push(job(entry, cr, head.as_ref())?);
897            }
898        }
899        Ok(jobs)
900    }
901
902    /// The names of the checks the repository's rulesets say block a merge into the
903    /// change request's base.
904    ///
905    /// The second question `gh pr checks --required` answers and a credential that
906    /// cannot read check runs cannot ask, because that command reads the same
907    /// rollup. This is what such a credential *can* read — and it is narrower, in a
908    /// direction that is safe rather than quiet: it reports rulesets and not classic
909    /// branch protection, so a repository protected the classic way answers "nothing
910    /// blocks" and the publication path then waits for a required check that never
911    /// arrives and stops. Under-reporting what blocks holds a merge; over-reporting
912    /// what has passed lets one through, and only one of those is recoverable.
913    fn ruled_checks(&self, cr: &ChangeRequest) -> Result<BTreeSet<String>> {
914        self.required_on(&cr.base, cr.url.as_ref())
915    }
916
917    /// The names of the checks the repository's rulesets require before a merge into
918    /// `base` — the same read as [`GitHub::ruled_checks`], addressed to a branch
919    /// rather than to a change request targeting one, and what
920    /// [`RemoteHost::required_checks_on`] answers with. It is the rulesets' answer
921    /// and carries the rulesets' limit: a repository protected the classic way names
922    /// nothing here.
923    ///
924    fn required_on(&self, base: &str, about: &str) -> Result<BTreeSet<String>> {
925        addressable_branch(base, "the base branch")?;
926        let value = self.api(&format!(
927            "repos/{}/rules/branches/{}",
928            self.repo,
929            path_segment(base)
930        ))?;
931        let rules = value.as_array().ok_or_else(|| {
932            invalid(format!(
933                "the rules on {about}'s base branch {base:?} came back as something that is \
934                 not a list of them, so which of its checks block the merge cannot be read \
935                 from it: {value}"
936            ))
937        })?;
938        let mut names = BTreeSet::new();
939        for rule in rules {
940            if rule.get("type").and_then(|value| value.as_str()) != Some("required_status_checks") {
941                continue;
942            }
943            // A rule that says it requires status checks and then will not say
944            // which is the one shape that must not be read as "none": that is the
945            // difference between a merge that was gated and one that only looked
946            // like it.
947            let required = rule
948                .get("parameters")
949                .and_then(|parameters| parameters.get("required_status_checks"))
950                .and_then(|value| value.as_array())
951                .ok_or_else(|| unsaid_about(about, &rule.to_string()))?;
952            for entry in required {
953                let name = entry
954                    .get("context")
955                    .and_then(|value| value.as_str())
956                    .filter(|value| !value.is_empty())
957                    .ok_or_else(|| unsaid_about(about, &entry.to_string()))?;
958                names.insert(name.to_owned());
959            }
960        }
961        Ok(names)
962    }
963
964    /// The contexts classic branch protection requires on `base`, or why the host
965    /// would not say.
966    ///
967    /// Three answers, told apart by what `gh` wrote. A protected branch answers with
968    /// its contexts; a branch with no classic protection answers `Branch not
969    /// protected`, a 404 that *is* an answer — the source was consulted and names
970    /// nothing; and anything else is the source not consulted, which the inner `Err`
971    /// carries so the caller records it beside what the rulesets did say rather than
972    /// losing that too. The outer `Err` is `gh` itself failing to run.
973    fn classic_protection(
974        &self,
975        base: &str,
976    ) -> Result<std::result::Result<BTreeSet<String>, String>> {
977        addressable_branch(base, "the base branch")?;
978        let path = format!(
979            "repos/{}/branches/{}/protection/required_status_checks",
980            self.repo,
981            path_segment(base)
982        );
983        let answer = gh::attempt(&["api", &path])?;
984        if answer.code != Some(0) {
985            if answer.stderr.contains(NOT_PROTECTED) {
986                return Ok(Ok(BTreeSet::new()));
987            }
988            return Ok(Err(answer.detail()));
989        }
990        let value = gh::json(&answer.stdout)?;
991        let contexts = value
992            .get("contexts")
993            .and_then(|value| value.as_array())
994            .ok_or_else(|| {
995                invalid(format!(
996                    "the classic branch protection on {}'s {base:?} came back without its \
997                     contexts, so which checks it requires cannot be read from it: {value}",
998                    self.repo
999                ))
1000            })?;
1001        let mut names = BTreeSet::new();
1002        for context in contexts {
1003            let name = context
1004                .as_str()
1005                .filter(|value| !value.is_empty())
1006                .ok_or_else(|| unsaid_about(&self.repo, &context.to_string()))?;
1007            names.insert(name.to_owned());
1008        }
1009        Ok(Ok(names))
1010    }
1011
1012    /// The log of the Actions job one check ran in, addressed by the job's id.
1013    ///
1014    /// The id comes from the same listing the checks did, so the name matched here
1015    /// is the name reported there — the two cannot drift apart the way a check's
1016    /// name and a details URL parsed out of a second command can.
1017    fn actions_log(&self, cr: &ChangeRequest, name: &str) -> Result<String> {
1018        let job = self
1019            .actions_jobs(cr)?
1020            .into_iter()
1021            .find(|job| job.name == name)
1022            .ok_or_else(|| {
1023                invalid(format!(
1024                    "GitHub Actions reports no job named {name:?} on the head commit of {}",
1025                    cr.url
1026                ))
1027            })?;
1028        gh::invoke_content(&[
1029            "api",
1030            &format!("repos/{}/actions/jobs/{}/logs", self.repo, job.id),
1031        ])
1032    }
1033
1034    fn api(&self, path: &str) -> Result<serde_json::Value> {
1035        gh::json(&gh::invoke(&["api", path])?)
1036    }
1037
1038    /// One change request as `gh` describes it, in the fields the caller reads and
1039    /// no others.
1040    ///
1041    /// The field list is the caller's, not a constant, because `gh pr view` fails
1042    /// *whole* when GitHub refuses one field of the several it was asked for — and
1043    /// the fields differ in what a credential has to be allowed to see.
1044    /// `statusCheckRollup` resolves the change request's check runs, which a
1045    /// fine-grained token may not read without the repository's Checks permission,
1046    /// while `state`, `headRefOid`, and `mergeCommit` need no more than the read
1047    /// access that found the change request at all. This build asked for all of them
1048    /// at every call, so a token that could open and merge a change request was
1049    /// refused at both over a field neither reads — and only from the moment a check
1050    /// first appeared on it, so the same credential merged a young change request and
1051    /// failed on an older one. Ask for what you read.
1052    fn view(&self, id: &str, fields: &str) -> Result<serde_json::Value> {
1053        addressable(id, "change request id")?;
1054        let raw = gh::invoke(&["pr", "view", id, "--repo", &self.repo, "--json", fields])?;
1055        gh::json(&raw)
1056    }
1057}
1058
1059/// One value bound for `gh`'s argument vector, checked before it gets there.
1060///
1061/// Every string in these methods arrives from outside — off a caller embedding this
1062/// crate, or out of the host's own answer — and each becomes a positional or an
1063/// option's value. `gh` reads a leading `-` as an option of its own and an empty
1064/// string as a present-but-blank value, so a name shaped like either is refused
1065/// here rather than silently addressing something other than what it names.
1066///
1067/// Those two and no others: the vector is handed to `gh` as a vector, so no shell
1068/// splits an argument this build wrote as one. Whitespace was refused here too, and
1069/// [`matchable`] records what that cost — a value with a space in it reaches `gh`
1070/// exactly as it was written, so it is nothing this boundary has to guard against.
1071fn addressable(value: &str, what: &str) -> Result<()> {
1072    if value.is_empty() || value.starts_with('-') {
1073        return Err(invalid(format!(
1074            "{what} {value:?} cannot address anything on the host: it must be non-empty and must \
1075             not begin with '-'"
1076        )));
1077    }
1078    Ok(())
1079}
1080
1081/// A check's name, checked before it is matched against the ones the host reports.
1082///
1083/// Deliberately not [`addressable`], because a check's name never becomes an
1084/// argument to `gh`: [`GitHub::job_log`] matches it against the `name` field of the
1085/// JSON `gh pr checks` returns, and [`GitHub::actions_log`] against the job names
1086/// the Actions API lists — the job's *id* is what either one then asks for a log by.
1087/// So `gh`'s argument grammar has no say over this value, and the shapes that
1088/// grammar refuses are ordinary job names here. Every GitHub matrix job is named
1089/// with whitespace — `check (macos-latest)`, `test-os (windows-latest)` — and
1090/// refusing it left every matrix check on every change request this crate published
1091/// recorded with no log at all.
1092///
1093/// What is refused is a name that can match nothing the host reports: the host names
1094/// every check it answers about, so an empty name is a value a caller made up rather
1095/// than a check anything has.
1096fn matchable(name: &str, cr: &ChangeRequest) -> Result<()> {
1097    if name.is_empty() {
1098        return Err(invalid(format!(
1099            "onevcs will not ask for the log of a check with no name on {}: every check the host \
1100             reports is named, so an empty name matches none of them. This build refused the \
1101             request; the host was not asked.",
1102            cr.url
1103        )));
1104    }
1105    Ok(())
1106}
1107
1108/// One value bound for a URL path segment, percent-encoded.
1109///
1110/// A branch name is the only one of these, and git allows characters in one that a
1111/// path does not — a `/` above all, which every stacked branch carries and which
1112/// would otherwise address a resource nobody asked for. Encoded rather than
1113/// refused: `feature/thing` is a branch a repository really has.
1114fn path_segment(value: &str) -> String {
1115    let mut encoded = String::with_capacity(value.len());
1116    for byte in value.bytes() {
1117        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
1118            encoded.push(char::from(byte));
1119        } else {
1120            encoded.push_str(&format!("%{byte:02X}"));
1121        }
1122    }
1123    encoded
1124}
1125
1126/// A commit hash bound for a query string, checked before it gets there.
1127///
1128/// It arrives off a host response and goes on to be one parameter of several, so a
1129/// value carrying anything but hex digits could address a query nobody wrote.
1130fn commit(sha: &Sha) -> Result<&str> {
1131    if !is_commit_hash(&sha.0) {
1132        return Err(invalid(format!(
1133            "{:?} is not a commit hash, so the checks reported against it cannot be asked for",
1134            sha.0
1135        )));
1136    }
1137    Ok(&sha.0)
1138}
1139
1140/// Whether text the host handed over is the shape of a commit hash.
1141///
1142/// The one shape rule, so the two boundaries that read a commit off this host agree
1143/// about what one is: the commit an Actions query is built from ([`commit`]) and the
1144/// commit a host says it attached a check to ([`reported_sha`]). Shared as the rule
1145/// rather than as the refusal because each of those refusals costs something
1146/// different and says so.
1147fn is_commit_hash(sha: &str) -> bool {
1148    !sha.is_empty() && sha.chars().all(|c| c.is_ascii_hexdigit())
1149}
1150
1151/// One workflow job, as the Actions API reports it.
1152struct Job {
1153    /// What `gh api .../actions/jobs/<id>/logs` addresses its log by.
1154    id: u64,
1155    /// The job's name, which is the name GitHub posts its check run under.
1156    name: String,
1157    /// Where it is, in the host's own vocabulary.
1158    status: String,
1159    /// How it ended, once it has.
1160    conclusion: Option<String>,
1161    /// The commit its workflow run was reported against, off that run's own record.
1162    head: Option<Sha>,
1163    /// Where a human reads this job on the host.
1164    url: Option<Url>,
1165}
1166
1167/// One job of an Actions listing, required to say what it is.
1168///
1169/// Defaulting a missing field is what would let a job that is still running be read
1170/// as a green check, which is the shape that must never be inferred — the same rule
1171/// [`check`] below is held to, for the same reason.
1172fn job(entry: &serde_json::Value, cr: &ChangeRequest, head: Option<&Sha>) -> Result<Job> {
1173    let field = |name: &str| -> Result<&str> {
1174        entry
1175            .get(name)
1176            .and_then(|value| value.as_str())
1177            .filter(|value| !value.is_empty())
1178            .ok_or_else(|| {
1179                invalid(format!(
1180                    "the Actions API returned a job on {} with no {name}: {entry}",
1181                    cr.url
1182                ))
1183            })
1184    };
1185    Ok(Job {
1186        id: entry
1187            .get("id")
1188            .and_then(serde_json::Value::as_u64)
1189            .ok_or_else(|| {
1190                invalid(format!(
1191                    "the Actions API returned a job on {} with no id, so its log cannot be asked \
1192                     for: {entry}",
1193                    cr.url
1194                ))
1195            })?,
1196        name: field("name")?.to_owned(),
1197        status: field("status")?.to_ascii_lowercase(),
1198        // Genuinely absent while a job is still running.
1199        conclusion: entry
1200            .get("conclusion")
1201            .and_then(|value| value.as_str())
1202            .filter(|value| !value.is_empty())
1203            .map(str::to_ascii_lowercase),
1204        head: head.cloned(),
1205        url: reported_url(entry, "html_url"),
1206    })
1207}
1208
1209/// The commit a host response names, off whichever field that response spells it
1210/// in, or `None` where it named none.
1211///
1212/// Lenient about *absence* where [`head_sha`] refuses, and the difference is what
1213/// each answer is for: a change request with no head is one this build cannot go on
1214/// to ask the Actions API about at all, while a check whose source would not say
1215/// which commit it is about is still a check, and reading it is still the answer.
1216/// Inventing one is the thing that must not happen — which is why an absent field
1217/// reads `None` rather than falling back to the head the caller already holds.
1218///
1219/// Strict about *shape* exactly where it is lenient about absence, and for the same
1220/// reason. This is host-supplied text arriving at a trust boundary, and it is held
1221/// to [`is_commit_hash`] like every other commit read off this host. Passed through
1222/// unchecked it would be worse than a refusal rather than more forgiving than one:
1223/// what a publication does with this value is compare it to the commit it pushed,
1224/// so anything that is not a commit hash matches nothing and reads as "the host has
1225/// said nothing about your commit yet" — silence — for as long as the watch runs,
1226/// and then times out naming a commit the host never had trouble with. A malformed
1227/// answer must not be able to wear the one shape this path exists to keep distinct
1228/// from an answer.
1229fn reported_sha(value: &serde_json::Value, field: &str) -> Result<Option<Sha>> {
1230    let Some(reported) = value
1231        .get(field)
1232        .and_then(|value| value.as_str())
1233        .filter(|value| !value.is_empty())
1234    else {
1235        return Ok(None);
1236    };
1237    if !is_commit_hash(reported) {
1238        return Err(invalid(format!(
1239            "gh reported {reported:?} as the {field} of a check, and that is not a commit hash, \
1240             so which commit the check is attached to cannot be decided"
1241        )));
1242    }
1243    Ok(Some(Sha(reported.to_owned())))
1244}
1245
1246/// Where the host says something is, off whichever field that response spells it
1247/// in, or `None` where it named nowhere this build can point a person at.
1248///
1249/// A URL that will not parse is `None` rather than a refusal: this is the address a
1250/// refusal hands over so somebody can go and look, and failing a publication over a
1251/// link would put the check's verdict behind a formatting complaint.
1252fn reported_url(entry: &serde_json::Value, field: &str) -> Option<Url> {
1253    entry
1254        .get(field)
1255        .and_then(|value| value.as_str())
1256        .filter(|value| !value.is_empty())
1257        .and_then(|value| Url::parse(value).ok())
1258}
1259
1260/// The entries of one Actions listing, refused unless the page carried them all.
1261///
1262/// These endpoints page, and a page that held entries back is a partial answer
1263/// about what ran — read as the whole of it, a check nobody saw is a check nobody
1264/// waited for. `total_count` is how the answer says how many there are, so the two
1265/// are compared rather than the list being trusted to be complete.
1266fn listed<'a>(
1267    value: &'a serde_json::Value,
1268    field: &str,
1269    what: &str,
1270) -> Result<&'a Vec<serde_json::Value>> {
1271    let entries = value
1272        .get(field)
1273        .and_then(|value| value.as_array())
1274        .ok_or_else(|| {
1275            invalid(format!(
1276                "the Actions API answered about {what} with something that lists no {field}: \
1277                 {value}"
1278            ))
1279        })?;
1280    let total = value
1281        .get("total_count")
1282        .and_then(serde_json::Value::as_u64)
1283        .ok_or_else(|| {
1284            invalid(format!(
1285                "the Actions API did not say how many {field} there are on {what}: {value}"
1286            ))
1287        })?;
1288    if total > entries.len() as u64 {
1289        return Err(invalid(format!(
1290            "the Actions API reports {total} {field} on {what} and returned {}, so this build has \
1291             not been shown all of them",
1292            entries.len()
1293        )));
1294    }
1295    Ok(entries)
1296}
1297
1298/// The refusal for a credential that can read none of the host's check sources.
1299///
1300/// Both refusals, verbatim, and the permission that answers them — because the
1301/// thing an operator cannot tell from GitHub's own words is that one of these is
1302/// not a scope to widen: a fine-grained personal access token has no `Checks`
1303/// permission to grant, so the rollup is out of reach for that credential class
1304/// however it is scoped, and `Actions: Read` is what makes the other source work.
1305fn unreadable(repo: &str, cr: &ChangeRequest, rollup: &Error, actions: &Error) -> Error {
1306    invalid(format!(
1307        "neither of GitHub's check sources could be read for {}, so what its checks say is \
1308         unknown rather than empty. Its check rollup answered: {rollup}. Its Actions API \
1309         answered: {actions}. Grant this credential `Actions: Read` on {repo} to read the \
1310         repository's workflow checks — a fine-grained personal access token cannot read the \
1311         rollup at all, whatever it is scoped to, because GitHub offers no Checks permission for \
1312         one.",
1313        cr.url
1314    ))
1315}
1316
1317/// A branch name a caller supplied, checked by the parser that decides branch names.
1318fn addressable_branch(value: &str, what: &str) -> Result<()> {
1319    if !git::is_valid_branch_name(value) {
1320        return Err(invalid(format!(
1321            "{what} {value:?} is a name git would not accept"
1322        )));
1323    }
1324    Ok(())
1325}
1326
1327impl RemoteHost for GitHub {
1328    fn authenticated_user(&self) -> Result<String> {
1329        let login = gh::invoke(&["api", "user", "--jq", ".login"])?
1330            .trim()
1331            .to_owned();
1332        if login.is_empty() {
1333            return Err(Error::Invalid {
1334                reason: "gh reported no authenticated user".to_owned(),
1335            });
1336        }
1337        Ok(login)
1338    }
1339
1340    fn open_change(&self, req: ChangeSpec) -> Result<ChangeRequest> {
1341        addressable_branch(&req.head, "the head branch")?;
1342        addressable_branch(&req.base, "the base branch")?;
1343        // The publication rule the crate states, applied rather than restated —
1344        // and applied here as well as where a publication takes a request in, because
1345        // [`ChangeSpec`] is public and this trait is reachable directly. A reason no
1346        // publication could have carried must not open a change request the record
1347        // then cannot say anything readable about.
1348        if let Some(reason) = &req.draft {
1349            reason.checked()?;
1350        }
1351        let body = req.body.unwrap_or_default();
1352        let mut args = vec![
1353            "pr", "create", "--repo", &self.repo, "--head", &req.head, "--base", &req.base,
1354            "--title", &req.title, "--body", &body,
1355        ];
1356        // The whole of what the reason does at the host: it opens as a draft. Nothing
1357        // of the reason itself is written there — see `DraftReason`.
1358        if req.draft.is_some() {
1359            args.push("--draft");
1360        }
1361        let raw = gh::invoke(&args)?;
1362        let url = raw
1363            .lines()
1364            .map(str::trim)
1365            .rfind(|line| line.starts_with("http"))
1366            .ok_or_else(|| invalid(format!("gh pr create printed no URL: {raw:?}")))?;
1367        let parsed = Url::parse(url)
1368            .map_err(|e| invalid(format!("gh pr create printed {url:?}, not a URL: {e}")))?;
1369        // The host numbers its change requests, and the number is the last segment
1370        // of the URL it printed. Anything else in that position is `gh` having
1371        // printed something other than a change request's URL, which is not an
1372        // identifier to go on addressing it by.
1373        let id = parsed
1374            .path_segments()
1375            .and_then(|mut segments| segments.next_back())
1376            .filter(|segment| !segment.is_empty() && segment.chars().all(|c| c.is_ascii_digit()))
1377            .ok_or_else(|| {
1378                invalid(format!(
1379                    "gh pr create printed {url:?}, which names no change"
1380                ))
1381            })?
1382            .to_owned();
1383        Ok(ChangeRequest {
1384            // The commit the new change request's checks will be reported against,
1385            // which `gh pr create` does not print.
1386            head_sha: head_sha(&self.view(&id, "headRefOid")?)?,
1387            id: ChangeId(id),
1388            url: parsed,
1389            base: req.base,
1390        })
1391    }
1392
1393    fn find_changes(&self, head: &str, base: &str) -> Result<Vec<ChangeRequest>> {
1394        addressable_branch(head, "the head branch")?;
1395        addressable_branch(base, "the base branch")?;
1396        let raw = gh::invoke(&[
1397            "pr",
1398            "list",
1399            "--repo",
1400            &self.repo,
1401            "--head",
1402            head,
1403            "--base",
1404            base,
1405            "--state",
1406            "open",
1407            "--json",
1408            "number,url,state,headRefOid",
1409        ])?;
1410        let value = gh::json(&raw)?;
1411        let items = value
1412            .as_array()
1413            .ok_or_else(|| invalid(format!("gh pr list returned {raw:?}, not a list")))?;
1414        let mut changes = Vec::new();
1415        for item in items {
1416            let url = item.get("url").and_then(|v| v.as_str()).unwrap_or_default();
1417            let parsed = Url::parse(url)
1418                .map_err(|e| invalid(format!("gh pr list returned {url:?}, not a URL: {e}")))?;
1419            let number = item
1420                .get("number")
1421                .and_then(|value| value.as_u64())
1422                .ok_or_else(|| invalid(format!("gh pr list returned no number: {raw:?}")))?
1423                .to_string();
1424            changes.push(ChangeRequest {
1425                id: ChangeId(number),
1426                url: parsed,
1427                head_sha: head_sha(item)?,
1428                base: base.to_owned(),
1429            });
1430        }
1431        Ok(changes)
1432    }
1433
1434    fn change_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks> {
1435        let rollup = |checks| ChangeChecks {
1436            checks,
1437            sources: [CheckSource::StatusChecks].into_iter().collect(),
1438        };
1439        match consult()? {
1440            Consult::StatusChecks => self.rollup_checks(cr).map(rollup),
1441            Consult::Actions => self.actions_checks(cr),
1442            // The rollup first, because it is the complete answer and this build
1443            // cannot know what the credential is until it is refused. A refusal is
1444            // never read as "no checks": the fallback either produces an answer of
1445            // its own or both refusals are reported together.
1446            Consult::Either => match self.rollup_checks(cr) {
1447                Ok(checks) => Ok(rollup(checks)),
1448                Err(refused) if check_rollup_refused_for_pat(&refused) => self
1449                    .actions_checks(cr)
1450                    .map_err(|actions| unreadable(&self.repo, cr, &refused, &actions)),
1451                Err(refused) => Err(refused),
1452            },
1453        }
1454    }
1455
1456    /// Store one check's log as an artifact, or refuse.
1457    ///
1458    /// A fetch that did not produce the log is an error and no artifact: an
1459    /// artifact reads as what the check printed, so one holding the reason there is
1460    /// none is a lie in the only record a consumer has. A caller that must not fail
1461    /// over a missing log declines to fail over this error, as [`crate::publish`]
1462    /// does.
1463    fn check_log(&self, cr: &ChangeRequest, check: &Check) -> Result<ArtifactId> {
1464        // The two are told apart, because they are two different things to whoever
1465        // reads the refusal: a name this build would not ask about is this build's
1466        // own doing and says so, while a host that would not produce the log is the
1467        // host's and quotes what it said. They used to arrive as one message
1468        // attributing both to the host, which is how a refusal this crate made read
1469        // as GitHub keeping its logs — and why it went unnoticed for as long as it
1470        // did. The kind stays `Invalid` for both, because the failure vocabulary is
1471        // fixed across the libraries that route on it; the message is where the
1472        // actor is named.
1473        matchable(&check.name, cr)?;
1474        let log = self.log_of(cr, &check.name).map_err(|error| {
1475            invalid(format!(
1476                "the host could not produce a log for check {:?} on {}: {error}",
1477                check.name, cr.url
1478            ))
1479        })?;
1480        Ok(ArtifactId(stream::store_artifact("log", &log)?.id))
1481    }
1482
1483    fn merge(&self, cr: &ChangeRequest, policy: MergePolicy) -> Result<MergeOutcome> {
1484        match policy {
1485            MergePolicy::LocalDirect | MergePolicy::ChangeOpen => Ok(MergeOutcome::Open),
1486            MergePolicy::ChangeAuto => {
1487                addressable(&cr.id.0, "change request id")?;
1488                gh::invoke(&[
1489                    "pr", "merge", &cr.id.0, "--repo", &self.repo, "--squash", "--auto",
1490                ])?;
1491                let view = self.view(&cr.id.0, MERGE_FIELDS)?;
1492                Ok(match merged_sha(&view, cr)? {
1493                    Some(sha) => MergeOutcome::Merged(sha),
1494                    None => MergeOutcome::Queued,
1495                })
1496            }
1497            MergePolicy::ChangeDirect => {
1498                addressable(&cr.id.0, "change request id")?;
1499                gh::invoke(&["pr", "merge", &cr.id.0, "--repo", &self.repo, "--squash"])?;
1500                let view = self.view(&cr.id.0, MERGE_FIELDS)?;
1501                match merged_sha(&view, cr)? {
1502                    Some(sha) => Ok(MergeOutcome::Merged(sha)),
1503                    None => Err(Error::GateFailed {
1504                        reason: format!(
1505                            "the host accepted the merge of {} but reports it unmerged",
1506                            cr.url
1507                        ),
1508                    }),
1509                }
1510            }
1511        }
1512    }
1513
1514    fn ready_for_review(&self, cr: &ChangeRequest) -> Result<()> {
1515        addressable(&cr.id.0, "change request id")?;
1516        gh::invoke(&["pr", "ready", &cr.id.0, "--repo", &self.repo]).map(|_| ())
1517    }
1518
1519    /// One `gh pr edit`, handing the body over as a file.
1520    ///
1521    /// A file rather than `--body`, because a body is prose of unbounded size and an
1522    /// argument vector is not where multi-line Markdown belongs: the same reason
1523    /// `onevcs publish` takes `--body-file`. The file is written under a scratch
1524    /// directory that goes when this returns, and `gh` reads it before then.
1525    fn describe_change(&self, cr: &ChangeRequest, title: Option<&str>, body: &str) -> Result<()> {
1526        addressable(&cr.id.0, "change request id")?;
1527        let scratch = tempfile::tempdir().map_err(|failure| {
1528            invalid(format!(
1529                "could not create a scratch directory to hand the body of {} to gh: {failure}",
1530                cr.url
1531            ))
1532        })?;
1533        let file = scratch.path().join("body.md");
1534        std::fs::write(&file, body).map_err(crate::error::at(
1535            "write the change request's body to",
1536            &file,
1537        ))?;
1538        let file = file.to_string_lossy().into_owned();
1539        let mut args = vec![
1540            "pr",
1541            "edit",
1542            &cr.id.0,
1543            "--repo",
1544            &self.repo,
1545            "--body-file",
1546            &file,
1547        ];
1548        if let Some(title) = title {
1549            args.extend(["--title", title]);
1550        }
1551        gh::invoke(&args).map(|_| ())
1552    }
1553
1554    /// One `gh pr view`, reading exactly the two fields a description is.
1555    ///
1556    /// A response missing either is refused rather than read as empty: "the change
1557    /// request has no body" and "the host would not say what the body is" are
1558    /// different facts, and a caller finishing a description off what it reads here
1559    /// would otherwise start from a blank the host never answered.
1560    fn change_description(&self, cr: &ChangeRequest) -> Result<Description> {
1561        addressable(&cr.id.0, "change request id")?;
1562        let view = self.view(&cr.id.0, "title,body")?;
1563        let read = |name: &str| {
1564            view.get(name)
1565                .and_then(serde_json::Value::as_str)
1566                .map(str::to_owned)
1567                .ok_or_else(|| {
1568                    invalid(format!(
1569                        "gh pr view answered about {} without its {name}, so what the change \
1570                         request says cannot be read",
1571                        cr.url
1572                    ))
1573                })
1574        };
1575        Ok(Description {
1576            title: read("title")?,
1577            body: read("body")?,
1578        })
1579    }
1580
1581    /// One `gh pr view`, reading the one field the host decides a draft by.
1582    ///
1583    /// A response that does not carry it is refused rather than read as "not a
1584    /// draft": what this decides is whether a change may be asked to merge, and
1585    /// "could not look" reported as "nothing is holding it" is the one answer that
1586    /// lands work somebody held back.
1587    fn is_draft(&self, cr: &ChangeRequest) -> Result<bool> {
1588        addressable(&cr.id.0, "change request id")?;
1589        let view = self.view(&cr.id.0, "isDraft")?;
1590        view.get("isDraft")
1591            .and_then(serde_json::Value::as_bool)
1592            .ok_or_else(|| {
1593                invalid(format!(
1594                    "gh pr view answered about {} without saying whether it is a draft, so \
1595                     whether the host is holding it cannot be read",
1596                    cr.url
1597                ))
1598            })
1599    }
1600
1601    /// One `gh pr view`, reading exactly the two fields a merge is decided from —
1602    /// the same read `merge` makes, through the same parser, so watching a change
1603    /// request and merging one cannot come to disagree about what merged means.
1604    fn merged_at(&self, cr: &ChangeRequest) -> Result<Option<Sha>> {
1605        addressable(&cr.id.0, "change request id")?;
1606        merged_sha(&self.view(&cr.id.0, MERGE_FIELDS)?, cr)
1607    }
1608
1609    fn required_checks_on(&self, base: &str) -> Result<RequiredChecks> {
1610        // The rulesets first, and their refusal is the whole read's: every
1611        // credential that can see the repository can read them, so one that cannot
1612        // has not answered about anything. Classic protection is asked second and
1613        // its refusal is recorded rather than raised, because the credential GitHub
1614        // steers people toward is refused it on every repository, and the rulesets'
1615        // answer is still worth having — marked as the part it is.
1616        let checks = self.required_on(base, &self.repo)?;
1617        let mut answer = RequiredChecks {
1618            checks,
1619            unconsulted: BTreeMap::new(),
1620        };
1621        match self.classic_protection(base)? {
1622            Ok(contexts) => answer.checks.extend(contexts),
1623            Err(refusal) => {
1624                answer
1625                    .unconsulted
1626                    .insert(ProtectionSource::BranchProtection, refusal);
1627            }
1628        }
1629        Ok(answer)
1630    }
1631}
1632
1633/// The refusal for a host that will not say which of its checks block the merge.
1634///
1635/// Inferring it is the one shape that must never be guessed: it is the difference
1636/// between a merge that was gated and one that only looked like it. What changed
1637/// with the real backend is *where* the question is asked, not that it may be
1638/// skipped — a host that answers `gh pr checks --required` with something other
1639/// than the checks it requires is refused here rather than read as requiring none.
1640fn unsaid(url: &Url, detail: &str) -> Error {
1641    invalid(format!(
1642        "gh pr checks --required answered about {url} with {detail}, so a check it reported does \
1643         not say whether it blocks the merge"
1644    ))
1645}
1646
1647/// The same refusal from the rulesets read, which is addressed to a base branch and
1648/// names whatever asked about it — a change request's URL, or an identity.
1649fn unsaid_about(about: &str, detail: &str) -> Error {
1650    invalid(format!(
1651        "the repository's rulesets answered about {about} with {detail}, so a check they \
1652         reported does not say whether it blocks the merge"
1653    ))
1654}
1655
1656/// The refusal for a host that has no check on the head to report yet.
1657///
1658/// Separate from [`unsaid`] because the next move differs: this one is a clock, and
1659/// whoever reads it waits rather than re-runs.
1660fn unregistered(url: &Url, said: &str) -> Error {
1661    invalid(format!(
1662        "the host reports no check at all yet on the head of {url} ({said}), which is not the \
1663         same as a repository that declares none required — it is what a head pushed moments ago \
1664         looks like — so whether anything blocks the merge cannot be read from it"
1665    ))
1666}
1667
1668/// One entry of the host's check rollup, required to say what it is.
1669///
1670/// Defaulting a missing field here is what would let a host that answered
1671/// partially be read as a green check — the one shape that must never be inferred.
1672/// Whether the check *blocks* is not in this entry at all and never was: it comes
1673/// from [`GitHub::required_checks`], which refuses a host that will not say.
1674fn check(
1675    entry: &serde_json::Value,
1676    cr: &ChangeRequest,
1677    required: &BTreeSet<String>,
1678    head: Option<&Sha>,
1679) -> Result<Check> {
1680    let field = |name: &str| -> Result<&str> {
1681        entry
1682            .get(name)
1683            .and_then(|value| value.as_str())
1684            .filter(|value| !value.is_empty())
1685            .ok_or_else(|| {
1686                invalid(format!(
1687                    "gh pr view returned a check on {} with no {name}: {entry}",
1688                    cr.url
1689                ))
1690            })
1691    };
1692    let name = field("name").or_else(|_| field("context"))?.to_owned();
1693    let blocks = required.contains(&name);
1694    Ok(Check {
1695        name,
1696        status: field("status")?.to_ascii_lowercase(),
1697        // Genuinely absent while a check is still running, which is the one thing
1698        // the host cannot yet know.
1699        conclusion: entry
1700            .get("conclusion")
1701            .and_then(|value| value.as_str())
1702            .filter(|value| !value.is_empty())
1703            .map(str::to_ascii_lowercase),
1704        required: blocks,
1705        head: head.cloned(),
1706        // A check run's own address, and only that spelling. A commit status
1707        // spells it `targetUrl` — and never reaches here: it carries `state` where
1708        // this reads `status`, so `field("status")` above refuses the whole answer
1709        // before an address is looked for. Reading the second spelling would be a
1710        // branch nothing can drive, on a path that already cannot be taken.
1711        url: reported_url(entry, "detailsUrl"),
1712    })
1713}
1714
1715/// What [`merged_sha`] reads, which is what a merge asks `gh pr view` for.
1716const MERGE_FIELDS: &str = "state,mergeCommit";
1717
1718/// The commit a merged change request landed as, or `None` while it is still open.
1719///
1720/// A host reporting `MERGED` without naming the commit is answering wrongly rather
1721/// than answering "not yet": the commit is the whole evidence that the change
1722/// reached its base, and reporting a merge with no SHA is the one thing that must
1723/// not be passed through.
1724fn merged_sha(view: &serde_json::Value, cr: &ChangeRequest) -> Result<Option<Sha>> {
1725    let state = view
1726        .get("state")
1727        .and_then(|value| value.as_str())
1728        .ok_or_else(|| invalid(format!("gh pr view returned no state for {}", cr.url)))?;
1729    if !state.eq_ignore_ascii_case("merged") {
1730        return Ok(None);
1731    }
1732    view.get("mergeCommit")
1733        .and_then(|commit| commit.get("oid"))
1734        .and_then(|value| value.as_str())
1735        .filter(|value| !value.is_empty())
1736        .map(|sha| Some(Sha(sha.to_owned())))
1737        .ok_or_else(|| {
1738            invalid(format!(
1739                "gh pr view reports {} merged without naming the commit it merged as",
1740                cr.url
1741            ))
1742        })
1743}
1744
1745/// The commit a change request's checks are reported against.
1746fn head_sha(view: &serde_json::Value) -> Result<Sha> {
1747    view.get("headRefOid")
1748        .and_then(|value| value.as_str())
1749        .filter(|value| !value.is_empty())
1750        .map(|sha| Sha(sha.to_owned()))
1751        .ok_or_else(|| invalid(format!("gh returned a change request with no head: {view}")))
1752}