Skip to main content

bitbucket_cli/api/
pullrequests.rs

1use anyhow::Result;
2
3use super::BitbucketClient;
4use crate::models::{
5    CommentRef, CommitStatus, CreatePullRequestRequest, DiffStat, InlineComment,
6    MergePullRequestRequest, Paginated, PrActivity, PrCommit, PrTask, PullRequest,
7    PullRequestComment, PullRequestState, UpdatePullRequestRequest,
8};
9
10/// Server-side filters for [`BitbucketClient::list_pull_requests_filtered`].
11#[derive(Default)]
12pub(crate) struct PrListFilters<'a> {
13    pub states: &'a [PullRequestState],
14    pub query: Option<&'a str>,
15    pub sort: Option<&'a str>,
16    pub page: Option<u32>,
17    pub pagelen: Option<u32>,
18}
19
20/// Input for [`BitbucketClient::add_pr_comment_full`]: the comment body plus
21/// optional inline placement and reply target.
22pub(crate) struct PrCommentInput<'a> {
23    pub content: &'a str,
24    pub path: Option<&'a str>,
25    pub line: Option<u32>,
26    pub parent: Option<u64>,
27}
28
29impl BitbucketClient {
30    /// List pull requests for a repository, filtered by at most one state.
31    ///
32    /// Thin wrapper over [`Self::list_pull_requests_filtered`] kept for
33    /// callers (e.g. the TUI) that only need the simple form.
34    pub async fn list_pull_requests(
35        &self,
36        workspace: &str,
37        repo_slug: &str,
38        state: Option<PullRequestState>,
39        page: Option<u32>,
40        pagelen: Option<u32>,
41    ) -> Result<Paginated<PullRequest>> {
42        let states: Vec<PullRequestState> = state.into_iter().collect();
43        self.list_pull_requests_filtered(
44            workspace,
45            repo_slug,
46            PrListFilters {
47                states: &states,
48                page,
49                pagelen,
50                ..Default::default()
51            },
52        )
53        .await
54    }
55
56    /// List pull requests with full filtering: multiple `state` values, a
57    /// BBQL `q` expression, a `sort` field, and explicit paging.
58    pub(crate) async fn list_pull_requests_filtered(
59        &self,
60        workspace: &str,
61        repo_slug: &str,
62        filters: PrListFilters<'_>,
63    ) -> Result<Paginated<PullRequest>> {
64        let mut params = Vec::new();
65
66        for state in filters.states {
67            params.push(("state", state.to_string()));
68        }
69        if let Some(q) = filters.query {
70            params.push(("q", q.to_string()));
71        }
72        if let Some(s) = filters.sort {
73            params.push(("sort", s.to_string()));
74        }
75        if let Some(p) = filters.page {
76            params.push(("page", p.to_string()));
77        }
78        if let Some(len) = filters.pagelen {
79            params.push(("pagelen", len.to_string()));
80        }
81
82        let query_refs: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
83
84        let path = format!("/repositories/{}/{}/pullrequests", workspace, repo_slug);
85        self.get_with_query(&path, &query_refs).await
86    }
87
88    /// Get a specific pull request
89    pub async fn get_pull_request(
90        &self,
91        workspace: &str,
92        repo_slug: &str,
93        pr_id: u64,
94    ) -> Result<PullRequest> {
95        let path = format!(
96            "/repositories/{}/{}/pullrequests/{}",
97            workspace, repo_slug, pr_id
98        );
99        self.get(&path).await
100    }
101
102    /// Create a new pull request
103    pub async fn create_pull_request(
104        &self,
105        workspace: &str,
106        repo_slug: &str,
107        request: &CreatePullRequestRequest,
108    ) -> Result<PullRequest> {
109        let path = format!("/repositories/{}/{}/pullrequests", workspace, repo_slug);
110        self.post(&path, request).await
111    }
112
113    /// Update a pull request; only the fields set on `request` are changed.
114    pub async fn update_pull_request(
115        &self,
116        workspace: &str,
117        repo_slug: &str,
118        pr_id: u64,
119        request: &UpdatePullRequestRequest,
120    ) -> Result<PullRequest> {
121        let path = format!(
122            "/repositories/{}/{}/pullrequests/{}",
123            workspace, repo_slug, pr_id
124        );
125        self.put(&path, request).await
126    }
127
128    /// Merge a pull request
129    pub async fn merge_pull_request(
130        &self,
131        workspace: &str,
132        repo_slug: &str,
133        pr_id: u64,
134        request: Option<&MergePullRequestRequest>,
135    ) -> Result<PullRequest> {
136        let default_request = MergePullRequestRequest::default();
137        let request = request.unwrap_or(&default_request);
138
139        let path = format!(
140            "/repositories/{}/{}/pullrequests/{}/merge",
141            workspace, repo_slug, pr_id
142        );
143        self.post(&path, request).await
144    }
145
146    /// Approve a pull request
147    pub async fn approve_pull_request(
148        &self,
149        workspace: &str,
150        repo_slug: &str,
151        pr_id: u64,
152    ) -> Result<()> {
153        let path = format!(
154            "/repositories/{}/{}/pullrequests/{}/approve",
155            workspace, repo_slug, pr_id
156        );
157        self.post_no_response(&path, &serde_json::json!({})).await
158    }
159
160    /// Unapprove a pull request
161    pub async fn unapprove_pull_request(
162        &self,
163        workspace: &str,
164        repo_slug: &str,
165        pr_id: u64,
166    ) -> Result<()> {
167        let path = format!(
168            "/repositories/{}/{}/pullrequests/{}/approve",
169            workspace, repo_slug, pr_id
170        );
171        self.delete(&path).await
172    }
173
174    /// Request changes on a pull request
175    pub async fn request_pr_changes(
176        &self,
177        workspace: &str,
178        repo_slug: &str,
179        pr_id: u64,
180    ) -> Result<()> {
181        let path = format!(
182            "/repositories/{}/{}/pullrequests/{}/request-changes",
183            workspace, repo_slug, pr_id
184        );
185        self.post_no_response(&path, &serde_json::json!({})).await
186    }
187
188    /// Withdraw a previous request for changes on a pull request
189    pub async fn unrequest_pr_changes(
190        &self,
191        workspace: &str,
192        repo_slug: &str,
193        pr_id: u64,
194    ) -> Result<()> {
195        let path = format!(
196            "/repositories/{}/{}/pullrequests/{}/request-changes",
197            workspace, repo_slug, pr_id
198        );
199        self.delete(&path).await
200    }
201
202    /// Decline a pull request
203    pub async fn decline_pull_request(
204        &self,
205        workspace: &str,
206        repo_slug: &str,
207        pr_id: u64,
208    ) -> Result<PullRequest> {
209        let path = format!(
210            "/repositories/{}/{}/pullrequests/{}/decline",
211            workspace, repo_slug, pr_id
212        );
213        self.post(&path, &serde_json::json!({})).await
214    }
215
216    /// List the most recent comments on a pull request, newest first.
217    ///
218    /// Requests pages sorted by `-created_on` and stops following the
219    /// pagination `next` links as soon as `max_items` comments have been
220    /// collected (or the pages are exhausted), so large PRs don't require
221    /// downloading their entire comment history.
222    pub async fn list_recent_pr_comments(
223        &self,
224        workspace: &str,
225        repo_slug: &str,
226        pr_id: u64,
227        max_items: usize,
228    ) -> Result<Vec<PullRequestComment>> {
229        let path = format!(
230            "/repositories/{}/{}/pullrequests/{}/comments",
231            workspace, repo_slug, pr_id
232        );
233
234        let first_page: Paginated<PullRequestComment> = self
235            .get_with_query(&path, &[("sort", "-created_on"), ("pagelen", "100")])
236            .await?;
237
238        collect_limited(first_page, max_items, |next_url| async move {
239            self.get_absolute(&next_url).await
240        })
241        .await
242    }
243
244    /// Get a specific comment on a pull request
245    pub async fn get_pr_comment(
246        &self,
247        workspace: &str,
248        repo_slug: &str,
249        pr_id: u64,
250        comment_id: u64,
251    ) -> Result<PullRequestComment> {
252        let path = format!(
253            "/repositories/{}/{}/pullrequests/{}/comments/{}",
254            workspace, repo_slug, pr_id, comment_id
255        );
256        self.get(&path).await
257    }
258
259    /// Add a comment to a pull request, optionally inline (`path` + `line`)
260    /// and/or as a reply to `parent`.
261    pub(crate) async fn add_pr_comment_full(
262        &self,
263        workspace: &str,
264        repo_slug: &str,
265        pr_id: u64,
266        input: PrCommentInput<'_>,
267    ) -> Result<PullRequestComment> {
268        #[derive(serde::Serialize)]
269        struct CommentRequest {
270            content: ContentRequest,
271            #[serde(skip_serializing_if = "Option::is_none")]
272            inline: Option<InlineComment>,
273            #[serde(skip_serializing_if = "Option::is_none")]
274            parent: Option<CommentRef>,
275        }
276
277        #[derive(serde::Serialize)]
278        struct ContentRequest {
279            raw: String,
280        }
281
282        let request = CommentRequest {
283            content: ContentRequest {
284                raw: input.content.to_string(),
285            },
286            inline: input.path.map(|p| InlineComment {
287                from: None,
288                to: input.line,
289                path: p.to_string(),
290            }),
291            parent: input.parent.map(|id| CommentRef { id }),
292        };
293
294        let api_path = format!(
295            "/repositories/{}/{}/pullrequests/{}/comments",
296            workspace, repo_slug, pr_id
297        );
298        self.post(&api_path, &request).await
299    }
300
301    /// Update the content of an existing pull request comment
302    pub async fn update_pr_comment(
303        &self,
304        workspace: &str,
305        repo_slug: &str,
306        pr_id: u64,
307        comment_id: u64,
308        content: &str,
309    ) -> Result<PullRequestComment> {
310        let request = serde_json::json!({ "content": { "raw": content } });
311
312        let path = format!(
313            "/repositories/{}/{}/pullrequests/{}/comments/{}",
314            workspace, repo_slug, pr_id, comment_id
315        );
316        self.put(&path, &request).await
317    }
318
319    /// Delete a pull request comment
320    pub async fn delete_pr_comment(
321        &self,
322        workspace: &str,
323        repo_slug: &str,
324        pr_id: u64,
325        comment_id: u64,
326    ) -> Result<()> {
327        let path = format!(
328            "/repositories/{}/{}/pullrequests/{}/comments/{}",
329            workspace, repo_slug, pr_id, comment_id
330        );
331        self.delete(&path).await
332    }
333
334    /// Resolve a pull request comment thread
335    pub async fn resolve_pr_comment(
336        &self,
337        workspace: &str,
338        repo_slug: &str,
339        pr_id: u64,
340        comment_id: u64,
341    ) -> Result<()> {
342        let path = format!(
343            "/repositories/{}/{}/pullrequests/{}/comments/{}/resolve",
344            workspace, repo_slug, pr_id, comment_id
345        );
346        self.post_no_response(&path, &serde_json::json!({})).await
347    }
348
349    /// Reopen (unresolve) a pull request comment thread
350    pub async fn unresolve_pr_comment(
351        &self,
352        workspace: &str,
353        repo_slug: &str,
354        pr_id: u64,
355        comment_id: u64,
356    ) -> Result<()> {
357        let path = format!(
358            "/repositories/{}/{}/pullrequests/{}/comments/{}/resolve",
359            workspace, repo_slug, pr_id, comment_id
360        );
361        self.delete(&path).await
362    }
363
364    /// Get the diff for a pull request
365    pub async fn get_pr_diff(
366        &self,
367        workspace: &str,
368        repo_slug: &str,
369        pr_id: u64,
370    ) -> Result<String> {
371        let path = format!(
372            "/repositories/{}/{}/pullrequests/{}/diff",
373            workspace, repo_slug, pr_id
374        );
375
376        self.get_text(&path, Some("text/plain")).await
377    }
378
379    /// Get the patch (mbox-style) for a pull request
380    pub async fn get_pr_patch(
381        &self,
382        workspace: &str,
383        repo_slug: &str,
384        pr_id: u64,
385    ) -> Result<String> {
386        let path = format!(
387            "/repositories/{}/{}/pullrequests/{}/patch",
388            workspace, repo_slug, pr_id
389        );
390
391        self.get_text(&path, None).await
392    }
393
394    /// List one page of commits on a pull request
395    pub async fn list_pr_commits(
396        &self,
397        workspace: &str,
398        repo_slug: &str,
399        pr_id: u64,
400        pagelen: Option<u32>,
401    ) -> Result<Paginated<PrCommit>> {
402        let path = format!(
403            "/repositories/{}/{}/pullrequests/{}/commits",
404            workspace, repo_slug, pr_id
405        );
406
407        match pagelen {
408            Some(len) => {
409                let len = len.to_string();
410                self.get_with_query(&path, &[("pagelen", len.as_str())])
411                    .await
412            }
413            None => self.get(&path).await,
414        }
415    }
416
417    /// List all commit statuses (builds) for a pull request's head commit
418    pub async fn list_pr_statuses(
419        &self,
420        workspace: &str,
421        repo_slug: &str,
422        pr_id: u64,
423    ) -> Result<Vec<CommitStatus>> {
424        let path = format!(
425            "/repositories/{}/{}/pullrequests/{}/statuses",
426            workspace, repo_slug, pr_id
427        );
428        self.get_all_pages(&path).await
429    }
430
431    /// Get one page of the diffstat (per-file change summary) for a pull request
432    pub async fn get_pr_diffstat(
433        &self,
434        workspace: &str,
435        repo_slug: &str,
436        pr_id: u64,
437        pagelen: Option<u32>,
438    ) -> Result<Paginated<DiffStat>> {
439        let path = format!(
440            "/repositories/{}/{}/pullrequests/{}/diffstat",
441            workspace, repo_slug, pr_id
442        );
443
444        match pagelen {
445            Some(len) => {
446                let len = len.to_string();
447                self.get_with_query(&path, &[("pagelen", len.as_str())])
448                    .await
449            }
450            None => self.get(&path).await,
451        }
452    }
453
454    /// List all tasks on a pull request
455    pub async fn list_pr_tasks(
456        &self,
457        workspace: &str,
458        repo_slug: &str,
459        pr_id: u64,
460    ) -> Result<Vec<PrTask>> {
461        let path = format!(
462            "/repositories/{}/{}/pullrequests/{}/tasks",
463            workspace, repo_slug, pr_id
464        );
465        self.get_all_pages(&path).await
466    }
467
468    /// Create a task on a pull request
469    pub async fn add_pr_task(
470        &self,
471        workspace: &str,
472        repo_slug: &str,
473        pr_id: u64,
474        content: &str,
475    ) -> Result<PrTask> {
476        let request = serde_json::json!({ "content": { "raw": content } });
477
478        let path = format!(
479            "/repositories/{}/{}/pullrequests/{}/tasks",
480            workspace, repo_slug, pr_id
481        );
482        self.post(&path, &request).await
483    }
484
485    /// Update a pull request task's content and/or state
486    /// (`state` is `"RESOLVED"` or `"UNRESOLVED"`).
487    pub async fn update_pr_task(
488        &self,
489        workspace: &str,
490        repo_slug: &str,
491        pr_id: u64,
492        task_id: u64,
493        content: Option<&str>,
494        state: Option<&str>,
495    ) -> Result<PrTask> {
496        #[derive(serde::Serialize)]
497        struct TaskUpdateRequest {
498            #[serde(skip_serializing_if = "Option::is_none")]
499            content: Option<TaskContentRequest>,
500            #[serde(skip_serializing_if = "Option::is_none")]
501            state: Option<String>,
502        }
503
504        #[derive(serde::Serialize)]
505        struct TaskContentRequest {
506            raw: String,
507        }
508
509        let request = TaskUpdateRequest {
510            content: content.map(|c| TaskContentRequest { raw: c.to_string() }),
511            state: state.map(|s| s.to_string()),
512        };
513
514        let path = format!(
515            "/repositories/{}/{}/pullrequests/{}/tasks/{}",
516            workspace, repo_slug, pr_id, task_id
517        );
518        self.put(&path, &request).await
519    }
520
521    /// Delete a pull request task
522    pub async fn delete_pr_task(
523        &self,
524        workspace: &str,
525        repo_slug: &str,
526        pr_id: u64,
527        task_id: u64,
528    ) -> Result<()> {
529        let path = format!(
530            "/repositories/{}/{}/pullrequests/{}/tasks/{}",
531            workspace, repo_slug, pr_id, task_id
532        );
533        self.delete(&path).await
534    }
535
536    /// List one page of the activity feed for a pull request
537    pub async fn list_pr_activity(
538        &self,
539        workspace: &str,
540        repo_slug: &str,
541        pr_id: u64,
542        pagelen: Option<u32>,
543    ) -> Result<Paginated<PrActivity>> {
544        let path = format!(
545            "/repositories/{}/{}/pullrequests/{}/activity",
546            workspace, repo_slug, pr_id
547        );
548
549        match pagelen {
550            Some(len) => {
551                let len = len.to_string();
552                self.get_with_query(&path, &[("pagelen", len.as_str())])
553                    .await
554            }
555            None => self.get(&path).await,
556        }
557    }
558}
559
560/// Accumulate paginated values until `max_items` have been collected.
561///
562/// Starts from an already-fetched `first_page`, follows pagination `next`
563/// links via `fetch_next` only while fewer than `max_items` values have been
564/// collected (or until a page has no `next` link), and truncates the result
565/// to at most `max_items`.
566async fn collect_limited<T, F, Fut>(
567    first_page: Paginated<T>,
568    max_items: usize,
569    mut fetch_next: F,
570) -> Result<Vec<T>>
571where
572    F: FnMut(String) -> Fut,
573    Fut: std::future::Future<Output = Result<Paginated<T>>>,
574{
575    let mut items: Vec<T> = Vec::new();
576    let mut page = first_page;
577
578    loop {
579        items.extend(page.values);
580
581        if items.len() >= max_items {
582            items.truncate(max_items);
583            break;
584        }
585
586        match page.next {
587            Some(next_url) => page = fetch_next(next_url).await?,
588            None => break,
589        }
590    }
591
592    Ok(items)
593}
594
595#[cfg(test)]
596mod tests {
597    use std::cell::Cell;
598    use std::future::{Ready, ready};
599
600    use super::collect_limited;
601    use crate::models::Paginated;
602
603    fn page(values: Vec<u32>, has_next: bool) -> Paginated<u32> {
604        Paginated {
605            size: None,
606            page: None,
607            pagelen: None,
608            next: has_next.then(|| "https://api.bitbucket.org/next".to_string()),
609            previous: None,
610            values,
611        }
612    }
613
614    type PageFuture = Ready<anyhow::Result<Paginated<u32>>>;
615
616    #[tokio::test]
617    async fn follows_next_links_until_exhausted_when_under_max() {
618        let calls = Cell::new(0u32);
619        let fetch = |url: String| -> PageFuture {
620            calls.set(calls.get() + 1);
621            assert_eq!(url, "https://api.bitbucket.org/next");
622            ready(Ok(page(vec![3], false)))
623        };
624
625        let items = collect_limited(page(vec![1, 2], true), 10, fetch)
626            .await
627            .expect("collection should succeed");
628
629        assert_eq!(items, vec![1, 2, 3]);
630        assert_eq!(calls.get(), 1);
631    }
632
633    #[tokio::test]
634    async fn truncates_to_max_and_stops_fetching_once_reached() {
635        let calls = Cell::new(0u32);
636        let fetch = |_url: String| -> PageFuture {
637            calls.set(calls.get() + 1);
638            // This page still advertises a `next` link, but the collection
639            // reaches `max_items` here, so no further fetch may happen.
640            ready(Ok(page(vec![3, 4], true)))
641        };
642
643        let items = collect_limited(page(vec![1, 2], true), 3, fetch)
644            .await
645            .expect("collection should succeed");
646
647        assert_eq!(items, vec![1, 2, 3]);
648        assert_eq!(calls.get(), 1);
649    }
650
651    #[tokio::test]
652    async fn exactly_max_on_first_page_makes_zero_fetches() {
653        let calls = Cell::new(0u32);
654        let fetch = |_url: String| -> PageFuture {
655            calls.set(calls.get() + 1);
656            panic!("no page beyond the first should be fetched");
657        };
658
659        let items = collect_limited(page(vec![1, 2, 3], true), 3, fetch)
660            .await
661            .expect("collection should succeed");
662
663        assert_eq!(items, vec![1, 2, 3]);
664        assert_eq!(calls.get(), 0);
665    }
666}