bb-cli 0.1.1

bb — a Bitbucket CLI, a gh for Bitbucket.
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
//! `bb repo view` — show a repository's details, or open it in the browser.

use crate::api::models::Repository;
use crate::api::BitbucketClient;
use crate::core::{AuthError, Context, FlagError, RepoId};
use clap::Args;

use crate::auth;
use crate::render::sanitize;

/// JSON fields a repository can be projected to with `--json`. Must match the
/// full set of keys `api::models::Repository` serializes (no `skip_serializing_if`,
/// so every field is emitted), or `--json <field>` rejects keys that `--jq '.'`
/// would happily dump.
const FIELDS: &[&str] = &[
    "slug",
    "name",
    "full_name",
    "is_private",
    "description",
    "mainbranch",
    "links",
    "has_issues",
    "parent",
];

#[derive(Args, Debug)]
pub struct ViewArgs {
    /// Repository as WORKSPACE/SLUG (defaults to the current repo)
    // `id = "target"` avoids colliding with the global `-R/--repo` (clap id
    // `repo`); a same-id local arg shadows the global's short, which made
    // `bb repo view -R …` error with "unexpected argument '-R'".
    #[arg(id = "target", value_name = "WORKSPACE/SLUG")]
    pub repo: Option<String>,
    /// Open the repository in the browser
    #[arg(long)]
    pub web: bool,
    #[command(flatten)]
    pub json: crate::output::JsonFlags,
}

/// Run `bb repo view`.
///
/// # Errors
/// Returns [`AuthError`] (exit 4) if not authenticated for the repo's host,
/// [`FlagError`] (exit 1) for a malformed target or when the repository is not
/// found, and propagates [`ApiError`](crate::core::ApiError) from the lookup.
pub fn run(ctx: &Context, args: ViewArgs) -> anyhow::Result<()> {
    let repo = resolve_target(ctx, args.repo.as_deref())?;
    let host = repo.host().to_owned();

    let header = auth::header_for(ctx.config.as_ref(), &host);
    if header.is_none() {
        return Err(AuthError::new(host).into());
    }
    let client = BitbucketClient::new(ctx.transport.clone(), header);

    let path = format!("/repositories/{}/{}", repo.workspace(), repo.slug());
    let repository: Repository = match client.get(&path) {
        Ok(r) => r,
        Err(e) if e.is_not_found() => {
            return Err(FlagError::new(format!(
                "repository {}/{} not found",
                repo.workspace(),
                repo.slug()
            ))
            .into());
        }
        Err(e) => return Err(e.into()),
    };

    if args.json.requested() {
        args.json.validate(FIELDS)?;
        args.json
            .emit(&ctx.io, serde_json::to_value(&repository)?)?;
        return Ok(());
    }

    if args.web {
        let url = repository
            .html_url()
            .ok_or_else(|| FlagError::new("no browser URL is available for this repository"))?;
        ctx.browser.browse(url)?;
        ctx.io.println(&format!("Opening {url} in your browser."));
        return Ok(());
    }

    ctx.io.print(&render_view(&repo, &repository));
    Ok(())
}

/// Resolve the repository the command targets: parse `WORKSPACE/SLUG` if given,
/// else fall back to the current repo (`ctx.base_repo()`).
fn resolve_target(ctx: &Context, arg: Option<&str>) -> anyhow::Result<RepoId> {
    match arg {
        Some(s) => s.parse::<RepoId>().map_err(|e| FlagError::new(e).into()),
        None => Ok(ctx.base_repo()?),
    }
}

/// Render a repository's details.
fn render_view(repo: &RepoId, r: &Repository) -> String {
    let full_name = r.full_name.clone().unwrap_or_else(|| repo.full_name());
    let visibility = match r.is_private {
        Some(true) => "private",
        _ => "public",
    };
    let description = r
        .description
        .as_deref()
        .map(str::trim)
        .filter(|d| !d.is_empty())
        .map_or_else(|| "No description.".to_owned(), sanitize);
    let branch = r.mainbranch.as_ref().map_or("", |b| b.name.as_str());
    let url = r.html_url().unwrap_or("");

    let mut out = format!("{}\n", sanitize(&full_name));
    out.push_str(&format!("{visibility}\n"));
    out.push('\n');
    out.push_str(&format!("{description}\n"));
    out.push('\n');
    if !branch.is_empty() {
        out.push_str(&format!("Default branch: {}\n", sanitize(branch)));
    }
    if !url.is_empty() {
        out.push_str(&format!("{url}\n"));
    }
    out
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::api::testing::FakeTransport;
    use crate::config::FileConfig;
    use crate::core::{ConfigProvider, GitClient, Method, RepoId, Transport};
    use crate::git::{ShellGit, StubRunner};

    use super::*;
    use crate::testsupport::{test_context, ScriptedPrompter};

    /// Git stub that answers `remote -v` (so `base_repo` can default).
    fn git() -> Arc<dyn GitClient> {
        let s = Arc::new(StubRunner::new());
        s.register(
            "remote -v",
            0,
            "origin\tgit@bitbucket.org:acme/widgets.git (fetch)\n\
             origin\tgit@bitbucket.org:acme/widgets.git (push)\n",
        );
        Arc::new(ShellGit::new(s))
    }

    /// Git stub that must never be called (the target comes from the arg).
    fn no_git() -> Arc<dyn GitClient> {
        Arc::new(ShellGit::new(Arc::new(StubRunner::new())))
    }

    fn config() -> Arc<dyn ConfigProvider> {
        let cfg = FileConfig::blank();
        cfg.set("bitbucket.org", "auth_type", "app_password")
            .unwrap();
        cfg.set("bitbucket.org", "username", "u").unwrap();
        cfg.set("bitbucket.org", "token", "t").unwrap();
        Arc::new(cfg)
    }

    fn args(repo: Option<&str>, web: bool) -> ViewArgs {
        ViewArgs {
            repo: repo.map(ToOwned::to_owned),
            web,
            json: crate::output::JsonFlags::default(),
        }
    }

    const WIDGETS: &str = r#"{
        "slug": "widgets",
        "name": "widgets",
        "full_name": "acme/widgets",
        "is_private": true,
        "description": "A widget factory.",
        "mainbranch": {"name": "main"},
        "links": {
            "html": {"href": "https://bitbucket.org/acme/widgets"},
            "clone": [
                {"name": "https", "href": "https://bitbucket.org/acme/widgets.git"},
                {"name": "ssh", "href": "git@bitbucket.org:acme/widgets.git"}
            ]
        }
    }"#;

    #[test]
    fn view_by_workspace_slug_renders() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, WIDGETS),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, no_git(), config(), prompter, false);

        run(&ctx, args(Some("acme/widgets"), false)).unwrap();

        let out = bufs.stdout_string();
        assert!(out.contains("acme/widgets"), "out: {out}");
        assert!(out.contains("private"), "out: {out}");
        assert!(out.contains("A widget factory."), "out: {out}");
        assert!(out.contains("Default branch: main"), "out: {out}");
        assert!(
            out.contains("https://bitbucket.org/acme/widgets"),
            "out: {out}"
        );
    }

    #[test]
    fn view_public_with_no_description_shows_placeholder() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, r#"{"full_name":"acme/widgets","is_private":false}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, no_git(), config(), prompter, false);

        run(&ctx, args(Some("acme/widgets"), false)).unwrap();

        let out = bufs.stdout_string();
        assert!(out.contains("public"), "out: {out}");
        assert!(out.contains("No description."), "out: {out}");
    }

    #[test]
    fn view_defaults_to_base_repo() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, WIDGETS),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, git(), config(), prompter, false);

        run(&ctx, args(None, false)).unwrap();
        assert!(bufs.stdout_string().contains("acme/widgets"));
    }

    #[test]
    fn view_web_browses_and_prints_url() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, WIDGETS),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, no_git(), config(), prompter, false);

        run(&ctx, args(Some("acme/widgets"), true)).unwrap();

        let out = bufs.stdout_string();
        assert!(
            out.contains("https://bitbucket.org/acme/widgets"),
            "out: {out}"
        );
        // --web must not render the description.
        assert!(!out.contains("A widget factory."), "out: {out}");
    }

    #[test]
    fn view_not_found_is_flag_error() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo 404",
            FakeTransport::rest(Method::Get, "/repositories/acme/nope"),
            FakeTransport::json(
                404,
                r#"{"error":{"message":"Repository acme/nope not found"}}"#,
            ),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, _bufs) = test_context(transport, no_git(), config(), prompter, false);

        let err = run(&ctx, args(Some("acme/nope"), false)).unwrap_err();
        let flag = err.downcast_ref::<FlagError>();
        assert!(flag.is_some(), "expected FlagError, got: {err}");
        assert!(flag.unwrap().0.contains("not found"));
    }

    #[test]
    fn view_invalid_target_is_flag_error() {
        let h = Arc::new(FakeTransport::new());
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, _bufs) = test_context(transport, no_git(), config(), prompter, false);

        let err = run(&ctx, args(Some("not-a-repo"), false)).unwrap_err();
        assert!(err.downcast_ref::<FlagError>().is_some());
    }

    #[test]
    fn view_json_emits_projected_fields() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo json",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, WIDGETS),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, no_git(), config(), prompter, false);

        let a = ViewArgs {
            repo: Some("acme/widgets".to_owned()),
            web: false,
            json: crate::output::JsonFlags {
                json: vec!["slug".into(), "full_name".into(), "is_private".into()],
                jq: None,
                template: None,
            },
        };
        run(&ctx, a).unwrap();

        let out = bufs.stdout_string();
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["slug"], "widgets");
        assert_eq!(v["full_name"], "acme/widgets");
        assert_eq!(v["is_private"], true);
        // Unrequested fields are projected away.
        assert!(v.get("description").is_none(), "out: {out}");
    }

    #[test]
    fn view_json_takes_precedence_over_web() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo json web",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, WIDGETS),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, no_git(), config(), prompter, false);

        let a = ViewArgs {
            repo: Some("acme/widgets".to_owned()),
            web: true,
            json: crate::output::JsonFlags {
                json: vec!["slug".into()],
                jq: None,
                template: None,
            },
        };
        run(&ctx, a).unwrap();

        let out = bufs.stdout_string();
        // --json wins: JSON is emitted, no browser-open message.
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["slug"], "widgets");
        assert!(!out.contains("Opening"), "out: {out}");
    }

    #[test]
    fn view_json_unknown_field_is_flag_error() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo json bogus",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(200, WIDGETS),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, _bufs) = test_context(transport, no_git(), config(), prompter, false);

        let a = ViewArgs {
            repo: Some("acme/widgets".to_owned()),
            web: false,
            json: crate::output::JsonFlags {
                json: vec!["bogus".into()],
                jq: None,
                template: None,
            },
        };
        let err = run(&ctx, a).unwrap_err();
        assert!(err.downcast_ref::<FlagError>().is_some());
    }

    #[test]
    fn view_json_accepts_full_serialized_field_set() {
        // `--jq '.'` dumps every key the `Repository` struct serializes (incl.
        // `has_issues`, `parent`). Those must therefore be accepted by
        // `--json <field>` too — previously `has_issues` was rejected as unknown.
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get repo json has_issues",
            FakeTransport::rest(Method::Get, "/repositories/acme/widgets"),
            FakeTransport::json(
                200,
                r#"{"full_name":"acme/widgets","is_private":true,"has_issues":true}"#,
            ),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, no_git(), config(), prompter, false);

        let a = ViewArgs {
            repo: Some("acme/widgets".to_owned()),
            web: false,
            json: crate::output::JsonFlags {
                json: vec!["has_issues".into()],
                jq: None,
                template: None,
            },
        };
        // Must not error (the field is now in the allowlist) and must project it.
        run(&ctx, a).unwrap();

        let out = bufs.stdout_string();
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["has_issues"], true, "out: {out}");
    }

    #[test]
    fn view_not_logged_in_is_auth_error() {
        let h = Arc::new(FakeTransport::new());
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let cfg: Arc<dyn ConfigProvider> = Arc::new(FileConfig::blank());
        let (ctx, _bufs) = test_context(transport, no_git(), cfg, prompter, false);

        let err = run(&ctx, args(Some("acme/widgets"), false)).unwrap_err();
        assert!(err.downcast_ref::<AuthError>().is_some());
    }

    #[test]
    fn render_view_sanitizes_description() {
        let r: Repository = serde_json::from_str(
            r#"{"full_name":"acme/widgets","is_private":false,
                "description":"line1\nline2"}"#,
        )
        .unwrap();
        let out = render_view(&RepoId::new("acme", "widgets"), &r);
        assert!(out.contains("line1 line2"), "out: {out}");
        assert!(!out.contains("line1\nline2"));
    }
}