Skip to main content

verctl_github/
release_state.rs

1use std::cell::OnceCell;
2
3use anyhow::{Context, Result, bail, ensure};
4use octocrab::Octocrab;
5use octocrab::models::repos::Object;
6use octocrab::params::repos::Reference;
7use verctl_core::repo::Repo;
8use verctl_core::stop;
9
10use crate::{block, client, drafts, is_not_found, lookup_failed};
11
12pub(crate) async fn require_tag_at(
13    crab: &Octocrab,
14    repo: &Repo,
15    tag: &str,
16    sha: &str,
17) -> Result<()> {
18    let named = read_tag(crab, repo, tag)
19        .await?
20        .with_context(|| format!("tag {tag} does not exist"))?;
21    ensure!(
22        named.eq_ignore_ascii_case(sha),
23        "tag {tag} names {named}, not the published commit {sha}"
24    );
25    Ok(())
26}
27
28/// The commit `tag` names, peeled through an annotated tag, or `None` when
29/// GitHub answers 404 for it.
30#[expect(
31    clippy::wildcard_enum_match_arm,
32    reason = "octocrab's ref Object is non_exhaustive, so a catch-all arm is required"
33)]
34pub(crate) async fn read_tag(crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<String>> {
35    let git_ref = match crab
36        .repos(&repo.owner, &repo.name)
37        .get_ref(&Reference::Tag(tag.to_owned()))
38        .await
39    {
40        Ok(git_ref) => git_ref,
41        Err(error) if is_not_found(&error) => return Ok(None),
42        Err(error) => return Err(lookup_failed(error, format!("read tag {tag}"))),
43    };
44    match git_ref.object {
45        Object::Commit { sha, url: _ } => Ok(Some(sha)),
46        Object::Tag {
47            sha: tag_sha,
48            url: _,
49        } => peel_tag(crab, repo, tag, &tag_sha).await.map(Some),
50        other => bail!("tag {tag} names {other:?}, not a commit"),
51    }
52}
53
54#[derive(serde::Deserialize)]
55struct TagTarget {
56    object: PeeledTarget,
57}
58
59#[derive(serde::Deserialize)]
60struct PeeledTarget {
61    sha: String,
62}
63
64async fn peel_tag(crab: &Octocrab, repo: &Repo, tag: &str, tag_sha: &str) -> Result<String> {
65    let peeled: TagTarget = crab
66        .get(
67            format!(
68                "/repos/{owner}/{name}/git/tags/{tag_sha}",
69                owner = repo.owner,
70                name = repo.name
71            ),
72            None::<&()>,
73        )
74        .await
75        .map_err(|error| lookup_failed(error, format!("peel tag {tag}")))?;
76    Ok(peeled.object.sha)
77}
78
79/// What GitHub has for one release tag.
80///
81/// Not `#[non_exhaustive]`: `verctl-release` constructs fixtures directly.
82#[derive(Debug, Clone, Default, PartialEq, Eq)]
83pub struct ReleaseState {
84    /// The commit the tag names, peeled through an annotated tag. `None` when
85    /// the tag does not exist.
86    pub tag: Option<String>,
87    /// Whether a Release exists for the tag, draft or published.
88    pub release: bool,
89    /// Whether that Release is a draft, which `release` publishes after its
90    /// uploads.
91    pub draft: bool,
92    /// Whether GitHub keeps that Release immutable: once published, its
93    /// assets and tag cannot change ([immutable releases]).
94    ///
95    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
96    pub immutable: bool,
97    /// The file names of the Release's assets whose upload completed.
98    pub assets: Vec<String>,
99    /// The stop record of a draft's body, which the last `release` run that
100    /// failed an upload wrote. Display only; a published Release has none.
101    pub stop: stop::Record,
102}
103
104/// Read the tag and the Release for `tag`, so a plan can tell which parts of a
105/// release still need doing.
106/// The Release is read even when the tag is missing: a draft has no tag
107/// until it is published, so a tagless draft is an incomplete release.
108///
109/// # Errors
110///
111/// Returns an error when the GitHub client cannot be built or when GitHub
112/// answers a tag or Release lookup with an error other than 404.
113/// It also returns one when the tag points at a tree or a blob.
114///
115/// Only a lookup that GitHub gave no answer to, meaning a transport failure
116/// or a 5xx, is a [`verctl_core::lookup::Unavailable`].
117/// A 401 from a bad token, a tag on a tree, and a malformed `GITHUB_API_URL`
118/// stay unmarked.
119///
120/// The Releases list comes from `list`, so the lookups of one plan read it
121/// once however many tags are missing.
122pub fn release_state(
123    token: &str,
124    repo: &Repo,
125    tag: &str,
126    list: &ReleaseList,
127) -> Result<ReleaseState> {
128    block(async {
129        let crab = client(token)?;
130        release_state_for_with(&crab, repo, tag, None, None, list).await
131    })
132}
133
134/// Like [`release_state`], also matching an untagged draft Release
135/// (`untagged-*`) whose title equals `name` and preferring drafts at `head`.
136///
137/// # Errors
138///
139/// Returns an error under the same conditions as [`release_state`].
140pub fn release_state_for(
141    token: &str,
142    repo: &Repo,
143    tag: &str,
144    name: &str,
145    head: &str,
146    list: &ReleaseList,
147) -> Result<ReleaseState> {
148    block(async {
149        let crab = client(token)?;
150        release_state_for_with(&crab, repo, tag, Some(name), Some(head), list).await
151    })
152}
153
154#[cfg(test)]
155pub(crate) async fn release_state_with(
156    crab: &Octocrab,
157    repo: &Repo,
158    tag: &str,
159    list: &ReleaseList,
160) -> Result<ReleaseState> {
161    release_state_for_with(crab, repo, tag, None, None, list).await
162}
163
164pub(crate) async fn release_state_for_with(
165    crab: &Octocrab,
166    repo: &Repo,
167    tag: &str,
168    title: Option<&str>,
169    head: Option<&str>,
170    list: &ReleaseList,
171) -> Result<ReleaseState> {
172    let tag_sha = read_tag(crab, repo, tag).await?;
173    let release = find_release_for(crab, repo, tag, title, head, list).await?;
174    Ok(ReleaseState {
175        tag: tag_sha,
176        release: release.is_some(),
177        draft: release.as_ref().is_some_and(|release| release.draft),
178        immutable: release.as_ref().is_some_and(|release| release.immutable),
179        assets: release
180            .as_ref()
181            .map_or_default(|release| release.uploaded().into_iter().map(str::to_owned).collect()),
182        stop: release
183            .as_ref()
184            .filter(|release| release.draft)
185            .map_or_default(|release| stop::read(release.body.as_deref().unwrap_or_default())),
186    })
187}
188
189/// The part of a Release verctl reads, draft or published.
190#[derive(Debug, Clone, serde::Deserialize)]
191pub struct ReleaseRecord {
192    pub(crate) id: u64,
193    pub(crate) html_url: String,
194    pub(crate) tag_name: String,
195    #[serde(default)]
196    pub(crate) name: Option<String>,
197    /// The commit or branch the tag is created at when the Release is
198    /// published. GitHub reports it for every Release. A server that does not
199    /// report it names no commit, so a draft without it is stale.
200    #[serde(default)]
201    pub(crate) target_commitish: String,
202    pub(crate) draft: bool,
203    /// Reported by GitHub for every Release. A server that does not report
204    /// it keeps the Release mutable.
205    #[serde(default)]
206    pub(crate) immutable: bool,
207    /// The notes. GitHub reports `null` for a Release with none.
208    #[serde(default)]
209    pub(crate) body: Option<String>,
210    #[serde(default)]
211    pub(crate) upload_url: String,
212    pub(crate) assets: Vec<ForgeAsset>,
213}
214
215impl ReleaseRecord {
216    /// The Release's id.
217    #[must_use]
218    pub const fn id(&self) -> u64 {
219        self.id
220    }
221
222    /// The Release's HTML URL.
223    #[must_use]
224    pub fn url(&self) -> &str {
225        &self.html_url
226    }
227
228    /// The names of the assets whose upload completed.
229    #[must_use]
230    pub fn uploaded(&self) -> Vec<&str> {
231        self.assets
232            .iter()
233            .filter(|asset| asset.state == "uploaded")
234            .map(|asset| asset.name.as_str())
235            .collect()
236    }
237}
238
239#[derive(Debug, Clone, serde::Deserialize)]
240pub(crate) struct ForgeAsset {
241    pub(crate) name: String,
242    /// The asset's API URL, which serves the file to a token that can read
243    /// the Release, a draft's included. GitHub reports it for every asset.
244    #[serde(default)]
245    pub(crate) url: String,
246    /// `uploaded` once GitHub has the whole file; an upload that broke off
247    /// leaves the asset in another state.
248    pub(crate) state: String,
249    /// `sha256:<hex>` of the stored file. GitHub reports `null` for an asset
250    /// it contains no digest for.
251    #[serde(default)]
252    pub(crate) digest: Option<String>,
253}
254
255/// Releases read per page; GitHub's maximum.
256const RELEASES_PER_PAGE: usize = 100;
257
258/// Pages of Releases a lookup reads before it stops, so a repository with
259/// thousands of Releases costs ten requests instead of one per page.
260/// A draft verctl creates is the newest Release, so it is on the first page.
261const MAX_RELEASE_PAGES: u32 = 10;
262
263/// The Releases of a repository as `GET /releases` lists them, drafts
264/// included, read at most once.
265///
266/// A run looks up several tags, and a draft has no tag until it is
267/// published, so each missing tag would otherwise read the list again, up to
268/// ten pages each. The caller has one for the lookups
269/// of a run, before it writes anything: a Release the run creates afterwards
270/// is not in it.
271#[derive(Debug, Default)]
272pub struct ReleaseList {
273    listed: OnceCell<Vec<ReleaseRecord>>,
274}
275
276impl ReleaseList {
277    async fn find_for(
278        &self,
279        crab: &Octocrab,
280        repo: &Repo,
281        tag: &str,
282        title: Option<&str>,
283        head: Option<&str>,
284    ) -> Result<Option<ReleaseRecord>> {
285        let listed = if let Some(listed) = self.listed.get() {
286            listed
287        } else {
288            let read = list_releases(crab, repo).await?;
289            self.listed.get_or_init(|| read)
290        };
291        Ok(drafts::select_release(listed, tag, title, head))
292    }
293}
294
295/// Every Release `GET /releases` lists, newest first, which shows drafts to
296/// a token with push access ([list releases]), up to [`MAX_RELEASE_PAGES`]
297/// pages.
298/// A draft verctl creates is the newest Release, so it is on the first page;
299/// a draft older than the newest 1000 Releases is not found.
300///
301/// [list releases]: https://docs.github.com/en/rest/releases/releases#list-releases
302async fn list_releases(crab: &Octocrab, repo: &Repo) -> Result<Vec<ReleaseRecord>> {
303    let mut listed = Vec::new();
304    for page in 1..=MAX_RELEASE_PAGES {
305        let releases: Vec<ReleaseRecord> = crab
306            .get(
307                format!(
308                    "/repos/{owner}/{name}/releases?per_page={RELEASES_PER_PAGE}&page={page}",
309                    owner = repo.owner,
310                    name = repo.name
311                ),
312                None::<&()>,
313            )
314            .await
315            .map_err(|error| lookup_failed(error, "list releases".to_owned()))?;
316        let last = releases.len() < RELEASES_PER_PAGE;
317        listed.extend(releases);
318        if last {
319            break;
320        }
321    }
322    Ok(listed)
323}
324
325/// The Release for `tag`, draft or published, or `None`.
326///
327/// `GET /releases/tags/{tag}` answers for a published Release in one
328/// request, even when GitHub serves its new tag a moment later. It returns
329/// 404 for a draft ([get a release by tag name]), and only then is the tag
330/// looked up in `list`, which a draft is in: a draft has no tag until it is
331/// published.
332///
333/// [get a release by tag name]: https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name
334pub(crate) async fn find_release(
335    crab: &Octocrab,
336    repo: &Repo,
337    tag: &str,
338    list: &ReleaseList,
339) -> Result<Option<ReleaseRecord>> {
340    find_release_for(crab, repo, tag, None, None, list).await
341}
342
343pub(crate) async fn find_release_for(
344    crab: &Octocrab,
345    repo: &Repo,
346    tag: &str,
347    title: Option<&str>,
348    head: Option<&str>,
349    list: &ReleaseList,
350) -> Result<Option<ReleaseRecord>> {
351    let published: Result<ReleaseRecord, _> = crab
352        .get(
353            format!(
354                "/repos/{owner}/{name}/releases/tags/{tag}",
355                owner = repo.owner,
356                name = repo.name
357            ),
358            None::<&()>,
359        )
360        .await;
361    match published {
362        Ok(found) => return Ok(Some(found)),
363        Err(error) if is_not_found(&error) => {}
364        Err(error) => return Err(lookup_failed(error, format!("get release {tag}"))),
365    }
366    list.find_for(crab, repo, tag, title, head).await
367}