Skip to main content

verctl_github/
pulls.rs

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/// An open pull request.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ExistingPr {
15    /// Link to the pull request.
16    pub url: String,
17    /// The pull request number.
18    pub number: u64,
19    /// Full hex SHA of the pull request's base branch tip as GitHub reports it.
20    pub base_sha: String,
21}
22
23/// The open pull request from `head` in this repository, if one exists.
24///
25/// # Errors
26///
27/// Returns an error when the GitHub client cannot be built or the call that
28/// lists pull requests fails.
29pub 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
52/// Sets the title and body of pull request `number` and returns its URL.
53///
54/// # Errors
55///
56/// Returns an error when the GitHub client cannot be built, the update
57/// request fails, or the response carries no URL.
58pub 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
75/// Opens a pull request from `head` into `base`.
76///
77/// # Errors
78///
79/// Returns an error when the GitHub client cannot be built or the create
80/// request fails, for example when `head` does not exist.
81/// It also returns one when the response carries no URL.
82pub 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
111/// Posts `comment` on pull request `number`, closes it, and returns its URL.
112///
113/// # Errors
114///
115/// Returns an error when the GitHub client cannot be built, the comment or
116/// close request fails, or the closed pull request response carries no URL.
117pub 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
163/// Whether the pull request of this `pull_request` event is a Version PR by
164/// the identity of the `version-pr-identity` design ยง1.
165/// Its head repository is this repository, and its head branch is
166/// `verctl/release/<base>` for the base it targets now.
167///
168/// The check reads all three through the API when it runs.
169/// It never reads the event payload, because a base can change after the
170/// event and a label applied after opening is missing from the `opened`
171/// payload.
172/// It never reads the title, body, or labels, and it ignores
173/// `GITHUB_HEAD_REF`.
174///
175/// Without an event, or for an event that is not a pull request's, it is
176/// `false`.
177///
178/// # Errors
179///
180/// Returns an error when the event names a pull request but no token is set.
181/// It also returns one when `GITHUB_REPOSITORY` is not `owner/name` or GitHub
182/// cannot read the pull request.
183pub 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/// Who opened a pull request, and where its head branch lives.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct PullAuthor {
218    /// The author's login.
219    pub login: String,
220    /// GitHub's user `type`: `User` for a person, `Bot` for an app.
221    pub kind: String,
222    /// The head branch lives outside the repository: a fork, or a branch that
223    /// GitHub has dropped. Maintainers push branches to the repository itself.
224    pub from_fork: bool,
225}
226
227/// The author of pull request `number`, from
228/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
229///
230/// # Errors
231///
232/// Returns an error when the GitHub client cannot be built or the request or
233/// its decoding fails, for example when pull request `number` does not exist.
234///
235/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
236pub 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
283/// The labels of pull request `number`, from
284/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
285///
286/// # Errors
287///
288/// Returns an error when the GitHub client cannot be built or the request or
289/// its decoding fails, for example when pull request `number` does not exist.
290///
291/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
292pub 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}