1use std::{env, fs};
2
3use anyhow::{Context, Result};
4use octocrab::Octocrab;
5use octocrab::params::State;
6use verctl_core::env as release_env;
7use verctl_core::env::pull_request_number;
8use verctl_core::repo::{Repo, parse_slug};
9
10use crate::{block, client};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ExistingPr {
15 pub url: String,
17 pub number: u64,
19 pub base_sha: String,
21}
22
23pub fn existing_pr(token: &str, repo: &Repo, head: &str) -> Result<Option<ExistingPr>> {
30 block(async {
31 let crab = client(token)?;
32 let page = crab
33 .pulls(&repo.owner, &repo.name)
34 .list()
35 .state(State::Open)
36 .head(format!("{}:{head}", repo.owner))
37 .per_page(1)
38 .send()
39 .await
40 .context("list pull requests")?;
41 Ok(page.items.into_iter().next().and_then(|pr| {
42 let url = pr.html_url?.to_string();
43 Some(ExistingPr {
44 url,
45 number: pr.number,
46 base_sha: pr.base.sha,
47 })
48 }))
49 })
50}
51
52pub fn update_pr(token: &str, repo: &Repo, number: u64, title: &str, body: &str) -> Result<String> {
59 block(async {
60 let crab = client(token)?;
61 let pr = crab
62 .pulls(&repo.owner, &repo.name)
63 .update(number)
64 .title(title)
65 .body(body)
66 .send()
67 .await
68 .context("update pull request")?;
69 pr.html_url
70 .map(|url| url.to_string())
71 .context("updated PR has no html_url")
72 })
73}
74
75pub fn create_pr(
83 token: &str,
84 repo: &Repo,
85 title: &str,
86 head: &str,
87 base: &str,
88 body: &str,
89) -> Result<ExistingPr> {
90 block(async {
91 let crab = client(token)?;
92 let pr = crab
93 .pulls(&repo.owner, &repo.name)
94 .create(title, head, base)
95 .body(body)
96 .send()
97 .await
98 .context("create pull request")?;
99 let url = pr
100 .html_url
101 .map(|url| url.to_string())
102 .context("created PR has no html_url")?;
103 Ok(ExistingPr {
104 url,
105 number: pr.number,
106 base_sha: pr.base.sha,
107 })
108 })
109}
110
111pub fn close_pr(token: &str, repo: &Repo, number: u64, comment: &str) -> Result<String> {
118 block(async {
119 let crab = client(token)?;
120 close_pr_with(&crab, repo, number, comment).await
121 })
122}
123
124pub(crate) async fn close_pr_with(
125 crab: &Octocrab,
126 repo: &Repo,
127 number: u64,
128 comment: &str,
129) -> Result<String> {
130 #[derive(serde::Serialize)]
131 struct CommentBody<'a> {
132 body: &'a str,
133 }
134 #[derive(serde::Serialize)]
135 struct CloseState {
136 state: &'static str,
137 }
138 #[derive(serde::Deserialize)]
139 struct ClosedPull {
140 html_url: Option<String>,
141 }
142 let comment_route = format!(
143 "/repos/{owner}/{name}/issues/{number}/comments",
144 owner = repo.owner,
145 name = repo.name,
146 );
147 let _: serde_json::Value = crab
148 .post(comment_route, Some(&CommentBody { body: comment }))
149 .await
150 .with_context(|| format!("comment on pull request #{number}"))?;
151 let pull_route = format!(
152 "/repos/{owner}/{name}/pulls/{number}",
153 owner = repo.owner,
154 name = repo.name,
155 );
156 let closed: ClosedPull = crab
157 .patch(pull_route, Some(&CloseState { state: "closed" }))
158 .await
159 .with_context(|| format!("close pull request #{number}"))?;
160 closed.html_url.context("closed PR has no html_url")
161}
162
163pub fn pull_request_is_version_pr() -> Result<bool> {
184 let Ok(path) = env::var("GITHUB_EVENT_PATH") else {
185 return Ok(false);
186 };
187 let Ok(raw) = fs::read_to_string(path) else {
188 return Ok(false);
189 };
190 let Some(number) = pull_request_number(&raw) else {
191 return Ok(false);
192 };
193 let token = release_env::env_token().context(
194 "the version check reads the pull request and needs GITHUB_TOKEN with pull-requests: read",
195 )?;
196 let slug = env::var("GITHUB_REPOSITORY").unwrap_or_default();
197 let repo = parse_slug(&slug)?;
198 block(async move {
199 let crab = client(&token)?;
200 let pr = crab
201 .pulls(&repo.owner, &repo.name)
202 .get(number)
203 .await
204 .with_context(|| format!("read pull request #{number}"))?;
205 let same_repo = pr
206 .head
207 .repo
208 .as_ref()
209 .and_then(|head| head.full_name.as_deref())
210 .is_some_and(|name| name.eq_ignore_ascii_case(&slug));
211 Ok(same_repo && pr.head.ref_field == release_env::version_branch(&pr.base.ref_field))
212 })
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct PullAuthor {
218 pub login: String,
220 pub kind: String,
222 pub from_fork: bool,
225}
226
227pub fn pull_author(token: &str, repo: &Repo, number: u64) -> Result<PullAuthor> {
237 block(async {
238 let crab = client(token)?;
239 pull_author_with(&crab, repo, number).await
240 })
241}
242
243pub(crate) async fn pull_author_with(
244 crab: &Octocrab,
245 repo: &Repo,
246 number: u64,
247) -> Result<PullAuthor> {
248 #[derive(serde::Deserialize)]
249 struct User {
250 login: String,
251 #[serde(rename = "type")]
252 account_class: String,
253 }
254 #[derive(serde::Deserialize)]
255 struct HeadRepo {
256 full_name: String,
257 }
258 #[derive(serde::Deserialize)]
259 struct Head {
260 repo: Option<HeadRepo>,
261 }
262 #[derive(serde::Deserialize)]
263 struct Pull {
264 user: User,
265 head: Head,
266 }
267 let route = format!("/repos/{}/{}/pulls/{number}", repo.owner, repo.name);
268 let pull: Pull = crab
269 .get(route, None::<&()>)
270 .await
271 .with_context(|| format!("read pull request #{number}"))?;
272 let own = format!("{}/{}", repo.owner, repo.name);
273 Ok(PullAuthor {
274 login: pull.user.login,
275 kind: pull.user.account_class,
276 from_fork: pull
277 .head
278 .repo
279 .is_none_or(|head| !head.full_name.eq_ignore_ascii_case(&own)),
280 })
281}
282
283pub fn pull_labels(token: &str, repo: &Repo, number: u64) -> Result<Vec<String>> {
293 #[derive(serde::Deserialize)]
294 struct Label {
295 name: String,
296 }
297 #[derive(serde::Deserialize)]
298 struct Pull {
299 labels: Vec<Label>,
300 }
301 block(async {
302 let crab = client(token)?;
303 let pull: Pull = crab
304 .get(
305 format!(
306 "/repos/{owner}/{name}/pulls/{number}",
307 owner = repo.owner,
308 name = repo.name
309 ),
310 None::<&()>,
311 )
312 .await
313 .with_context(|| format!("read pull request #{number}"))?;
314 Ok(pull.labels.into_iter().map(|label| label.name).collect())
315 })
316}