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
627
#![forbid(unsafe_code)]
use bb_cli::commands;
use bb_cli::error::{BbError, Result};
use bb_cli::output::{self, Format};
use bb_cli::skill;
use clap::{CommandFactory, Parser, Subcommand};
#[derive(Parser)]
#[command(
name = "bb",
version,
about = "Bitbucket Cloud CLI",
propagate_version = true
)]
struct Cli {
/// Output machine-readable json
#[arg(long, global = true)]
json: bool,
/// Repository to act on, as `workspace/repo` or a bitbucket url
#[arg(long, short = 'R', global = true, env = "BB_REPO")]
repo: Option<String>,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Manage authentication
Auth {
#[command(subcommand)]
command: AuthCommand,
},
/// Work with pull requests
Pr {
#[command(subcommand)]
command: PrCommand,
},
/// Work with branches
Branch {
#[command(subcommand)]
command: BranchCommand,
},
/// Open the repository in a browser
#[command(alias = "b")]
Browse {
/// Print the url instead of opening it
#[arg(long)]
print: bool,
/// Open a specific pull request
#[arg(long, conflicts_with = "branches")]
pr: Option<u64>,
/// Open the branches page
#[arg(long)]
branches: bool,
},
/// Print a shell completion script
Completions {
/// bash, zsh, fish, powershell or elvish
shell: clap_complete::Shell,
},
/// Check for a newer release and update this install
Update,
/// Install the bundled agent skill so your coding agent can drive `bb`
Skill {
#[command(subcommand)]
command: SkillCommand,
},
}
#[derive(Subcommand)]
enum SkillCommand {
/// Install or refresh the skill for the agents in this project
Install {
/// Which agent layout to write: agents, claude or all (default: auto-detect)
#[arg(long)]
agent: Option<String>,
/// Install into your home directory instead of this project
#[arg(long)]
global: bool,
/// Overwrite a skill file that was edited locally
#[arg(long)]
force: bool,
/// Only act on this skill; omit for all of them
#[arg(long)]
skill: Option<String>,
/// Install every skill without asking
#[arg(long, conflicts_with = "skill")]
all: bool,
},
/// Show where the skill is installed and whether it is current
Status,
/// Remove skills this tool installed
Uninstall {
/// Act on your home directory instead of this project
#[arg(long)]
global: bool,
/// Remove a skill file that was edited locally
#[arg(long)]
force: bool,
/// Only act on this skill; omit for all of them
#[arg(long)]
skill: Option<String>,
},
}
#[derive(Subcommand)]
enum BranchCommand {
/// List branches
#[command(alias = "l", alias = "ls")]
List {
/// Only branches whose last commit author matches this substring
#[arg(long, short = 'u')]
user: Option<String>,
/// Only branches whose name matches this substring
#[arg(long, short = 'n')]
name: Option<String>,
/// Maximum rows to print
#[arg(long, default_value_t = 100)]
limit: usize,
},
}
#[derive(Subcommand)]
enum PrCommand {
/// List pull requests
#[command(alias = "l", alias = "ls")]
List {
/// Only show pull requests targeting this branch
destination: Option<String>,
/// State filter: OPEN, MERGED, DECLINED, SUPERSEDED, DRAFT or ALL
#[arg(long, default_value = "OPEN")]
state: String,
/// Only pull requests this person is tagged to review
#[arg(long)]
reviewer: Option<String>,
/// Only pull requests opened by this person; `@me` for yourself
#[arg(long)]
author: Option<String>,
/// Your own review state on the pull request
#[arg(long, value_enum)]
review_state: Option<commands::pr_list::ReviewStateArg>,
/// Only pull requests waiting on your review
#[arg(long)]
needs_my_review: bool,
/// Show the build status column (one extra request per pull request)
#[arg(long)]
build: bool,
/// Only pull requests whose build rolls up to this state
#[arg(long, value_enum)]
build_status: Option<commands::pr_list::BuildStateArg>,
},
/// Print the raw diff for a pull request
#[command(alias = "d")]
Diff { id: u64 },
/// List files changed in a pull request
Files { id: u64 },
/// List commits in a pull request
#[command(alias = "c")]
Commits { id: u64 },
/// Show the build statuses reported on a pull request
Build { id: u64 },
/// Request changes on a pull request
#[command(name = "request-changes", alias = "rc")]
RequestChanges { id: u64 },
/// Withdraw a change request
#[command(name = "no-request-changes", alias = "nrc")]
NoRequestChanges { id: u64 },
/// Open a pull request
Create {
/// Target branch, or a comma-separated list of target branches
target: String,
/// Source branch (defaults to the current branch)
source: Option<String>,
#[arg(long)]
title: Option<String>,
#[arg(long)]
description: Option<String>,
/// Do not attach the repository's default reviewers
#[arg(long)]
no_default_reviewers: bool,
/// Prompt for title and description
#[arg(long, short = 'i')]
interactive: bool,
/// Open the new pull request in a browser
#[arg(long, short = 'w')]
web: bool,
/// Delete the source branch once merged
#[arg(long)]
close_source_branch: bool,
},
/// Show a pull request with its comments
#[command(alias = "show", alias = "v")]
View {
id: u64,
/// Hide inline threads that have been resolved
#[arg(long)]
unresolved: bool,
/// Skip the pull request header and print only comments
#[arg(long)]
comments_only: bool,
},
/// Show, add or remove the reviewers tagged on a pull request
#[command(args_conflicts_with_subcommands = true)]
Reviewers {
/// Pull request id (omit when using add/remove)
id: Option<u64>,
#[command(subcommand)]
command: Option<ReviewersCommand>,
},
/// Comment on a pull request
Comment {
id: u64,
/// Comment text
#[arg(long, short = 'b')]
body: Option<String>,
/// Read the comment text from stdin
#[arg(long)]
body_stdin: bool,
/// Attach the comment to this file
#[arg(long, short = 'f')]
file: Option<String>,
/// Attach the comment to this line of --file
#[arg(long, short = 'l')]
line: Option<u64>,
/// Reply to an existing comment id
#[arg(long)]
reply_to: Option<u64>,
/// Open the comment in a browser
#[arg(long, short = 'w')]
web: bool,
},
/// Mark a comment thread as resolved, after confirming
Resolve {
id: u64,
/// Id of the thread's first comment
comment: u64,
/// Approve without the confirmation prompt
#[arg(long, short = 'y')]
yes: bool,
},
/// Reopen a resolved comment thread
Unresolve {
id: u64,
/// Id of the thread's first comment
comment: u64,
},
/// List your pull requests across every repository you can see
Mine {
/// Which pull requests: author, reviewer or all
#[arg(long, value_enum, default_value = "all")]
role: commands::pr_mine::RoleArg,
/// State filter: OPEN, MERGED, DECLINED, SUPERSEDED or ALL
#[arg(long, default_value = "OPEN")]
state: String,
/// Workspace(s) to scan, comma-separated. Falls back to BB_WORKSPACE,
/// then to the workspace of the current git checkout.
#[arg(long)]
workspace: Option<String>,
/// Most recently updated repositories to scan per workspace
#[arg(long, default_value_t = 30)]
repo_limit: usize,
/// Show the build status column (one extra request per pull request)
#[arg(long)]
build: bool,
},
}
#[derive(Subcommand)]
enum ReviewersCommand {
/// List the reviewers on a pull request and what each has decided
#[command(alias = "l", alias = "ls")]
List { id: u64 },
/// Tag one or more reviewers, comma-separated
Add {
id: u64,
/// Reviewer names, comma-separated; a `{uuid}` is taken verbatim
names: String,
},
/// Untag one or more reviewers, comma-separated
#[command(alias = "rm")]
Remove {
id: u64,
/// Reviewer names, comma-separated; a `{uuid}` is taken verbatim
names: String,
},
}
#[derive(Subcommand)]
enum AuthCommand {
/// Store an atlassian api token in the os keyring
#[command(long_about = "Store an atlassian api token in the os keyring.
Create the token at https://id.atlassian.com/manage-profile/security/api-tokens,
choosing \"Create API token with scopes\" and Bitbucket as the product, then grant:
read:user:bitbucket required — login verifies the token against /user
read:pullrequest:bitbucket pr list, view, diff, files, commits, mine
read:repository:bitbucket branch list, default reviewers, the pr mine scan
write:pullrequest:bitbucket pr create, comment, resolve, request-changes
The write scope is only needed to create pull requests and comment; everything
read-only works with the first three.")]
Login {
/// Atlassian account email
#[arg(long)]
email: Option<String>,
/// Read the api token from stdin instead of prompting
#[arg(long)]
token_stdin: bool,
},
/// Show the active account with the token redacted
Status,
/// Remove stored credentials
Logout,
}
/// `brew upgrade bb` and `cargo install` replace the binary without running any
/// of our code, so an installed skill file would otherwise keep describing an
/// older CLI until someone noticed `bb skill status` saying `stale` and re-ran
/// the install. Every tracked entry records the version that wrote it, so the
/// check is a string compare and costs nothing once everything is current.
///
/// Five properties this keeps, each with a test: it never overwrites a locally
/// edited file (`refresh_tracked` reports those as skipped), it never writes to
/// stdout so `--json` stays pure, it never fails the command the user actually
/// asked for, `BB_SKILL_NO_AUTO_REFRESH=1` turns it off, and `refresh_tracked`
/// stamps the running version onto every entry it looked at — including skipped
/// ones — so this fires once per upgrade rather than on every invocation.
fn auto_refresh_skills(format: Format) {
if std::env::var_os("BB_SKILL_NO_AUTO_REFRESH").is_some() {
return;
}
let (entries, _warning) = skill::load_state();
if entries.is_empty() || !skill::tracked_version_differs(&entries) {
return;
}
// `Preserve` because this call runs ahead of a command the user did not
// ask to refresh anything with — a file they deliberately deleted must
// stay deleted here. Only explicit `bb skill install`/`bb update` restore
// a missing file.
match skill::refresh_tracked(skill::MissingPolicy::Preserve) {
Ok(outcomes) => {
// Refreshed, pruned and failed are different events and the line
// must not conflate them: "refreshed 2" when some were actually
// dropped or left broken reads as a write that never happened.
let refreshed = outcomes
.iter()
.filter(|o| o.action == skill::Action::Refreshed)
.count();
let pruned = outcomes
.iter()
.filter(|o| o.action == skill::Action::Pruned)
.count();
let failed = outcomes
.iter()
.filter(|o| o.action == skill::Action::Failed)
.count();
if (refreshed > 0 || pruned > 0 || failed > 0) && !format.is_json() {
let mut parts = Vec::new();
if refreshed > 0 {
parts.push(format!(
"refreshed {refreshed} skill file{}",
if refreshed == 1 { "" } else { "s" }
));
}
if pruned > 0 {
parts.push(format!(
"forgot {pruned} skill path{} that no longer exist{}",
if pruned == 1 { "" } else { "s" },
if pruned == 1 { "s" } else { "" }
));
}
// Named once, as a count — not per path — so a read-only
// checkout does not spam a line per tracked entry on every
// single invocation.
if failed > 0 {
parts.push(format!(
"could not refresh {failed} skill file{}",
if failed == 1 { "" } else { "s" }
));
}
output::warn(&format!(
"{} for bb {}",
parts.join(", "),
env!("CARGO_PKG_VERSION")
));
}
}
// The user asked for something else. A read-only filesystem or a
// vanished directory must not turn their command into a failure. Per
// entry write failures no longer reach here at all (see
// `refresh_tracked`'s `Action::Failed`) — only `save_state` itself
// failing does, which is rare enough that warning every time is fine.
Err(err) => {
if !format.is_json() {
output::warn(&format!("could not refresh agent skills: {err}"));
}
}
}
}
async fn run(cli: Cli) -> Result<()> {
let format = Format::from_json_flag(cli.json);
auto_refresh_skills(format);
match cli.command {
Command::Auth { command } => match command {
AuthCommand::Login { email, token_stdin } => {
commands::auth::login(email, token_stdin, format).await
}
AuthCommand::Status => commands::auth::status(format).await,
AuthCommand::Logout => commands::auth::logout(format),
},
Command::Pr { command } => {
if let PrCommand::Mine {
role,
state,
workspace,
repo_limit,
build,
} = command
{
return commands::pr_mine::run(
format,
commands::pr_mine::MineArgs {
role,
state,
workspace,
repo_limit,
build,
},
)
.await;
}
let ctx = commands::pr::Ctx::new(cli.repo.as_deref(), format)?;
match command {
PrCommand::List {
destination,
state,
reviewer,
author,
review_state,
needs_my_review,
build,
build_status,
} => {
commands::pr_list::list(
&ctx,
commands::pr_list::ListArgs {
destination,
state,
reviewer,
author,
review_state,
needs_my_review,
build,
build_status,
},
)
.await
}
PrCommand::Diff { id } => commands::pr::diff(&ctx, id).await,
PrCommand::Files { id } => commands::pr::files(&ctx, id).await,
PrCommand::Commits { id } => commands::pr::commits(&ctx, id).await,
PrCommand::Build { id } => commands::pr_build::run(&ctx, id).await,
PrCommand::RequestChanges { id } => commands::pr::request_changes(&ctx, id).await,
PrCommand::NoRequestChanges { id } => {
commands::pr::unrequest_changes(&ctx, id).await
}
PrCommand::Create {
target,
source,
title,
description,
no_default_reviewers,
interactive,
web,
close_source_branch,
} => {
commands::pr::create(
&ctx,
commands::pr::CreateArgs {
target,
source,
title,
description,
no_default_reviewers,
interactive,
web,
close_source_branch,
},
)
.await
}
PrCommand::Reviewers { id, command } => match (id, command) {
(_, Some(ReviewersCommand::List { id })) => {
commands::pr_reviewers::list(&ctx, id).await
}
(_, Some(ReviewersCommand::Add { id, names })) => {
commands::pr_reviewers::add(&ctx, id, &names).await
}
(_, Some(ReviewersCommand::Remove { id, names })) => {
commands::pr_reviewers::remove(&ctx, id, &names).await
}
(Some(id), None) => commands::pr_reviewers::list(&ctx, id).await,
(None, None) => Err(bb_cli::error::BbError::Config(
"pass a pull request id, or `add`/`remove`".into(),
)),
},
PrCommand::View {
id,
unresolved,
comments_only,
} => commands::pr_comments::view(&ctx, id, unresolved, comments_only).await,
PrCommand::Comment {
id,
body,
body_stdin,
file,
line,
reply_to,
web,
} => {
commands::pr_comments::comment(
&ctx,
commands::pr_comments::CommentArgs {
id,
body,
body_stdin,
file,
line,
reply_to,
web,
},
)
.await
}
PrCommand::Resolve { id, comment, yes } => {
commands::pr_comments::resolve(&ctx, id, comment, yes).await
}
PrCommand::Unresolve { id, comment } => {
commands::pr_comments::unresolve(&ctx, id, comment).await
}
PrCommand::Mine { .. } => {
Err(BbError::Config("pr mine does not take a repository".into()))
}
}
}
Command::Branch { command } => {
let ctx = commands::pr::Ctx::new(cli.repo.as_deref(), format)?;
match command {
BranchCommand::List { user, name, limit } => {
commands::branch::list(&ctx, user, name, limit).await
}
}
}
Command::Browse {
print,
pr,
branches,
} => {
let target = if let Some(id) = pr {
Some(commands::browse::BrowseTarget::Pr(id))
} else if branches {
Some(commands::browse::BrowseTarget::Branches)
} else {
None
};
commands::browse::browse(cli.repo.as_deref(), target, print, format)
}
Command::Completions { shell } => {
commands::completions::generate::<Cli>(shell);
Ok(())
}
Command::Update => {
commands::update::run(format, &commands::update::release_api_base()).await
}
Command::Skill { command } => match command {
SkillCommand::Install {
agent,
global,
force,
skill,
all,
} => commands::skill::install(
format,
agent.as_deref(),
global,
force,
skill.as_deref(),
all,
),
SkillCommand::Status => commands::skill::status(format),
SkillCommand::Uninstall {
global,
force,
skill,
} => commands::skill::uninstall(format, global, force, skill.as_deref()),
},
}
}
#[tokio::main]
async fn main() {
let cli = Cli::parse();
// `clap`'s `conflicts_with` cannot span a global, top-level arg and an id
// that only exists on one nested subcommand's own `Command` node, so this
// is enforced by hand instead, using clap's own error rendering — `pr
// mine` is not repository-scoped, and accepting `-R`/`--repo` there would
// silently discard it (see `PrCommand::Mine { .. }`'s residual match arm).
if cli.repo.is_some()
&& matches!(&cli.command, Command::Pr { command } if matches!(command, PrCommand::Mine { .. }))
{
let mut cmd = Cli::command();
cmd.error(
clap::error::ErrorKind::ArgumentConflict,
"the argument '--repo' cannot be used with 'pr mine': it scans every repository, not one",
)
.exit();
}
if let Err(err) = run(cli).await {
eprintln!("error: {err}");
std::process::exit(err.exit_code());
}
}