Skip to main content

gitfox_client/
pull_request.rs

1//! Pull request endpoints.
2//!
3//! Verified against the GitFox API v1.3.0 OpenAPI document:
4//!
5//! | Operation | Endpoint |
6//! |---|---|
7//! | list          | `GET /api/v1/repos/{repo_ref}/pullreq` |
8//! | list in space | `GET /api/v1/spaces/{space_ref}/pullreq` |
9//! | view          | `GET /api/v1/repos/{repo_ref}/pullreq/{pullreq_number}` |
10//! | create        | `POST /api/v1/repos/{repo_ref}/pullreq` |
11//! | merge         | `POST …/pullreq/{pullreq_number}/merge` |
12//! | delete branch | `DELETE …/pullreq/{pullreq_number}/branch` |
13//! | close/reopen  | `POST …/pullreq/{pullreq_number}/state` |
14//! | diff          | `GET …/pullreq/{pullreq_number}/diff` |
15//! | checks        | `GET …/pullreq/{pullreq_number}/checks` |
16//! | commits       | `GET …/pullreq/{pullreq_number}/commits` (unused so far) |
17//!
18//! The diff endpoint content-negotiates: `application/json` yields per-file
19//! entries, `text/plain` a raw unified diff. `fx pr diff` picks by output mode.
20
21use serde_json::json;
22
23use crate::client::{GitFoxClient, Method, Query};
24use crate::error::Result;
25use crate::models::{
26    CreatePullRequest, FileDiff, MergePullRequest, MergeResult, PullRequest, PullRequestChecks,
27    PullRequestState, RepoRef,
28};
29
30/// Filters for [`PullRequestsApi::list`].
31///
32/// An empty `state` means "whatever the server defaults to"; the CLI always
33/// sets one so the default never surprises anybody.
34#[derive(Debug, Clone)]
35pub struct PullRequestFilter {
36    pub state: Vec<PullRequestState>,
37    pub author_id: Option<i64>,
38    pub source_branch: Option<String>,
39    pub target_branch: Option<String>,
40    pub query: Option<String>,
41    pub page: u32,
42    pub limit: u32,
43}
44
45impl Default for PullRequestFilter {
46    fn default() -> Self {
47        Self {
48            state: vec![PullRequestState::Open],
49            author_id: None,
50            source_branch: None,
51            target_branch: None,
52            query: None,
53            page: 1,
54            limit: 30,
55        }
56    }
57}
58
59impl PullRequestFilter {
60    fn to_query(&self) -> Query {
61        let mut q = Query::new();
62        q.extend("state", self.state.iter().map(|s| s.as_str()))
63            .push_opt("author_id", self.author_id)
64            .push_opt("source_branch", self.source_branch.as_deref())
65            .push_opt("target_branch", self.target_branch.as_deref())
66            .push_opt("query", self.query.as_deref())
67            .push("page", self.page)
68            .push("limit", self.limit);
69        q
70    }
71}
72
73pub struct PullRequestsApi<'a> {
74    client: &'a GitFoxClient,
75}
76
77impl<'a> PullRequestsApi<'a> {
78    pub(crate) fn new(client: &'a GitFoxClient) -> Self {
79        Self { client }
80    }
81
82    /// `GET /api/v1/repos/{repo_ref}/pullreq`
83    pub async fn list(
84        &self,
85        repo: &RepoRef,
86        filter: &PullRequestFilter,
87    ) -> Result<Vec<PullRequest>> {
88        let path = format!("/api/v1/repos/{}/pullreq", repo.encoded());
89        self.client.get_json(&filter.to_query().apply(&path)).await
90    }
91
92    /// `GET /api/v1/repos/{repo_ref}/pullreq/{pullreq_number}`
93    pub async fn get(&self, repo: &RepoRef, number: u64) -> Result<PullRequest> {
94        self.client
95            .get_json(&format!(
96                "/api/v1/repos/{}/pullreq/{number}",
97                repo.encoded()
98            ))
99            .await
100    }
101
102    /// The open pull request whose source branch is `branch`, if there is one.
103    ///
104    /// This is how `fx pr view` works with no number: the branch you are
105    /// standing on identifies the pull request.
106    pub async fn find_for_branch(
107        &self,
108        repo: &RepoRef,
109        branch: &str,
110    ) -> Result<Option<PullRequest>> {
111        let filter = PullRequestFilter {
112            source_branch: Some(branch.to_string()),
113            limit: 2,
114            ..Default::default()
115        };
116        Ok(self.list(repo, &filter).await?.into_iter().next())
117    }
118
119    /// `POST /api/v1/repos/{repo_ref}/pullreq`
120    pub async fn create(&self, repo: &RepoRef, input: &CreatePullRequest) -> Result<PullRequest> {
121        let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
122        self.client
123            .request(
124                Method::POST,
125                &format!("/api/v1/repos/{}/pullreq", repo.encoded()),
126                Some(&body),
127                &[],
128            )
129            .await?
130            .deserialize()
131    }
132
133    /// `POST /api/v1/repos/{repo_ref}/pullreq/{pullreq_number}/merge`
134    pub async fn merge(
135        &self,
136        repo: &RepoRef,
137        number: u64,
138        input: &MergePullRequest,
139    ) -> Result<MergeResult> {
140        let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
141        self.client
142            .request(
143                Method::POST,
144                &format!("/api/v1/repos/{}/pullreq/{number}/merge", repo.encoded()),
145                Some(&body),
146                &[],
147            )
148            .await?
149            .deserialize()
150    }
151
152    /// `DELETE /api/v1/repos/{repo_ref}/pullreq/{pullreq_number}/branch`
153    ///
154    /// Separate from the merge call: GitFox has no `delete_branch` flag on
155    /// merge, so `fx pr merge --delete-branch` is two requests.
156    pub async fn delete_source_branch(&self, repo: &RepoRef, number: u64) -> Result<()> {
157        self.client
158            .request(
159                Method::DELETE,
160                &format!("/api/v1/repos/{}/pullreq/{number}/branch", repo.encoded()),
161                None,
162                &[],
163            )
164            .await
165            .map(|_| ())
166    }
167
168    /// `GET …/pullreq/{pullreq_number}/diff` as structured per-file entries.
169    ///
170    /// The endpoint content-negotiates: JSON here, raw text in
171    /// [`Self::diff_text`]. Both describe the same change.
172    pub async fn diff_files(&self, repo: &RepoRef, number: u64) -> Result<Vec<FileDiff>> {
173        self.client
174            .get_json(&format!(
175                "/api/v1/repos/{}/pullreq/{number}/diff",
176                repo.encoded()
177            ))
178            .await
179    }
180
181    /// `GET …/pullreq/{pullreq_number}/diff` as a raw unified diff.
182    pub async fn diff_text(&self, repo: &RepoRef, number: u64) -> Result<String> {
183        let response = self
184            .client
185            .request(
186                Method::GET,
187                &format!("/api/v1/repos/{}/pullreq/{number}/diff", repo.encoded()),
188                None,
189                &[("Accept".to_string(), "text/plain".to_string())],
190            )
191            .await?;
192        Ok(response.text)
193    }
194
195    /// `GET …/pullreq/{pullreq_number}/checks`
196    pub async fn checks(&self, repo: &RepoRef, number: u64) -> Result<PullRequestChecks> {
197        self.client
198            .get_json(&format!(
199                "/api/v1/repos/{}/pullreq/{number}/checks",
200                repo.encoded()
201            ))
202            .await
203    }
204
205    /// `POST /api/v1/repos/{repo_ref}/pullreq/{pullreq_number}/state`
206    pub async fn set_state(
207        &self,
208        repo: &RepoRef,
209        number: u64,
210        state: PullRequestState,
211    ) -> Result<PullRequest> {
212        let body = json!({ "state": state.as_str() });
213        self.client
214            .request(
215                Method::POST,
216                &format!("/api/v1/repos/{}/pullreq/{number}/state", repo.encoded()),
217                Some(&body),
218                &[],
219            )
220            .await?
221            .deserialize()
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn the_default_filter_asks_for_open_pull_requests_only() {
231        let q = PullRequestFilter::default().to_query();
232        assert_eq!(q.apply("/p"), "/p?state=open&page=1&limit=30");
233    }
234
235    #[test]
236    fn several_states_become_repeated_parameters() {
237        let filter = PullRequestFilter {
238            state: vec![PullRequestState::Open, PullRequestState::Merged],
239            ..Default::default()
240        };
241        assert!(
242            filter
243                .to_query()
244                .encode()
245                .contains("state=open&state=merged")
246        );
247    }
248
249    #[test]
250    fn unset_filters_are_left_out_entirely() {
251        let encoded = PullRequestFilter::default().to_query().encode();
252        for absent in ["author_id", "source_branch", "target_branch", "query"] {
253            assert!(
254                !encoded.contains(absent),
255                "{absent} should be absent: {encoded}"
256            );
257        }
258    }
259}