verctl-github 0.9.6

GitHub REST client for verctl releases, pull requests, tags, and branch rules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use std::fmt;
use std::time::Duration;

use anyhow::{Context, Result, bail, ensure};
use octocrab::Octocrab;
use octocrab::repos::releases::MakeLatest;
use tokio::time;
use verctl_core::repo::Repo;

use crate::drafts::{self, finalize, open_draft_with, publish_draft_with};
use crate::release_state::{
    ReleaseList, ReleaseRecord, find_release, find_release_for, read_tag, require_tag_at,
};
use crate::{asset_upload, block, client, is_not_found};

/// Where a Release stands: the stable one, or a candidate before it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    /// A stable version: GitHub's defaults apply, so the Release becomes the
    /// repository's latest.
    Stable,
    /// A candidate: a prerelease that never becomes the latest Release, so
    /// the repository's latest stays the stable one ([create a release]).
    ///
    /// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
    Candidate,
}

/// The Release a run creates for a tag: a draft for `release`, or a Release
/// published at once for [`ensure_release`].
///
/// Not `#[non_exhaustive]`: `verctl-release` constructs it directly.
#[derive(Debug, Clone, Copy)]
pub struct NewRelease<'a> {
    /// The tag the Release is for.
    pub tag: &'a str,
    /// The Release title.
    pub name: &'a str,
    /// The Release notes.
    pub body: &'a str,
    /// The commit the tag is created at, and the one an existing tag must name.
    pub sha: &'a str,
    /// Whether the Release is the stable one or a candidate.
    pub stage: Stage,
    /// The asset names the draft must contain before it is published, because
    /// an immutable Release takes no asset once published ([immutable
    /// releases]). Empty, the draft is published with none.
    ///
    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
    pub assets: &'a [String],
}

/// Whether a release run uploaded a package under a tag.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PackageUpload {
    /// This run published a package under the tag, so an existing release's
    /// tag must match `sha`.
    #[default]
    Shipped,
    /// Nothing under the tag shipped in this run; an existing published
    /// release may stay at its earlier commit.
    Skipped,
}

/// Create `tag` at `sha` if it is missing. Returns the release HTML URL.
///
/// A new Release is a [`Stage::Stable`] one, with GitHub's defaults, and is
/// published at once. An existing release is used as it is, and a draft found
/// is published.
///
/// An existing release is not trusted: GitHub's `target_commitish` on the
/// Release object is a branch name more often than a SHA. The git ref is
/// re-read either way, and a tag that names another commit fails.
///
/// # Errors
///
/// Returns an error when:
///
/// - The GitHub client cannot be built.
/// - A release or tag lookup fails.
/// - The release cannot be created, or a draft found cannot be published.
/// - The tag does not point at `sha`.
///
/// The tag is checked against an existing release only when `upload` is
/// [`PackageUpload::Shipped`].
pub fn ensure_release(
    token: &str,
    repo: &Repo,
    tag: &str,
    name: &str,
    body: &str,
    sha: &str,
    upload: PackageUpload,
) -> Result<String> {
    let release = NewRelease {
        tag,
        name,
        body,
        sha,
        stage: Stage::Stable,
        assets: &[],
    };
    block(async {
        let crab = client(token)?;
        ensure_release_with(&crab, repo, &release, upload).await
    })
}

/// [`PackageUpload::Shipped`] means this run published a package under the
/// tag. With [`PackageUpload::Skipped`], an existing published release belongs
/// to the run that did, and its tag may name that earlier commit. A draft's
/// tag is always checked.
pub(crate) async fn ensure_release_with(
    crab: &Octocrab,
    repo: &Repo,
    release: &NewRelease<'_>,
    upload: PackageUpload,
) -> Result<String> {
    let NewRelease {
        tag,
        name,
        body,
        sha,
        stage,
        assets: _,
    } = *release;
    let existing = if read_tag(crab, repo, tag).await?.is_some() {
        find_release(crab, repo, tag, &ReleaseList::default()).await?
    } else {
        None
    };
    match existing {
        Some(found) if !found.draft => {
            if matches!(upload, PackageUpload::Shipped) {
                require_tag_at(crab, repo, tag, sha).await?;
            }
            return Ok(found.html_url);
        }
        Some(draft) => {
            require_tag_at(crab, repo, tag, sha).await?;
            return finalize(crab, repo, release, &draft).await;
        }
        None => {}
    }
    let repos = crab.repos(&repo.owner, &repo.name);
    let releases = repos.releases();
    let create = releases.create(tag).name(name).body(body);
    let create = match stage {
        Stage::Stable => create,
        Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
    };
    let created = create
        .target_commitish(sha)
        .send()
        .await
        .map_err(|error| release_error(error, tag, sha))?;
    require_tag_at(crab, repo, tag, sha).await?;
    Ok(created.html_url.to_string())
}

/// How long the tag proof waits before each read after the first, while
/// GitHub answers 404 for a tag that publishing the draft created.
/// Five reads over 15 seconds, inside the 30 seconds the release-tag-order
/// spec allows: GitHub can serve a new tag a moment after the Release that
/// created it, as in rawr run 43414046487.
pub const TAG_PROOF_DELAYS: [Duration; 4] = [
    Duration::from_secs(1),
    Duration::from_secs(2),
    Duration::from_secs(4),
    Duration::from_secs(8),
];

/// What a run finds on GitHub for one release tag, before it writes
/// anything.
#[derive(Debug)]
pub enum ExistingRelease {
    /// A Release published at HEAD. The run opens no draft for it and proves
    /// its tag. A mutable one takes the declared tarballs it lacks, so an
    /// older release missing a target can still be finished.
    Published(ReleaseRecord),
    /// No published Release: the run opens a draft for the tag.
    DraftState(DraftState),
}

impl ExistingRelease {
    /// The asset names already on the Release the run uploads to, or `None`
    /// for a published immutable Release, which takes no asset ([immutable
    /// releases]). Its shortfall is reported, and nothing is uploaded.
    ///
    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
    #[must_use]
    pub fn uploaded(&self) -> Option<Vec<&str>> {
        match self {
            Self::Published(release) if release.immutable => None,
            Self::Published(release) => Some(release.uploaded()),
            Self::DraftState(draft) => Some(draft.uploaded()),
        }
    }
}

/// A tag with no published Release, and the draft a run finds for it.
#[derive(Debug)]
pub enum DraftState {
    /// No Release exists for the tag.
    Missing,
    /// A draft at HEAD, which the run uploads to and publishes.
    AtHead(ReleaseRecord),
    /// A draft at another commit or at a branch name. Its tarballs were built
    /// from other code, so the run deletes it and creates a draft at HEAD.
    Stale(ReleaseRecord),
}

impl DraftState {
    /// The asset names uploaded on the draft the run keeps. A stale draft is
    /// deleted, so nothing on it counts.
    #[must_use]
    pub fn uploaded(&self) -> Vec<&str> {
        match self {
            Self::AtHead(draft) => draft.uploaded(),
            Self::Missing | Self::Stale(_) => Vec::new(),
        }
    }
}

/// Read what GitHub has for `tag`: the tag and its Release, draft or
/// published, so a run reads what to create before it writes anything.
///
/// A tag that exists must name `head`, whatever the Release's state: GitHub
/// uses an existing tag when a draft is published, so a tag on another commit
/// would fail the tag proof after the uploads.
/// A published Release counts as at HEAD when its tag names `head`, or when
/// GitHub serves no tag yet and the Release's `target_commitish` is `head`.
/// A draft counts as at HEAD when its `target_commitish` is `head`, or when
/// its tag names `head`.
///
/// The Releases list comes from `list`, which the run shares with its plan.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, when a lookup
/// fails, when the tag names a commit other than `head`, or when a Release is
/// published at another commit.
pub fn read_release(
    token: &str,
    repo: &Repo,
    tag: &str,
    head: &str,
    list: &ReleaseList,
) -> Result<ExistingRelease> {
    block(async {
        let crab = client(token)?;
        read_release_with(&crab, repo, tag, None, head, list).await
    })
}

/// Like [`read_release`], also matching an untagged draft Release
/// (`untagged-*`) whose title equals `name` so reruns reuse or replace drafts
/// whose tag GitHub cleared.
///
/// # Errors
///
/// Returns an error under the same conditions as [`read_release`].
pub fn read_release_for(
    token: &str,
    repo: &Repo,
    tag: &str,
    name: &str,
    head: &str,
    list: &ReleaseList,
) -> Result<ExistingRelease> {
    block(async {
        let crab = client(token)?;
        read_release_with(&crab, repo, tag, Some(name), head, list).await
    })
}

pub(crate) async fn read_release_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    title: Option<&str>,
    head: &str,
    list: &ReleaseList,
) -> Result<ExistingRelease> {
    let named = read_tag(crab, repo, tag).await?;
    if let Some(named) = &named {
        ensure!(
            named.eq_ignore_ascii_case(head),
            "tag {tag} names {named}, not HEAD {head}"
        );
    }
    let Some(release) = find_release_for(crab, repo, tag, title, Some(head), list).await? else {
        return Ok(ExistingRelease::DraftState(DraftState::Missing));
    };
    let untagged = release.tag_name != tag;
    let at_head =
        (named.is_some() && !untagged) || release.target_commitish.eq_ignore_ascii_case(head);
    if release.draft {
        return Ok(ExistingRelease::DraftState(if at_head {
            DraftState::AtHead(release)
        } else {
            DraftState::Stale(release)
        }));
    }
    ensure!(
        at_head,
        "release {tag} is published at {target}, not HEAD {head}, and GitHub serves no tag {tag}",
        target = release.target_commitish
    );
    Ok(ExistingRelease::Published(release))
}

/// The id of the draft for `release`: the one `found` names at HEAD, or a new
/// draft with `target_commitish` set to `release.sha`.
/// A stale draft is deleted first.
///
/// The draft creates no tag: GitHub creates it at `target_commitish` when the
/// draft is published ([create a release]).
/// Until then the draft can still be changed or deleted, so a failed upload
/// leaves no tag behind.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, a stale draft
/// cannot be deleted, or the draft cannot be created.
/// A 403 on the create names the missing permission.
///
/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
pub fn open_draft(
    token: &str,
    repo: &Repo,
    release: &NewRelease<'_>,
    found: &DraftState,
) -> Result<u64> {
    block(async {
        let crab = client(token)?;
        open_draft_with(&crab, repo, release, found).await
    })
}

/// The HTML URL of the Release `id`, draft or published, which the report of
/// a run that leaves the draft names.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the Release
/// cannot be read.
pub fn release_url(token: &str, repo: &Repo, id: u64) -> Result<String> {
    block(async {
        let crab = client(token)?;
        let release: ReleaseRecord = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/releases/{id}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read the release {id}"))?;
        Ok(release.url().to_owned())
    })
}

/// Publish the draft `id` for `release`, which creates its tag at
/// `release.sha`, and return the Release URL.
///
/// The draft is read again first, so the check sees what GitHub has: a
/// draft that lacks a declared asset is never published.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the draft cannot
/// be read or published, or it lacks a declared asset.
pub fn publish_draft(
    token: &str,
    repo: &Repo,
    release: &NewRelease<'_>,
    id: u64,
) -> Result<String> {
    block(async {
        let crab = client(token)?;
        publish_draft_with(&crab, repo, release, id).await
    })
}

/// Write `body` as the notes of draft `id` of `tag`, preserving `tag_name`
/// while leaving `draft` unset so the draft keeps both its state and its tag.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the update
/// fails.
pub fn write_draft_body(token: &str, repo: &Repo, tag: &str, id: u64, body: &str) -> Result<()> {
    block(async {
        let crab = client(token)?;
        drafts::write_draft_body_with(&crab, repo, tag, id, body).await
    })
}

/// Prove that `tag` names `head`, reading it again after each of `delays`
/// while GitHub answers 404.
///
/// Publishing a draft creates its tag, and GitHub can serve the tag a moment
/// after the Release. Only a 404 is read again: any other error, and a tag
/// that names another commit, fail at once.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, a read fails with
/// anything but 404, the tag names a commit other than `head`, or every read
/// answers 404. The last names the tag and the number of reads.
pub fn prove_tag(
    token: &str,
    repo: &Repo,
    tag: &str,
    head: &str,
    delays: &[Duration],
) -> Result<()> {
    block(async {
        let crab = client(token)?;
        prove_tag_with(&crab, repo, tag, head, delays).await
    })
}

pub(crate) async fn prove_tag_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    head: &str,
    delays: &[Duration],
) -> Result<()> {
    let mut waits = delays.iter();
    let mut reads = 0_usize;
    loop {
        reads += 1;
        if let Some(named) = read_tag(crab, repo, tag).await? {
            ensure!(
                named.eq_ignore_ascii_case(head),
                "tag {tag} names {named}, not HEAD {head}"
            );
            return Ok(());
        }
        let Some(wait) = waits.next() else {
            bail!(
                "GitHub serves no tag {tag} after {reads} reads, though its Release is published; rerun release to read the tag again"
            );
        };
        time::sleep(*wait).await;
    }
}

/// The Release for a vendored set's `tag`, created at `sha` when the tag has
/// none. Returns its HTML URL.
///
/// An existing Release is used as it is.
/// Its tag records which commit built the first asset, and that commit is
/// not a version commit, so the tag target is not checked.
///
/// A new Release is created with `make_latest: false`.
/// GitHub otherwise makes every new published Release the latest of the
/// repository ([create a release]).
/// A vendored library must not displace the Release of the repository itself.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or when reading the
/// Release fails with anything but 404.
/// It also returns one when creating the Release fails for any reason other
/// than another job having created it first.
///
/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
pub fn ensure_vendored_release(
    token: &str,
    repo: &Repo,
    tag: &str,
    body: &str,
    sha: &str,
) -> Result<String> {
    block(async {
        let crab = client(token)?;
        ensure_vendored_release_with(&crab, repo, tag, body, sha).await
    })
}

/// Every target's job runs this, so two can find the Release missing at once.
/// GitHub refuses one of them with `already_exists`, and that job reads the
/// Release the other created.
pub(crate) async fn ensure_vendored_release_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    body: &str,
    sha: &str,
) -> Result<String> {
    let repos = crab.repos(&repo.owner, &repo.name);
    let releases = repos.releases();
    match releases.get_by_tag(tag).await {
        Ok(release) => return Ok(release.html_url.to_string()),
        Err(error) if is_not_found(&error) => {}
        Err(error) => return Err(error).with_context(|| format!("read release {tag}")),
    }
    let created = releases
        .create(tag)
        .name(tag)
        .body(body)
        .target_commitish(sha)
        .make_latest(MakeLatest::False)
        .send()
        .await;
    match created {
        Ok(release) => Ok(release.html_url.to_string()),
        Err(error) if asset_upload::is_already_exists(&error) => {
            let release = releases
                .get_by_tag(tag)
                .await
                .with_context(|| format!("read release {tag}, which another job created"))?;
            Ok(release.html_url.to_string())
        }
        Err(error) => Err(release_error(error, tag, sha)),
    }
}

/// Names the cause of GitHub's 403 for a new Release.
/// Creating a Release takes `contents: write`, plus `workflows: write` when
/// the commit the tag would point at has a `.github/workflows` tree that
/// differs from the default branch.
/// The `X-Accepted-GitHub-Permissions` header of the refusal lists both sets.
///
/// An Actions `GITHUB_TOKEN` can never carry `workflows`, so releasing an
/// older version commit fails once a later commit changes a workflow.
pub(crate) fn release_error(error: octocrab::Error, tag: &str, sha: &str) -> anyhow::Error {
    let forbidden = matches!(
        &error,
        octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 403
    );
    let error = anyhow::Error::new(error).context("create GitHub release");
    if forbidden {
        error.context(ReleaseRefused {
            tag: tag.to_owned(),
            sha: sha.to_owned(),
        })
    } else {
        error
    }
}

/// GitHub's 403 on creating a Release.
/// The token lacks a permission the commit needs.
/// A rerun with a token that has the permission can still create the Release.
#[derive(Debug)]
pub(crate) struct ReleaseRefused {
    tag: String,
    sha: String,
}

impl fmt::Display for ReleaseRefused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "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",
            tag = self.tag,
            sha = self.sha
        )
    }
}