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