bitbucket-cli 0.3.11

A powerful command-line interface for Bitbucket Cloud - manage repos, PRs, issues, and pipelines from your terminal with OAuth 2.0
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use anyhow::{Context, Result};
use clap::{Subcommand, ValueEnum};
use colored::Colorize;
use tabled::{Table, Tabled};

use crate::api::BitbucketClient;
use crate::models::{
    BranchInfo, CreatePullRequestRequest, MergePullRequestRequest, MergeStrategy,
    PullRequestBranchRef, PullRequestState,
};

#[derive(Subcommand)]
pub enum PrCommands {
    /// List pull requests
    List {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Filter by state
        #[arg(short, long, value_enum)]
        state: Option<PrState>,

        /// Number of results
        #[arg(short, long, default_value = "25")]
        limit: u32,
    },

    /// View pull request details
    View {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,

        /// Open in browser
        #[arg(short, long)]
        web: bool,
    },

    /// Create a new pull request
    Create {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Title of the pull request
        #[arg(short, long)]
        title: String,

        /// Source branch
        #[arg(short, long)]
        source: String,

        /// Destination branch (defaults to main branch)
        #[arg(short, long)]
        destination: Option<String>,

        /// Description of the pull request
        #[arg(short = 'b', long)]
        body: Option<String>,

        /// Close source branch after merge
        #[arg(long)]
        close_source_branch: bool,
    },

    /// Merge a pull request
    Merge {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,

        /// Merge strategy
        #[arg(short, long, value_enum, default_value = "merge-commit")]
        strategy: MergeStrategyArg,

        /// Commit message
        #[arg(short, long)]
        message: Option<String>,

        /// Close source branch
        #[arg(long)]
        close_source_branch: bool,
    },

    /// Approve a pull request
    Approve {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,
    },

    /// Decline a pull request
    Decline {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,
    },

    /// Checkout a pull request branch locally
    Checkout {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,
    },

    /// View pull request diff
    Diff {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,
    },

    /// Add a comment to a pull request
    Comment {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,

        /// Comment text
        #[arg(short, long)]
        body: String,
    },

    /// List comments on a pull request
    ListComments {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        id: u64,

        /// Number of results
        #[arg(short, long, default_value = "25")]
        limit: u32,
    },

    /// View a specific comment on a pull request
    ViewComment {
        /// Repository in format workspace/repo-slug
        repo: String,

        /// Pull request ID
        #[arg(value_name = "PR_ID")]
        id: u64,

        /// Comment ID
        comment_id: u64,
    },
}

#[derive(ValueEnum, Clone)]
pub enum PrState {
    Open,
    Merged,
    Declined,
    Superseded,
}

impl From<PrState> for PullRequestState {
    fn from(state: PrState) -> Self {
        match state {
            PrState::Open => PullRequestState::Open,
            PrState::Merged => PullRequestState::Merged,
            PrState::Declined => PullRequestState::Declined,
            PrState::Superseded => PullRequestState::Superseded,
        }
    }
}

#[derive(ValueEnum, Clone)]
pub enum MergeStrategyArg {
    MergeCommit,
    Squash,
    FastForward,
}

impl From<MergeStrategyArg> for MergeStrategy {
    fn from(strategy: MergeStrategyArg) -> Self {
        match strategy {
            MergeStrategyArg::MergeCommit => MergeStrategy::MergeCommit,
            MergeStrategyArg::Squash => MergeStrategy::Squash,
            MergeStrategyArg::FastForward => MergeStrategy::FastForward,
        }
    }
}

#[derive(Tabled)]
struct PrRow {
    #[tabled(rename = "ID")]
    id: u64,
    #[tabled(rename = "TITLE")]
    title: String,
    #[tabled(rename = "AUTHOR")]
    author: String,
    #[tabled(rename = "STATE")]
    state: String,
    #[tabled(rename = "UPDATED")]
    updated: String,
}

#[derive(Tabled)]
struct CommentRow {
    #[tabled(rename = "ID")]
    id: u64,
    #[tabled(rename = "AUTHOR")]
    author: String,
    #[tabled(rename = "CREATED")]
    created: String,
    #[tabled(rename = "TYPE")]
    comment_type: String,
    #[tabled(rename = "CONTENT")]
    content: String,
}

impl PrCommands {
    pub async fn run(self) -> Result<()> {
        match self {
            PrCommands::List { repo, state, limit } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let prs = client
                    .list_pull_requests(
                        &workspace,
                        &repo_slug,
                        state.map(|s| s.into()),
                        None,
                        Some(limit),
                    )
                    .await?;

                if prs.values.is_empty() {
                    println!("No pull requests found");
                    return Ok(());
                }

                let rows: Vec<PrRow> = prs
                    .values
                    .iter()
                    .map(|pr| PrRow {
                        id: pr.id,
                        title: pr.title.chars().take(50).collect(),
                        author: pr.author.display_name.clone(),
                        state: format_state(&pr.state),
                        updated: pr.updated_on.format("%Y-%m-%d").to_string(),
                    })
                    .collect();

                let table = Table::new(rows).to_string();
                println!("{}", table);

                Ok(())
            }

            PrCommands::View { repo, id, web } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;
                let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;

                if web {
                    if let Some(links) = &pr.links {
                        if let Some(html) = &links.html {
                            open::that(&html.href)?;
                            println!("Opened {} in browser", html.href.cyan());
                            return Ok(());
                        }
                    }
                    anyhow::bail!("Could not find PR URL");
                }

                println!("{} {} #{}", format_state(&pr.state), pr.title.bold(), pr.id);
                println!("{}", "".repeat(60));

                println!(
                    "{} {}{}",
                    "Branches:".dimmed(),
                    pr.source.branch.name.cyan(),
                    pr.destination.branch.name.green()
                );
                println!("{} {}", "Author:".dimmed(), pr.author.display_name);
                println!(
                    "{} {}",
                    "Created:".dimmed(),
                    pr.created_on.format("%Y-%m-%d %H:%M")
                );
                println!(
                    "{} {}",
                    "Updated:".dimmed(),
                    pr.updated_on.format("%Y-%m-%d %H:%M")
                );

                if let Some(count) = pr.comment_count {
                    println!("{} {}", "Comments:".dimmed(), count);
                }

                if let Some(tasks) = pr.task_count {
                    if tasks > 0 {
                        println!("{} {}", "Tasks:".dimmed(), tasks);
                    }
                }

                // Show reviewers/approvals
                if let Some(participants) = &pr.participants {
                    let approvals: Vec<_> = participants
                        .iter()
                        .filter(|p| p.approved)
                        .map(|p| p.user.display_name.clone())
                        .collect();

                    if !approvals.is_empty() {
                        println!(
                            "{} {}",
                            "Approved by:".dimmed(),
                            approvals.join(", ").green()
                        );
                    }
                }

                if let Some(description) = &pr.description {
                    if !description.is_empty() {
                        println!();
                        println!("{}", description);
                    }
                }

                if let Some(links) = &pr.links {
                    if let Some(html) = &links.html {
                        println!();
                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
                    }
                }

                Ok(())
            }

            PrCommands::Create {
                repo,
                title,
                source,
                destination,
                body,
                close_source_branch,
            } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let request = CreatePullRequestRequest {
                    title,
                    source: PullRequestBranchRef {
                        branch: BranchInfo { name: source },
                    },
                    destination: destination.map(|d| PullRequestBranchRef {
                        branch: BranchInfo { name: d },
                    }),
                    description: body,
                    close_source_branch: Some(close_source_branch),
                    reviewers: None,
                };

                let pr = client
                    .create_pull_request(&workspace, &repo_slug, &request)
                    .await?;

                println!("{} Created pull request #{}", "".green(), pr.id);

                if let Some(links) = &pr.links {
                    if let Some(html) = &links.html {
                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
                    }
                }

                Ok(())
            }

            PrCommands::Merge {
                repo,
                id,
                strategy,
                message,
                close_source_branch,
            } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let request = MergePullRequestRequest {
                    merge_type: Some("pullrequest".to_string()),
                    message,
                    close_source_branch: Some(close_source_branch),
                    merge_strategy: Some(strategy.into()),
                };

                let pr = client
                    .merge_pull_request(&workspace, &repo_slug, id, Some(&request))
                    .await?;

                println!("{} Merged pull request #{}", "".green(), pr.id);

                Ok(())
            }

            PrCommands::Approve { repo, id } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                client
                    .approve_pull_request(&workspace, &repo_slug, id)
                    .await?;

                println!("{} Approved pull request #{}", "".green(), id);

                Ok(())
            }

            PrCommands::Decline { repo, id } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                client
                    .decline_pull_request(&workspace, &repo_slug, id)
                    .await?;

                println!("{} Declined pull request #{}", "".green(), id);

                Ok(())
            }

            PrCommands::Checkout { repo, id } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let pr = client.get_pull_request(&workspace, &repo_slug, id).await?;
                let branch = &pr.source.branch.name;

                println!("Fetching and checking out branch {}...", branch.cyan());

                // Fetch the branch
                let status = std::process::Command::new("git")
                    .args(["fetch", "origin", branch])
                    .status()
                    .context("Failed to fetch branch")?;

                if !status.success() {
                    anyhow::bail!("git fetch failed");
                }

                // Checkout the branch
                let status = std::process::Command::new("git")
                    .args(["checkout", branch])
                    .status()
                    .context("Failed to checkout branch")?;

                if status.success() {
                    println!("{} Checked out branch {}", "".green(), branch);
                } else {
                    // Try creating a tracking branch
                    let status = std::process::Command::new("git")
                        .args(["checkout", "-b", branch, &format!("origin/{}", branch)])
                        .status()
                        .context("Failed to create tracking branch")?;

                    if status.success() {
                        println!("{} Created and checked out branch {}", "".green(), branch);
                    } else {
                        anyhow::bail!("git checkout failed");
                    }
                }

                Ok(())
            }

            PrCommands::Diff { repo, id } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let diff = client.get_pr_diff(&workspace, &repo_slug, id).await?;
                println!("{}", diff);

                Ok(())
            }

            PrCommands::Comment { repo, id, body } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                client
                    .add_pr_comment(&workspace, &repo_slug, id, &body)
                    .await?;

                println!("{} Added comment to pull request #{}", "".green(), id);

                Ok(())
            }

            PrCommands::ListComments { repo, id, limit } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let comments = client
                    .list_pr_comments(&workspace, &repo_slug, id)
                    .await?;

                let mut values: Vec<_> = comments.values.into_iter().take(limit as usize).collect();

                if values.is_empty() {
                    println!("No comments found");
                    return Ok(());
                }

                values.sort_by_key(|c| c.created_on);

                let rows: Vec<CommentRow> = values
                    .iter()
                    .map(|c| CommentRow {
                        id: c.id,
                        author: c.user.display_name.clone(),
                        created: c.created_on.format("%Y-%m-%d %H:%M").to_string(),
                        comment_type: if c.inline.is_some() {
                            "inline".to_string()
                        } else {
                            "general".to_string()
                        },
                        content: c.content.raw.chars().take(50).collect(),
                    })
                    .collect();

                let table = Table::new(rows).to_string();
                println!("{}", table);

                Ok(())
            }

            PrCommands::ViewComment {
                repo,
                id,
                comment_id,
            } => {
                let (workspace, repo_slug) = parse_repo(&repo)?;
                let client = BitbucketClient::from_stored().await?;

                let comment = client
                    .get_pr_comment(&workspace, &repo_slug, id, comment_id)
                    .await?;

                println!(
                    "{} #{} on PR #{}",
                    "Comment".bold(),
                    comment.id,
                    id
                );
                println!("{}", "".repeat(60));

                println!("{} {}", "Author:".dimmed(), comment.user.display_name);
                println!(
                    "{} {}",
                    "Created:".dimmed(),
                    comment.created_on.format("%Y-%m-%d %H:%M")
                );

                if let Some(updated) = comment.updated_on {
                    println!(
                        "{} {}",
                        "Updated:".dimmed(),
                        updated.format("%Y-%m-%d %H:%M")
                    );
                }

                if let Some(inline) = &comment.inline {
                    let line = inline.to.or(inline.from);
                    let location = match line {
                        Some(l) => format!("{}:{}", inline.path, l),
                        None => inline.path.clone(),
                    };
                    println!("{} {}", "Type:".dimmed(), "inline");
                    println!("{} {}", "File:".dimmed(), location.cyan());
                } else {
                    println!("{} {}", "Type:".dimmed(), "general");
                }

                println!();
                println!("{}", comment.content.raw);

                if let Some(links) = &comment.links {
                    if let Some(html) = &links.html {
                        println!();
                        println!("{} {}", "URL:".dimmed(), html.href.cyan());
                    }
                }

                Ok(())
            }
        }
    }
}

fn parse_repo(repo: &str) -> Result<(String, String)> {
    let parts: Vec<&str> = repo.split('/').collect();
    if parts.len() != 2 {
        anyhow::bail!(
            "Invalid repository format. Expected 'workspace/repo-slug', got '{}'",
            repo
        );
    }
    Ok((parts[0].to_string(), parts[1].to_string()))
}

fn format_state(state: &PullRequestState) -> String {
    match state {
        PullRequestState::Open => "OPEN".green().to_string(),
        PullRequestState::Merged => "MERGED".purple().to_string(),
        PullRequestState::Declined => "DECLINED".red().to_string(),
        PullRequestState::Superseded => "SUPERSEDED".yellow().to_string(),
    }
}