verctl-github 0.9.5

GitHub REST client for verctl releases, pull requests, tags, and branch rules
Documentation
use std::{env, fs};

use anyhow::{Context, Result};
use octocrab::Octocrab;
use octocrab::params::State;
use verctl_core::env as release_env;
use verctl_core::env::pull_request_number;
use verctl_core::repo::{Repo, parse_slug};

use crate::{block, client};

/// An open pull request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingPr {
    /// Link to the pull request.
    pub url: String,
    /// The pull request number.
    pub number: u64,
    /// Full hex SHA of the pull request's base branch tip as GitHub reports it.
    pub base_sha: String,
}

/// The open pull request from `head` in this repository, if one exists.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the call that
/// lists pull requests fails.
pub fn existing_pr(token: &str, repo: &Repo, head: &str) -> Result<Option<ExistingPr>> {
    block(async {
        let crab = client(token)?;
        let page = crab
            .pulls(&repo.owner, &repo.name)
            .list()
            .state(State::Open)
            .head(format!("{}:{head}", repo.owner))
            .per_page(1)
            .send()
            .await
            .context("list pull requests")?;
        Ok(page.items.into_iter().next().and_then(|pr| {
            let url = pr.html_url?.to_string();
            Some(ExistingPr {
                url,
                number: pr.number,
                base_sha: pr.base.sha,
            })
        }))
    })
}

/// Sets the title and body of pull request `number` and returns its URL.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the update
/// request fails, or the response carries no URL.
pub fn update_pr(token: &str, repo: &Repo, number: u64, title: &str, body: &str) -> Result<String> {
    block(async {
        let crab = client(token)?;
        let pr = crab
            .pulls(&repo.owner, &repo.name)
            .update(number)
            .title(title)
            .body(body)
            .send()
            .await
            .context("update pull request")?;
        pr.html_url
            .map(|url| url.to_string())
            .context("updated PR has no html_url")
    })
}

/// Opens a pull request from `head` into `base`.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the create
/// request fails, for example when `head` does not exist.
/// It also returns one when the response carries no URL.
pub fn create_pr(
    token: &str,
    repo: &Repo,
    title: &str,
    head: &str,
    base: &str,
    body: &str,
) -> Result<ExistingPr> {
    block(async {
        let crab = client(token)?;
        let pr = crab
            .pulls(&repo.owner, &repo.name)
            .create(title, head, base)
            .body(body)
            .send()
            .await
            .context("create pull request")?;
        let url = pr
            .html_url
            .map(|url| url.to_string())
            .context("created PR has no html_url")?;
        Ok(ExistingPr {
            url,
            number: pr.number,
            base_sha: pr.base.sha,
        })
    })
}

/// Posts `comment` on pull request `number`, closes it, and returns its URL.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the comment or
/// close request fails, or the closed pull request response carries no URL.
pub fn close_pr(token: &str, repo: &Repo, number: u64, comment: &str) -> Result<String> {
    block(async {
        let crab = client(token)?;
        close_pr_with(&crab, repo, number, comment).await
    })
}

pub(crate) async fn close_pr_with(
    crab: &Octocrab,
    repo: &Repo,
    number: u64,
    comment: &str,
) -> Result<String> {
    #[derive(serde::Serialize)]
    struct CommentBody<'a> {
        body: &'a str,
    }
    #[derive(serde::Serialize)]
    struct CloseState {
        state: &'static str,
    }
    #[derive(serde::Deserialize)]
    struct ClosedPull {
        html_url: Option<String>,
    }
    let comment_route = format!(
        "/repos/{owner}/{name}/issues/{number}/comments",
        owner = repo.owner,
        name = repo.name,
    );
    let _: serde_json::Value = crab
        .post(comment_route, Some(&CommentBody { body: comment }))
        .await
        .with_context(|| format!("comment on pull request #{number}"))?;
    let pull_route = format!(
        "/repos/{owner}/{name}/pulls/{number}",
        owner = repo.owner,
        name = repo.name,
    );
    let closed: ClosedPull = crab
        .patch(pull_route, Some(&CloseState { state: "closed" }))
        .await
        .with_context(|| format!("close pull request #{number}"))?;
    closed.html_url.context("closed PR has no html_url")
}

/// Whether the pull request of this `pull_request` event is a Version PR by
/// the identity of the `version-pr-identity` design §1.
/// Its head repository is this repository, and its head branch is
/// `verctl/release/<base>` for the base it targets now.
///
/// The check reads all three through the API when it runs.
/// It never reads the event payload, because a base can change after the
/// event and a label applied after opening is missing from the `opened`
/// payload.
/// It never reads the title, body, or labels, and it ignores
/// `GITHUB_HEAD_REF`.
///
/// Without an event, or for an event that is not a pull request's, it is
/// `false`.
///
/// # Errors
///
/// Returns an error when the event names a pull request but no token is set.
/// It also returns one when `GITHUB_REPOSITORY` is not `owner/name` or GitHub
/// cannot read the pull request.
pub fn pull_request_is_version_pr() -> Result<bool> {
    let Ok(path) = env::var("GITHUB_EVENT_PATH") else {
        return Ok(false);
    };
    let Ok(raw) = fs::read_to_string(path) else {
        return Ok(false);
    };
    let Some(number) = pull_request_number(&raw) else {
        return Ok(false);
    };
    let token = release_env::env_token().context(
        "the version check reads the pull request and needs GITHUB_TOKEN with pull-requests: read",
    )?;
    let slug = env::var("GITHUB_REPOSITORY").unwrap_or_default();
    let repo = parse_slug(&slug)?;
    block(async move {
        let crab = client(&token)?;
        let pr = crab
            .pulls(&repo.owner, &repo.name)
            .get(number)
            .await
            .with_context(|| format!("read pull request #{number}"))?;
        let same_repo = pr
            .head
            .repo
            .as_ref()
            .and_then(|head| head.full_name.as_deref())
            .is_some_and(|name| name.eq_ignore_ascii_case(&slug));
        Ok(same_repo && pr.head.ref_field == release_env::version_branch(&pr.base.ref_field))
    })
}

/// Who opened a pull request, and where its head branch lives.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullAuthor {
    /// The author's login.
    pub login: String,
    /// GitHub's user `type`: `User` for a person, `Bot` for an app.
    pub kind: String,
    /// The head branch lives outside the repository: a fork, or a branch that
    /// GitHub has dropped. Maintainers push branches to the repository itself.
    pub from_fork: bool,
}

/// The author of pull request `number`, from
/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, for example when pull request `number` does not exist.
///
/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
pub fn pull_author(token: &str, repo: &Repo, number: u64) -> Result<PullAuthor> {
    block(async {
        let crab = client(token)?;
        pull_author_with(&crab, repo, number).await
    })
}

pub(crate) async fn pull_author_with(
    crab: &Octocrab,
    repo: &Repo,
    number: u64,
) -> Result<PullAuthor> {
    #[derive(serde::Deserialize)]
    struct User {
        login: String,
        #[serde(rename = "type")]
        account_class: String,
    }
    #[derive(serde::Deserialize)]
    struct HeadRepo {
        full_name: String,
    }
    #[derive(serde::Deserialize)]
    struct Head {
        repo: Option<HeadRepo>,
    }
    #[derive(serde::Deserialize)]
    struct Pull {
        user: User,
        head: Head,
    }
    let route = format!("/repos/{}/{}/pulls/{number}", repo.owner, repo.name);
    let pull: Pull = crab
        .get(route, None::<&()>)
        .await
        .with_context(|| format!("read pull request #{number}"))?;
    let own = format!("{}/{}", repo.owner, repo.name);
    Ok(PullAuthor {
        login: pull.user.login,
        kind: pull.user.account_class,
        from_fork: pull
            .head
            .repo
            .is_none_or(|head| !head.full_name.eq_ignore_ascii_case(&own)),
    })
}

/// The labels of pull request `number`, from
/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, for example when pull request `number` does not exist.
///
/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
pub fn pull_labels(token: &str, repo: &Repo, number: u64) -> Result<Vec<String>> {
    #[derive(serde::Deserialize)]
    struct Label {
        name: String,
    }
    #[derive(serde::Deserialize)]
    struct Pull {
        labels: Vec<Label>,
    }
    block(async {
        let crab = client(token)?;
        let pull: Pull = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/pulls/{number}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read pull request #{number}"))?;
        Ok(pull.labels.into_iter().map(|label| label.name).collect())
    })
}