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};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingPr {
pub url: String,
pub number: u64,
pub base_sha: String,
}
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,
})
}))
})
}
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")
})
}
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,
})
})
}
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")
}
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))
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullAuthor {
pub login: String,
pub kind: String,
pub from_fork: bool,
}
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)),
})
}
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())
})
}