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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! `bb api` — make an authenticated Bitbucket API request and print the result.
//!
//! The `gh api` analog: an authenticated raw passthrough to the Bitbucket REST
//! API. Builds the `Authorization` header from stored config, sends the request
//! verbatim (no 2xx-only filtering), pretty-prints JSON responses, and maps an
//! HTTP status `>= 400` to a non-zero exit.

use crate::core::{Context, FlagError, Method, SilentError};
use clap::Args;
use serde_json::Value;

#[derive(Args, Debug)]
pub struct ApiArgs {
    /// API path, e.g. `/user` or `/repositories/WS/SLUG` (a full URL also works)
    #[arg(value_name = "PATH")]
    pub path: String,
    /// HTTP method
    #[arg(short = 'X', long = "method", default_value = "GET")]
    pub method: String,
    /// Add a string field `key=value` (repeatable). On GET it becomes a
    /// query-string parameter; on other methods a JSON request body field
    #[arg(short = 'f', long = "raw-field", value_name = "KEY=VALUE")]
    pub fields: Vec<String>,
    /// Add a typed field `key=value` (true/false/null/number parsed as JSON,
    /// else string) (repeatable). On GET it becomes a query-string parameter;
    /// on other methods a JSON request body field
    #[arg(short = 'F', long = "field", value_name = "KEY=VALUE")]
    pub typed: Vec<String>,
    /// Follow pagination, concatenating each page's `values` into one array
    #[arg(long)]
    pub paginate: bool,
    /// Filter the JSON response with a jq `expression`
    #[arg(short = 'q', long, value_name = "EXPRESSION")]
    pub jq: Option<String>,
    /// Format the JSON response with a `template`
    #[arg(long, value_name = "TEMPLATE")]
    pub template: Option<String>,
}

impl ApiArgs {
    /// The output filter (jq/template) as a [`JsonFlags`], or `None` when neither
    /// is set. `bb api` has no `--json <fields>`, so the field list is empty and
    /// the filter operates on the full response.
    fn output_filter(&self) -> Option<crate::output::JsonFlags> {
        if self.jq.is_none() && self.template.is_none() {
            return None;
        }
        Some(crate::output::JsonFlags {
            json: Vec::new(),
            jq: self.jq.clone(),
            template: self.template.clone(),
        })
    }
}

/// Run `bb api`.
///
/// # Errors
/// Returns [`crate::core::AuthError`] when no credentials are stored,
/// [`FlagError`] for an unknown method / malformed `-f`/`-F` field / illegal flag
/// combination, and [`SilentError`] when the response status is `>= 400`.
pub fn run(ctx: &Context, args: ApiArgs) -> anyhow::Result<()> {
    let host = ctx.host();
    let Some(header) = crate::auth::header_for(ctx.config.as_ref(), &host) else {
        return Err(crate::core::AuthError::new(host).into());
    };
    let client = crate::api::BitbucketClient::new(ctx.transport.clone(), Some(header));

    let method = parse_method(&args.method)?;

    // `gh` maps -f/-F on a GET to query-string params (a GET has no body); on
    // any other method they form a JSON request body. We map fields→query for
    // every GET, including --paginate, so the paginate path needs no special
    // case (and the first page carries the params; Bitbucket echoes them in its
    // `next` URL).
    let (path, body) = if method == Method::Get {
        (append_query(&args.path, &args.fields, &args.typed)?, None)
    } else {
        (args.path.clone(), build_body(&args.fields, &args.typed)?)
    };

    if args.paginate {
        if method != Method::Get {
            return Err(FlagError::new("--paginate is only supported for GET requests").into());
        }
        return run_paginate(ctx, &client, &path, args.output_filter().as_ref());
    }

    let resp = client.execute_raw(method, &path, body)?;
    emit_response(ctx, &resp.body, args.output_filter().as_ref())?;

    if resp.status >= 400 {
        return Err(SilentError.into());
    }
    Ok(())
}

/// Render a response body to stdout. With a jq/template `filter`, parse the body
/// as JSON and emit through it; otherwise pretty-print JSON (or print raw text).
fn emit_response(
    ctx: &Context,
    body: &[u8],
    filter: Option<&crate::output::JsonFlags>,
) -> anyhow::Result<()> {
    if let Some(filter) = filter {
        let value: Value = serde_json::from_slice(body)
            .map_err(|e| FlagError::new(format!("response is not JSON: {e}")))?;
        return filter.emit(&ctx.io, value);
    }
    // Pretty-print the body as JSON, falling back to the raw text.
    match serde_json::from_slice::<Value>(body) {
        Ok(value) => ctx.io.println(
            &serde_json::to_string_pretty(&value)
                .unwrap_or_else(|_| String::from_utf8_lossy(body).into_owned()),
        ),
        Err(_) => ctx.io.println(&String::from_utf8_lossy(body)),
    }
    Ok(())
}

/// Follow body-based pagination: GET each page, concatenate every page's
/// `values` array, and print the combined array once.
fn run_paginate(
    ctx: &Context,
    client: &crate::api::BitbucketClient,
    path: &str,
    filter: Option<&crate::output::JsonFlags>,
) -> anyhow::Result<()> {
    let mut all: Vec<Value> = Vec::new();
    // The first request uses the (possibly relative) `path`; subsequent ones use
    // the absolute `next` URL returned by Bitbucket.
    let resp = client.execute_raw(Method::Get, path, None)?;
    let mut next = collect_page(&resp.body, &mut all)?;
    while let Some(url) = next {
        let resp = client.execute_raw(Method::Get, &url, None)?;
        next = collect_page(&resp.body, &mut all)?;
    }
    let combined = Value::Array(all);
    if let Some(filter) = filter {
        return filter.emit(&ctx.io, combined);
    }
    ctx.io
        .println(&serde_json::to_string_pretty(&combined).unwrap_or_else(|_| combined.to_string()));
    Ok(())
}

/// Parse one page: append its `values` to `all` and return the `next` URL, if
/// any. A page that is not a JSON object with a `values` array is a hard error.
fn collect_page(body: &[u8], all: &mut Vec<Value>) -> anyhow::Result<Option<String>> {
    let page: Value = serde_json::from_slice(body)
        .map_err(|e| FlagError::new(format!("--paginate: response is not JSON: {e}")))?;
    let obj = page
        .as_object()
        .ok_or_else(|| FlagError::new("--paginate: response page is not a JSON object"))?;
    if let Some(values) = obj.get("values").and_then(Value::as_array) {
        all.extend(values.iter().cloned());
    }
    Ok(obj.get("next").and_then(Value::as_str).map(str::to_owned))
}

/// Map a case-insensitive method string onto a [`Method`].
fn parse_method(raw: &str) -> Result<Method, FlagError> {
    match raw.to_ascii_uppercase().as_str() {
        "GET" => Ok(Method::Get),
        "POST" => Ok(Method::Post),
        "PUT" => Ok(Method::Put),
        "DELETE" => Ok(Method::Delete),
        "PATCH" => Ok(Method::Patch),
        other => Err(FlagError::new(format!("unknown HTTP method: {other}"))),
    }
}

/// Build a JSON-object request body from `-f` (raw string) and `-F` (typed)
/// `key=value` repeats. Returns `None` when no fields were given. On a duplicate
/// key the typed value (inserted last) wins.
fn build_body(raw: &[String], typed: &[String]) -> Result<Option<Vec<u8>>, FlagError> {
    if raw.is_empty() && typed.is_empty() {
        return Ok(None);
    }
    let mut obj = serde_json::Map::with_capacity(raw.len() + typed.len());
    for field in raw {
        let (key, value) = split_field(field)?;
        obj.insert(key.to_owned(), Value::String(value.to_owned()));
    }
    for field in typed {
        let (key, value) = split_field(field)?;
        obj.insert(key.to_owned(), parse_typed_value(value));
    }
    let bytes = serde_json::to_vec(&Value::Object(obj))
        .map_err(|e| FlagError::new(format!("failed to encode request body: {e}")))?;
    Ok(Some(bytes))
}

/// Append `-f`/`-F` fields to `path` as percent-encoded query-string params (the
/// `gh` behavior for GET). Fields are appended in order — raw `-f` first, then
/// typed `-F` — and query values are always strings (the typed-vs-string `-F`
/// distinction only matters for a JSON body). Returns `path` unchanged when no
/// fields were given. If `path` already contains a `?`, params are joined with
/// `&`, otherwise the first one starts the query with `?`.
fn append_query(path: &str, raw: &[String], typed: &[String]) -> Result<String, FlagError> {
    if raw.is_empty() && typed.is_empty() {
        return Ok(path.to_owned());
    }
    let mut out = path.to_owned();
    let mut sep = if path.contains('?') { '&' } else { '?' };
    for field in raw.iter().chain(typed.iter()) {
        let (key, value) = split_field(field)?;
        out.push(sep);
        out.push_str(&crate::render::percent_encode(key));
        out.push('=');
        out.push_str(&crate::render::percent_encode(value));
        sep = '&';
    }
    Ok(out)
}

/// Split a `KEY=VALUE` field, erroring if there is no `=`.
fn split_field(field: &str) -> Result<(&str, &str), FlagError> {
    field
        .split_once('=')
        .ok_or_else(|| FlagError::new(format!("invalid field (expected KEY=VALUE): {field}")))
}

/// Parse a `-F` value: JSON literals (`true`/`false`/`null`) and numbers become
/// the corresponding JSON value; anything else is sent as a string (the `gh -F`
/// rule). Arbitrary JSON objects/arrays are *not* parsed — pass those as raw.
fn parse_typed_value(raw: &str) -> Value {
    match raw {
        "true" => return Value::Bool(true),
        "false" => return Value::Bool(false),
        "null" => return Value::Null,
        _ => {}
    }
    if let Ok(i) = raw.parse::<i64>() {
        return Value::Number(i.into());
    }
    if let Ok(u) = raw.parse::<u64>() {
        return Value::Number(u.into());
    }
    if let Ok(f) = raw.parse::<f64>() {
        if let Some(n) = serde_json::Number::from_f64(f) {
            return Value::Number(n);
        }
    }
    Value::String(raw.to_owned())
}

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

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

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

    fn 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", "davidd").unwrap();
        cfg.set("bitbucket.org", "token", "secret").unwrap();
        Arc::new(cfg)
    }

    fn api_args(path: &str) -> ApiArgs {
        ApiArgs {
            path: path.to_owned(),
            method: "GET".to_owned(),
            fields: Vec::new(),
            typed: Vec::new(),
            paginate: false,
            jq: None,
            template: None,
        }
    }

    fn sent_body(h: &FakeTransport) -> Value {
        let reqs = h.requests.lock().unwrap();
        serde_json::from_slice(reqs[0].body.as_ref().expect("body present")).unwrap()
    }

    fn post_with(h: &Arc<FakeTransport>, raw: Vec<&str>, typed: Vec<&str>) -> ApiArgs {
        h.stub(
            "post typed",
            FakeTransport::rest(Method::Post, "/2.0/some/path"),
            FakeTransport::json(200, r#"{"ok":true}"#),
        );
        ApiArgs {
            path: "/some/path".to_owned(),
            method: "POST".to_owned(),
            fields: raw.into_iter().map(str::to_owned).collect(),
            typed: typed.into_iter().map(str::to_owned).collect(),
            paginate: false,
            jq: None,
            template: None,
        }
    }

    #[test]
    fn typed_field_parses_literals() {
        let h = Arc::new(FakeTransport::new());
        let args = post_with(
            &h,
            vec![],
            vec!["b=true", "f=false", "n=5", "z=null", "r=1.5"],
        );
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, _b) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        run(&ctx, args).unwrap();
        assert_eq!(
            sent_body(&h),
            serde_json::json!({"b": true, "f": false, "n": 5, "z": null, "r": 1.5})
        );
    }

    #[test]
    fn typed_field_non_literal_is_string() {
        let h = Arc::new(FakeTransport::new());
        let args = post_with(&h, vec![], vec!["name=foo"]);
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, _b) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        run(&ctx, args).unwrap();
        assert_eq!(sent_body(&h), serde_json::json!({"name": "foo"}));
    }

    #[test]
    fn raw_field_keeps_string_for_literal() {
        let h = Arc::new(FakeTransport::new());
        let args = post_with(&h, vec!["flag=true"], vec![]);
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, _b) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        run(&ctx, args).unwrap();
        assert_eq!(sent_body(&h), serde_json::json!({"flag": "true"}));
    }

    #[test]
    fn raw_and_typed_merge() {
        let h = Arc::new(FakeTransport::new());
        let args = post_with(&h, vec!["a=x"], vec!["b=true"]);
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, _b) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        run(&ctx, args).unwrap();
        assert_eq!(sent_body(&h), serde_json::json!({"a": "x", "b": true}));
    }

    #[test]
    fn malformed_typed_field_is_flag_error() {
        let h = Arc::new(FakeTransport::new());
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, _b) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        let args = ApiArgs {
            method: "POST".to_owned(),
            typed: vec!["novalue".to_owned()],
            ..api_args("/some/path")
        };
        let err = run(&ctx, args).unwrap_err();
        assert!(err.downcast_ref::<FlagError>().is_some(), "got: {err:?}");
        assert_eq!(h.request_count(), 0);
    }

    #[test]
    fn get_user_prints_pretty_json() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "get user",
            FakeTransport::rest(Method::Get, "/2.0/user"),
            FakeTransport::json(200, r#"{"username":"davidd","display_name":"David D"}"#),
        );
        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, api_args("/user")).unwrap();

        let out = bufs.stdout_string();
        // Pretty-printed: indented, multi-line.
        assert!(out.contains("\"username\": \"davidd\""), "out: {out}");
        assert!(out.contains("\"display_name\": \"David D\""), "out: {out}");
        assert!(
            out.contains('\n'),
            "expected pretty (multi-line) output: {out}"
        );
    }

    #[test]
    fn fields_build_json_body_and_post_method() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "post fields",
            FakeTransport::rest(Method::Post, "/2.0/some/path"),
            FakeTransport::json(200, r#"{"ok":true}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, _bufs) = test_context(transport, git(), config(), prompter, false);

        let args = ApiArgs {
            path: "/some/path".to_owned(),
            method: "POST".to_owned(),
            fields: vec!["a=b".to_owned(), "c=d".to_owned()],
            typed: Vec::new(),
            paginate: false,
            jq: None,
            template: None,
        };
        run(&ctx, args).unwrap();

        let reqs = h.requests.lock().unwrap();
        let req = &reqs[0];
        assert_eq!(req.method, Method::Post);
        let sent: Value = serde_json::from_slice(req.body.as_ref().expect("body present")).unwrap();
        assert_eq!(sent, serde_json::json!({"a": "b", "c": "d"}));
    }

    #[test]
    fn get_fields_become_query_string() {
        let h = Arc::new(FakeTransport::new());
        // Matcher requires the param in the URL: a body-encoded field (the old
        // bug) would not match and would panic instead.
        h.stub(
            "get with query",
            FakeTransport::rest(Method::Get, "/2.0/items?pagelen=1"),
            FakeTransport::json(200, r#"{"values":[]}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, _bufs) = test_context(transport, git(), config(), prompter, false);

        let args = ApiArgs {
            fields: vec!["pagelen=1".to_owned()],
            ..api_args("/items")
        };
        run(&ctx, args).unwrap();

        let reqs = h.requests.lock().unwrap();
        let req = &reqs[0];
        assert_eq!(req.method, Method::Get);
        assert!(req.url.contains("pagelen=1"), "url: {}", req.url);
        // A GET must carry no body — the fields went into the query string.
        assert!(
            req.body.is_none(),
            "GET should have no body: {:?}",
            req.body
        );
    }

    #[test]
    fn http_404_prints_body_and_returns_silent_error() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "404",
            FakeTransport::rest(Method::Get, "/2.0/missing"),
            FakeTransport::json(404, r#"{"type":"error","error":{"message":"not found"}}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, git(), config(), prompter, false);

        let err = run(&ctx, api_args("/missing")).unwrap_err();
        assert!(
            err.downcast_ref::<SilentError>().is_some(),
            "expected SilentError, got: {err:?}"
        );
        // The body is still shown despite the error.
        let out = bufs.stdout_string();
        assert!(out.contains("not found"), "out: {out}");
    }

    #[test]
    fn paginate_concatenates_values_across_pages() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "page 1",
            FakeTransport::rest(Method::Get, "/2.0/items"),
            FakeTransport::json(
                200,
                r#"{"values":[{"id":1},{"id":2}],"next":"https://api.bitbucket.org/2.0/items?page=2"}"#,
            ),
        );
        h.stub(
            "page 2",
            FakeTransport::rest(Method::Get, "items?page=2"),
            FakeTransport::json(200, r#"{"values":[{"id":3}]}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, bufs) = test_context(transport, git(), config(), prompter, false);

        let args = ApiArgs {
            paginate: true,
            ..api_args("/items")
        };
        run(&ctx, args).unwrap();

        let out = bufs.stdout_string();
        let parsed: Value = serde_json::from_str(&out).unwrap();
        let ids: Vec<u64> = parsed
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v["id"].as_u64().unwrap())
            .collect();
        assert_eq!(ids, vec![1, 2, 3]);
        assert_eq!(h.request_count(), 2);
    }

    #[test]
    fn invalid_field_without_equals_is_flag_error() {
        let h = Arc::new(FakeTransport::new());
        // No stub registered: a malformed field must error before any request.
        let transport: Arc<dyn Transport> = h.clone();
        let prompter = Arc::new(ScriptedPrompter::new());
        let (ctx, _bufs) = test_context(transport, git(), config(), prompter, false);

        let args = ApiArgs {
            path: "/some/path".to_owned(),
            method: "POST".to_owned(),
            fields: vec!["novalue".to_owned()],
            typed: Vec::new(),
            paginate: false,
            jq: None,
            template: None,
        };
        let err = run(&ctx, args).unwrap_err();
        assert!(
            err.downcast_ref::<FlagError>().is_some(),
            "expected FlagError, got: {err:?}"
        );
        assert_eq!(h.request_count(), 0);
    }

    #[test]
    fn not_authenticated_returns_auth_error() {
        let h = Arc::new(FakeTransport::new());
        // No stub: AuthError must fire before any request.
        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, git(), cfg, prompter, false);

        let err = run(&ctx, api_args("/user")).unwrap_err();
        assert!(
            err.downcast_ref::<AuthError>().is_some(),
            "expected AuthError, got: {err:?}"
        );
        assert_eq!(h.request_count(), 0);
    }

    #[test]
    fn unknown_method_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, git(), config(), prompter, false);

        let args = ApiArgs {
            method: "FETCH".to_owned(),
            ..api_args("/user")
        };
        let err = run(&ctx, args).unwrap_err();
        assert!(
            err.downcast_ref::<FlagError>().is_some(),
            "expected FlagError, got: {err:?}"
        );
        assert_eq!(h.request_count(), 0);
    }

    #[test]
    fn api_jq_filters_response() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "jq",
            FakeTransport::rest(Method::Get, "/2.0/user"),
            FakeTransport::json(200, r#"{"username":"davidd","display_name":"David D"}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, bufs) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        let args = ApiArgs {
            jq: Some(".username".to_owned()),
            ..api_args("/user")
        };
        run(&ctx, args).unwrap();
        assert_eq!(bufs.stdout_string(), "\"davidd\"\n");
    }

    #[test]
    fn api_template_renders_response() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "tmpl",
            FakeTransport::rest(Method::Get, "/2.0/user"),
            FakeTransport::json(200, r#"{"username":"davidd"}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, bufs) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        let args = ApiArgs {
            template: Some("{username}".to_owned()),
            ..api_args("/user")
        };
        run(&ctx, args).unwrap();
        assert_eq!(bufs.stdout_string().trim_end(), "davidd");
    }

    #[test]
    fn api_jq_on_paginate() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "page 1",
            FakeTransport::rest(Method::Get, "/2.0/items"),
            FakeTransport::json(
                200,
                r#"{"values":[{"id":1},{"id":2}],"next":"https://api.bitbucket.org/2.0/items?page=2"}"#,
            ),
        );
        h.stub(
            "page 2",
            FakeTransport::rest(Method::Get, "items?page=2"),
            FakeTransport::json(200, r#"{"values":[{"id":3}]}"#),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, bufs) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        let args = ApiArgs {
            paginate: true,
            jq: Some(".[].id".to_owned()),
            ..api_args("/items")
        };
        run(&ctx, args).unwrap();
        assert_eq!(bufs.stdout_string(), "1\n2\n3\n");
    }

    #[test]
    fn api_jq_non_json_body_is_flag_error() {
        let h = Arc::new(FakeTransport::new());
        h.stub(
            "non json",
            FakeTransport::rest(Method::Get, "/2.0/raw"),
            FakeTransport::json(200, "this is not json"),
        );
        let transport: Arc<dyn Transport> = h.clone();
        let (ctx, _b) = test_context(
            transport,
            git(),
            config(),
            Arc::new(ScriptedPrompter::new()),
            false,
        );
        let args = ApiArgs {
            jq: Some(".".to_owned()),
            ..api_args("/raw")
        };
        let err = run(&ctx, args).unwrap_err();
        assert!(err.downcast_ref::<FlagError>().is_some(), "got: {err:?}");
    }
}