Skip to main content

bitbucket_cli/cli/
pr.rs

1use anyhow::{Context, Result};
2use clap::{Subcommand, ValueEnum};
3use colored::Colorize;
4use tabled::{Table, Tabled};
5
6use super::parse_repo;
7use crate::api::BitbucketClient;
8use crate::models::{
9    BranchInfo, CreatePullRequestRequest, MergePullRequestRequest, MergeStrategy,
10    PullRequestBranchRef, PullRequestComment, PullRequestState,
11};
12
13#[derive(Subcommand)]
14pub enum PrCommands {
15    /// List pull requests
16    List {
17        /// Repository in format workspace/repo-slug
18        repo: String,
19
20        /// Filter by state
21        #[arg(short, long, value_enum)]
22        state: Option<PrState>,
23
24        /// Number of results
25        #[arg(short, long, default_value = "25")]
26        limit: u32,
27    },
28
29    /// View pull request details
30    View {
31        /// Repository in format workspace/repo-slug
32        repo: String,
33
34        /// Pull request ID
35        id: u64,
36
37        /// Open in browser
38        #[arg(short, long)]
39        web: bool,
40    },
41
42    /// Create a new pull request
43    Create {
44        /// Repository in format workspace/repo-slug
45        repo: String,
46
47        /// Title of the pull request
48        #[arg(short, long)]
49        title: String,
50
51        /// Source branch
52        #[arg(short, long)]
53        source: String,
54
55        /// Destination branch (defaults to main branch)
56        #[arg(short, long)]
57        destination: Option<String>,
58
59        /// Description of the pull request
60        #[arg(short = 'b', long)]
61        body: Option<String>,
62
63        /// Close source branch after merge
64        #[arg(long)]
65        close_source_branch: bool,
66    },
67
68    /// Merge a pull request
69    Merge {
70        /// Repository in format workspace/repo-slug
71        repo: String,
72
73        /// Pull request ID
74        id: u64,
75
76        /// Merge strategy
77        #[arg(short, long, value_enum, default_value = "merge-commit")]
78        strategy: MergeStrategyArg,
79
80        /// Commit message
81        #[arg(short, long)]
82        message: Option<String>,
83
84        /// Close source branch
85        #[arg(long)]
86        close_source_branch: bool,
87    },
88
89    /// Approve a pull request
90    Approve {
91        /// Repository in format workspace/repo-slug
92        repo: String,
93
94        /// Pull request ID
95        id: u64,
96    },
97
98    /// Decline a pull request
99    Decline {
100        /// Repository in format workspace/repo-slug
101        repo: String,
102
103        /// Pull request ID
104        id: u64,
105    },
106
107    /// Checkout a pull request branch locally
108    Checkout {
109        /// Repository in format workspace/repo-slug
110        repo: String,
111
112        /// Pull request ID
113        id: u64,
114    },
115
116    /// View pull request diff
117    Diff {
118        /// Repository in format workspace/repo-slug
119        repo: String,
120
121        /// Pull request ID
122        id: u64,
123    },
124
125    /// Add a comment to a pull request
126    Comment {
127        /// Repository in format workspace/repo-slug
128        repo: String,
129
130        /// Pull request ID
131        id: u64,
132
133        /// Comment text
134        #[arg(short, long)]
135        body: String,
136    },
137
138    /// List comments on a pull request
139    ListComments {
140        /// Repository in format workspace/repo-slug
141        repo: String,
142
143        /// Pull request ID
144        id: u64,
145
146        /// Number of results
147        #[arg(short, long, default_value = "25")]
148        limit: u32,
149    },
150
151    /// View a specific comment on a pull request
152    ViewComment {
153        /// Repository in format workspace/repo-slug
154        repo: String,
155
156        /// Pull request ID
157        #[arg(value_name = "PR_ID")]
158        id: u64,
159
160        /// Comment ID
161        comment_id: u64,
162    },
163
164    /// List pipelines for the PR's head commit
165    Pipelines {
166        /// Repository in format workspace/repo-slug
167        repo: String,
168
169        /// Pull request ID
170        id: u64,
171
172        /// Maximum recent pipelines to scan for matches (capped at 100)
173        #[arg(short, long, default_value = "100")]
174        scan_limit: u32,
175    },
176}
177
178#[derive(ValueEnum, Clone)]
179pub enum PrState {
180    Open,
181    Merged,
182    Declined,
183    Superseded,
184}
185
186impl From<PrState> for PullRequestState {
187    fn from(state: PrState) -> Self {
188        match state {
189            PrState::Open => PullRequestState::Open,
190            PrState::Merged => PullRequestState::Merged,
191            PrState::Declined => PullRequestState::Declined,
192            PrState::Superseded => PullRequestState::Superseded,
193        }
194    }
195}
196
197#[derive(ValueEnum, Clone)]
198pub enum MergeStrategyArg {
199    MergeCommit,
200    Squash,
201    FastForward,
202}
203
204impl From<MergeStrategyArg> for MergeStrategy {
205    fn from(strategy: MergeStrategyArg) -> Self {
206        match strategy {
207            MergeStrategyArg::MergeCommit => MergeStrategy::MergeCommit,
208            MergeStrategyArg::Squash => MergeStrategy::Squash,
209            MergeStrategyArg::FastForward => MergeStrategy::FastForward,
210        }
211    }
212}
213
214#[derive(Tabled)]
215struct PrRow {
216    #[tabled(rename = "ID")]
217    id: u64,
218    #[tabled(rename = "TITLE")]
219    title: String,
220    #[tabled(rename = "AUTHOR")]
221    author: String,
222    #[tabled(rename = "STATE")]
223    state: String,
224    #[tabled(rename = "UPDATED")]
225    updated: String,
226}
227
228#[derive(Tabled)]
229struct PipelineRow {
230    #[tabled(rename = "#")]
231    build: u64,
232    #[tabled(rename = "STATUS")]
233    status: String,
234    #[tabled(rename = "BRANCH")]
235    branch: String,
236    #[tabled(rename = "COMMIT")]
237    commit: String,
238    #[tabled(rename = "TRIGGERED")]
239    triggered: String,
240    #[tabled(rename = "DURATION")]
241    duration: String,
242}
243
244#[derive(Tabled)]
245struct CommentRow {
246    #[tabled(rename = "ID")]
247    id: u64,
248    #[tabled(rename = "AUTHOR")]
249    author: String,
250    #[tabled(rename = "CREATED")]
251    created: String,
252    #[tabled(rename = "TYPE")]
253    comment_type: String,
254    #[tabled(rename = "CONTENT")]
255    content: String,
256}
257
258impl PrCommands {
259    pub async fn run(self) -> Result<()> {
260        match self {
261            PrCommands::List { repo, state, limit } => {
262                let (workspace, repo_slug) = parse_repo(&repo)?;
263                let client = BitbucketClient::from_stored().await?;
264
265                let prs = client
266                    .list_pull_requests(
267                        &workspace,
268                        &repo_slug,
269                        state.map(|s| s.into()),
270                        None,
271                        Some(limit),
272                    )
273                    .await?;
274
275                if prs.values.is_empty() {
276                    println!("No pull requests found");
277                    return Ok(());
278                }
279
280                let rows: Vec<PrRow> = prs
281                    .values
282                    .iter()
283                    .map(|pr| PrRow {
284                        id: pr.id,
285                        title: pr.title.chars().take(50).collect(),
286                        author: pr.author.display_name.clone(),
287                        state: format_state(&pr.state),
288                        updated: pr.updated_on.format("%Y-%m-%d").to_string(),
289                    })
290                    .collect();
291
292                let table = Table::new(rows).to_string();
293                println!("{}", table);
294
295                Ok(())
296            }
297
298            PrCommands::View { repo, id, web } => {
299                let (workspace, repo_slug) = parse_repo(&repo)?;
300                let client = BitbucketClient::from_stored().await?;
301                let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
302
303                if web {
304                    if let Some(links) = &pr.links {
305                        if let Some(html) = &links.html {
306                            open::that(&html.href)?;
307                            println!("Opened {} in browser", html.href.cyan());
308                            return Ok(());
309                        }
310                    }
311                    anyhow::bail!("Could not find PR URL");
312                }
313
314                println!("{} {} #{}", format_state(&pr.state), pr.title.bold(), pr.id);
315                println!("{}", "─".repeat(60));
316
317                println!(
318                    "{} {} → {}",
319                    "Branches:".dimmed(),
320                    pr.source.branch.name.cyan(),
321                    pr.destination.branch.name.green()
322                );
323                println!("{} {}", "Author:".dimmed(), pr.author.display_name);
324                println!(
325                    "{} {}",
326                    "Created:".dimmed(),
327                    pr.created_on.format("%Y-%m-%d %H:%M")
328                );
329                println!(
330                    "{} {}",
331                    "Updated:".dimmed(),
332                    pr.updated_on.format("%Y-%m-%d %H:%M")
333                );
334
335                if let Some(count) = pr.comment_count {
336                    println!("{} {}", "Comments:".dimmed(), count);
337                }
338
339                if let Some(tasks) = pr.task_count {
340                    if tasks > 0 {
341                        println!("{} {}", "Tasks:".dimmed(), tasks);
342                    }
343                }
344
345                // Show reviewers/approvals
346                if let Some(participants) = &pr.participants {
347                    let approvals: Vec<_> = participants
348                        .iter()
349                        .filter(|p| p.approved)
350                        .map(|p| p.user.display_name.clone())
351                        .collect();
352
353                    if !approvals.is_empty() {
354                        println!(
355                            "{} {}",
356                            "Approved by:".dimmed(),
357                            approvals.join(", ").green()
358                        );
359                    }
360                }
361
362                if let Some(description) = &pr.description {
363                    if !description.is_empty() {
364                        println!();
365                        println!("{}", description);
366                    }
367                }
368
369                if let Some(links) = &pr.links {
370                    if let Some(html) = &links.html {
371                        println!();
372                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
373                    }
374                }
375
376                Ok(())
377            }
378
379            PrCommands::Create {
380                repo,
381                title,
382                source,
383                destination,
384                body,
385                close_source_branch,
386            } => {
387                let (workspace, repo_slug) = parse_repo(&repo)?;
388                let client = BitbucketClient::from_stored().await?;
389
390                let request = CreatePullRequestRequest {
391                    title,
392                    source: PullRequestBranchRef {
393                        branch: BranchInfo { name: source },
394                    },
395                    destination: destination.map(|d| PullRequestBranchRef {
396                        branch: BranchInfo { name: d },
397                    }),
398                    description: body,
399                    close_source_branch: Some(close_source_branch),
400                    reviewers: None,
401                };
402
403                let pr = client
404                    .create_pull_request(&workspace, &repo_slug, &request)
405                    .await?;
406
407                println!("{} Created pull request #{}", "✓".green(), pr.id);
408
409                if let Some(links) = &pr.links {
410                    if let Some(html) = &links.html {
411                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
412                    }
413                }
414
415                Ok(())
416            }
417
418            PrCommands::Merge {
419                repo,
420                id,
421                strategy,
422                message,
423                close_source_branch,
424            } => {
425                let (workspace, repo_slug) = parse_repo(&repo)?;
426                let client = BitbucketClient::from_stored().await?;
427
428                let request = MergePullRequestRequest {
429                    merge_type: Some("pullrequest".to_string()),
430                    message,
431                    close_source_branch: Some(close_source_branch),
432                    merge_strategy: Some(strategy.into()),
433                };
434
435                let pr = client
436                    .merge_pull_request(&workspace, &repo_slug, id, Some(&request))
437                    .await?;
438
439                println!("{} Merged pull request #{}", "✓".green(), pr.id);
440
441                Ok(())
442            }
443
444            PrCommands::Approve { repo, id } => {
445                let (workspace, repo_slug) = parse_repo(&repo)?;
446                let client = BitbucketClient::from_stored().await?;
447
448                client
449                    .approve_pull_request(&workspace, &repo_slug, id)
450                    .await?;
451
452                println!("{} Approved pull request #{}", "✓".green(), id);
453
454                Ok(())
455            }
456
457            PrCommands::Decline { repo, id } => {
458                let (workspace, repo_slug) = parse_repo(&repo)?;
459                let client = BitbucketClient::from_stored().await?;
460
461                client
462                    .decline_pull_request(&workspace, &repo_slug, id)
463                    .await?;
464
465                println!("{} Declined pull request #{}", "✓".green(), id);
466
467                Ok(())
468            }
469
470            PrCommands::Checkout { repo, id } => {
471                let (workspace, repo_slug) = parse_repo(&repo)?;
472                let client = BitbucketClient::from_stored().await?;
473
474                let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
475                let branch = &pr.source.branch.name;
476
477                println!("Fetching and checking out branch {}...", branch.cyan());
478
479                // Fetch the branch
480                let status = std::process::Command::new("git")
481                    .args(["fetch", "origin", branch])
482                    .status()
483                    .context("Failed to fetch branch")?;
484
485                if !status.success() {
486                    anyhow::bail!("git fetch failed");
487                }
488
489                // Checkout the branch
490                let status = std::process::Command::new("git")
491                    .args(["checkout", branch])
492                    .status()
493                    .context("Failed to checkout branch")?;
494
495                if status.success() {
496                    println!("{} Checked out branch {}", "✓".green(), branch);
497                } else {
498                    // Try creating a tracking branch
499                    let status = std::process::Command::new("git")
500                        .args(["checkout", "-b", branch, &format!("origin/{}", branch)])
501                        .status()
502                        .context("Failed to create tracking branch")?;
503
504                    if status.success() {
505                        println!("{} Created and checked out branch {}", "✓".green(), branch);
506                    } else {
507                        anyhow::bail!("git checkout failed");
508                    }
509                }
510
511                Ok(())
512            }
513
514            PrCommands::Diff { repo, id } => {
515                let (workspace, repo_slug) = parse_repo(&repo)?;
516                let client = BitbucketClient::from_stored().await?;
517
518                let diff = client.get_pr_diff(&workspace, &repo_slug, id).await?;
519                println!("{}", diff);
520
521                Ok(())
522            }
523
524            PrCommands::Comment { repo, id, body } => {
525                let (workspace, repo_slug) = parse_repo(&repo)?;
526                let client = BitbucketClient::from_stored().await?;
527
528                client
529                    .add_pr_comment(&workspace, &repo_slug, id, &body)
530                    .await?;
531
532                println!("{} Added comment to pull request #{}", "✓".green(), id);
533
534                Ok(())
535            }
536
537            PrCommands::ListComments { repo, id, limit } => {
538                let (workspace, repo_slug) = parse_repo(&repo)?;
539                let client = BitbucketClient::from_stored().await?;
540
541                let comments = client
542                    .list_recent_pr_comments(&workspace, &repo_slug, id, limit as usize)
543                    .await?;
544
545                if comments.is_empty() {
546                    println!("No comments found");
547                    return Ok(());
548                }
549
550                let hit_limit = comments.len() >= limit as usize;
551                let values = newest_comments_chronological(comments, limit as usize);
552
553                let rows: Vec<CommentRow> = values
554                    .iter()
555                    .map(|c| CommentRow {
556                        id: c.id,
557                        author: c.user.display_name.clone(),
558                        created: c.created_on.format("%Y-%m-%d %H:%M").to_string(),
559                        comment_type: if c.inline.is_some() {
560                            "inline".to_string()
561                        } else {
562                            "general".to_string()
563                        },
564                        content: c.content.raw.chars().take(50).collect(),
565                    })
566                    .collect();
567
568                let table = Table::new(rows).to_string();
569                println!("{}", table);
570
571                if hit_limit {
572                    println!(
573                        "Showing the {} most recent comments. Use --limit to see more.",
574                        limit
575                    );
576                }
577
578                Ok(())
579            }
580
581            PrCommands::Pipelines {
582                repo,
583                id,
584                scan_limit,
585            } => {
586                let (workspace, repo_slug) = parse_repo(&repo)?;
587                let client = BitbucketClient::from_stored().await?;
588
589                let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
590                let head_commit = pr
591                    .source
592                    .commit
593                    .as_ref()
594                    .map(|c| c.hash.clone())
595                    .context("PR has no head commit hash")?;
596
597                let pipelines = client
598                    .list_pipelines_for_commit(&workspace, &repo_slug, &head_commit, scan_limit)
599                    .await?;
600
601                if pipelines.is_empty() {
602                    println!(
603                        "No pipelines found for PR #{} head commit {} (scanned {} most recent).",
604                        id,
605                        head_commit.chars().take(12).collect::<String>(),
606                        scan_limit.clamp(1, 100)
607                    );
608                    return Ok(());
609                }
610
611                let rows: Vec<PipelineRow> = pipelines
612                    .iter()
613                    .map(|p| {
614                        let duration = match (p.build_seconds_used, &p.state.name) {
615                            (Some(s), _) => super::pipeline::format_duration(s),
616                            (None, crate::models::PipelineStateName::InProgress) => {
617                                "running...".to_string()
618                            }
619                            _ => "-".to_string(),
620                        };
621
622                        PipelineRow {
623                            build: p.build_number,
624                            status: super::pipeline::format_status(
625                                &p.state.name,
626                                p.state.result.as_ref().map(|r| &r.name),
627                            ),
628                            branch: p.target.ref_name.clone().unwrap_or_else(|| "-".to_string()),
629                            commit: p
630                                .target
631                                .commit
632                                .as_ref()
633                                .map(|c| c.hash.chars().take(12).collect())
634                                .unwrap_or_else(|| "-".to_string()),
635                            triggered: p.created_on.format("%Y-%m-%d %H:%M").to_string(),
636                            duration,
637                        }
638                    })
639                    .collect();
640
641                println!("{}", Table::new(rows));
642
643                Ok(())
644            }
645
646            PrCommands::ViewComment {
647                repo,
648                id,
649                comment_id,
650            } => {
651                let (workspace, repo_slug) = parse_repo(&repo)?;
652                let client = BitbucketClient::from_stored().await?;
653
654                let comment = client
655                    .get_pr_comment(&workspace, &repo_slug, id, comment_id)
656                    .await?;
657
658                println!("{} #{} on PR #{}", "Comment".bold(), comment.id, id);
659                println!("{}", "─".repeat(60));
660
661                println!("{} {}", "Author:".dimmed(), comment.user.display_name);
662                println!(
663                    "{} {}",
664                    "Created:".dimmed(),
665                    comment.created_on.format("%Y-%m-%d %H:%M")
666                );
667
668                if let Some(updated) = comment.updated_on {
669                    println!(
670                        "{} {}",
671                        "Updated:".dimmed(),
672                        updated.format("%Y-%m-%d %H:%M")
673                    );
674                }
675
676                if let Some(inline) = &comment.inline {
677                    let line = inline.to.or(inline.from);
678                    let location = match line {
679                        Some(l) => format!("{}:{}", inline.path, l),
680                        None => inline.path.clone(),
681                    };
682                    println!("{} inline", "Type:".dimmed());
683                    println!("{} {}", "File:".dimmed(), location.cyan());
684                } else {
685                    println!("{} general", "Type:".dimmed());
686                }
687
688                println!();
689                println!("{}", comment.content.raw);
690
691                if let Some(links) = &comment.links {
692                    if let Some(html) = &links.html {
693                        println!();
694                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
695                    }
696                }
697
698                Ok(())
699            }
700        }
701    }
702}
703
704fn format_state(state: &PullRequestState) -> String {
705    match state {
706        PullRequestState::Open => "OPEN".green().to_string(),
707        PullRequestState::Merged => "MERGED".purple().to_string(),
708        PullRequestState::Declined => "DECLINED".red().to_string(),
709        PullRequestState::Superseded => "SUPERSEDED".yellow().to_string(),
710    }
711}
712
713/// Keep the newest `limit` comments and return them in chronological
714/// (oldest -> newest) display order.
715fn newest_comments_chronological(
716    mut comments: Vec<PullRequestComment>,
717    limit: usize,
718) -> Vec<PullRequestComment> {
719    comments.sort_by_key(|c| std::cmp::Reverse(c.created_on));
720    comments.truncate(limit);
721    comments.reverse();
722    comments
723}
724
725#[cfg(test)]
726mod tests {
727    use super::newest_comments_chronological;
728    use crate::models::{CommentContent, PullRequestComment, User};
729    use chrono::{DateTime, Utc};
730
731    fn ts(s: &str) -> DateTime<Utc> {
732        s.parse().unwrap()
733    }
734
735    fn comment(id: u64, created_on: DateTime<Utc>) -> PullRequestComment {
736        PullRequestComment {
737            id,
738            content: CommentContent {
739                raw: format!("comment {}", id),
740                markup: None,
741                html: None,
742            },
743            user: User {
744                uuid: "{user-uuid}".to_string(),
745                username: None,
746                display_name: "Test User".to_string(),
747                account_id: None,
748                user_type: "user".to_string(),
749                links: None,
750            },
751            created_on,
752            updated_on: None,
753            deleted: None,
754            inline: None,
755            parent: None,
756            links: None,
757        }
758    }
759
760    #[test]
761    fn keeps_the_newest_comments_in_ascending_display_order() {
762        let t1 = ts("2024-01-01T00:00:00Z");
763        let t2 = ts("2024-01-02T00:00:00Z");
764        let t3 = ts("2024-01-03T00:00:00Z");
765        let input = vec![comment(3, t3), comment(1, t1), comment(2, t2)];
766
767        let result = newest_comments_chronological(input, 2);
768
769        let times: Vec<DateTime<Utc>> = result.iter().map(|c| c.created_on).collect();
770        assert_eq!(times, vec![t2, t3]);
771    }
772
773    #[test]
774    fn limit_larger_than_input_returns_all_in_ascending_order() {
775        let t1 = ts("2024-01-01T00:00:00Z");
776        let t2 = ts("2024-01-02T00:00:00Z");
777        let t3 = ts("2024-01-03T00:00:00Z");
778        let input = vec![comment(3, t3), comment(1, t1), comment(2, t2)];
779
780        let result = newest_comments_chronological(input, 10);
781
782        let times: Vec<DateTime<Utc>> = result.iter().map(|c| c.created_on).collect();
783        assert_eq!(times, vec![t1, t2, t3]);
784    }
785}