Skip to main content

jouet_github/pr/
land.rs

1//! The GitHub writes behind `jouet pr land`: updating a branch with its
2//! base, merging, and confirming the merge.
3//!
4//! Both writes go through the REST endpoints that take the head SHA as a
5//! guard, so a push between the check and the write makes GitHub refuse
6//! rather than merge something nobody looked at. Neither ever force-pushes:
7//! updating merges the base into the branch on GitHub. Merging asks for the
8//! same merge a person gets from the button, so branch protection applies
9//! and nothing here asks to bypass it.
10//!
11//! A PR in one of GitHub's native stacks cannot go through the merge
12//! endpoint: GitHub only merges it through the asynchronous one, which
13//! takes the same head SHA guard, merges in the background, and is polled
14//! for its result. It merges every PR below the one named as well, so
15//! callers use it only for the bottom PR of a stack.
16
17use super::target::Repo;
18use crate::{Client, Failure, Rest};
19use serde_json::{Value, json};
20
21/// How the merge is made.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Method {
24    Squash,
25    Merge,
26    Rebase,
27}
28
29impl Method {
30    pub fn parse(s: &str) -> Option<Self> {
31        match s {
32            "squash" => Some(Self::Squash),
33            "merge" => Some(Self::Merge),
34            "rebase" => Some(Self::Rebase),
35            _ => None,
36        }
37    }
38
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::Squash => "squash",
42            Self::Merge => "merge",
43            Self::Rebase => "rebase",
44        }
45    }
46}
47
48/// Why a write did not happen.
49#[derive(Debug)]
50pub enum Refused {
51    /// GitHub refused it: branch protection, a head that moved, a method
52    /// the repository does not allow, or missing permission. Its message.
53    Rejected(String),
54    NotFound(String),
55    /// The request failed: network, rate limit, or a 5xx.
56    Failed(Failure),
57}
58
59impl From<Failure> for Refused {
60    fn from(f: Failure) -> Self {
61        Self::Failed(f)
62    }
63}
64
65fn pulls(repo: &Repo, number: u64) -> String {
66    format!("/repos/{}/{}/pulls/{number}", repo.owner, repo.name)
67}
68
69/// Asks GitHub to merge the base into the branch, if the head is still
70/// `head_oid`. GitHub does this in the background, so the new head appears
71/// a moment after this returns.
72pub fn update_branch(
73    client: &mut Client,
74    repo: &Repo,
75    number: u64,
76    head_oid: &str,
77) -> Result<(), Refused> {
78    let path = format!("{}/update-branch", pulls(repo, number));
79    let resp = client.put(&path, &json!({ "expected_head_sha": head_oid }))?;
80    match resp.status {
81        200..=299 => Ok(()),
82        _ => Err(refusal(repo, number, &resp)),
83    }
84}
85
86/// Merges the PR if its head is still `head_oid`, and returns the merge
87/// commit GitHub reports.
88pub fn merge(
89    client: &mut Client,
90    repo: &Repo,
91    number: u64,
92    head_oid: &str,
93    method: Method,
94) -> Result<Option<String>, Refused> {
95    let path = format!("{}/merge", pulls(repo, number));
96    let body = json!({ "merge_method": method.as_str(), "sha": head_oid });
97    let resp = client.put(&path, &body)?;
98    match resp.status {
99        200 => Ok(read(&resp)?["sha"].as_str().map(str::to_string)),
100        _ => Err(refusal(repo, number, &resp)),
101    }
102}
103
104/// Asks GitHub to merge a stacked PR in the background through the
105/// asynchronous merge endpoint, if its head is still `head_oid`. Like the
106/// merge endpoint, it applies branch protection; `direct_merge` keeps it from
107/// queueing the PR instead. It merges the PRs below this one too.
108pub fn merge_async(
109    client: &mut Client,
110    repo: &Repo,
111    number: u64,
112    head_oid: &str,
113    method: Method,
114) -> Result<Async, Refused> {
115    let path = format!("{}/merge-async", pulls(repo, number));
116    let body = json!({
117        "merge_method": method.as_str(),
118        "merge_action": "direct_merge",
119        "sha": head_oid,
120    });
121    let resp = client.put(&path, &body)?;
122    match resp.status {
123        200 | 202 => Ok(Async::read(&read(&resp)?)),
124        // Not mergeable, such as closed or a draft.
125        400 => Err(Refused::Rejected(Async::message(&resp))),
126        409 => Err(Refused::Rejected(format!(
127            "GitHub already has a merge request for it, which may use other options: {}",
128            Async::message(&resp)
129        ))),
130        // GitHub sends 404 both when the asynchronous merge, which a
131        // stacked PR needs, is not available and when the PR is not found.
132        404 => Err(Refused::Rejected(format!(
133            "GitHub's asynchronous merge is not available for {repo}, or {repo}#{number} was not found: {}",
134            Async::message(&resp)
135        ))),
136        _ => Err(refusal(repo, number, &resp)),
137    }
138}
139
140/// Where an asynchronous merge GitHub accepted as `uuid` stands now.
141pub fn merge_async_result(
142    client: &mut Client,
143    repo: &Repo,
144    number: u64,
145    uuid: &str,
146) -> Result<Async, Refused> {
147    let path = format!("{}/merge-async/{uuid}", pulls(repo, number));
148    let resp = client.get(&path, None)?;
149    match resp.status {
150        200 => Ok(Async::read(&read(&resp)?)),
151        _ => Err(refusal(repo, number, &resp)),
152    }
153}
154
155/// Where an asynchronous merge stands.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub enum Async {
158    /// Running in the background; poll it by this id.
159    Pending(String),
160    /// Merged, with the merge commit GitHub reports.
161    Merged(Option<String>),
162    /// Added to the base branch's merge queue instead.
163    Enqueued,
164    /// Not merged (a conflict, an unmet branch rule), and why. The merge is
165    /// atomic, so nothing in the stack was merged.
166    Failed(String),
167}
168
169impl Async {
170    fn read(v: &Value) -> Self {
171        let details = &v["details"];
172        let text = |key: &str| details[key].as_str().map(str::to_string);
173        match v["status"].as_str() {
174            Some("pending") => Self::Pending(text("uuid").unwrap_or_default()),
175            Some("merged") => Self::Merged(text("sha")),
176            Some("enqueued") => Self::Enqueued,
177            _ => Self::Failed(text("message").unwrap_or_else(|| v.to_string())),
178        }
179    }
180
181    /// The message of a refused request, which comes either as the result
182    /// object or as GitHub's usual error.
183    fn message(resp: &Rest) -> String {
184        let v = serde_json::from_str::<Value>(&resp.body).unwrap_or_default();
185        v["details"]["message"]
186            .as_str()
187            .or(v["message"].as_str())
188            .map_or_else(|| resp.body.trim().to_string(), str::to_string)
189    }
190}
191
192/// The PR as the REST API reads it: whether it is merged, its merge commit,
193/// its base, and the stack it is in.
194pub fn pull(client: &mut Client, repo: &Repo, number: u64) -> Result<Pull, Refused> {
195    let resp = client.get(&pulls(repo, number), None)?;
196    if resp.status != 200 {
197        return Err(refusal(repo, number, &resp));
198    }
199    let pr = read(&resp)?;
200    let stack = &pr["stack"];
201    Ok(Pull {
202        merged: pr["merged"].as_bool().unwrap_or(false),
203        merge_commit: pr["merge_commit_sha"].as_str().map(str::to_string),
204        base: pr["base"]["ref"].as_str().unwrap_or_default().to_string(),
205        stack: stack["number"].as_u64().map(|number| Stack {
206            number,
207            base: stack["base"]["ref"]
208                .as_str()
209                .unwrap_or_default()
210                .to_string(),
211        }),
212    })
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct Pull {
217    pub merged: bool,
218    pub merge_commit: Option<String>,
219    /// The branch the PR targets.
220    pub base: String,
221    pub stack: Option<Stack>,
222}
223
224/// A GitHub native stack a PR is in.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct Stack {
227    pub number: u64,
228    /// The branch the whole stack targets. Only the bottom open PR targets
229    /// it directly; the others target the branch of the PR below them.
230    pub base: String,
231}
232
233fn read(resp: &Rest) -> Result<Value, Failure> {
234    serde_json::from_str(&resp.body)
235        .map_err(|e| Failure::Other(format!("GitHub sent a response jouet could not read: {e}")))
236}
237
238/// A response other than success, as GitHub explained it. A 5xx is a
239/// failure, not a refusal, since the write may still have happened.
240fn refusal(repo: &Repo, number: u64, resp: &Rest) -> Refused {
241    let message = serde_json::from_str::<Value>(&resp.body)
242        .ok()
243        .and_then(|v| v["message"].as_str().map(str::to_string))
244        .unwrap_or_else(|| resp.body.trim().to_string());
245    match resp.status {
246        404 => Refused::NotFound(format!("{repo}#{number} does not exist")),
247        403 | 405 | 409 | 422 => Refused::Rejected(message),
248        status => Refused::Failed(Failure::Other(format!(
249            "GitHub returned {status}: {message}"
250        ))),
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn methods_are_the_three_github_allows() {
260        for m in ["squash", "merge", "rebase"] {
261            assert_eq!(Method::parse(m).map(Method::as_str), Some(m));
262        }
263        assert_eq!(Method::parse("fast-forward"), None);
264    }
265
266    #[test]
267    fn rejections_carry_githubs_message() {
268        let repo = Repo::parse("jdx/demo").unwrap();
269        let resp = |status, body: &str| Rest {
270            status,
271            etag: None,
272            link: None,
273            body: body.into(),
274        };
275        let protected = resp(
276            405,
277            r#"{"message":"At least 1 approving review is required by reviewers with write access."}"#,
278        );
279        assert!(matches!(
280            refusal(&repo, 7, &protected),
281            Refused::Rejected(m) if m.starts_with("At least 1 approving review")
282        ));
283        assert!(matches!(
284            refusal(&repo, 7, &resp(404, r#"{"message":"Not Found"}"#)),
285            Refused::NotFound(m) if m == "jdx/demo#7 does not exist"
286        ));
287        assert!(matches!(
288            refusal(&repo, 7, &resp(502, "bad gateway")),
289            Refused::Failed(Failure::Other(m)) if m == "GitHub returned 502: bad gateway"
290        ));
291    }
292}