Skip to main content

bitbucket_cli/api/
pullrequests.rs

1use anyhow::Result;
2
3use super::BitbucketClient;
4use crate::models::{
5    CreatePullRequestRequest, MergePullRequestRequest, Paginated, PullRequest, PullRequestComment,
6    PullRequestState,
7};
8
9impl BitbucketClient {
10    /// List pull requests for a repository
11    pub async fn list_pull_requests(
12        &self,
13        workspace: &str,
14        repo_slug: &str,
15        state: Option<PullRequestState>,
16        page: Option<u32>,
17        pagelen: Option<u32>,
18    ) -> Result<Paginated<PullRequest>> {
19        let mut query = Vec::new();
20
21        if let Some(s) = state {
22            query.push(("state", s.to_string()));
23        }
24        if let Some(p) = page {
25            query.push(("page", p.to_string()));
26        }
27        if let Some(len) = pagelen {
28            query.push(("pagelen", len.to_string()));
29        }
30
31        let query_refs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
32
33        let path = format!("/repositories/{}/{}/pullrequests", workspace, repo_slug);
34        self.get_with_query(&path, &query_refs).await
35    }
36
37    /// Get a specific pull request
38    pub async fn get_pull_request(
39        &self,
40        workspace: &str,
41        repo_slug: &str,
42        pr_id: u64,
43    ) -> Result<PullRequest> {
44        let path = format!(
45            "/repositories/{}/{}/pullrequests/{}",
46            workspace, repo_slug, pr_id
47        );
48        self.get(&path).await
49    }
50
51    /// Create a new pull request
52    pub async fn create_pull_request(
53        &self,
54        workspace: &str,
55        repo_slug: &str,
56        request: &CreatePullRequestRequest,
57    ) -> Result<PullRequest> {
58        let path = format!("/repositories/{}/{}/pullrequests", workspace, repo_slug);
59        self.post(&path, request).await
60    }
61
62    /// Update a pull request
63    pub async fn update_pull_request(
64        &self,
65        workspace: &str,
66        repo_slug: &str,
67        pr_id: u64,
68        title: Option<&str>,
69        description: Option<&str>,
70    ) -> Result<PullRequest> {
71        #[derive(serde::Serialize)]
72        struct UpdateRequest {
73            #[serde(skip_serializing_if = "Option::is_none")]
74            title: Option<String>,
75            #[serde(skip_serializing_if = "Option::is_none")]
76            description: Option<String>,
77        }
78
79        let request = UpdateRequest {
80            title: title.map(|t| t.to_string()),
81            description: description.map(|d| d.to_string()),
82        };
83
84        let path = format!(
85            "/repositories/{}/{}/pullrequests/{}",
86            workspace, repo_slug, pr_id
87        );
88        self.put(&path, &request).await
89    }
90
91    /// Merge a pull request
92    pub async fn merge_pull_request(
93        &self,
94        workspace: &str,
95        repo_slug: &str,
96        pr_id: u64,
97        request: Option<&MergePullRequestRequest>,
98    ) -> Result<PullRequest> {
99        let default_request = MergePullRequestRequest::default();
100        let request = request.unwrap_or(&default_request);
101
102        let path = format!(
103            "/repositories/{}/{}/pullrequests/{}/merge",
104            workspace, repo_slug, pr_id
105        );
106        self.post(&path, request).await
107    }
108
109    /// Approve a pull request
110    pub async fn approve_pull_request(
111        &self,
112        workspace: &str,
113        repo_slug: &str,
114        pr_id: u64,
115    ) -> Result<()> {
116        let path = format!(
117            "/repositories/{}/{}/pullrequests/{}/approve",
118            workspace, repo_slug, pr_id
119        );
120        self.post_no_response(&path, &serde_json::json!({})).await
121    }
122
123    /// Unapprove a pull request
124    pub async fn unapprove_pull_request(
125        &self,
126        workspace: &str,
127        repo_slug: &str,
128        pr_id: u64,
129    ) -> Result<()> {
130        let path = format!(
131            "/repositories/{}/{}/pullrequests/{}/approve",
132            workspace, repo_slug, pr_id
133        );
134        self.delete(&path).await
135    }
136
137    /// Decline a pull request
138    pub async fn decline_pull_request(
139        &self,
140        workspace: &str,
141        repo_slug: &str,
142        pr_id: u64,
143    ) -> Result<PullRequest> {
144        let path = format!(
145            "/repositories/{}/{}/pullrequests/{}/decline",
146            workspace, repo_slug, pr_id
147        );
148        self.post(&path, &serde_json::json!({})).await
149    }
150
151    /// List the most recent comments on a pull request, newest first.
152    ///
153    /// Requests pages sorted by `-created_on` and stops following the
154    /// pagination `next` links as soon as `max_items` comments have been
155    /// collected (or the pages are exhausted), so large PRs don't require
156    /// downloading their entire comment history.
157    pub async fn list_recent_pr_comments(
158        &self,
159        workspace: &str,
160        repo_slug: &str,
161        pr_id: u64,
162        max_items: usize,
163    ) -> Result<Vec<PullRequestComment>> {
164        let path = format!(
165            "/repositories/{}/{}/pullrequests/{}/comments",
166            workspace, repo_slug, pr_id
167        );
168
169        let first_page: Paginated<PullRequestComment> = self
170            .get_with_query(&path, &[("sort", "-created_on"), ("pagelen", "100")])
171            .await?;
172
173        collect_limited(first_page, max_items, |next_url| async move {
174            self.get_absolute(&next_url).await
175        })
176        .await
177    }
178
179    /// Get a specific comment on a pull request
180    pub async fn get_pr_comment(
181        &self,
182        workspace: &str,
183        repo_slug: &str,
184        pr_id: u64,
185        comment_id: u64,
186    ) -> Result<PullRequestComment> {
187        let path = format!(
188            "/repositories/{}/{}/pullrequests/{}/comments/{}",
189            workspace, repo_slug, pr_id, comment_id
190        );
191        self.get(&path).await
192    }
193
194    /// Add a comment to a pull request
195    pub async fn add_pr_comment(
196        &self,
197        workspace: &str,
198        repo_slug: &str,
199        pr_id: u64,
200        content: &str,
201    ) -> Result<PullRequestComment> {
202        #[derive(serde::Serialize)]
203        struct CommentRequest {
204            content: ContentRequest,
205        }
206
207        #[derive(serde::Serialize)]
208        struct ContentRequest {
209            raw: String,
210        }
211
212        let request = CommentRequest {
213            content: ContentRequest {
214                raw: content.to_string(),
215            },
216        };
217
218        let path = format!(
219            "/repositories/{}/{}/pullrequests/{}/comments",
220            workspace, repo_slug, pr_id
221        );
222        self.post(&path, &request).await
223    }
224
225    /// Get the diff for a pull request
226    pub async fn get_pr_diff(
227        &self,
228        workspace: &str,
229        repo_slug: &str,
230        pr_id: u64,
231    ) -> Result<String> {
232        let path = format!(
233            "/repositories/{}/{}/pullrequests/{}/diff",
234            workspace, repo_slug, pr_id
235        );
236
237        self.get_text(&path, Some("text/plain")).await
238    }
239}
240
241/// Accumulate paginated values until `max_items` have been collected.
242///
243/// Starts from an already-fetched `first_page`, follows pagination `next`
244/// links via `fetch_next` only while fewer than `max_items` values have been
245/// collected (or until a page has no `next` link), and truncates the result
246/// to at most `max_items`.
247async fn collect_limited<T, F, Fut>(
248    first_page: Paginated<T>,
249    max_items: usize,
250    mut fetch_next: F,
251) -> Result<Vec<T>>
252where
253    F: FnMut(String) -> Fut,
254    Fut: std::future::Future<Output = Result<Paginated<T>>>,
255{
256    let mut items: Vec<T> = Vec::new();
257    let mut page = first_page;
258
259    loop {
260        items.extend(page.values);
261
262        if items.len() >= max_items {
263            items.truncate(max_items);
264            break;
265        }
266
267        match page.next {
268            Some(next_url) => page = fetch_next(next_url).await?,
269            None => break,
270        }
271    }
272
273    Ok(items)
274}
275
276#[cfg(test)]
277mod tests {
278    use std::cell::Cell;
279    use std::future::{Ready, ready};
280
281    use super::collect_limited;
282    use crate::models::Paginated;
283
284    fn page(values: Vec<u32>, has_next: bool) -> Paginated<u32> {
285        Paginated {
286            size: None,
287            page: None,
288            pagelen: None,
289            next: has_next.then(|| "https://api.bitbucket.org/next".to_string()),
290            previous: None,
291            values,
292        }
293    }
294
295    type PageFuture = Ready<anyhow::Result<Paginated<u32>>>;
296
297    #[tokio::test]
298    async fn follows_next_links_until_exhausted_when_under_max() {
299        let calls = Cell::new(0u32);
300        let fetch = |url: String| -> PageFuture {
301            calls.set(calls.get() + 1);
302            assert_eq!(url, "https://api.bitbucket.org/next");
303            ready(Ok(page(vec![3], false)))
304        };
305
306        let items = collect_limited(page(vec![1, 2], true), 10, fetch)
307            .await
308            .expect("collection should succeed");
309
310        assert_eq!(items, vec![1, 2, 3]);
311        assert_eq!(calls.get(), 1);
312    }
313
314    #[tokio::test]
315    async fn truncates_to_max_and_stops_fetching_once_reached() {
316        let calls = Cell::new(0u32);
317        let fetch = |_url: String| -> PageFuture {
318            calls.set(calls.get() + 1);
319            // This page still advertises a `next` link, but the collection
320            // reaches `max_items` here, so no further fetch may happen.
321            ready(Ok(page(vec![3, 4], true)))
322        };
323
324        let items = collect_limited(page(vec![1, 2], true), 3, fetch)
325            .await
326            .expect("collection should succeed");
327
328        assert_eq!(items, vec![1, 2, 3]);
329        assert_eq!(calls.get(), 1);
330    }
331
332    #[tokio::test]
333    async fn exactly_max_on_first_page_makes_zero_fetches() {
334        let calls = Cell::new(0u32);
335        let fetch = |_url: String| -> PageFuture {
336            calls.set(calls.get() + 1);
337            panic!("no page beyond the first should be fetched");
338        };
339
340        let items = collect_limited(page(vec![1, 2, 3], true), 3, fetch)
341            .await
342            .expect("collection should succeed");
343
344        assert_eq!(items, vec![1, 2, 3]);
345        assert_eq!(calls.get(), 0);
346    }
347}