Skip to main content

gitpoulpi_hosting/
request_actions.rs

1//! Merging and closing a pull / merge request on the host.
2//!
3//! The one outward-facing write the Radar's row actions make: GitHub, GitLab
4//! and Gitea / Forgejo (the three families the Radar lists account-wide).
5//! Every other provider answers `Unsupported`; [`request_actions`] says which
6//! calls a kind takes, so a caller can gray the button before asking.
7//!
8//! Neither call is undoable locally: the host owns the result.
9
10use serde::{Deserialize, Serialize};
11
12use crate::integration::IntegrationKind;
13
14/// How a request is merged.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum MergeMethod {
18    /// A merge commit.
19    Merge,
20    /// All commits squashed into one.
21    Squash,
22    /// The commits replayed on the target (a fast-forward history).
23    Rebase,
24}
25
26impl MergeMethod {
27    pub const ALL: [MergeMethod; 3] =
28        [MergeMethod::Merge, MergeMethod::Squash, MergeMethod::Rebase];
29}
30
31/// What the host of a kind lets a request do.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub struct RequestActions {
34    pub merge: bool,
35    /// Rebase and merge (GitLab has no such call: its rebase is a separate,
36    /// asynchronous one).
37    pub rebase: bool,
38    pub close: bool,
39    /// Take a draft out of draft (GitHub, GitLab, Gitea, Forgejo).
40    pub ready: bool,
41}
42
43impl RequestActions {
44    pub fn takes(&self, method: MergeMethod) -> bool {
45        match method {
46            MergeMethod::Merge | MergeMethod::Squash => self.merge,
47            MergeMethod::Rebase => self.rebase,
48        }
49    }
50}
51
52/// `title` without its draft marker (`Draft:`, `[Draft]`, `(Draft)`, `WIP:`,
53/// `[WIP]`), or `None` when it carries none.
54pub fn strip_draft_prefix(title: &str) -> Option<String> {
55    let t = title.trim_start();
56    let lower = t.to_ascii_lowercase();
57    for prefix in ["draft:", "[draft]", "(draft)", "wip:", "[wip]"] {
58        if lower.starts_with(prefix) {
59            return Some(t[prefix.len()..].trim_start().to_string());
60        }
61    }
62    None
63}
64
65/// The calls the client of `kind` implements.
66pub fn request_actions(kind: IntegrationKind) -> RequestActions {
67    use gitpoulpi_config::ApiFamily;
68    match kind.family() {
69        ApiFamily::Github | ApiFamily::Gitea => RequestActions {
70            merge: true,
71            rebase: true,
72            close: true,
73            ready: true,
74        },
75        ApiFamily::Gitlab => RequestActions {
76            merge: true,
77            rebase: false,
78            close: true,
79            ready: true,
80        },
81        _ => RequestActions::default(),
82    }
83}
84
85#[cfg(any(feature = "github", feature = "gitea"))]
86fn method_word(method: MergeMethod) -> &'static str {
87    match method {
88        MergeMethod::Merge => "merge",
89        MergeMethod::Squash => "squash",
90        MergeMethod::Rebase => "rebase",
91    }
92}
93
94#[cfg(feature = "github")]
95impl crate::github::GitHubClient {
96    /// `PUT /pulls/{n}/merge` with the method.
97    pub(crate) async fn merge_request_now(
98        &self,
99        project: &str,
100        number: u64,
101        method: MergeMethod,
102    ) -> crate::Result<()> {
103        let url = format!(
104            "{}/repos/{project}/pulls/{number}/merge",
105            self.integration.api_base()
106        );
107        let body = serde_json::json!({ "merge_method": method_word(method) });
108        let request = self.authed(crate::http::HttpRequest::put_json(url, &body));
109        let response = self.transport.send(request).await?;
110        response.error_for_status("merging a GitHub pull request")
111    }
112
113    /// `PATCH /pulls/{n}` with `state: closed`.
114    pub(crate) async fn close_request_now(&self, project: &str, number: u64) -> crate::Result<()> {
115        let url = format!(
116            "{}/repos/{project}/pulls/{number}",
117            self.integration.api_base()
118        );
119        let body = serde_json::json!({ "state": "closed" });
120        let request = self.authed(crate::http::HttpRequest::patch_json(url, &body));
121        let response = self.transport.send(request).await?;
122        response.error_for_status("closing a GitHub pull request")
123    }
124
125    /// GraphQL `markPullRequestReadyForReview` (REST has no such call).
126    pub(crate) async fn ready_request_now(&self, project: &str, number: u64) -> crate::Result<()> {
127        let url = format!(
128            "{}/repos/{project}/pulls/{number}",
129            self.integration.api_base()
130        );
131        let response = self
132            .transport
133            .send(self.authed(crate::http::HttpRequest::get(url)))
134            .await?;
135        response.error_for_status("reading a GitHub pull request")?;
136        let pull: serde_json::Value = response.json()?;
137        let id = pull["node_id"]
138            .as_str()
139            .ok_or_else(|| crate::Error::Decode("no node_id in the pull request".to_string()))?;
140        self.graphql(
141            "marking a GitHub pull request ready for review",
142            "mutation($id: ID!) { markPullRequestReadyForReview(input: {pullRequestId: $id}) { pullRequest { id } } }",
143            serde_json::json!({ "id": id }),
144        )
145        .await?;
146        Ok(())
147    }
148}
149
150#[cfg(feature = "gitlab")]
151impl crate::gitlab::GitLabClient {
152    /// `PUT /merge_requests/{iid}/merge` (`squash` for the squash method).
153    pub(crate) async fn merge_request_now(
154        &self,
155        project: &str,
156        number: u64,
157        method: MergeMethod,
158    ) -> crate::Result<()> {
159        if method == MergeMethod::Rebase {
160            return Err(crate::Error::Unsupported("merge_pull_request".to_string()));
161        }
162        let url = format!(
163            "{}/projects/{}/merge_requests/{number}/merge",
164            self.integration.api_base(),
165            crate::gitlab::encode_gitlab_project_path(project)
166        );
167        let body = serde_json::json!({ "squash": method == MergeMethod::Squash });
168        let request = self.authed(crate::http::HttpRequest::put_json(url, &body));
169        let response = self.transport.send(request).await?;
170        response.error_for_status("merging a GitLab merge request")
171    }
172
173    /// `PUT /merge_requests/{iid}` with `state_event: close`.
174    pub(crate) async fn close_request_now(&self, project: &str, number: u64) -> crate::Result<()> {
175        let url = format!(
176            "{}/projects/{}/merge_requests/{number}",
177            self.integration.api_base(),
178            crate::gitlab::encode_gitlab_project_path(project)
179        );
180        let body = serde_json::json!({ "state_event": "close" });
181        let request = self.authed(crate::http::HttpRequest::put_json(url, &body));
182        let response = self.transport.send(request).await?;
183        response.error_for_status("closing a GitLab merge request")
184    }
185
186    /// Removes the `Draft:` marker from the title (`PUT` with the new title).
187    pub(crate) async fn ready_request_now(&self, project: &str, number: u64) -> crate::Result<()> {
188        let url = format!(
189            "{}/projects/{}/merge_requests/{number}",
190            self.integration.api_base(),
191            crate::gitlab::encode_gitlab_project_path(project)
192        );
193        let response = self
194            .transport
195            .send(self.authed(crate::http::HttpRequest::get(url.clone())))
196            .await?;
197        response.error_for_status("reading a GitLab merge request")?;
198        let mr: serde_json::Value = response.json()?;
199        let title = mr["title"].as_str().unwrap_or_default();
200        let Some(clean) = strip_draft_prefix(title) else {
201            return Ok(());
202        };
203        let body = serde_json::json!({ "title": clean });
204        let response = self
205            .transport
206            .send(self.authed(crate::http::HttpRequest::put_json(url, &body)))
207            .await?;
208        response.error_for_status("marking a GitLab merge request ready")
209    }
210}
211
212#[cfg(feature = "gitea")]
213impl crate::gitea::GiteaClient {
214    /// `POST /pulls/{n}/merge` with `Do`.
215    pub(crate) async fn merge_request_now(
216        &self,
217        project: &str,
218        number: u64,
219        method: MergeMethod,
220    ) -> crate::Result<()> {
221        let url = self.repo_url(project, &format!("pulls/{number}/merge"));
222        let body = serde_json::json!({ "Do": method_word(method) });
223        let response = self.transport.send(self.post(url, &body)).await?;
224        response.error_for_status("merging a pull request")
225    }
226
227    /// `PATCH /pulls/{n}` with `state: closed`.
228    pub(crate) async fn close_request_now(&self, project: &str, number: u64) -> crate::Result<()> {
229        let url = self.repo_url(project, &format!("pulls/{number}"));
230        let body = serde_json::json!({ "state": "closed" });
231        let request = self.authed(crate::http::HttpRequest::patch_json(url, &body));
232        let response = self.transport.send(request).await?;
233        response.error_for_status("closing a pull request")
234    }
235
236    /// Removes the `WIP:` marker from the title (`PATCH` with the new title).
237    pub(crate) async fn ready_request_now(&self, project: &str, number: u64) -> crate::Result<()> {
238        let url = self.repo_url(project, &format!("pulls/{number}"));
239        let response = self.transport.send(self.get(url.clone())).await?;
240        response.error_for_status("reading a pull request")?;
241        let pull: serde_json::Value = response.json()?;
242        let title = pull["title"].as_str().unwrap_or_default();
243        let Some(clean) = strip_draft_prefix(title) else {
244            return Ok(());
245        };
246        let body = serde_json::json!({ "title": clean });
247        let request = self.authed(crate::http::HttpRequest::patch_json(url, &body));
248        let response = self.transport.send(request).await?;
249        response.error_for_status("marking a pull request ready")
250    }
251}
252
253#[cfg(all(test, any(feature = "github", feature = "gitlab", feature = "gitea")))]
254mod tests;