Skip to main content

verctl_github/
lib.rs

1//! GitHub REST client for `verctl` pull requests, Releases, drafts, tags,
2//! branch rules, and workflow runs.
3
4use std::cell::OnceCell;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7use std::{env, fmt, fs, io};
8
9use anyhow::{Context, Result, bail, ensure};
10use octocrab::Octocrab;
11use octocrab::models::repos::Object;
12use octocrab::params::State;
13use octocrab::params::repos::Reference;
14use octocrab::repos::releases::MakeLatest;
15use reqwest::header::HeaderValue;
16use reqwest::redirect::Policy;
17use tokio::runtime::Builder;
18use tokio::time;
19pub use verctl_core::env::{
20    default_branch_of, event_default_branch, event_is_merge_group, is_merge_group,
21    pull_request_number, write_github_output as write_output,
22};
23pub use verctl_core::repo::{Repo, parse_remote, parse_slug};
24use verctl_core::{env as release_env, lookup, stop};
25
26/// Actions sets `GITHUB_REPOSITORY`. Locally, `origin` is the contract.
27///
28/// # Errors
29///
30/// Returns an error when `GITHUB_REPOSITORY` is set but is not `owner/name`,
31/// or, without it, when the `origin` URL cannot be read or is not a GitHub
32/// remote. Without `GITHUB_REPOSITORY`, the error is a
33/// [`lookup::Unavailable`]: the repository names no GitHub repository to ask.
34/// A malformed `GITHUB_REPOSITORY` is a setting to fix, so it stays unmarked.
35pub fn repo_with(origin_url: impl FnOnce() -> Result<String>) -> Result<Repo> {
36    if let Ok(slug) = env::var("GITHUB_REPOSITORY")
37        && !slug.is_empty()
38    {
39        return parse_slug(&slug);
40    }
41    origin_url()
42        .and_then(|url| parse_remote(url.trim()))
43        .map_err(lookup::unavailable)
44}
45
46/// The branch a Version PR targets: `GITHUB_REF_NAME`, else
47/// `VERCTL_DEFAULT_BRANCH`, else the branch `origin/HEAD` names.
48///
49/// If none of them is set, the call fails instead of guessing.
50/// A repository whose default is not `main` would otherwise get a Version PR
51/// against a branch it does not release from.
52///
53/// # Errors
54///
55/// Returns an error when none of those three sources names a branch.
56pub fn base_branch_with(
57    configured: Option<String>,
58    upstream: impl FnOnce() -> Option<String>,
59) -> Result<String> {
60    if let Ok(name) = env::var("GITHUB_REF_NAME")
61        && !name.is_empty()
62    {
63        return Ok(name);
64    }
65    configured
66        .or_else(upstream)
67        .context(
68            "cannot tell which branch the Version PR targets: set VERCTL_DEFAULT_BRANCH, or run `git remote set-head origin --auto`",
69        )
70}
71
72/// An open pull request.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct ExistingPr {
75    /// Link to the pull request.
76    pub url: String,
77    /// The pull request number.
78    pub number: u64,
79    /// Full hex SHA of the pull request's base branch tip as GitHub reports it.
80    pub base_sha: String,
81}
82
83/// The open pull request from `head` in this repository, if one exists.
84///
85/// # Errors
86///
87/// Returns an error when the GitHub client cannot be built or the call that
88/// lists pull requests fails.
89pub fn existing_pr(token: &str, repo: &Repo, head: &str) -> Result<Option<ExistingPr>> {
90    block(async {
91        let crab = client(token)?;
92        let page = crab
93            .pulls(&repo.owner, &repo.name)
94            .list()
95            .state(State::Open)
96            .head(format!("{}:{head}", repo.owner))
97            .per_page(1)
98            .send()
99            .await
100            .context("list pull requests")?;
101        Ok(page.items.into_iter().next().and_then(|pr| {
102            let url = pr.html_url?.to_string();
103            Some(ExistingPr {
104                url,
105                number: pr.number,
106                base_sha: pr.base.sha,
107            })
108        }))
109    })
110}
111
112/// Sets the title and body of pull request `number` and returns its URL.
113///
114/// # Errors
115///
116/// Returns an error when the GitHub client cannot be built, the update
117/// request fails, or the response carries no URL.
118pub fn update_pr(token: &str, repo: &Repo, number: u64, title: &str, body: &str) -> Result<String> {
119    block(async {
120        let crab = client(token)?;
121        let pr = crab
122            .pulls(&repo.owner, &repo.name)
123            .update(number)
124            .title(title)
125            .body(body)
126            .send()
127            .await
128            .context("update pull request")?;
129        pr.html_url
130            .map(|url| url.to_string())
131            .context("updated PR has no html_url")
132    })
133}
134
135/// Opens a pull request from `head` into `base`.
136///
137/// # Errors
138///
139/// Returns an error when the GitHub client cannot be built or the create
140/// request fails, for example when `head` does not exist.
141/// It also returns one when the response carries no URL.
142pub fn create_pr(
143    token: &str,
144    repo: &Repo,
145    title: &str,
146    head: &str,
147    base: &str,
148    body: &str,
149) -> Result<ExistingPr> {
150    block(async {
151        let crab = client(token)?;
152        let pr = crab
153            .pulls(&repo.owner, &repo.name)
154            .create(title, head, base)
155            .body(body)
156            .send()
157            .await
158            .context("create pull request")?;
159        let url = pr
160            .html_url
161            .map(|url| url.to_string())
162            .context("created PR has no html_url")?;
163        Ok(ExistingPr {
164            url,
165            number: pr.number,
166            base_sha: pr.base.sha,
167        })
168    })
169}
170
171/// Posts `comment` on pull request `number`, closes it, and returns its URL.
172///
173/// # Errors
174///
175/// Returns an error when the GitHub client cannot be built, the comment or
176/// close request fails, or the closed pull request response carries no URL.
177pub fn close_pr(token: &str, repo: &Repo, number: u64, comment: &str) -> Result<String> {
178    block(async {
179        let crab = client(token)?;
180        close_pr_with(&crab, repo, number, comment).await
181    })
182}
183
184async fn close_pr_with(crab: &Octocrab, repo: &Repo, number: u64, comment: &str) -> Result<String> {
185    #[derive(serde::Serialize)]
186    struct CommentBody<'a> {
187        body: &'a str,
188    }
189    #[derive(serde::Serialize)]
190    struct CloseState {
191        state: &'static str,
192    }
193    #[derive(serde::Deserialize)]
194    struct ClosedPull {
195        html_url: Option<String>,
196    }
197    let comment_route = format!(
198        "/repos/{owner}/{name}/issues/{number}/comments",
199        owner = repo.owner,
200        name = repo.name,
201    );
202    let _: serde_json::Value = crab
203        .post(comment_route, Some(&CommentBody { body: comment }))
204        .await
205        .with_context(|| format!("comment on pull request #{number}"))?;
206    let pull_route = format!(
207        "/repos/{owner}/{name}/pulls/{number}",
208        owner = repo.owner,
209        name = repo.name,
210    );
211    let closed: ClosedPull = crab
212        .patch(pull_route, Some(&CloseState { state: "closed" }))
213        .await
214        .with_context(|| format!("close pull request #{number}"))?;
215    closed.html_url.context("closed PR has no html_url")
216}
217
218/// Whether the pull request of this `pull_request` event is a Version PR by
219/// the identity of the `version-pr-identity` design ยง1.
220/// Its head repository is this repository, and its head branch is
221/// `verctl/release/<base>` for the base it targets now.
222///
223/// The check reads all three through the API when it runs.
224/// It never reads the event payload, because a base can change after the
225/// event and a label applied after opening is missing from the `opened`
226/// payload.
227/// It never reads the title, body, or labels, and it ignores
228/// `GITHUB_HEAD_REF`.
229///
230/// Without an event, or for an event that is not a pull request's, it is
231/// `false`.
232///
233/// # Errors
234///
235/// Returns an error when the event names a pull request but no token is set.
236/// It also returns one when `GITHUB_REPOSITORY` is not `owner/name` or GitHub
237/// cannot read the pull request.
238pub fn pull_request_is_version_pr() -> Result<bool> {
239    let Ok(path) = env::var("GITHUB_EVENT_PATH") else {
240        return Ok(false);
241    };
242    let Ok(raw) = fs::read_to_string(path) else {
243        return Ok(false);
244    };
245    let Some(number) = pull_request_number(&raw) else {
246        return Ok(false);
247    };
248    let token = release_env::env_token().context(
249        "the version check reads the pull request and needs GITHUB_TOKEN with pull-requests: read",
250    )?;
251    let slug = env::var("GITHUB_REPOSITORY").unwrap_or_default();
252    let repo = parse_slug(&slug)?;
253    block(async move {
254        let crab = client(&token)?;
255        let pr = crab
256            .pulls(&repo.owner, &repo.name)
257            .get(number)
258            .await
259            .with_context(|| format!("read pull request #{number}"))?;
260        let same_repo = pr
261            .head
262            .repo
263            .as_ref()
264            .and_then(|head| head.full_name.as_deref())
265            .is_some_and(|name| name.eq_ignore_ascii_case(&slug));
266        Ok(same_repo && pr.head.ref_field == release_env::version_branch(&pr.base.ref_field))
267    })
268}
269
270/// Where a Release stands: the stable one, or a candidate before it.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub enum Stage {
273    /// A stable version: GitHub's defaults apply, so the Release becomes the
274    /// repository's latest.
275    Stable,
276    /// A candidate: a prerelease that never becomes the latest Release, so
277    /// the repository's latest stays the stable one ([create a release]).
278    ///
279    /// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
280    Candidate,
281}
282
283/// The Release a run creates for a tag: a draft for `release`, or a Release
284/// published at once for [`ensure_release`].
285///
286/// Not `#[non_exhaustive]`: `verctl-release` constructs it directly.
287#[derive(Debug, Clone, Copy)]
288pub struct NewRelease<'a> {
289    /// The tag the Release is for.
290    pub tag: &'a str,
291    /// The Release title.
292    pub name: &'a str,
293    /// The Release notes.
294    pub body: &'a str,
295    /// The commit the tag is created at, and the one an existing tag must name.
296    pub sha: &'a str,
297    /// Whether the Release is the stable one or a candidate.
298    pub stage: Stage,
299    /// The asset names the draft must contain before it is published, because
300    /// an immutable Release takes no asset once published ([immutable
301    /// releases]). Empty, the draft is published with none.
302    ///
303    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
304    pub assets: &'a [String],
305}
306
307/// Whether a release run uploaded a package under a tag.
308#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
309pub enum PackageUpload {
310    /// This run published a package under the tag, so an existing release's
311    /// tag must match `sha`.
312    #[default]
313    Shipped,
314    /// Nothing under the tag shipped in this run; an existing published
315    /// release may stay at its earlier commit.
316    Skipped,
317}
318
319/// Create `tag` at `sha` if it is missing. Returns the release HTML URL.
320///
321/// A new Release is a [`Stage::Stable`] one, with GitHub's defaults, and is
322/// published at once. An existing release is used as it is, and a draft found
323/// is published.
324///
325/// An existing release is not trusted: GitHub's `target_commitish` on the
326/// Release object is a branch name more often than a SHA. The git ref is
327/// re-read either way, and a tag that names another commit fails.
328///
329/// # Errors
330///
331/// Returns an error when:
332///
333/// - The GitHub client cannot be built.
334/// - A release or tag lookup fails.
335/// - The release cannot be created, or a draft found cannot be published.
336/// - The tag does not point at `sha`.
337///
338/// The tag is checked against an existing release only when `upload` is
339/// [`PackageUpload::Shipped`].
340pub fn ensure_release(
341    token: &str,
342    repo: &Repo,
343    tag: &str,
344    name: &str,
345    body: &str,
346    sha: &str,
347    upload: PackageUpload,
348) -> Result<String> {
349    let release = NewRelease {
350        tag,
351        name,
352        body,
353        sha,
354        stage: Stage::Stable,
355        assets: &[],
356    };
357    block(async {
358        let crab = client(token)?;
359        ensure_release_with(&crab, repo, &release, upload).await
360    })
361}
362
363/// [`PackageUpload::Shipped`] means this run published a package under the
364/// tag. With [`PackageUpload::Skipped`], an existing published release belongs
365/// to the run that did, and its tag may name that earlier commit. A draft's
366/// tag is always checked.
367async fn ensure_release_with(
368    crab: &Octocrab,
369    repo: &Repo,
370    release: &NewRelease<'_>,
371    upload: PackageUpload,
372) -> Result<String> {
373    let NewRelease {
374        tag,
375        name,
376        body,
377        sha,
378        stage,
379        assets: _,
380    } = *release;
381    let existing = if read_tag(crab, repo, tag).await?.is_some() {
382        find_release(crab, repo, tag, &ReleaseList::default()).await?
383    } else {
384        None
385    };
386    match existing {
387        Some(found) if !found.draft => {
388            if matches!(upload, PackageUpload::Shipped) {
389                require_tag_at(crab, repo, tag, sha).await?;
390            }
391            return Ok(found.html_url);
392        }
393        Some(draft) => {
394            require_tag_at(crab, repo, tag, sha).await?;
395            return finalize(crab, repo, release, &draft).await;
396        }
397        None => {}
398    }
399    let repos = crab.repos(&repo.owner, &repo.name);
400    let releases = repos.releases();
401    let create = releases.create(tag).name(name).body(body);
402    let create = match stage {
403        Stage::Stable => create,
404        Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
405    };
406    let created = create
407        .target_commitish(sha)
408        .send()
409        .await
410        .map_err(|error| release_error(error, tag, sha))?;
411    require_tag_at(crab, repo, tag, sha).await?;
412    Ok(created.html_url.to_string())
413}
414
415/// How long the tag proof waits before each read after the first, while
416/// GitHub answers 404 for a tag that publishing the draft created.
417/// Five reads over 15 seconds, inside the 30 seconds the release-tag-order
418/// spec allows: GitHub can serve a new tag a moment after the Release that
419/// created it, as in rawr run 43414046487.
420pub const TAG_PROOF_DELAYS: [Duration; 4] = [
421    Duration::from_secs(1),
422    Duration::from_secs(2),
423    Duration::from_secs(4),
424    Duration::from_secs(8),
425];
426
427/// What a run finds on GitHub for one release tag, before it writes
428/// anything.
429#[derive(Debug)]
430pub enum ExistingRelease {
431    /// A Release published at HEAD. The run opens no draft for it and proves
432    /// its tag. A mutable one takes the declared tarballs it lacks, so an
433    /// older release missing a target can still be finished.
434    Published(ReleaseRecord),
435    /// No published Release: the run opens a draft for the tag.
436    DraftState(DraftState),
437}
438
439impl ExistingRelease {
440    /// The asset names already on the Release the run uploads to, or `None`
441    /// for a published immutable Release, which takes no asset ([immutable
442    /// releases]). Its shortfall is reported, and nothing is uploaded.
443    ///
444    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
445    #[must_use]
446    pub fn uploaded(&self) -> Option<Vec<&str>> {
447        match self {
448            Self::Published(release) if release.immutable => None,
449            Self::Published(release) => Some(release.uploaded()),
450            Self::DraftState(draft) => Some(draft.uploaded()),
451        }
452    }
453}
454
455/// A tag with no published Release, and the draft a run finds for it.
456#[derive(Debug)]
457pub enum DraftState {
458    /// No Release exists for the tag.
459    Missing,
460    /// A draft at HEAD, which the run uploads to and publishes.
461    AtHead(ReleaseRecord),
462    /// A draft at another commit or at a branch name. Its tarballs were built
463    /// from other code, so the run deletes it and creates a draft at HEAD.
464    Stale(ReleaseRecord),
465}
466
467impl DraftState {
468    /// The asset names uploaded on the draft the run keeps. A stale draft is
469    /// deleted, so nothing on it counts.
470    #[must_use]
471    pub fn uploaded(&self) -> Vec<&str> {
472        match self {
473            Self::AtHead(draft) => draft.uploaded(),
474            Self::Missing | Self::Stale(_) => Vec::new(),
475        }
476    }
477}
478
479/// Read what GitHub has for `tag`: the tag and its Release, draft or
480/// published, so a run reads what to create before it writes anything.
481///
482/// A tag that exists must name `head`, whatever the Release's state: GitHub
483/// uses an existing tag when a draft is published, so a tag on another commit
484/// would fail the tag proof after the uploads.
485/// A published Release counts as at HEAD when its tag names `head`, or when
486/// GitHub serves no tag yet and the Release's `target_commitish` is `head`.
487/// A draft counts as at HEAD when its `target_commitish` is `head`, or when
488/// its tag names `head`.
489///
490/// The Releases list comes from `list`, which the run shares with its plan.
491///
492/// # Errors
493///
494/// Returns an error when the GitHub client cannot be built, when a lookup
495/// fails, when the tag names a commit other than `head`, or when a Release is
496/// published at another commit.
497pub fn read_release(
498    token: &str,
499    repo: &Repo,
500    tag: &str,
501    head: &str,
502    list: &ReleaseList,
503) -> Result<ExistingRelease> {
504    block(async {
505        let crab = client(token)?;
506        read_release_with(&crab, repo, tag, head, list).await
507    })
508}
509
510async fn read_release_with(
511    crab: &Octocrab,
512    repo: &Repo,
513    tag: &str,
514    head: &str,
515    list: &ReleaseList,
516) -> Result<ExistingRelease> {
517    let named = read_tag(crab, repo, tag).await?;
518    if let Some(named) = &named {
519        ensure!(
520            named.eq_ignore_ascii_case(head),
521            "tag {tag} names {named}, not HEAD {head}"
522        );
523    }
524    let Some(release) = find_release(crab, repo, tag, list).await? else {
525        return Ok(ExistingRelease::DraftState(DraftState::Missing));
526    };
527    let at_head = named.is_some() || release.target_commitish.eq_ignore_ascii_case(head);
528    if release.draft {
529        return Ok(ExistingRelease::DraftState(if at_head {
530            DraftState::AtHead(release)
531        } else {
532            DraftState::Stale(release)
533        }));
534    }
535    ensure!(
536        at_head,
537        "release {tag} is published at {target}, not HEAD {head}, and GitHub serves no tag {tag}",
538        target = release.target_commitish
539    );
540    Ok(ExistingRelease::Published(release))
541}
542
543/// The id of the draft for `release`: the one `found` names at HEAD, or a new
544/// draft with `target_commitish` set to `release.sha`.
545/// A stale draft is deleted first.
546///
547/// The draft creates no tag: GitHub creates it at `target_commitish` when the
548/// draft is published ([create a release]).
549/// Until then the draft can still be changed or deleted, so a failed upload
550/// leaves no tag behind.
551///
552/// # Errors
553///
554/// Returns an error when the GitHub client cannot be built, a stale draft
555/// cannot be deleted, or the draft cannot be created.
556/// A 403 on the create names the missing permission.
557///
558/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
559pub fn open_draft(
560    token: &str,
561    repo: &Repo,
562    release: &NewRelease<'_>,
563    found: &DraftState,
564) -> Result<u64> {
565    block(async {
566        let crab = client(token)?;
567        open_draft_with(&crab, repo, release, found).await
568    })
569}
570
571async fn open_draft_with(
572    crab: &Octocrab,
573    repo: &Repo,
574    release: &NewRelease<'_>,
575    found: &DraftState,
576) -> Result<u64> {
577    let NewRelease {
578        tag,
579        name,
580        body,
581        sha,
582        stage,
583        assets: _,
584    } = *release;
585    let repos = crab.repos(&repo.owner, &repo.name);
586    let releases = repos.releases();
587    match found {
588        DraftState::AtHead(draft) => return Ok(draft.id),
589        DraftState::Stale(draft) => releases.delete(draft.id).await.with_context(|| {
590            format!(
591                "delete the draft release {tag} at {target}",
592                target = draft.target_commitish
593            )
594        })?,
595        DraftState::Missing => {}
596    }
597    let create = releases
598        .create(tag)
599        .name(name)
600        .body(body)
601        .draft(true)
602        .target_commitish(sha);
603    let create = match stage {
604        Stage::Stable => create,
605        Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
606    };
607    let created = create
608        .send()
609        .await
610        .map_err(|error| release_error(error, tag, sha))?;
611    Ok(created.id.into_inner())
612}
613
614/// The HTML URL of the Release `id`, draft or published, which the report of
615/// a run that leaves the draft names.
616///
617/// # Errors
618///
619/// Returns an error when the GitHub client cannot be built or the Release
620/// cannot be read.
621pub fn release_url(token: &str, repo: &Repo, id: u64) -> Result<String> {
622    block(async {
623        let crab = client(token)?;
624        let release: ReleaseRecord = crab
625            .get(
626                format!(
627                    "/repos/{owner}/{name}/releases/{id}",
628                    owner = repo.owner,
629                    name = repo.name
630                ),
631                None::<&()>,
632            )
633            .await
634            .with_context(|| format!("read the release {id}"))?;
635        Ok(release.url().to_owned())
636    })
637}
638
639/// Publish the draft `id` for `release`, which creates its tag at
640/// `release.sha`, and return the Release URL.
641///
642/// The draft is read again first, so the check sees what GitHub has: a
643/// draft that lacks a declared asset is never published.
644///
645/// # Errors
646///
647/// Returns an error when the GitHub client cannot be built, the draft cannot
648/// be read or published, or it lacks a declared asset.
649pub fn publish_draft(
650    token: &str,
651    repo: &Repo,
652    release: &NewRelease<'_>,
653    id: u64,
654) -> Result<String> {
655    block(async {
656        let crab = client(token)?;
657        publish_draft_with(&crab, repo, release, id).await
658    })
659}
660
661async fn publish_draft_with(
662    crab: &Octocrab,
663    repo: &Repo,
664    release: &NewRelease<'_>,
665    id: u64,
666) -> Result<String> {
667    let draft: ReleaseRecord = crab
668        .get(
669            format!(
670                "/repos/{owner}/{name}/releases/{id}",
671                owner = repo.owner,
672                name = repo.name
673            ),
674            None::<&()>,
675        )
676        .await
677        .with_context(|| format!("read the draft release {}", release.tag))?;
678    finalize(crab, repo, release, &draft).await
679}
680
681/// Write `body` as the notes of draft `id` of `tag`, and nothing else, so
682/// the draft keeps its state: a failed run records why it stopped there.
683///
684/// # Errors
685///
686/// Returns an error when the GitHub client cannot be built or the update
687/// fails.
688pub fn write_draft_body(token: &str, repo: &Repo, tag: &str, id: u64, body: &str) -> Result<()> {
689    block(async {
690        let crab = client(token)?;
691        crab.repos(&repo.owner, &repo.name)
692            .releases()
693            .update(id)
694            .body(body)
695            .send()
696            .await
697            .with_context(|| format!("write the stop record into the draft release {tag}"))?;
698        Ok(())
699    })
700}
701
702/// Publish `draft` once every asset `release` declares is `uploaded` on it,
703/// and return its URL.
704///
705/// The update sends the title and notes this run has, `target_commitish`,
706/// and the settings its stage sets, so a draft someone edited reads as this
707/// run would have written it.
708/// A candidate stays a prerelease and never becomes the latest.
709/// A stable one sends `make_latest: legacy`, so GitHub decides by date and
710/// version, and an older version published late does not take the latest from
711/// a newer one ([update a release]).
712///
713/// [update a release]: https://docs.github.com/en/rest/releases/releases#update-a-release
714async fn finalize(
715    crab: &Octocrab,
716    repo: &Repo,
717    release: &NewRelease<'_>,
718    draft: &ReleaseRecord,
719) -> Result<String> {
720    let uploaded = draft.uploaded();
721    let missing: Vec<&str> = release
722        .assets
723        .iter()
724        .map(String::as_str)
725        .filter(|name| !uploaded.contains(name))
726        .collect();
727    ensure!(
728        missing.is_empty(),
729        "the draft release {tag} lacks {missing}, so it stays a draft; rerun release with them in --assets-dir, or with --skip-assets to publish it without them",
730        tag = draft.tag_name,
731        missing = missing.join(", ")
732    );
733    let repos = crab.repos(&repo.owner, &repo.name);
734    let releases = repos.releases();
735    let update = releases
736        .update(draft.id)
737        .name(release.name)
738        .body(release.body)
739        .target_commitish(release.sha)
740        .draft(false);
741    let update = match release.stage {
742        Stage::Stable => update.make_latest(MakeLatest::Legacy),
743        Stage::Candidate => update.prerelease(true).make_latest(MakeLatest::False),
744    };
745    let published = update
746        .send()
747        .await
748        .with_context(|| format!("publish the draft release {}", draft.tag_name))?;
749    Ok(published.html_url.to_string())
750}
751
752/// Prove that `tag` names `head`, reading it again after each of `delays`
753/// while GitHub answers 404.
754///
755/// Publishing a draft creates its tag, and GitHub can serve the tag a moment
756/// after the Release. Only a 404 is read again: any other error, and a tag
757/// that names another commit, fail at once.
758///
759/// # Errors
760///
761/// Returns an error when the GitHub client cannot be built, a read fails with
762/// anything but 404, the tag names a commit other than `head`, or every read
763/// answers 404. The last names the tag and the number of reads.
764pub fn prove_tag(
765    token: &str,
766    repo: &Repo,
767    tag: &str,
768    head: &str,
769    delays: &[Duration],
770) -> Result<()> {
771    block(async {
772        let crab = client(token)?;
773        prove_tag_with(&crab, repo, tag, head, delays).await
774    })
775}
776
777async fn prove_tag_with(
778    crab: &Octocrab,
779    repo: &Repo,
780    tag: &str,
781    head: &str,
782    delays: &[Duration],
783) -> Result<()> {
784    let mut waits = delays.iter();
785    let mut reads = 0_usize;
786    loop {
787        reads += 1;
788        if let Some(named) = read_tag(crab, repo, tag).await? {
789            ensure!(
790                named.eq_ignore_ascii_case(head),
791                "tag {tag} names {named}, not HEAD {head}"
792            );
793            return Ok(());
794        }
795        let Some(wait) = waits.next() else {
796            bail!(
797                "GitHub serves no tag {tag} after {reads} reads, though its Release is published; rerun release to read the tag again"
798            );
799        };
800        time::sleep(*wait).await;
801    }
802}
803
804/// The Release for a vendored set's `tag`, created at `sha` when the tag has
805/// none. Returns its HTML URL.
806///
807/// An existing Release is used as it is.
808/// Its tag records which commit built the first asset, and that commit is
809/// not a version commit, so the tag target is not checked.
810///
811/// A new Release is created with `make_latest: false`.
812/// GitHub otherwise makes every new published Release the latest of the
813/// repository ([create a release]).
814/// A vendored library must not displace the Release of the repository itself.
815///
816/// # Errors
817///
818/// Returns an error when the GitHub client cannot be built or when reading the
819/// Release fails with anything but 404.
820/// It also returns one when creating the Release fails for any reason other
821/// than another job having created it first.
822///
823/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
824pub fn ensure_vendored_release(
825    token: &str,
826    repo: &Repo,
827    tag: &str,
828    body: &str,
829    sha: &str,
830) -> Result<String> {
831    block(async {
832        let crab = client(token)?;
833        ensure_vendored_release_with(&crab, repo, tag, body, sha).await
834    })
835}
836
837/// Every target's job runs this, so two can find the Release missing at once.
838/// GitHub refuses one of them with `already_exists`, and that job reads the
839/// Release the other created.
840async fn ensure_vendored_release_with(
841    crab: &Octocrab,
842    repo: &Repo,
843    tag: &str,
844    body: &str,
845    sha: &str,
846) -> Result<String> {
847    let repos = crab.repos(&repo.owner, &repo.name);
848    let releases = repos.releases();
849    match releases.get_by_tag(tag).await {
850        Ok(release) => return Ok(release.html_url.to_string()),
851        Err(error) if is_not_found(&error) => {}
852        Err(error) => return Err(error).with_context(|| format!("read release {tag}")),
853    }
854    let created = releases
855        .create(tag)
856        .name(tag)
857        .body(body)
858        .target_commitish(sha)
859        .make_latest(MakeLatest::False)
860        .send()
861        .await;
862    match created {
863        Ok(release) => Ok(release.html_url.to_string()),
864        Err(error) if is_already_exists(&error) => {
865            let release = releases
866                .get_by_tag(tag)
867                .await
868                .with_context(|| format!("read release {tag}, which another job created"))?;
869            Ok(release.html_url.to_string())
870        }
871        Err(error) => Err(release_error(error, tag, sha)),
872    }
873}
874
875/// The hex SHA-256 that GitHub stores for asset `name` in the `tag` Release.
876/// It comes from the `digest` of the asset (`sha256:<hex>`, see
877/// [release assets]).
878/// Reading the digest from GitHub, instead of hashing a local file, keeps the
879/// checksum matching the stored asset.
880/// A rerun's build can differ in bytes from the one GitHub kept.
881///
882/// # Errors
883///
884/// Returns an error when the GitHub client cannot be built or the Release
885/// cannot be read.
886/// It also returns one when the Release does not list `name` or the asset has
887/// no SHA-256 digest.
888///
889/// [release assets]: https://docs.github.com/en/rest/releases/assets
890pub fn asset_sha256(token: &str, repo: &Repo, tag: &str, name: &str) -> Result<String> {
891    block(async {
892        let crab = client(token)?;
893        asset_sha256_with(&crab, repo, tag, name).await
894    })
895}
896
897async fn asset_sha256_with(crab: &Octocrab, repo: &Repo, tag: &str, name: &str) -> Result<String> {
898    let release = upload_target(crab, repo, Target::Tag(tag)).await?;
899    let asset = release
900        .assets
901        .iter()
902        .find(|asset| asset.name == name)
903        .with_context(|| format!("release {tag} does not list asset {name}"))?;
904    asset
905        .digest
906        .as_deref()
907        .and_then(|digest| digest.strip_prefix("sha256:"))
908        .map(str::to_owned)
909        .with_context(|| format!("GitHub reports no SHA-256 digest for asset {name} of {tag}"))
910}
911
912/// The names of the assets of the Release of `tag`, draft or published,
913/// whose upload completed.
914///
915/// # Errors
916///
917/// Returns an error when the GitHub client cannot be built, or when no
918/// Release exists for `tag`.
919pub fn uploaded_assets(token: &str, repo: &Repo, tag: &str) -> Result<Vec<String>> {
920    block(async {
921        let crab = client(token)?;
922        let release = upload_target(&crab, repo, Target::Tag(tag)).await?;
923        Ok(release.uploaded().into_iter().map(str::to_owned).collect())
924    })
925}
926
927/// A Release asset [`download_release_assets`] saved.
928#[derive(Debug)]
929#[non_exhaustive]
930pub struct AssetFile {
931    /// The asset's name, which is the file name it was saved under.
932    pub name: String,
933    /// Where it was saved.
934    pub path: PathBuf,
935    /// The SHA-256 GitHub reports for the stored file, in lowercase hex.
936    pub sha256: String,
937}
938
939/// How long one asset download may take.
940const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);
941
942/// Save each of `names` from the Release of `tag`, draft or published, into
943/// `dir` under its own name.
944///
945/// GitHub answers the asset API with a redirect to its storage. The token goes
946/// to GitHub only: the client follows no redirect itself, and fetches the
947/// storage URL without it ([release assets]).
948///
949/// # Errors
950///
951/// Returns an error when the GitHub client cannot be built, the Release does
952/// not exist or does not list one of `names`, or GitHub reports no SHA-256
953/// digest for one. It also returns one when a download fails or a file cannot
954/// be written.
955///
956/// [release assets]: https://docs.github.com/en/rest/releases/assets#get-a-release-asset
957pub fn download_release_assets(
958    token: &str,
959    repo: &Repo,
960    tag: &str,
961    names: &[&str],
962    dir: &Path,
963) -> Result<Vec<AssetFile>> {
964    block(async {
965        let crab = client(token)?;
966        download_release_assets_with(&crab, token, repo, tag, names, dir).await
967    })
968}
969
970async fn download_release_assets_with(
971    crab: &Octocrab,
972    token: &str,
973    repo: &Repo,
974    tag: &str,
975    names: &[&str],
976    dir: &Path,
977) -> Result<Vec<AssetFile>> {
978    let release = upload_target(crab, repo, Target::Tag(tag)).await?;
979    let http = reqwest::Client::builder()
980        .redirect(Policy::none())
981        .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
982        .timeout(DOWNLOAD_TIMEOUT)
983        .build()
984        .context("HTTP client")?;
985    let mut saved = Vec::new();
986    for name in names {
987        let asset = release
988            .assets
989            .iter()
990            .find(|asset| asset.name == *name)
991            .with_context(|| format!("release {tag} does not list asset {name}"))?;
992        ensure!(
993            !asset.url.is_empty(),
994            "GitHub reports no API URL for asset {name} of {tag}"
995        );
996        let sha256 = asset
997            .digest
998            .as_deref()
999            .and_then(|digest| digest.strip_prefix("sha256:"))
1000            .map(str::to_owned)
1001            .with_context(|| {
1002                format!("GitHub reports no SHA-256 digest for asset {name} of {tag}")
1003            })?;
1004        let body = download_asset(&http, token, &asset.url)
1005            .await
1006            .with_context(|| format!("download {name} from release {tag}"))?;
1007        let path = dir.join(name);
1008        fs::write(&path, &body).with_context(|| path.display().to_string())?;
1009        saved.push(AssetFile {
1010            name: (*name).to_owned(),
1011            path,
1012            sha256,
1013        });
1014    }
1015    Ok(saved)
1016}
1017
1018/// The bytes of the asset at `url`: its API URL with the token, then the
1019/// storage URL GitHub redirects to, without it. An error names `url` and
1020/// never the storage URL, whose query string signs the download.
1021async fn download_asset(http: &reqwest::Client, token: &str, url: &str) -> Result<bytes::Bytes> {
1022    use reqwest::header::{ACCEPT, LOCATION};
1023    let response = http
1024        .get(url)
1025        .bearer_auth(token)
1026        .header(ACCEPT, "application/octet-stream")
1027        .send()
1028        .await
1029        .with_context(|| format!("GET {url}"))?;
1030    let response = if response.status().is_redirection() {
1031        let location = response
1032            .headers()
1033            .get(LOCATION)
1034            .and_then(|value| value.to_str().ok())
1035            .with_context(|| format!("GET {url}: a redirect with no Location"))?
1036            .to_owned();
1037        http.get(location)
1038            .send()
1039            .await
1040            .map_err(reqwest::Error::without_url)
1041            .with_context(|| format!("GET the storage URL {url} redirects to"))?
1042    } else {
1043        response
1044    };
1045    let response = response
1046        .error_for_status()
1047        .map_err(reqwest::Error::without_url)
1048        .with_context(|| format!("GET {url}"))?;
1049    ensure!(
1050        response.status().is_success(),
1051        "GET {url}: unexpected status {}",
1052        response.status()
1053    );
1054    response
1055        .bytes()
1056        .await
1057        .map_err(reqwest::Error::without_url)
1058        .with_context(|| format!("read {url}"))
1059}
1060
1061/// Names the cause of GitHub's 403 for a new Release.
1062/// Creating a Release takes `contents: write`, plus `workflows: write` when
1063/// the commit the tag would point at has a `.github/workflows` tree that
1064/// differs from the default branch.
1065/// The `X-Accepted-GitHub-Permissions` header of the refusal lists both sets.
1066///
1067/// An Actions `GITHUB_TOKEN` can never carry `workflows`, so releasing an
1068/// older version commit fails once a later commit changes a workflow.
1069fn release_error(error: octocrab::Error, tag: &str, sha: &str) -> anyhow::Error {
1070    let forbidden = matches!(
1071        &error,
1072        octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 403
1073    );
1074    let error = anyhow::Error::new(error).context("create GitHub release");
1075    if forbidden {
1076        error.context(ReleaseRefused {
1077            tag: tag.to_owned(),
1078            sha: sha.to_owned(),
1079        })
1080    } else {
1081        error
1082    }
1083}
1084
1085/// GitHub's 403 on creating a Release.
1086/// The token lacks a permission the commit needs.
1087/// A rerun with a token that has the permission can still create the Release.
1088#[derive(Debug)]
1089struct ReleaseRefused {
1090    tag: String,
1091    sha: String,
1092}
1093
1094impl fmt::Display for ReleaseRefused {
1095    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096        write!(
1097            f,
1098            "GitHub refused to create {tag} at {sha}. When that commit's .github/workflows differ from the default branch, the Releases API also needs workflows: write, which GITHUB_TOKEN lacks; rerun verctl release at that commit with a token that has it",
1099            tag = self.tag,
1100            sha = self.sha
1101        )
1102    }
1103}
1104
1105async fn require_tag_at(crab: &Octocrab, repo: &Repo, tag: &str, sha: &str) -> Result<()> {
1106    let named = read_tag(crab, repo, tag)
1107        .await?
1108        .with_context(|| format!("tag {tag} does not exist"))?;
1109    ensure!(
1110        named.eq_ignore_ascii_case(sha),
1111        "tag {tag} names {named}, not the published commit {sha}"
1112    );
1113    Ok(())
1114}
1115
1116/// The commit `tag` names, peeled through an annotated tag, or `None` when
1117/// GitHub answers 404 for it.
1118#[expect(
1119    clippy::wildcard_enum_match_arm,
1120    reason = "octocrab's ref Object is non_exhaustive, so a catch-all arm is required"
1121)]
1122async fn read_tag(crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<String>> {
1123    let git_ref = match crab
1124        .repos(&repo.owner, &repo.name)
1125        .get_ref(&Reference::Tag(tag.to_owned()))
1126        .await
1127    {
1128        Ok(git_ref) => git_ref,
1129        Err(error) if is_not_found(&error) => return Ok(None),
1130        Err(error) => return Err(lookup_failed(error, format!("read tag {tag}"))),
1131    };
1132    match git_ref.object {
1133        Object::Commit { sha, url: _ } => Ok(Some(sha)),
1134        Object::Tag {
1135            sha: tag_sha,
1136            url: _,
1137        } => peel_tag(crab, repo, tag, &tag_sha).await.map(Some),
1138        other => bail!("tag {tag} names {other:?}, not a commit"),
1139    }
1140}
1141
1142#[derive(serde::Deserialize)]
1143struct TagTarget {
1144    object: PeeledTarget,
1145}
1146
1147#[derive(serde::Deserialize)]
1148struct PeeledTarget {
1149    sha: String,
1150}
1151
1152async fn peel_tag(crab: &Octocrab, repo: &Repo, tag: &str, tag_sha: &str) -> Result<String> {
1153    let peeled: TagTarget = crab
1154        .get(
1155            format!(
1156                "/repos/{owner}/{name}/git/tags/{tag_sha}",
1157                owner = repo.owner,
1158                name = repo.name
1159            ),
1160            None::<&()>,
1161        )
1162        .await
1163        .map_err(|error| lookup_failed(error, format!("peel tag {tag}")))?;
1164    Ok(peeled.object.sha)
1165}
1166
1167/// What GitHub has for one release tag.
1168///
1169/// Not `#[non_exhaustive]`: `verctl-release` constructs fixtures directly.
1170#[derive(Debug, Clone, Default, PartialEq, Eq)]
1171pub struct ReleaseState {
1172    /// The commit the tag names, peeled through an annotated tag. `None` when
1173    /// the tag does not exist.
1174    pub tag: Option<String>,
1175    /// Whether a Release exists for the tag, draft or published.
1176    pub release: bool,
1177    /// Whether that Release is a draft, which `release` publishes after its
1178    /// uploads.
1179    pub draft: bool,
1180    /// Whether GitHub keeps that Release immutable: once published, its
1181    /// assets and tag cannot change ([immutable releases]).
1182    ///
1183    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
1184    pub immutable: bool,
1185    /// The file names of the Release's assets whose upload completed.
1186    pub assets: Vec<String>,
1187    /// The stop record of a draft's body, which the last `release` run that
1188    /// failed an upload wrote. Display only; a published Release has none.
1189    pub stop: stop::Record,
1190}
1191
1192/// Read the tag and the Release for `tag`, so a plan can tell which parts of a
1193/// release still need doing.
1194/// The Release is read even when the tag is missing: a draft has no tag
1195/// until it is published, so a tagless draft is an incomplete release.
1196///
1197/// # Errors
1198///
1199/// Returns an error when the GitHub client cannot be built or when GitHub
1200/// answers a tag or Release lookup with an error other than 404.
1201/// It also returns one when the tag points at a tree or a blob.
1202///
1203/// Only a lookup that GitHub gave no answer to, meaning a transport failure
1204/// or a 5xx, is a [`lookup::Unavailable`].
1205/// A 401 from a bad token, a tag on a tree, and a malformed `GITHUB_API_URL`
1206/// stay unmarked.
1207///
1208/// The Releases list comes from `list`, so the lookups of one plan read it
1209/// once however many tags are missing.
1210pub fn release_state(
1211    token: &str,
1212    repo: &Repo,
1213    tag: &str,
1214    list: &ReleaseList,
1215) -> Result<ReleaseState> {
1216    block(async {
1217        let crab = client(token)?;
1218        release_state_with(&crab, repo, tag, list).await
1219    })
1220}
1221
1222async fn release_state_with(
1223    crab: &Octocrab,
1224    repo: &Repo,
1225    tag: &str,
1226    list: &ReleaseList,
1227) -> Result<ReleaseState> {
1228    let tag_sha = read_tag(crab, repo, tag).await?;
1229    let release = find_release(crab, repo, tag, list).await?;
1230    Ok(ReleaseState {
1231        tag: tag_sha,
1232        release: release.is_some(),
1233        draft: release.as_ref().is_some_and(|release| release.draft),
1234        immutable: release.as_ref().is_some_and(|release| release.immutable),
1235        assets: release
1236            .as_ref()
1237            .map_or_default(|release| release.uploaded().into_iter().map(str::to_owned).collect()),
1238        stop: release
1239            .as_ref()
1240            .filter(|release| release.draft)
1241            .map_or_default(|release| stop::read(release.body.as_deref().unwrap_or_default())),
1242    })
1243}
1244
1245/// `error` under `context`, marked as a [`lookup::Unavailable`] when GitHub
1246/// gave no answer.
1247/// That covers two cases.
1248/// The request failed in transport (DNS, connect, a timeout, a connection
1249/// dropped while the body was read).
1250/// Or GitHub answered with a 5xx or a rate limit after the retries of
1251/// octocrab.
1252/// [`lookup::no_answer`] separates those statuses from the rest.
1253///
1254/// Any other answer, such as a 401 or a plain 403, stays an error.
1255///
1256/// octocrab 0.54.5 turns every non-2xx answer into `GitHub` with its status
1257/// and headers, whatever the body contains.
1258/// Its `map_github_error` falls back to the body text when the body is not
1259/// GitHub JSON.
1260/// An HTML 502 from a proxy therefore keeps its status.
1261///
1262/// A transport failure reaches octocrab as `Service` from the HTTP client.
1263/// It also arrives as `Hyper` while octocrab reads a body, alone or inside
1264/// `Service`.
1265/// `Service` also carries a request that the client blocks before sending.
1266/// It counts only when an I/O or body error caused it.
1267fn lookup_failed(error: octocrab::Error, context: String) -> anyhow::Error {
1268    let refused = matches!(&error, octocrab::Error::GitHub { source, backtrace: _ }
1269    if lookup::no_answer(
1270        source.status_code.as_u16(),
1271        source
1272            .headers
1273            .as_ref()
1274            .and_then(|headers| headers.get("x-ratelimit-remaining"))
1275            .map(HeaderValue::as_bytes),
1276    ));
1277    let body = matches!(
1278        &error,
1279        octocrab::Error::Hyper {
1280            source: _,
1281            backtrace: _
1282        }
1283    );
1284    let service = matches!(
1285        &error,
1286        octocrab::Error::Service {
1287            source: _,
1288            backtrace: _
1289        }
1290    );
1291    let error = anyhow::Error::new(error);
1292    let transport = service
1293        && error.chain().any(|cause| {
1294            cause.is::<io::Error>()
1295                || matches!(
1296                    cause.downcast_ref::<octocrab::Error>(),
1297                    Some(octocrab::Error::Hyper {
1298                        source: _,
1299                        backtrace: _
1300                    })
1301                )
1302        });
1303    let error = error.context(context);
1304    if refused || body || transport {
1305        lookup::unavailable(error)
1306    } else {
1307        error
1308    }
1309}
1310
1311fn is_not_found(error: &octocrab::Error) -> bool {
1312    matches!(error, octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 404)
1313}
1314
1315/// The part of a Release verctl reads, draft or published.
1316#[derive(Debug, Clone, serde::Deserialize)]
1317pub struct ReleaseRecord {
1318    id: u64,
1319    html_url: String,
1320    tag_name: String,
1321    /// The commit or branch the tag is created at when the Release is
1322    /// published. GitHub reports it for every Release. A server that does not
1323    /// report it names no commit, so a draft without it is stale.
1324    #[serde(default)]
1325    target_commitish: String,
1326    draft: bool,
1327    /// Reported by GitHub for every Release. A server that does not report
1328    /// it keeps the Release mutable.
1329    #[serde(default)]
1330    immutable: bool,
1331    /// The notes. GitHub reports `null` for a Release with none.
1332    #[serde(default)]
1333    body: Option<String>,
1334    assets: Vec<ForgeAsset>,
1335}
1336
1337impl ReleaseRecord {
1338    /// The Release's id.
1339    #[must_use]
1340    pub const fn id(&self) -> u64 {
1341        self.id
1342    }
1343
1344    /// The Release's HTML URL.
1345    #[must_use]
1346    pub fn url(&self) -> &str {
1347        &self.html_url
1348    }
1349
1350    /// The names of the assets whose upload completed.
1351    #[must_use]
1352    pub fn uploaded(&self) -> Vec<&str> {
1353        self.assets
1354            .iter()
1355            .filter(|asset| asset.state == "uploaded")
1356            .map(|asset| asset.name.as_str())
1357            .collect()
1358    }
1359}
1360
1361#[derive(Debug, Clone, serde::Deserialize)]
1362struct ForgeAsset {
1363    name: String,
1364    /// The asset's API URL, which serves the file to a token that can read
1365    /// the Release, a draft's included. GitHub reports it for every asset.
1366    #[serde(default)]
1367    url: String,
1368    /// `uploaded` once GitHub has the whole file; an upload that broke off
1369    /// leaves the asset in another state.
1370    state: String,
1371    /// `sha256:<hex>` of the stored file. GitHub reports `null` for an asset
1372    /// it contains no digest for.
1373    #[serde(default)]
1374    digest: Option<String>,
1375}
1376
1377/// Releases read per page; GitHub's maximum.
1378const RELEASES_PER_PAGE: usize = 100;
1379
1380/// Pages of Releases a lookup reads before it stops, so a repository with
1381/// thousands of Releases costs ten requests instead of one per page.
1382/// A draft verctl creates is the newest Release, so it is on the first page.
1383const MAX_RELEASE_PAGES: u32 = 10;
1384
1385/// The Releases of a repository as `GET /releases` lists them, drafts
1386/// included, read at most once.
1387///
1388/// A run looks up several tags, and a draft has no tag until it is
1389/// published, so each missing tag would otherwise read the list again, up to
1390/// ten pages each. The caller has one for the lookups
1391/// of a run, before it writes anything: a Release the run creates afterwards
1392/// is not in it.
1393#[derive(Debug, Default)]
1394pub struct ReleaseList {
1395    listed: OnceCell<Vec<ReleaseRecord>>,
1396}
1397
1398impl ReleaseList {
1399    /// The newest Release the list contains for `tag`, reading the list first
1400    /// when no lookup has yet.
1401    async fn find(&self, crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<ReleaseRecord>> {
1402        let listed = if let Some(listed) = self.listed.get() {
1403            listed
1404        } else {
1405            let read = list_releases(crab, repo).await?;
1406            self.listed.get_or_init(|| read)
1407        };
1408        Ok(listed
1409            .iter()
1410            .find(|release| release.tag_name == tag)
1411            .cloned())
1412    }
1413}
1414
1415/// Every Release `GET /releases` lists, newest first, which shows drafts to
1416/// a token with push access ([list releases]), up to [`MAX_RELEASE_PAGES`]
1417/// pages.
1418/// A draft verctl creates is the newest Release, so it is on the first page;
1419/// a draft older than the newest 1000 Releases is not found.
1420///
1421/// [list releases]: https://docs.github.com/en/rest/releases/releases#list-releases
1422async fn list_releases(crab: &Octocrab, repo: &Repo) -> Result<Vec<ReleaseRecord>> {
1423    let mut listed = Vec::new();
1424    for page in 1..=MAX_RELEASE_PAGES {
1425        let releases: Vec<ReleaseRecord> = crab
1426            .get(
1427                format!(
1428                    "/repos/{owner}/{name}/releases?per_page={RELEASES_PER_PAGE}&page={page}",
1429                    owner = repo.owner,
1430                    name = repo.name
1431                ),
1432                None::<&()>,
1433            )
1434            .await
1435            .map_err(|error| lookup_failed(error, "list releases".to_owned()))?;
1436        let last = releases.len() < RELEASES_PER_PAGE;
1437        listed.extend(releases);
1438        if last {
1439            break;
1440        }
1441    }
1442    Ok(listed)
1443}
1444
1445/// The Release for `tag`, draft or published, or `None`.
1446///
1447/// `GET /releases/tags/{tag}` answers for a published Release in one
1448/// request, even when GitHub serves its new tag a moment later. It returns
1449/// 404 for a draft ([get a release by tag name]), and only then is the tag
1450/// looked up in `list`, which a draft is in: a draft has no tag until it is
1451/// published.
1452///
1453/// [get a release by tag name]: https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name
1454async fn find_release(
1455    crab: &Octocrab,
1456    repo: &Repo,
1457    tag: &str,
1458    list: &ReleaseList,
1459) -> Result<Option<ReleaseRecord>> {
1460    let published: Result<ReleaseRecord, _> = crab
1461        .get(
1462            format!(
1463                "/repos/{owner}/{name}/releases/tags/{tag}",
1464                owner = repo.owner,
1465                name = repo.name
1466            ),
1467            None::<&()>,
1468        )
1469        .await;
1470    match published {
1471        Ok(found) => return Ok(Some(found)),
1472        Err(error) if is_not_found(&error) => {}
1473        Err(error) => return Err(lookup_failed(error, format!("get release {tag}"))),
1474    }
1475    list.find(crab, repo, tag).await
1476}
1477
1478/// Attach `tarball` to the release for `tag`.
1479///
1480/// Returns the download URL, or `already <name>` when GitHub refuses the
1481/// upload because the release already has a complete asset of that name.
1482/// The run that got there first, or an earlier attempt of this one, uploaded
1483/// it.
1484///
1485/// # Errors
1486///
1487/// Returns an error when:
1488///
1489/// - `tarball` has no UTF-8 file name or cannot be read.
1490/// - The GitHub client cannot be built.
1491/// - The release for `tag` does not exist.
1492/// - The asset of that name exists but its upload does not complete within a
1493///   minute.
1494/// - The upload fails for a reason other than a duplicate asset.
1495pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
1496    upload(token, repo, Target::Tag(tag), tarball)
1497}
1498
1499/// [`upload_release_asset`] to the Release `id` of `tag`, which this run
1500/// opened or found, so the upload never looks the Release up by its tag
1501/// again: two drafts can share a tag name.
1502///
1503/// # Errors
1504///
1505/// Returns the errors of [`upload_release_asset`], with the Release read by
1506/// its id.
1507pub fn upload_to_release(
1508    token: &str,
1509    repo: &Repo,
1510    id: u64,
1511    tag: &str,
1512    tarball: &Path,
1513) -> Result<String> {
1514    upload(token, repo, Target::Id { id, tag }, tarball)
1515}
1516
1517fn upload(token: &str, repo: &Repo, target: Target<'_>, tarball: &Path) -> Result<String> {
1518    let name = tarball
1519        .file_name()
1520        .and_then(|name| name.to_str())
1521        .context("asset name")?
1522        .to_owned();
1523    let body =
1524        bytes::Bytes::from(fs::read(tarball).with_context(|| tarball.display().to_string())?);
1525    block(async {
1526        let crab = client(token)?;
1527        upload_release_asset_with(&crab, repo, target, &name, body, &UPLOAD_SETTLE_DELAYS).await
1528    })
1529}
1530
1531/// How long an upload refused as a duplicate waits for the other upload to
1532/// finish. GitHub lists an asset as soon as its upload starts, in a state
1533/// other than `uploaded`. A tarball of a few megabytes uploads in seconds, so a
1534/// minute covers a run that lost the race while the winner was still sending.
1535const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];
1536
1537/// The Release an upload or a checksum reads.
1538#[derive(Debug, Clone, Copy)]
1539enum Target<'a> {
1540    /// The Release found by its tag, draft or published.
1541    Tag(&'a str),
1542    /// The Release `id` of `tag`, which the run uses.
1543    Id {
1544        /// The Release id.
1545        id: u64,
1546        /// Its tag, for the messages.
1547        tag: &'a str,
1548    },
1549}
1550
1551/// The Release `target` names.
1552async fn upload_target(crab: &Octocrab, repo: &Repo, target: Target<'_>) -> Result<ReleaseRecord> {
1553    match target {
1554        Target::Tag(tag) => find_release(crab, repo, tag, &ReleaseList::default())
1555            .await?
1556            .with_context(|| format!("release {tag} does not exist")),
1557        Target::Id { id, tag } => crab
1558            .get(
1559                format!(
1560                    "/repos/{owner}/{name}/releases/{id}",
1561                    owner = repo.owner,
1562                    name = repo.name
1563                ),
1564                None::<&()>,
1565            )
1566            .await
1567            .with_context(|| format!("read release {tag} (id {id})")),
1568    }
1569}
1570
1571async fn upload_release_asset_with(
1572    crab: &Octocrab,
1573    repo: &Repo,
1574    target: Target<'_>,
1575    name: &str,
1576    body: bytes::Bytes,
1577    settle: &[Duration],
1578) -> Result<String> {
1579    let tag = match target {
1580        Target::Tag(tag) | Target::Id { tag, id: _ } => tag,
1581    };
1582    let release = upload_target(crab, repo, target).await?;
1583    if release.uploaded().contains(&name) {
1584        return Ok(format!("already {name}"));
1585    }
1586    let uploaded = crab
1587        .repos(&repo.owner, &repo.name)
1588        .releases()
1589        .upload_asset(release.id, name, body)
1590        .send()
1591        .await;
1592    match uploaded {
1593        Ok(asset) => Ok(asset.browser_download_url.to_string()),
1594        // Two runs can release the same commit, and both build every asset.
1595        // The tarballs differ in bytes (tar records file times), so a digest
1596        // cannot separate a duplicate from a mismatch. The name carries the
1597        // version and the target, and the tag fixes the commit, so a complete
1598        // asset of that name is this asset.
1599        Err(error) if is_already_exists(&error) => {
1600            let mut delays = settle.iter();
1601            loop {
1602                let release = upload_target(crab, repo, target).await?;
1603                let asset = release
1604                    .assets
1605                    .iter()
1606                    .find(|asset| asset.name == name)
1607                    .with_context(|| {
1608                        format!(
1609                            "GitHub reports asset {name} exists, but release {tag} does not list it"
1610                        )
1611                    })?;
1612                if asset.state == "uploaded" {
1613                    return Ok(format!("already {name}"));
1614                }
1615                let Some(delay) = delays.next() else {
1616                    bail!(
1617                        "release {tag} has asset {name} in state {:?}, not uploaded, after waiting for another upload to finish; delete the asset and rerun",
1618                        asset.state
1619                    );
1620                };
1621                time::sleep(*delay).await;
1622            }
1623        }
1624        Err(error) => Err(error).context("upload release asset"),
1625    }
1626}
1627
1628/// GitHub's 422 for an upload whose name the release already has, from
1629/// [upload a release asset].
1630/// The code is only in the error's body: octocrab displays a GitHub error as
1631/// "GitHub", so its text never names it.
1632///
1633/// [upload a release asset]: https://docs.github.com/en/rest/releases/assets#upload-a-release-asset
1634fn is_already_exists(error: &octocrab::Error) -> bool {
1635    matches!(error, octocrab::Error::GitHub { source, backtrace: _ }
1636    if source.status_code.as_u16() == 422
1637        && source.errors.iter().flatten().any(|detail| {
1638            detail.get("code").and_then(serde_json::Value::as_str) == Some("already_exists")
1639        }))
1640}
1641
1642/// Who opened a pull request, and where its head branch lives.
1643#[derive(Debug, Clone, PartialEq, Eq)]
1644pub struct PullAuthor {
1645    /// The author's login.
1646    pub login: String,
1647    /// GitHub's user `type`: `User` for a person, `Bot` for an app.
1648    pub kind: String,
1649    /// The head branch lives outside the repository: a fork, or a branch that
1650    /// GitHub has dropped. Maintainers push branches to the repository itself.
1651    pub from_fork: bool,
1652}
1653
1654/// The author of pull request `number`, from
1655/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
1656///
1657/// # Errors
1658///
1659/// Returns an error when the GitHub client cannot be built or the request or
1660/// its decoding fails, for example when pull request `number` does not exist.
1661///
1662/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
1663pub fn pull_author(token: &str, repo: &Repo, number: u64) -> Result<PullAuthor> {
1664    block(async {
1665        let crab = client(token)?;
1666        pull_author_with(&crab, repo, number).await
1667    })
1668}
1669
1670async fn pull_author_with(crab: &Octocrab, repo: &Repo, number: u64) -> Result<PullAuthor> {
1671    #[derive(serde::Deserialize)]
1672    struct User {
1673        login: String,
1674        #[serde(rename = "type")]
1675        kind: String,
1676    }
1677    #[derive(serde::Deserialize)]
1678    struct HeadRepo {
1679        full_name: String,
1680    }
1681    #[derive(serde::Deserialize)]
1682    struct Head {
1683        repo: Option<HeadRepo>,
1684    }
1685    #[derive(serde::Deserialize)]
1686    struct Pull {
1687        user: User,
1688        head: Head,
1689    }
1690    let route = format!("/repos/{}/{}/pulls/{number}", repo.owner, repo.name);
1691    let pull: Pull = crab
1692        .get(route, None::<&()>)
1693        .await
1694        .with_context(|| format!("read pull request #{number}"))?;
1695    let own = format!("{}/{}", repo.owner, repo.name);
1696    Ok(PullAuthor {
1697        login: pull.user.login,
1698        kind: pull.user.kind,
1699        from_fork: pull
1700            .head
1701            .repo
1702            .is_none_or(|head| !head.full_name.eq_ignore_ascii_case(&own)),
1703    })
1704}
1705
1706/// A workflow run that has not ended.
1707#[derive(Debug, Clone, PartialEq, Eq)]
1708#[non_exhaustive]
1709pub struct ActiveRun {
1710    /// The run's page on GitHub.
1711    pub url: String,
1712}
1713
1714/// The first run of the workflow file `workflow` at commit `sha` that has not
1715/// ended, from `GET /repos/{owner}/{repo}/actions/workflows/{workflow}/runs`
1716/// with `head_sha` ([list workflow runs]). The first 100 runs of that commit
1717/// are read, and the commit is checked again on each, so a server that
1718/// ignores the filter finds no run for another commit.
1719///
1720/// A run has not ended unless its `status` is `completed`, so a status GitHub
1721/// adds later, or none at all, counts as running.
1722///
1723/// # Errors
1724///
1725/// Returns an error when the GitHub client cannot be built or the request or
1726/// its decoding fails, for example when no workflow file has that name. Only
1727/// a lookup that GitHub gave no answer to is a [`lookup::Unavailable`].
1728///
1729/// [list workflow runs]: https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow
1730pub fn active_run(
1731    token: &str,
1732    repo: &Repo,
1733    workflow: &str,
1734    sha: &str,
1735) -> Result<Option<ActiveRun>> {
1736    #[derive(serde::Deserialize)]
1737    struct Run {
1738        html_url: String,
1739        head_sha: String,
1740        status: Option<String>,
1741    }
1742    #[derive(serde::Deserialize)]
1743    struct Runs {
1744        workflow_runs: Vec<Run>,
1745    }
1746    block(async {
1747        let crab = client(token)?;
1748        let runs: Runs = crab
1749            .get(
1750                format!(
1751                    "/repos/{owner}/{name}/actions/workflows/{workflow}/runs?head_sha={sha}&per_page=100",
1752                    owner = repo.owner,
1753                    name = repo.name
1754                ),
1755                None::<&()>,
1756            )
1757            .await
1758            .map_err(|error| lookup_failed(error, format!("list the runs of {workflow}")))?;
1759        Ok(runs
1760            .workflow_runs
1761            .into_iter()
1762            .find(|run| {
1763                run.head_sha.eq_ignore_ascii_case(sha) && run.status.as_deref() != Some("completed")
1764            })
1765            .map(|run| ActiveRun { url: run.html_url }))
1766    })
1767}
1768
1769/// The labels of pull request `number`, from
1770/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
1771///
1772/// # Errors
1773///
1774/// Returns an error when the GitHub client cannot be built or the request or
1775/// its decoding fails, for example when pull request `number` does not exist.
1776///
1777/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
1778pub fn pull_labels(token: &str, repo: &Repo, number: u64) -> Result<Vec<String>> {
1779    #[derive(serde::Deserialize)]
1780    struct Label {
1781        name: String,
1782    }
1783    #[derive(serde::Deserialize)]
1784    struct Pull {
1785        labels: Vec<Label>,
1786    }
1787    block(async {
1788        let crab = client(token)?;
1789        let pull: Pull = crab
1790            .get(
1791                format!(
1792                    "/repos/{owner}/{name}/pulls/{number}",
1793                    owner = repo.owner,
1794                    name = repo.name
1795                ),
1796                None::<&()>,
1797            )
1798            .await
1799            .with_context(|| format!("read pull request #{number}"))?;
1800        Ok(pull.labels.into_iter().map(|label| label.name).collect())
1801    })
1802}
1803
1804/// The `type` of each rule that applies to `branch`, from
1805/// `GET /repos/{owner}/{repo}/rules/branches/{branch}` ([get rules for a
1806/// branch]). The list is empty when no rule applies.
1807///
1808/// # Errors
1809///
1810/// Returns an error when the GitHub client cannot be built or the request or
1811/// its decoding fails, including the 403 and 404 answers of a token that
1812/// cannot read the rules.
1813///
1814/// [get rules for a branch]: https://docs.github.com/en/rest/repos/rules#get-rules-for-a-branch
1815pub fn branch_rule_types(token: &str, repo: &Repo, branch: &str) -> Result<Vec<String>> {
1816    #[derive(serde::Deserialize)]
1817    struct Rule {
1818        #[serde(rename = "type")]
1819        kind: String,
1820    }
1821    block(async {
1822        let crab = client(token)?;
1823        let rules: Vec<Rule> = crab
1824            .get(
1825                format!(
1826                    "/repos/{owner}/{name}/rules/branches/{branch}",
1827                    owner = repo.owner,
1828                    name = repo.name
1829                ),
1830                None::<&()>,
1831            )
1832            .await
1833            .with_context(|| format!("read the rules of {branch}"))?;
1834        Ok(rules.into_iter().map(|rule| rule.kind).collect())
1835    })
1836}
1837
1838/// A GitHub client for `token`.
1839/// It uses the API from `GITHUB_API_URL` when that is set, as on a GitHub
1840/// Enterprise Server or a test's mock server.
1841/// Otherwise it uses api.github.com.
1842fn client(token: &str) -> Result<Octocrab> {
1843    let mut builder = Octocrab::builder().personal_token(token.to_owned());
1844    if let Ok(base) = env::var("GITHUB_API_URL")
1845        && !base.is_empty()
1846    {
1847        builder = builder.base_uri(base).context("GITHUB_API_URL")?;
1848    }
1849    builder.build().context("GitHub client")
1850}
1851
1852/// Run one future to completion on a fresh current-thread runtime, so the
1853/// blocking command handlers can call async clients.
1854/// Request a GitHub Actions OIDC JWT from `request_url` for `audience`, using
1855/// bearer `request_token`, without exposing the token or URL query string in
1856/// any error message.
1857///
1858/// # Errors
1859///
1860/// Returns an error when the HTTP client cannot be built, the request fails,
1861/// or the JSON body contains no `value` token field.
1862pub fn fetch_oidc_token(
1863    request_url: &str,
1864    request_token: &str,
1865    audience: &str,
1866    url_env_name: &str,
1867    timeout: Duration,
1868) -> Result<String> {
1869    #[derive(serde::Deserialize)]
1870    struct Issued {
1871        value: String,
1872    }
1873    block(async {
1874        let http = reqwest::Client::builder()
1875            .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
1876            .timeout(timeout)
1877            .build()
1878            .context("HTTP client")?;
1879        let separator = if request_url.contains('?') { '&' } else { '?' };
1880        let response = http
1881            .get(format!("{request_url}{separator}audience={audience}"))
1882            .bearer_auth(request_token)
1883            .send()
1884            .await
1885            .and_then(reqwest::Response::error_for_status)
1886            .map_err(reqwest::Error::without_url)
1887            .with_context(|| format!("request the OIDC token from {url_env_name}"))?;
1888        let body = response
1889            .bytes()
1890            .await
1891            .map_err(reqwest::Error::without_url)
1892            .with_context(|| format!("read the OIDC token from {url_env_name}"))?;
1893        let issued: Issued = serde_json::from_slice(&body)
1894            .ok()
1895            .with_context(|| format!("the answer of {url_env_name} has no OIDC token"))?;
1896        Ok(issued.value)
1897    })
1898}
1899
1900fn block<F, T>(fut: F) -> Result<T>
1901where
1902    F: Future<Output = Result<T>>,
1903{
1904    Builder::new_current_thread()
1905        .enable_all()
1906        .build()
1907        .context("tokio")?
1908        .block_on(fut)
1909}
1910
1911#[cfg(test)]
1912mod tests {
1913    use std::fs;
1914    use std::time::Duration;
1915
1916    use indoc::indoc;
1917    use octocrab::service::middleware::retry::RetryConfig;
1918    use verctl_core::stop::{Record, Stop};
1919    use wiremock::matchers::{body_partial_json, header, method, path, path_regex, query_param};
1920    use wiremock::{Mock, MockServer, ResponseTemplate};
1921
1922    use super::{Octocrab, ReleaseList, parse_remote, parse_slug};
1923
1924    #[test]
1925    fn slug_and_remotes() {
1926        let expected = super::Repo {
1927            owner: "victor-software-house".into(),
1928            name: "verctl".into(),
1929        };
1930        assert_eq!(
1931            parse_slug("victor-software-house/verctl").unwrap(),
1932            expected
1933        );
1934        assert_eq!(
1935            parse_remote("https://github.com/victor-software-house/verctl.git").unwrap(),
1936            expected
1937        );
1938        assert_eq!(
1939            parse_remote("git@github.com:victor-software-house/verctl.git").unwrap(),
1940            expected
1941        );
1942        assert_eq!(
1943            parse_remote("ssh://git@github.com/victor-software-house/verctl.git").unwrap(),
1944            expected
1945        );
1946    }
1947
1948    #[test]
1949    fn pull_request_number_reads_only_a_pull_request_event() {
1950        assert_eq!(
1951            super::pull_request_number(r#"{"pull_request":{"number":187,"labels":[]}}"#),
1952            Some(187)
1953        );
1954        assert_eq!(super::pull_request_number("{}"), None);
1955        assert_eq!(super::pull_request_number("not json"), None);
1956        assert_eq!(
1957            super::pull_request_number(r#"{"issue":{"number":187}}"#),
1958            None
1959        );
1960    }
1961
1962    #[test]
1963    fn is_merge_group_reads_only_a_merge_group_event() {
1964        assert!(super::is_merge_group(
1965            r#"{"action":"checks_requested","merge_group":{"head_ref":"refs/heads/gh-readonly-queue/main/pr-7-0000000000000000000000000000000000000001"}}"#
1966        ));
1967        assert!(!super::is_merge_group(r#"{"pull_request":{"number":7}}"#));
1968        assert!(!super::is_merge_group(r#"{"merge_group":null}"#));
1969        assert!(!super::is_merge_group("not json"));
1970    }
1971
1972    #[test]
1973    fn default_branch_of_reads_the_event_repository() {
1974        assert_eq!(
1975            super::default_branch_of(
1976                r#"{"pull_request":{"number":1},"repository":{"default_branch":"main"}}"#
1977            ),
1978            Some("main".to_owned())
1979        );
1980        assert_eq!(
1981            super::default_branch_of(r#"{"repository":{"default_branch":""}}"#),
1982            None
1983        );
1984        assert_eq!(super::default_branch_of("{}"), None);
1985        assert_eq!(super::default_branch_of("not json"), None);
1986    }
1987
1988    async fn pull_author_from(head: serde_json::Value) -> super::PullAuthor {
1989        let server = MockServer::start().await;
1990        Mock::given(method("GET"))
1991            .and(path(format!("/repos/{OWNER}/{NAME}/pulls/12")))
1992            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1993                "number": 12,
1994                "user": { "login": "octo", "type": "User" },
1995                "head": head
1996            })))
1997            .mount(&server)
1998            .await;
1999        super::pull_author_with(&crab(&server.uri()), &repo(), 12)
2000            .await
2001            .unwrap()
2002    }
2003
2004    #[tokio::test]
2005    async fn a_fork_head_is_a_fork() {
2006        let author =
2007            pull_author_from(serde_json::json!({ "repo": { "full_name": "octo/app" } })).await;
2008        assert_eq!(author.login, "octo");
2009        assert_eq!(author.kind, "User");
2010        assert!(author.from_fork);
2011    }
2012
2013    #[tokio::test]
2014    async fn a_head_in_the_repository_is_not_a_fork() {
2015        let author = pull_author_from(serde_json::json!({
2016            "repo": { "full_name": format!("{OWNER}/{NAME}") }
2017        }))
2018        .await;
2019        assert!(!author.from_fork);
2020    }
2021
2022    #[tokio::test]
2023    async fn a_deleted_fork_is_a_fork() {
2024        let author = pull_author_from(serde_json::json!({ "repo": null })).await;
2025        assert!(author.from_fork);
2026    }
2027
2028    #[test]
2029    fn rejects_non_github() {
2030        parse_remote("https://gitlab.com/acme/app.git").unwrap_err();
2031    }
2032
2033    const OWNER: &str = "acme";
2034    const NAME: &str = "app";
2035    const TAG: &str = "v1.0.0";
2036    const PUBLISHED: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
2037    const OTHER: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
2038    const TAG_OBJECT: &str = "cccccccccccccccccccccccccccccccccccccccc";
2039
2040    fn repo() -> super::Repo {
2041        super::Repo {
2042            owner: OWNER.into(),
2043            name: NAME.into(),
2044        }
2045    }
2046
2047    fn crab(uri: &str) -> Octocrab {
2048        Octocrab::builder()
2049            .personal_token("token".to_owned())
2050            .base_uri(uri)
2051            .unwrap()
2052            .build()
2053            .unwrap()
2054    }
2055
2056    fn missing_release() -> Mock {
2057        Mock::given(method("GET"))
2058            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
2059            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
2060                "message": "Not Found",
2061                "documentation_url": "https://docs.github.com"
2062            })))
2063    }
2064
2065    /// `GET /releases`, the only listing that shows drafts. The lookup reads
2066    /// it when `GET /releases/tags/{tag}` answers 404.
2067    fn listed_releases(listed: serde_json::Value) -> Mock {
2068        Mock::given(method("GET"))
2069            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2070            .respond_with(ResponseTemplate::new(200).set_body_json(listed))
2071    }
2072
2073    fn no_releases_listed() -> Mock {
2074        listed_releases(serde_json::json!([]))
2075    }
2076
2077    fn existing_release() -> Mock {
2078        Mock::given(method("GET"))
2079            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
2080            .respond_with(ResponseTemplate::new(200).set_body_json(release_json("main")))
2081    }
2082
2083    /// A draft that contains `assets`, each a name and the state GitHub
2084    /// reports.
2085    fn draft_json(assets: &[(&str, &str)]) -> serde_json::Value {
2086        let mut json = release_json(PUBLISHED);
2087        json["draft"] = true.into();
2088        json["html_url"] =
2089            format!("https://github.com/{OWNER}/{NAME}/releases/tag/untagged-1").into();
2090        json["assets"] = assets
2091            .iter()
2092            .map(|(name, state)| serde_json::json!({ "name": name, "state": state }))
2093            .collect();
2094        json
2095    }
2096
2097    fn declared() -> Vec<String> {
2098        vec![
2099            "app.pkg".to_owned(),
2100            "app_1.0.0_linux_x64.tar.gz".to_owned(),
2101        ]
2102    }
2103
2104    /// `stable()` with the assets `declared()` names.
2105    fn with_assets(declared: &[String]) -> super::NewRelease<'_> {
2106        super::NewRelease {
2107            assets: declared,
2108            ..stable()
2109        }
2110    }
2111
2112    fn create_tag_ref() -> Mock {
2113        Mock::given(method("POST"))
2114            .and(path(format!("/repos/{OWNER}/{NAME}/git/refs")))
2115            .and(body_partial_json(serde_json::json!({
2116                "ref": format!("refs/tags/{TAG}"),
2117                "sha": PUBLISHED
2118            })))
2119            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
2120                "ref": format!("refs/tags/{TAG}"),
2121                "node_id": "R",
2122                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
2123                "object": {
2124                    "type": "commit",
2125                    "sha": PUBLISHED,
2126                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{PUBLISHED}")
2127                }
2128            })))
2129    }
2130
2131    fn create_draft() -> Mock {
2132        Mock::given(method("POST"))
2133            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2134            .and(body_partial_json(serde_json::json!({
2135                "tag_name": TAG,
2136                "draft": true,
2137                "target_commitish": PUBLISHED
2138            })))
2139            .respond_with(ResponseTemplate::new(201).set_body_json(draft_json(&[])))
2140    }
2141
2142    fn publish_draft() -> wiremock::MockBuilder {
2143        Mock::given(method("PATCH"))
2144            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
2145            .and(body_partial_json(serde_json::json!({ "draft": false })))
2146    }
2147
2148    fn create_at_published_sha() -> Mock {
2149        Mock::given(method("POST"))
2150            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2151            .and(body_partial_json(serde_json::json!({
2152                "tag_name": TAG,
2153                "target_commitish": PUBLISHED
2154            })))
2155            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
2156    }
2157
2158    fn stable() -> super::NewRelease<'static> {
2159        super::NewRelease {
2160            tag: TAG,
2161            name: TAG,
2162            body: "notes",
2163            sha: PUBLISHED,
2164            stage: super::Stage::Stable,
2165            assets: &[],
2166        }
2167    }
2168
2169    fn lightweight_tag(sha: &str) -> Mock {
2170        Mock::given(method("GET"))
2171            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
2172            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2173                "ref": format!("refs/tags/{TAG}"),
2174                "node_id": "R",
2175                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
2176                "object": {
2177                    "type": "commit",
2178                    "sha": sha,
2179                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{sha}")
2180                }
2181            })))
2182    }
2183
2184    fn annotated_tag() -> Mock {
2185        Mock::given(method("GET"))
2186            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
2187            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2188                "ref": format!("refs/tags/{TAG}"),
2189                "node_id": "R",
2190                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
2191                "object": {
2192                    "type": "tag",
2193                    "sha": TAG_OBJECT,
2194                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}")
2195                }
2196            })))
2197    }
2198
2199    fn peeled_tag_object(sha: &str) -> Mock {
2200        Mock::given(method("GET"))
2201            .and(path(format!("/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}")))
2202            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
2203                "node_id": "T",
2204                "tag": TAG,
2205                "sha": TAG_OBJECT,
2206                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}"),
2207                "message": TAG,
2208                "object": {
2209                    "type": "commit",
2210                    "sha": sha,
2211                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{sha}")
2212                }
2213            })))
2214    }
2215
2216    fn release_json(target_commitish: &str) -> serde_json::Value {
2217        serde_json::json!({
2218            "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/releases/1"),
2219            "html_url": format!("https://github.com/{OWNER}/{NAME}/releases/tag/{TAG}"),
2220            "assets_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/releases/1/assets"),
2221            "upload_url": format!("https://uploads.github.com/repos/{OWNER}/{NAME}/releases/1/assets{{?name,label}}"),
2222            "tarball_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/tarball/{TAG}"),
2223            "zipball_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/zipball/{TAG}"),
2224            "id": 1,
2225            "node_id": "R",
2226            "tag_name": TAG,
2227            "target_commitish": target_commitish,
2228            "name": TAG,
2229            "body": "notes",
2230            "draft": false,
2231            "prerelease": false,
2232            "created_at": "2026-08-22T00:00:00Z",
2233            "published_at": "2026-08-22T00:00:00Z",
2234            "assets": []
2235        })
2236    }
2237
2238    fn release_with_assets(assets: &[(&str, &str)]) -> Mock {
2239        let mut json = release_json("main");
2240        json["assets"] = assets
2241            .iter()
2242            .map(|(name, state)| serde_json::json!({ "name": name, "state": state }))
2243            .collect();
2244        Mock::given(method("GET"))
2245            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
2246            .respond_with(ResponseTemplate::new(200).set_body_json(json))
2247    }
2248
2249    fn missing_tag() -> Mock {
2250        Mock::given(method("GET"))
2251            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
2252            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
2253                "message": "Not Found",
2254                "documentation_url": "https://docs.github.com"
2255            })))
2256    }
2257
2258    #[tokio::test]
2259    async fn a_release_never_made_has_no_tag_and_no_release() {
2260        let server = MockServer::start().await;
2261        missing_tag().mount(&server).await;
2262        missing_release().expect(1).mount(&server).await;
2263        no_releases_listed().expect(1).mount(&server).await;
2264        let state =
2265            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2266                .await
2267                .unwrap();
2268        assert_eq!(state, super::ReleaseState::default());
2269    }
2270
2271    #[tokio::test]
2272    async fn a_finished_release_names_its_commit_and_assets() {
2273        let server = MockServer::start().await;
2274        lightweight_tag(PUBLISHED).mount(&server).await;
2275        release_with_assets(&[
2276            ("app-darwin-arm64.tar.gz", "uploaded"),
2277            ("app-linux-x64.tar.gz", "uploaded"),
2278            ("app.pkg", "starter"),
2279        ])
2280        .mount(&server)
2281        .await;
2282        let state =
2283            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2284                .await
2285                .unwrap();
2286        assert_eq!(state.tag.as_deref(), Some(PUBLISHED));
2287        assert!(state.release);
2288        assert!(!state.draft);
2289        assert_eq!(
2290            state.assets,
2291            ["app-darwin-arm64.tar.gz", "app-linux-x64.tar.gz"]
2292        );
2293    }
2294
2295    #[tokio::test]
2296    async fn an_immutable_release_is_read_as_immutable() {
2297        let server = MockServer::start().await;
2298        lightweight_tag(PUBLISHED).mount(&server).await;
2299        let mut json = release_json("main");
2300        json["immutable"] = true.into();
2301        Mock::given(method("GET"))
2302            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
2303            .respond_with(ResponseTemplate::new(200).set_body_json(json))
2304            .mount(&server)
2305            .await;
2306        let state =
2307            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2308                .await
2309                .unwrap();
2310        assert!(
2311            state.release && !state.draft && state.immutable,
2312            "{state:?}"
2313        );
2314    }
2315
2316    /// `GET /releases/tags/{tag}` answers 404 for a draft, so the lookup reads
2317    /// the list, and only an asset in state `uploaded` counts.
2318    #[tokio::test]
2319    async fn a_draft_is_found_through_the_release_list() {
2320        let server = MockServer::start().await;
2321        lightweight_tag(PUBLISHED).mount(&server).await;
2322        missing_release().mount(&server).await;
2323        let mut other = release_json("main");
2324        other["tag_name"] = "v0.9.0".into();
2325        listed_releases(serde_json::json!([
2326            other,
2327            draft_json(&[
2328                ("app.pkg", "uploaded"),
2329                ("app_1.0.0_linux_x64.tar.gz", "starter")
2330            ])
2331        ]))
2332        .mount(&server)
2333        .await;
2334        let state =
2335            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2336                .await
2337                .unwrap();
2338        assert!(
2339            state.release && state.draft && !state.immutable,
2340            "{state:?}"
2341        );
2342        assert_eq!(state.assets, ["app.pkg"]);
2343    }
2344
2345    /// A tag with no Release opens a draft at HEAD, and no tag is created:
2346    /// GitHub creates it when the draft is published.
2347    #[tokio::test]
2348    async fn a_missing_release_opens_a_draft_at_head_with_no_tag() {
2349        let server = MockServer::start().await;
2350        create_tag_ref().expect(0).mount(&server).await;
2351        create_draft().expect(1).mount(&server).await;
2352        let declared = declared();
2353        let id = super::open_draft_with(
2354            &crab(&server.uri()),
2355            &repo(),
2356            &with_assets(&declared),
2357            &super::DraftState::Missing,
2358        )
2359        .await
2360        .unwrap();
2361        assert_eq!(id, 1);
2362    }
2363
2364    #[tokio::test]
2365    async fn a_release_with_no_assets_is_published_at_once() {
2366        let server = MockServer::start().await;
2367        missing_release().mount(&server).await;
2368        no_releases_listed().mount(&server).await;
2369        lightweight_tag(PUBLISHED).mount(&server).await;
2370        Mock::given(method("POST"))
2371            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2372            .and(body_partial_json(serde_json::json!({
2373                "tag_name": TAG,
2374                "target_commitish": PUBLISHED
2375            })))
2376            .and(|request: &wiremock::Request| {
2377                let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
2378                body.get("draft").is_none()
2379            })
2380            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
2381            .expect(1)
2382            .mount(&server)
2383            .await;
2384        create_tag_ref().expect(0).mount(&server).await;
2385        let url = super::ensure_release_with(
2386            &crab(&server.uri()),
2387            &repo(),
2388            &stable(),
2389            super::PackageUpload::Shipped,
2390        )
2391        .await
2392        .unwrap();
2393        assert!(url.contains(TAG), "{url}");
2394    }
2395
2396    /// The draft as `GET /releases/{id}` returns it, containing `assets`.
2397    fn draft_by_id(assets: &[(&str, &str)]) -> Mock {
2398        Mock::given(method("GET"))
2399            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
2400            .respond_with(ResponseTemplate::new(200).set_body_json(draft_json(assets)))
2401    }
2402
2403    /// The update sends this run's title, notes and commit, so a draft
2404    /// someone edited reads as this run would have written it.
2405    #[tokio::test]
2406    async fn a_draft_with_every_asset_uploaded_is_published() {
2407        let server = MockServer::start().await;
2408        draft_by_id(&[
2409            ("app.pkg", "uploaded"),
2410            ("app_1.0.0_linux_x64.tar.gz", "uploaded"),
2411        ])
2412        .mount(&server)
2413        .await;
2414        publish_draft()
2415            .and(body_partial_json(serde_json::json!({
2416                "name": TAG,
2417                "body": "notes",
2418                "target_commitish": PUBLISHED,
2419                "make_latest": "legacy"
2420            })))
2421            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
2422            .expect(1)
2423            .mount(&server)
2424            .await;
2425        let declared = declared();
2426        let url =
2427            super::publish_draft_with(&crab(&server.uri()), &repo(), &with_assets(&declared), 1)
2428                .await
2429                .unwrap();
2430        assert_eq!(
2431            url,
2432            format!("https://github.com/{OWNER}/{NAME}/releases/tag/{TAG}")
2433        );
2434    }
2435
2436    #[tokio::test]
2437    async fn a_candidate_draft_is_published_as_a_prerelease_that_is_never_the_latest() {
2438        let server = MockServer::start().await;
2439        draft_by_id(&[("app.pkg", "uploaded")]).mount(&server).await;
2440        Mock::given(method("PATCH"))
2441            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
2442            .and(body_partial_json(serde_json::json!({
2443                "draft": false,
2444                "prerelease": true,
2445                "make_latest": "false"
2446            })))
2447            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
2448            .expect(1)
2449            .mount(&server)
2450            .await;
2451        let declared = ["app.pkg".to_owned()];
2452        let candidate = super::NewRelease {
2453            stage: super::Stage::Candidate,
2454            ..with_assets(&declared)
2455        };
2456        super::publish_draft_with(&crab(&server.uri()), &repo(), &candidate, 1)
2457            .await
2458            .unwrap();
2459    }
2460
2461    /// Only an asset in state `uploaded` counts, and a draft that lacks one is
2462    /// never published.
2463    #[tokio::test]
2464    async fn a_draft_missing_an_asset_is_not_published_and_names_what_it_lacks() {
2465        let server = MockServer::start().await;
2466        draft_by_id(&[
2467            ("app.pkg", "uploaded"),
2468            ("app_1.0.0_linux_x64.tar.gz", "starter"),
2469        ])
2470        .mount(&server)
2471        .await;
2472        publish_draft()
2473            .respond_with(ResponseTemplate::new(500))
2474            .expect(0)
2475            .mount(&server)
2476            .await;
2477        let declared = declared();
2478        let error =
2479            super::publish_draft_with(&crab(&server.uri()), &repo(), &with_assets(&declared), 1)
2480                .await
2481                .unwrap_err();
2482        let message = format!("{error:#}");
2483        assert!(
2484            message.contains(&format!("{TAG} lacks app_1.0.0_linux_x64.tar.gz")),
2485            "{message}"
2486        );
2487    }
2488
2489    async fn found(server: &MockServer) -> anyhow::Result<super::ExistingRelease> {
2490        super::read_release_with(
2491            &crab(&server.uri()),
2492            &repo(),
2493            TAG,
2494            PUBLISHED,
2495            &ReleaseList::default(),
2496        )
2497        .await
2498    }
2499
2500    /// A tag on another commit fails before any write, whatever its Release:
2501    /// publishing a draft keeps an existing tag where it is.
2502    #[tokio::test]
2503    async fn a_tag_on_another_commit_fails_before_any_write() {
2504        let server = MockServer::start().await;
2505        missing_release().mount(&server).await;
2506        lightweight_tag(OTHER).mount(&server).await;
2507        listed_releases(serde_json::json!([draft_json(&[])]))
2508            .mount(&server)
2509            .await;
2510        let message = format!("{:#}", found(&server).await.unwrap_err());
2511        assert!(message.contains(OTHER), "{message}");
2512        assert!(message.contains(PUBLISHED), "{message}");
2513    }
2514
2515    #[tokio::test]
2516    async fn a_draft_at_head_is_kept() {
2517        let server = MockServer::start().await;
2518        missing_tag().mount(&server).await;
2519        missing_release().mount(&server).await;
2520        listed_releases(serde_json::json!([draft_json(&[("app.pkg", "uploaded")])]))
2521            .mount(&server)
2522            .await;
2523        let super::ExistingRelease::DraftState(draft @ super::DraftState::AtHead(_)) =
2524            found(&server).await.unwrap()
2525        else {
2526            panic!("a draft at HEAD");
2527        };
2528        assert_eq!(draft.uploaded(), ["app.pkg"]);
2529    }
2530
2531    /// A draft at a branch name, as one created with GitHub's default target,
2532    /// is stale, and none of its assets count.
2533    #[tokio::test]
2534    async fn a_draft_at_another_commit_is_stale() {
2535        let server = MockServer::start().await;
2536        missing_tag().mount(&server).await;
2537        missing_release().mount(&server).await;
2538        let mut stale = draft_json(&[("app.pkg", "uploaded")]);
2539        stale["target_commitish"] = "main".into();
2540        listed_releases(serde_json::json!([stale]))
2541            .mount(&server)
2542            .await;
2543        let super::ExistingRelease::DraftState(draft @ super::DraftState::Stale(_)) =
2544            found(&server).await.unwrap()
2545        else {
2546            panic!("a stale draft");
2547        };
2548        assert_eq!(draft.uploaded(), Vec::<&str>::new());
2549    }
2550
2551    /// GitHub can answer 404 for a tag a moment after the Release that created
2552    /// it is published. A Release published at HEAD then counts as at HEAD.
2553    #[tokio::test]
2554    async fn a_release_published_at_head_before_its_tag_is_served_counts_as_published() {
2555        let server = MockServer::start().await;
2556        missing_tag().mount(&server).await;
2557        Mock::given(method("GET"))
2558            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
2559            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
2560            .mount(&server)
2561            .await;
2562        assert!(
2563            matches!(
2564                found(&server).await.unwrap(),
2565                super::ExistingRelease::Published(_)
2566            ),
2567            "published at HEAD"
2568        );
2569    }
2570
2571    #[tokio::test]
2572    async fn a_release_published_elsewhere_with_no_tag_fails() {
2573        let server = MockServer::start().await;
2574        missing_tag().mount(&server).await;
2575        Mock::given(method("GET"))
2576            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
2577            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(OTHER)))
2578            .mount(&server)
2579            .await;
2580        let message = format!("{:#}", found(&server).await.unwrap_err());
2581        assert!(message.contains(OTHER), "{message}");
2582        assert!(message.contains(PUBLISHED), "{message}");
2583    }
2584
2585    /// A stale draft is deleted before the draft at HEAD is created.
2586    #[tokio::test]
2587    async fn a_stale_draft_is_deleted_and_created_again_at_head() {
2588        let server = MockServer::start().await;
2589        Mock::given(method("DELETE"))
2590            .and(path(format!("/repos/{OWNER}/{NAME}/releases/7")))
2591            .respond_with(ResponseTemplate::new(204))
2592            .expect(1)
2593            .mount(&server)
2594            .await;
2595        create_draft().expect(1).mount(&server).await;
2596        let mut stale = draft_json(&[]);
2597        stale["id"] = 7.into();
2598        stale["target_commitish"] = OTHER.into();
2599        let stale = serde_json::from_value(stale).unwrap();
2600        let id = super::open_draft_with(
2601            &crab(&server.uri()),
2602            &repo(),
2603            &stable(),
2604            &super::DraftState::Stale(stale),
2605        )
2606        .await
2607        .unwrap();
2608        assert_eq!(id, 1);
2609        let methods: Vec<String> = server
2610            .received_requests()
2611            .await
2612            .unwrap()
2613            .iter()
2614            .map(|request| request.method.to_string())
2615            .collect();
2616        assert_eq!(methods, ["DELETE", "POST"]);
2617    }
2618
2619    /// A 403 on the draft names the permission, and the run stops there,
2620    /// before any upload.
2621    #[tokio::test]
2622    async fn a_forbidden_draft_names_the_workflows_permission() {
2623        let server = MockServer::start().await;
2624        Mock::given(method("POST"))
2625            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2626            .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
2627                "message": "Resource not accessible by integration",
2628                "documentation_url": "https://docs.github.com/rest/releases/releases#create-a-release"
2629            })))
2630            .mount(&server)
2631            .await;
2632        let error = super::open_draft_with(
2633            &crab(&server.uri()),
2634            &repo(),
2635            &stable(),
2636            &super::DraftState::Missing,
2637        )
2638        .await
2639        .unwrap_err();
2640        let message = format!("{error:#}");
2641        assert!(message.contains("workflows: write"), "{message}");
2642        assert!(
2643            error.downcast_ref::<super::ReleaseRefused>().is_some(),
2644            "{message}"
2645        );
2646    }
2647
2648    #[tokio::test]
2649    async fn a_draft_at_head_is_used_as_it_is() {
2650        let server = MockServer::start().await;
2651        let draft = serde_json::from_value(draft_json(&[])).unwrap();
2652        let id = super::open_draft_with(
2653            &crab(&server.uri()),
2654            &repo(),
2655            &stable(),
2656            &super::DraftState::AtHead(draft),
2657        )
2658        .await
2659        .unwrap();
2660        assert_eq!(id, 1);
2661        assert_eq!(server.received_requests().await.unwrap().len(), 0);
2662    }
2663
2664    const NO_WAIT: [Duration; 4] = [Duration::ZERO; 4];
2665
2666    async fn reads_of_the_tag(server: &MockServer) -> usize {
2667        server.received_requests().await.unwrap().len()
2668    }
2669
2670    #[tokio::test]
2671    async fn the_tag_proof_reads_again_after_a_404() {
2672        let server = MockServer::start().await;
2673        missing_tag().up_to_n_times(1).mount(&server).await;
2674        lightweight_tag(PUBLISHED).mount(&server).await;
2675        super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
2676            .await
2677            .unwrap();
2678        assert_eq!(reads_of_the_tag(&server).await, 2);
2679    }
2680
2681    #[tokio::test]
2682    async fn the_tag_proof_fails_after_five_404s() {
2683        let server = MockServer::start().await;
2684        missing_tag().mount(&server).await;
2685        let error = super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
2686            .await
2687            .unwrap_err();
2688        let message = format!("{error:#}");
2689        assert!(message.contains(&format!("no tag {TAG}")), "{message}");
2690        assert!(message.contains("after 5 reads"), "{message}");
2691        assert_eq!(reads_of_the_tag(&server).await, 5);
2692    }
2693
2694    /// Any error but a 404 fails at once. octocrab retries a 5xx itself, so
2695    /// the client here makes one request per read.
2696    #[tokio::test]
2697    async fn the_tag_proof_fails_at_once_on_any_other_error() {
2698        let server = MockServer::start().await;
2699        Mock::given(method("GET"))
2700            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
2701            .respond_with(ResponseTemplate::new(500))
2702            .mount(&server)
2703            .await;
2704        let once = Octocrab::builder()
2705            .personal_token("token".to_owned())
2706            .base_uri(server.uri())
2707            .unwrap()
2708            .add_retry_config(RetryConfig::None)
2709            .build()
2710            .unwrap();
2711        let error = super::prove_tag_with(&once, &repo(), TAG, PUBLISHED, &NO_WAIT)
2712            .await
2713            .unwrap_err();
2714        assert!(
2715            format!("{error:#}").contains(&format!("read tag {TAG}")),
2716            "{error:#}"
2717        );
2718        assert_eq!(reads_of_the_tag(&server).await, 1);
2719    }
2720
2721    #[tokio::test]
2722    async fn the_tag_proof_fails_on_a_tag_at_another_commit() {
2723        let server = MockServer::start().await;
2724        lightweight_tag(OTHER).mount(&server).await;
2725        let error = super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
2726            .await
2727            .unwrap_err();
2728        let message = format!("{error:#}");
2729        assert!(message.contains(OTHER), "{message}");
2730        assert!(message.contains(PUBLISHED), "{message}");
2731    }
2732
2733    fn other_releases(count: usize) -> Vec<serde_json::Value> {
2734        (0..count)
2735            .map(|n| {
2736                let mut json = release_json("main");
2737                json["tag_name"] = format!("v0.0.{n}").into();
2738                json
2739            })
2740            .collect()
2741    }
2742
2743    /// The list is read a page at a time, 100 to a page, until a Release has
2744    /// the tag. Each mock answers only its own page.
2745    #[tokio::test]
2746    async fn the_release_list_is_read_page_by_page_until_the_tag_is_found() {
2747        let server = MockServer::start().await;
2748        missing_release().mount(&server).await;
2749        Mock::given(method("GET"))
2750            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2751            .and(query_param("per_page", "100"))
2752            .and(query_param("page", "1"))
2753            .respond_with(ResponseTemplate::new(200).set_body_json(other_releases(100)))
2754            .expect(1)
2755            .mount(&server)
2756            .await;
2757        Mock::given(method("GET"))
2758            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2759            .and(query_param("per_page", "100"))
2760            .and(query_param("page", "2"))
2761            .respond_with(
2762                ResponseTemplate::new(200).set_body_json(serde_json::json!([draft_json(&[])])),
2763            )
2764            .expect(1)
2765            .mount(&server)
2766            .await;
2767        let found =
2768            super::find_release(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2769                .await
2770                .unwrap()
2771                .expect("the draft on page 2");
2772        assert!(found.draft);
2773    }
2774
2775    /// A draft has no tag until it is published, so a missing tag still reads
2776    /// the Releases, and a tagless draft is an incomplete release.
2777    #[tokio::test]
2778    async fn a_tagless_draft_is_an_incomplete_release() {
2779        let server = MockServer::start().await;
2780        missing_tag().mount(&server).await;
2781        missing_release().mount(&server).await;
2782        listed_releases(serde_json::json!([draft_json(&[("app.pkg", "uploaded")])]))
2783            .mount(&server)
2784            .await;
2785        let state =
2786            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2787                .await
2788                .unwrap();
2789        assert_eq!(state.tag, None);
2790        assert!(state.release && state.draft, "{state:?}");
2791        assert_eq!(state.assets, ["app.pkg"]);
2792    }
2793
2794    /// A draft's stop record is read from its body, for `status` to show.
2795    #[tokio::test]
2796    async fn a_drafts_stop_record_is_read() {
2797        let server = MockServer::start().await;
2798        missing_tag().mount(&server).await;
2799        missing_release().mount(&server).await;
2800        let mut draft = draft_json(&[]);
2801        draft["body"] = indoc! {r#"
2802            notes
2803
2804            <!-- verctl:stop {"package":"app","version":"1.0.0","cause":"429 Too Many Requests"} -->
2805        "#}
2806        .into();
2807        listed_releases(serde_json::json!([draft]))
2808            .mount(&server)
2809            .await;
2810        let state =
2811            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2812                .await
2813                .unwrap();
2814        assert_eq!(
2815            state.stop,
2816            Record::Read(Stop::new("app", "1.0.0", "429 Too Many Requests", None))
2817        );
2818    }
2819
2820    /// A tag with no Release in a repository with many reads ten pages, then
2821    /// counts as having none, instead of one request per page forever.
2822    #[tokio::test]
2823    async fn the_release_list_is_read_for_ten_pages_at_most() {
2824        let server = MockServer::start().await;
2825        missing_release().mount(&server).await;
2826        Mock::given(method("GET"))
2827            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2828            .respond_with(ResponseTemplate::new(200).set_body_json(other_releases(100)))
2829            .expect(10)
2830            .mount(&server)
2831            .await;
2832        let found =
2833            super::find_release(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
2834                .await
2835                .unwrap();
2836        assert!(found.is_none(), "{found:?}");
2837    }
2838
2839    #[tokio::test]
2840    async fn create_tags_the_published_commit_not_the_default_branch() {
2841        let server = MockServer::start().await;
2842        missing_release().mount(&server).await;
2843        no_releases_listed().mount(&server).await;
2844        create_at_published_sha().mount(&server).await;
2845        lightweight_tag(PUBLISHED).mount(&server).await;
2846        let url = super::ensure_release_with(
2847            &crab(&server.uri()),
2848            &repo(),
2849            &stable(),
2850            super::PackageUpload::Shipped,
2851        )
2852        .await
2853        .unwrap();
2854        assert!(url.contains(TAG), "{url}");
2855    }
2856
2857    #[tokio::test]
2858    async fn a_candidate_release_is_a_prerelease_that_is_never_the_latest() {
2859        let server = MockServer::start().await;
2860        missing_release().mount(&server).await;
2861        no_releases_listed().mount(&server).await;
2862        Mock::given(method("POST"))
2863            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2864            .and(body_partial_json(serde_json::json!({
2865                "tag_name": TAG,
2866                "prerelease": true,
2867                "make_latest": "false"
2868            })))
2869            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
2870            .mount(&server)
2871            .await;
2872        lightweight_tag(PUBLISHED).mount(&server).await;
2873        let candidate = super::NewRelease {
2874            stage: super::Stage::Candidate,
2875            ..stable()
2876        };
2877        let url = super::ensure_release_with(
2878            &crab(&server.uri()),
2879            &repo(),
2880            &candidate,
2881            super::PackageUpload::Shipped,
2882        )
2883        .await
2884        .unwrap();
2885        assert!(url.contains(TAG), "{url}");
2886    }
2887
2888    #[tokio::test]
2889    async fn a_stable_release_sets_neither_prerelease_nor_latest() {
2890        let server = MockServer::start().await;
2891        missing_release().mount(&server).await;
2892        no_releases_listed().mount(&server).await;
2893        Mock::given(method("POST"))
2894            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2895            .and(|request: &wiremock::Request| {
2896                let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
2897                body.get("prerelease").is_none() && body.get("make_latest").is_none()
2898            })
2899            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
2900            .mount(&server)
2901            .await;
2902        lightweight_tag(PUBLISHED).mount(&server).await;
2903        let url = super::ensure_release_with(
2904            &crab(&server.uri()),
2905            &repo(),
2906            &stable(),
2907            super::PackageUpload::Shipped,
2908        )
2909        .await
2910        .unwrap();
2911        assert!(url.contains(TAG), "{url}");
2912    }
2913
2914    #[tokio::test]
2915    async fn a_forbidden_release_names_the_workflows_permission() {
2916        let server = MockServer::start().await;
2917        missing_release().mount(&server).await;
2918        no_releases_listed().mount(&server).await;
2919        Mock::given(method("POST"))
2920            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
2921            .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
2922                "message": "Resource not accessible by integration",
2923                "documentation_url": "https://docs.github.com/rest/releases/releases#create-a-release"
2924            })))
2925            .mount(&server)
2926            .await;
2927        let error = super::ensure_release_with(
2928            &crab(&server.uri()),
2929            &repo(),
2930            &stable(),
2931            super::PackageUpload::Shipped,
2932        )
2933        .await
2934        .unwrap_err();
2935        let message = format!("{error:#}");
2936        assert!(message.contains("workflows: write"), "{message}");
2937        assert!(message.contains(PUBLISHED), "{message}");
2938        assert!(
2939            error.downcast_ref::<super::ReleaseRefused>().is_some(),
2940            "{message}"
2941        );
2942    }
2943
2944    #[tokio::test]
2945    async fn create_fails_when_the_tag_lands_elsewhere() {
2946        let server = MockServer::start().await;
2947        missing_release().mount(&server).await;
2948        no_releases_listed().mount(&server).await;
2949        create_at_published_sha().mount(&server).await;
2950        lightweight_tag(OTHER).mount(&server).await;
2951        let error = super::ensure_release_with(
2952            &crab(&server.uri()),
2953            &repo(),
2954            &stable(),
2955            super::PackageUpload::Shipped,
2956        )
2957        .await
2958        .unwrap_err();
2959        let message = format!("{error:#}");
2960        assert!(message.contains(OTHER), "{message}");
2961        assert!(message.contains(PUBLISHED), "{message}");
2962    }
2963
2964    #[tokio::test]
2965    async fn existing_release_at_the_published_commit_is_ok() {
2966        let server = MockServer::start().await;
2967        existing_release().mount(&server).await;
2968        lightweight_tag(PUBLISHED).mount(&server).await;
2969        let url = super::ensure_release_with(
2970            &crab(&server.uri()),
2971            &repo(),
2972            &stable(),
2973            super::PackageUpload::Shipped,
2974        )
2975        .await
2976        .unwrap();
2977        assert!(url.contains(TAG), "{url}");
2978    }
2979
2980    #[tokio::test]
2981    async fn existing_release_at_another_commit_fails() {
2982        let server = MockServer::start().await;
2983        existing_release().mount(&server).await;
2984        lightweight_tag(OTHER).mount(&server).await;
2985        let error = super::ensure_release_with(
2986            &crab(&server.uri()),
2987            &repo(),
2988            &stable(),
2989            super::PackageUpload::Shipped,
2990        )
2991        .await
2992        .unwrap_err();
2993        let message = format!("{error:#}");
2994        assert!(message.contains(OTHER), "{message}");
2995        assert!(message.contains(PUBLISHED), "{message}");
2996    }
2997
2998    #[tokio::test]
2999    async fn existing_release_is_kept_when_nothing_under_it_shipped() {
3000        let server = MockServer::start().await;
3001        existing_release().mount(&server).await;
3002        lightweight_tag(OTHER).mount(&server).await;
3003        let url = super::ensure_release_with(
3004            &crab(&server.uri()),
3005            &repo(),
3006            &stable(),
3007            super::PackageUpload::Skipped,
3008        )
3009        .await
3010        .unwrap();
3011        assert!(url.contains(TAG), "{url}");
3012    }
3013
3014    #[tokio::test]
3015    async fn annotated_tag_peels_to_the_commit() {
3016        let server = MockServer::start().await;
3017        existing_release().mount(&server).await;
3018        annotated_tag().mount(&server).await;
3019        peeled_tag_object(PUBLISHED).mount(&server).await;
3020        let url = super::ensure_release_with(
3021            &crab(&server.uri()),
3022            &repo(),
3023            &stable(),
3024            super::PackageUpload::Shipped,
3025        )
3026        .await
3027        .unwrap();
3028        assert!(url.contains(TAG), "{url}");
3029    }
3030
3031    /// The lookups of one plan share the Releases list: two missing tags
3032    /// read it once.
3033    #[tokio::test]
3034    async fn two_missing_tags_read_the_release_list_once() {
3035        let server = MockServer::start().await;
3036        Mock::given(method("GET"))
3037            .and(path_regex(format!(
3038                "^/repos/{OWNER}/{NAME}/git/ref/tags/.+$"
3039            )))
3040            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
3041                "message": "Not Found",
3042                "documentation_url": "https://docs.github.com"
3043            })))
3044            .mount(&server)
3045            .await;
3046        Mock::given(method("GET"))
3047            .and(path_regex(format!(
3048                "^/repos/{OWNER}/{NAME}/releases/tags/.+$"
3049            )))
3050            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
3051                "message": "Not Found",
3052                "documentation_url": "https://docs.github.com"
3053            })))
3054            .expect(2)
3055            .mount(&server)
3056            .await;
3057        no_releases_listed().expect(1).mount(&server).await;
3058        let list = ReleaseList::default();
3059        let crab = crab(&server.uri());
3060        for tag in ["v1.0.0", "v2.0.0"] {
3061            let state = super::release_state_with(&crab, &repo(), tag, &list)
3062                .await
3063                .unwrap();
3064            assert_eq!(state, super::ReleaseState::default());
3065        }
3066    }
3067
3068    /// An upload goes to the Release id the run has, and never looks the
3069    /// tag up again, so a second draft with the same tag name is left alone.
3070    #[tokio::test]
3071    async fn an_upload_goes_to_the_drafts_id_when_two_drafts_share_the_tag() {
3072        let server = MockServer::start().await;
3073        let uri = server.uri();
3074        let mut first = draft_json(&[]);
3075        first["id"] = 1.into();
3076        let mut second = draft_json(&[]);
3077        second["id"] = 2.into();
3078        listed_releases(serde_json::json!([first, second]))
3079            .expect(0)
3080            .mount(&server)
3081            .await;
3082        let mut draft = release_json(PUBLISHED);
3083        draft["id"] = 2.into();
3084        draft["draft"] = true.into();
3085        draft["upload_url"] =
3086            format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/2/assets{{?name,label}}").into();
3087        Mock::given(method("GET"))
3088            .and(path(format!("/repos/{OWNER}/{NAME}/releases/2")))
3089            .respond_with(ResponseTemplate::new(200).set_body_json(draft))
3090            .mount(&server)
3091            .await;
3092        Mock::given(method("POST"))
3093            .and(path(format!(
3094                "/upload/repos/{OWNER}/{NAME}/releases/2/assets"
3095            )))
3096            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
3097                "url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
3098                "browser_download_url": format!("https://github.com/{OWNER}/{NAME}/releases/download/{TAG}/app.tar.gz"),
3099                "id": 9,
3100                "node_id": "A",
3101                "name": "app.tar.gz",
3102                "label": null,
3103                "state": "uploaded",
3104                "content_type": "application/gzip",
3105                "size": 7,
3106                "digest": null,
3107                "download_count": 0,
3108                "created_at": "2026-11-13T00:00:00Z",
3109                "updated_at": "2026-11-13T00:00:00Z",
3110                "uploader": null
3111            })))
3112            .expect(1)
3113            .mount(&server)
3114            .await;
3115        let url = super::upload_release_asset_with(
3116            &crab(&uri),
3117            &repo(),
3118            super::Target::Id { id: 2, tag: TAG },
3119            "app.tar.gz",
3120            bytes::Bytes::from_static(b"tarball"),
3121            &[Duration::ZERO; 2],
3122        )
3123        .await
3124        .unwrap();
3125        assert!(url.ends_with("/app.tar.gz"), "{url}");
3126    }
3127
3128    fn upload_target_json(assets: &serde_json::Value) -> Mock {
3129        let mut json = release_json("main");
3130        json["assets"] = assets.clone();
3131        Mock::given(method("GET"))
3132            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
3133            .respond_with(ResponseTemplate::new(200).set_body_json(json))
3134    }
3135
3136    /// The release octocrab reads before an upload, pointing uploads at `uri`.
3137    fn release_by_id(uri: &str) -> Mock {
3138        let mut json = release_json("main");
3139        json["upload_url"] =
3140            format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/1/assets{{?name,label}}").into();
3141        Mock::given(method("GET"))
3142            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
3143            .respond_with(ResponseTemplate::new(200).set_body_json(json))
3144    }
3145
3146    fn upload_refused(status: u16, body: serde_json::Value) -> Mock {
3147        Mock::given(method("POST"))
3148            .and(path(format!(
3149                "/upload/repos/{OWNER}/{NAME}/releases/1/assets"
3150            )))
3151            .respond_with(ResponseTemplate::new(status).set_body_json(body))
3152    }
3153
3154    fn already_exists() -> serde_json::Value {
3155        serde_json::json!({
3156            "message": "Validation Failed",
3157            "errors": [{ "resource": "ReleaseAsset", "code": "already_exists", "field": "name" }],
3158            "documentation_url": "https://docs.github.com/rest/releases/assets#upload-a-release-asset"
3159        })
3160    }
3161
3162    async fn upload(server: &MockServer) -> anyhow::Result<String> {
3163        super::upload_release_asset_with(
3164            &crab(&server.uri()),
3165            &repo(),
3166            super::Target::Tag(TAG),
3167            "app_1.0.0_linux_x64.tar.gz",
3168            bytes::Bytes::from_static(b"tarball"),
3169            &[Duration::ZERO; 2],
3170        )
3171        .await
3172    }
3173
3174    #[tokio::test]
3175    async fn an_asset_another_run_uploaded_is_already_done() {
3176        let server = MockServer::start().await;
3177        upload_target_json(&serde_json::json!([
3178            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "uploaded" }
3179        ]))
3180        .mount(&server)
3181        .await;
3182        release_by_id(&server.uri()).mount(&server).await;
3183        upload_refused(422, already_exists())
3184            .expect(0)
3185            .mount(&server)
3186            .await;
3187        assert_eq!(
3188            upload(&server).await.unwrap(),
3189            "already app_1.0.0_linux_x64.tar.gz"
3190        );
3191    }
3192
3193    #[tokio::test]
3194    async fn a_duplicate_waits_for_the_other_upload_to_finish() {
3195        let server = MockServer::start().await;
3196        // The read before the upload and the first read after the refusal see
3197        // the other run still sending.
3198        upload_target_json(&serde_json::json!([
3199            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "starter" }
3200        ]))
3201        .up_to_n_times(2)
3202        .mount(&server)
3203        .await;
3204        upload_target_json(&serde_json::json!([
3205            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "uploaded" }
3206        ]))
3207        .mount(&server)
3208        .await;
3209        release_by_id(&server.uri()).mount(&server).await;
3210        upload_refused(422, already_exists()).mount(&server).await;
3211        assert_eq!(
3212            upload(&server).await.unwrap(),
3213            "already app_1.0.0_linux_x64.tar.gz"
3214        );
3215    }
3216
3217    #[tokio::test]
3218    async fn an_asset_whose_upload_broke_off_fails() {
3219        let server = MockServer::start().await;
3220        upload_target_json(&serde_json::json!([
3221            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "starter" }
3222        ]))
3223        .mount(&server)
3224        .await;
3225        release_by_id(&server.uri()).mount(&server).await;
3226        upload_refused(422, already_exists()).mount(&server).await;
3227        let error = upload(&server).await.unwrap_err();
3228        assert!(format!("{error:#}").contains("\"starter\""), "{error:#}");
3229    }
3230
3231    #[tokio::test]
3232    async fn another_validation_failure_fails_the_upload() {
3233        let server = MockServer::start().await;
3234        upload_target_json(&serde_json::json!([]))
3235            .mount(&server)
3236            .await;
3237        release_by_id(&server.uri()).mount(&server).await;
3238        upload_refused(
3239            422,
3240            serde_json::json!({
3241                "message": "Validation Failed",
3242                "errors": [{ "resource": "ReleaseAsset", "code": "invalid", "field": "name" }]
3243            }),
3244        )
3245        .mount(&server)
3246        .await;
3247        let error = upload(&server).await.unwrap_err();
3248        assert!(
3249            format!("{error:#}").contains("upload release asset"),
3250            "{error:#}"
3251        );
3252    }
3253
3254    fn create_vendored_release() -> wiremock::MockBuilder {
3255        Mock::given(method("POST"))
3256            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
3257            .and(body_partial_json(serde_json::json!({
3258                "tag_name": TAG,
3259                "name": TAG,
3260                "body": "Built from upstream.",
3261                "target_commitish": PUBLISHED,
3262                "make_latest": "false"
3263            })))
3264    }
3265
3266    async fn vendored_release(server: &MockServer) -> anyhow::Result<String> {
3267        super::ensure_vendored_release_with(
3268            &crab(&server.uri()),
3269            &repo(),
3270            TAG,
3271            "Built from upstream.",
3272            PUBLISHED,
3273        )
3274        .await
3275    }
3276
3277    #[tokio::test]
3278    async fn a_missing_vendored_release_is_created_and_not_made_latest() {
3279        let server = MockServer::start().await;
3280        missing_release().mount(&server).await;
3281        create_vendored_release()
3282            .respond_with(ResponseTemplate::new(201).set_body_json(release_json(PUBLISHED)))
3283            .expect(1)
3284            .mount(&server)
3285            .await;
3286        let url = vendored_release(&server).await.unwrap();
3287        assert!(url.ends_with(&format!("/releases/tag/{TAG}")), "{url}");
3288    }
3289
3290    #[tokio::test]
3291    async fn an_existing_vendored_release_is_used_wherever_its_tag_points() {
3292        let server = MockServer::start().await;
3293        existing_release().mount(&server).await;
3294        Mock::given(method("POST"))
3295            .respond_with(ResponseTemplate::new(500))
3296            .expect(0)
3297            .mount(&server)
3298            .await;
3299        let url = vendored_release(&server).await.unwrap();
3300        assert!(url.contains(TAG), "{url}");
3301    }
3302
3303    #[tokio::test]
3304    async fn a_vendored_release_another_job_created_first_is_used() {
3305        let server = MockServer::start().await;
3306        missing_release().up_to_n_times(1).mount(&server).await;
3307        existing_release().mount(&server).await;
3308        create_vendored_release()
3309            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
3310                "message": "Validation Failed",
3311                "errors": [{ "resource": "Release", "code": "already_exists", "field": "tag_name" }]
3312            })))
3313            .expect(1)
3314            .mount(&server)
3315            .await;
3316        let url = vendored_release(&server).await.unwrap();
3317        assert!(url.contains(TAG), "{url}");
3318    }
3319
3320    async fn sha256_of(server: &MockServer, name: &str) -> anyhow::Result<String> {
3321        super::asset_sha256_with(&crab(&server.uri()), &repo(), TAG, name).await
3322    }
3323
3324    #[tokio::test]
3325    async fn the_checksum_is_the_digest_github_holds() {
3326        let server = MockServer::start().await;
3327        upload_target_json(&serde_json::json!([
3328            { "name": "lib-1.0.0-linux-x64.tar.gz", "state": "uploaded", "digest": "sha256:abc123" }
3329        ]))
3330        .mount(&server)
3331        .await;
3332        assert_eq!(
3333            sha256_of(&server, "lib-1.0.0-linux-x64.tar.gz")
3334                .await
3335                .unwrap(),
3336            "abc123"
3337        );
3338    }
3339
3340    #[tokio::test]
3341    async fn an_asset_without_a_digest_has_no_checksum() {
3342        let server = MockServer::start().await;
3343        upload_target_json(&serde_json::json!([
3344            { "name": "lib-1.0.0-linux-x64.tar.gz", "state": "uploaded", "digest": null }
3345        ]))
3346        .mount(&server)
3347        .await;
3348        let error = sha256_of(&server, "lib-1.0.0-linux-x64.tar.gz")
3349            .await
3350            .unwrap_err();
3351        assert!(
3352            format!("{error:#}").contains("no SHA-256 digest"),
3353            "{error:#}"
3354        );
3355    }
3356
3357    /// A request that carries no `Authorization` header.
3358    struct Anonymous;
3359
3360    impl wiremock::Match for Anonymous {
3361        fn matches(&self, request: &wiremock::Request) -> bool {
3362            !request.headers.contains_key("authorization")
3363        }
3364    }
3365
3366    /// The asset API redirects to storage, and the token stays with GitHub.
3367    #[tokio::test]
3368    async fn a_draft_asset_downloads_through_the_redirect_without_the_token() {
3369        let server = MockServer::start().await;
3370        let uri = server.uri();
3371        upload_target_json(&serde_json::json!([{
3372            "name": "app.tar.gz",
3373            "state": "uploaded",
3374            "url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
3375            "digest": "sha256:abc123"
3376        }]))
3377        .mount(&server)
3378        .await;
3379        Mock::given(method("GET"))
3380            .and(path(format!("/repos/{OWNER}/{NAME}/releases/assets/9")))
3381            .and(header("accept", "application/octet-stream"))
3382            .and(header("authorization", "Bearer token"))
3383            .respond_with(
3384                ResponseTemplate::new(302)
3385                    .insert_header("location", format!("{uri}/storage/app.tar.gz")),
3386            )
3387            .expect(1)
3388            .mount(&server)
3389            .await;
3390        Mock::given(method("GET"))
3391            .and(path("/storage/app.tar.gz"))
3392            .and(Anonymous)
3393            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"tarball".to_vec()))
3394            .expect(1)
3395            .mount(&server)
3396            .await;
3397        let dir = tempfile::TempDir::new().unwrap();
3398        let saved = super::download_release_assets_with(
3399            &crab(&uri),
3400            "token",
3401            &repo(),
3402            TAG,
3403            &["app.tar.gz"],
3404            dir.path(),
3405        )
3406        .await
3407        .unwrap();
3408        assert_eq!(saved.len(), 1);
3409        assert_eq!(saved[0].name, "app.tar.gz");
3410        assert_eq!(saved[0].sha256, "abc123");
3411        assert_eq!(fs::read(dir.path().join("app.tar.gz")).unwrap(), b"tarball");
3412    }
3413
3414    /// Storage that redirects again is refused: the client follows no
3415    /// redirect, so a second 3xx body never becomes the asset.
3416    #[tokio::test]
3417    async fn a_second_redirect_fails_the_download() {
3418        let server = MockServer::start().await;
3419        let uri = server.uri();
3420        upload_target_json(&serde_json::json!([{
3421            "name": "app.tar.gz",
3422            "state": "uploaded",
3423            "url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
3424            "digest": "sha256:abc123"
3425        }]))
3426        .mount(&server)
3427        .await;
3428        Mock::given(method("GET"))
3429            .and(path(format!("/repos/{OWNER}/{NAME}/releases/assets/9")))
3430            .respond_with(
3431                ResponseTemplate::new(302)
3432                    .insert_header("location", format!("{uri}/storage/app.tar.gz")),
3433            )
3434            .mount(&server)
3435            .await;
3436        Mock::given(method("GET"))
3437            .and(path("/storage/app.tar.gz"))
3438            .respond_with(
3439                ResponseTemplate::new(302).insert_header("location", format!("{uri}/elsewhere")),
3440            )
3441            .mount(&server)
3442            .await;
3443        let dir = tempfile::TempDir::new().unwrap();
3444        let error = super::download_release_assets_with(
3445            &crab(&uri),
3446            "token",
3447            &repo(),
3448            TAG,
3449            &["app.tar.gz"],
3450            dir.path(),
3451        )
3452        .await
3453        .unwrap_err();
3454        assert!(
3455            format!("{error:#}").contains("unexpected status 302"),
3456            "{error:#}"
3457        );
3458        assert!(!dir.path().join("app.tar.gz").exists());
3459    }
3460
3461    #[tokio::test]
3462    async fn close_pr_comments_and_closes_pull_request() {
3463        let server = MockServer::start().await;
3464        let expected_url = format!("https://github.com/{OWNER}/{NAME}/pull/42");
3465        Mock::given(method("POST"))
3466            .and(path(format!("/repos/{OWNER}/{NAME}/issues/42/comments")))
3467            .and(body_partial_json(serde_json::json!({
3468                "body": "Closing this Version PR: no pending fragments remain on `main` at abc123."
3469            })))
3470            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
3471                "id": 99
3472            })))
3473            .expect(1)
3474            .mount(&server)
3475            .await;
3476        Mock::given(method("PATCH"))
3477            .and(path(format!("/repos/{OWNER}/{NAME}/pulls/42")))
3478            .and(body_partial_json(serde_json::json!({
3479                "state": "closed"
3480            })))
3481            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
3482                "number": 42,
3483                "state": "closed",
3484                "html_url": expected_url,
3485            })))
3486            .expect(1)
3487            .mount(&server)
3488            .await;
3489        let url = super::close_pr_with(
3490            &crab(&server.uri()),
3491            &repo(),
3492            42,
3493            "Closing this Version PR: no pending fragments remain on `main` at abc123.",
3494        )
3495        .await
3496        .unwrap();
3497        assert_eq!(url, expected_url);
3498    }
3499}