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