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::{env, io};
5
6use anyhow::{Context, Result};
7use octocrab::Octocrab;
8use reqwest::header::HeaderValue;
9use tokio::runtime::Builder;
10pub use verctl_core::env::{
11    default_branch_of, event_default_branch, event_is_merge_group, is_merge_group,
12    pull_request_number, write_github_output as write_output,
13};
14use verctl_core::lookup;
15pub use verctl_core::repo::{Repo, parse_remote, parse_slug};
16
17mod actions;
18mod asset_upload;
19mod drafts;
20mod pulls;
21mod release_assets;
22mod release_state;
23mod releases;
24
25pub use actions::{ActiveRun, active_run, branch_rule_types, fetch_oidc_token};
26pub use asset_upload::asset_content_type;
27#[cfg(test)]
28use drafts::{open_draft_with, publish_draft_with};
29pub use pulls::{
30    ExistingPr, PullAuthor, close_pr, create_pr, existing_pr, pull_author, pull_labels,
31    pull_request_is_version_pr, update_pr,
32};
33#[cfg(test)]
34use pulls::{close_pr_with, pull_author_with};
35pub use release_assets::{
36    AssetFile, asset_sha256, download_release_assets, upload_release_asset, upload_to_release,
37    uploaded_assets,
38};
39#[cfg(test)]
40use release_assets::{
41    Target, asset_sha256_with, download_release_assets_with, upload_release_asset_with,
42};
43pub use release_state::{
44    ReleaseList, ReleaseRecord, ReleaseState, release_state, release_state_for,
45};
46#[cfg(test)]
47use release_state::{find_release, release_state_for_with, release_state_with};
48pub(crate) use releases::release_error;
49pub use releases::{
50    DraftState, ExistingRelease, NewRelease, PackageUpload, Stage, TAG_PROOF_DELAYS,
51    ensure_release, ensure_vendored_release, open_draft, prove_tag, publish_draft, read_release,
52    read_release_for, release_url, write_draft_body,
53};
54#[cfg(test)]
55use releases::{
56    ReleaseRefused, ensure_release_with, ensure_vendored_release_with, prove_tag_with,
57    read_release_with,
58};
59
60/// Actions sets `GITHUB_REPOSITORY`. Locally, `origin` is the contract.
61///
62/// # Errors
63///
64/// Returns an error when `GITHUB_REPOSITORY` is set but is not `owner/name`,
65/// or, without it, when the `origin` URL cannot be read or is not a GitHub
66/// remote. Without `GITHUB_REPOSITORY`, the error is a
67/// [`lookup::Unavailable`]: the repository names no GitHub repository to ask.
68/// A malformed `GITHUB_REPOSITORY` is a setting to fix, so it stays unmarked.
69pub fn repo_with(origin_url: impl FnOnce() -> Result<String>) -> Result<Repo> {
70    if let Ok(slug) = env::var("GITHUB_REPOSITORY")
71        && !slug.is_empty()
72    {
73        return parse_slug(&slug);
74    }
75    origin_url()
76        .and_then(|url| parse_remote(url.trim()))
77        .map_err(lookup::unavailable)
78}
79
80/// The branch a Version PR targets: `GITHUB_REF_NAME`, else
81/// `VERCTL_DEFAULT_BRANCH`, else the branch `origin/HEAD` names.
82///
83/// If none of them is set, the call fails instead of guessing.
84/// A repository whose default is not `main` would otherwise get a Version PR
85/// against a branch it does not release from.
86///
87/// # Errors
88///
89/// Returns an error when none of those three sources names a branch.
90pub fn base_branch_with(
91    configured: Option<String>,
92    upstream: impl FnOnce() -> Option<String>,
93) -> Result<String> {
94    if let Ok(name) = env::var("GITHUB_REF_NAME")
95        && !name.is_empty()
96    {
97        return Ok(name);
98    }
99    configured
100        .or_else(upstream)
101        .context(
102            "cannot tell which branch the Version PR targets: set VERCTL_DEFAULT_BRANCH, or run `git remote set-head origin --auto`",
103        )
104}
105
106/// `error` under `context`, marked as a [`lookup::Unavailable`] when GitHub
107/// gave no answer.
108/// That covers two cases.
109/// The request failed in transport (DNS, connect, a timeout, a connection
110/// dropped while the body was read).
111/// Or GitHub answered with a 5xx or a rate limit after the retries of
112/// octocrab.
113/// [`lookup::no_answer`] separates those statuses from the rest.
114///
115/// Any other answer, such as a 401 or a plain 403, stays an error.
116///
117/// octocrab 0.54.5 turns every non-2xx answer into `GitHub` with its status
118/// and headers, whatever the body contains.
119/// Its `map_github_error` falls back to the body text when the body is not
120/// GitHub JSON.
121/// An HTML 502 from a proxy therefore keeps its status.
122///
123/// A transport failure reaches octocrab as `Service` from the HTTP client.
124/// It also arrives as `Hyper` while octocrab reads a body, alone or inside
125/// `Service`.
126/// `Service` also carries a request that the client blocks before sending.
127/// It counts only when an I/O or body error caused it.
128pub(crate) fn lookup_failed(error: octocrab::Error, context: String) -> anyhow::Error {
129    let refused = matches!(&error, octocrab::Error::GitHub { source, backtrace: _ }
130    if lookup::no_answer(
131        source.status_code.as_u16(),
132        source
133            .headers
134            .as_ref()
135            .and_then(|headers| headers.get("x-ratelimit-remaining"))
136            .map(HeaderValue::as_bytes),
137    ));
138    let body = matches!(
139        &error,
140        octocrab::Error::Hyper {
141            source: _,
142            backtrace: _
143        }
144    );
145    let service = matches!(
146        &error,
147        octocrab::Error::Service {
148            source: _,
149            backtrace: _
150        }
151    );
152    let error = anyhow::Error::new(error);
153    let transport = service
154        && error.chain().any(|cause| {
155            cause.is::<io::Error>()
156                || matches!(
157                    cause.downcast_ref::<octocrab::Error>(),
158                    Some(octocrab::Error::Hyper {
159                        source: _,
160                        backtrace: _
161                    })
162                )
163        });
164    let error = error.context(context);
165    if refused || body || transport {
166        lookup::unavailable(error)
167    } else {
168        error
169    }
170}
171
172pub(crate) fn is_not_found(error: &octocrab::Error) -> bool {
173    matches!(error, octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 404)
174}
175
176/// A GitHub client for `token`.
177/// It uses the API from `GITHUB_API_URL` when that is set, as on a GitHub
178/// Enterprise Server or a test's mock server.
179/// Otherwise it uses api.github.com.
180pub(crate) fn client(token: &str) -> Result<Octocrab> {
181    let mut builder = Octocrab::builder().personal_token(token.to_owned());
182    if let Ok(base) = env::var("GITHUB_API_URL")
183        && !base.is_empty()
184    {
185        builder = builder.base_uri(base).context("GITHUB_API_URL")?;
186    }
187    builder.build().context("GitHub client")
188}
189
190pub(crate) fn block<F, T>(fut: F) -> Result<T>
191where
192    F: Future<Output = Result<T>>,
193{
194    Builder::new_current_thread()
195        .enable_all()
196        .build()
197        .context("tokio")?
198        .block_on(fut)
199}
200
201#[cfg(test)]
202mod tests;