gitbucket-cli 0.9.0

A command-line tool for GitBucket, inspired by GitHub CLI
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
mod support;

use serde_json::{json, Value};
use support::{
    gb_cmd::{assert_failure, assert_success, with_stdin, GbTestEnv},
    git_repo::*,
    mock_http::{spawn_scripted_server, ScriptedResponse},
};

fn response(method: &str, path: &str, body: Value) -> ScriptedResponse {
    ScriptedResponse::json(
        &format!("{method} /api/v3/{path} HTTP/1.1"),
        "200 OK",
        &body.to_string(),
    )
}

#[test]
fn explicit_body_sources_conflict_before_any_io() {
    for args in [
        vec!["issue", "create"],
        vec!["issue", "edit", "1"],
        vec!["issue", "comment", "1"],
        vec!["pr", "create"],
        vec!["pr", "edit", "1"],
        vec!["pr", "comment", "1"],
        vec![
            "pr", "comment", "edit", "1", "--kind", "inline", "--id", "2", "--web",
        ],
    ] {
        let output = GbTestEnv::new()
            .command()
            .args(args)
            .args(["--body", "a", "--body-file", "nonexistent"])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(2));
    }
}

#[test]
fn create_preserves_file_and_stdin_markdown_and_optional_body_omission() {
    for kind in ["issue", "pr"] {
        for mode in ["file", "stdin", "omitted", "empty"] {
            let env = GbTestEnv::new();
            let text = "# 日本語 👩‍💻\r\n\n  indented\n\tcode\n\x1b[2J\n";
            let file = env.path().join("body.md");
            std::fs::write(&file, if mode == "empty" { "" } else { text }).unwrap();
            let path = if kind == "pr" { "pulls" } else { "issues" };
            let (port, server) = spawn_scripted_server(vec![response(
                "POST",
                &format!("repos/alice/project/{path}"),
                json!({"number":1,"title":"title","state":"open"}),
            )]);
            let mut command = env.repo_api_command(format!("127.0.0.1:{port}"), "alice/project");
            command.args([kind, "create", "--title", "title"]);
            if kind == "pr" {
                command.args(["--head", "topic", "--base", "main"]);
            }
            if mode == "file" || mode == "empty" {
                command.arg("--body-file").arg(&file);
            }
            if mode == "stdin" {
                command.args(["--body-file", "-"]);
            }
            let output = if mode == "stdin" {
                with_stdin(&mut command, text.as_bytes())
            } else {
                command.output().unwrap()
            };
            assert_success(&output);
            let requests = server.join().unwrap();
            let body: Value = serde_json::from_str(&requests[0].body).unwrap();
            match mode {
                "omitted" => assert!(body.get("body").is_none()),
                "empty" => assert_eq!(body["body"], ""),
                _ => assert_eq!(body["body"], text),
            }
        }
    }
}

#[test]
fn edits_clear_body_from_an_empty_file_and_preserve_multiline_stdin() {
    for kind in ["issue", "pr"] {
        for text in ["", "\n## heading\r\n\ntext  \n"] {
            let env = GbTestEnv::new();
            let file = env.path().join("empty.md");
            std::fs::write(&file, "").unwrap();
            let path = format!(
                "repos/alice/project/{}/1",
                if kind == "pr" { "pulls" } else { "issues" }
            );
            let before = json!({"number":1,"title":"old","state":"open","body":"before"});
            let after = json!({"number":1,"title":"old","state":"open","body":text});
            let mut responses = vec![
                response("GET", &path, before),
                response("PATCH", &path, after.clone()),
            ];
            if kind == "issue" {
                responses.push(response("GET", &path, after));
            }
            let (port, server) = spawn_scripted_server(responses);
            let mut command = env.repo_api_command(format!("127.0.0.1:{port}"), "alice/project");
            command.args([kind, "edit", "1", "--body-file"]);
            let output = if text.is_empty() {
                command.arg(file).output().unwrap()
            } else {
                with_stdin(command.arg("-"), text.as_bytes())
            };
            assert_success(&output);
            let requests = server.join().unwrap();
            let body: Value = serde_json::from_str(&requests[1].body).unwrap();
            assert_eq!(body["body"], text);
        }
    }
}

#[test]
fn discussion_comments_preserve_multiline_stdin() {
    for kind in ["issue", "pr"] {
        let env = GbTestEnv::new();
        let text = "\n日本語\r\n\n```rust\nlet x = 1;\n```\n";
        let mut responses = Vec::new();
        if kind == "pr" {
            responses.push(response(
                "GET",
                "repos/alice/project/pulls/1",
                json!({"number":1,"title":"title","state":"open"}),
            ));
        }
        responses.push(response(
            "POST",
            "repos/alice/project/issues/1/comments",
            json!({"id":2,"body":text}),
        ));
        let (port, server) = spawn_scripted_server(responses);
        let output = with_stdin(
            env.repo_api_command(format!("127.0.0.1:{port}"), "alice/project")
                .args([kind, "comment", "1", "--body-file", "-"]),
            text.as_bytes(),
        );
        assert_success(&output);
        let requests = server.join().unwrap();
        assert_eq!(
            serde_json::from_str::<Value>(&requests.last().unwrap().body).unwrap()["body"],
            text
        );
    }
}

#[test]
fn noninteractive_missing_input_blank_comments_and_bad_utf8_fail_before_mutation() {
    for args in [
        vec!["issue", "create"],
        vec!["pr", "create", "--head", "topic", "--base", "main"],
        vec!["issue", "comment", "1"],
        vec!["pr", "comment", "1"],
    ] {
        let env = GbTestEnv::new();
        let output = env
            .repo_api_command("127.0.0.1:1", "alice/project")
            .arg("--json-errors")
            .args(args)
            .output()
            .unwrap();
        assert_failure(&output);
        let error: Value = serde_json::from_slice(&output.stderr).unwrap();
        assert_eq!(error["error"]["code"], "input_required");
    }
    for kind in ["issue", "pr"] {
        let env = GbTestEnv::new();
        let output = with_stdin(
            env.repo_api_command("127.0.0.1:1", "alice/project").args([
                kind,
                "comment",
                "1",
                "--body-file",
                "-",
            ]),
            b" \n\t",
        );
        assert_failure(&output);
        assert!(String::from_utf8_lossy(&output.stderr).contains("must not be blank"));
        let output = with_stdin(
            env.repo_api_command("127.0.0.1:1", "alice/project").args([
                kind,
                "create",
                "--title",
                "x",
                "--body-file",
                "-",
            ]),
            &[0xff],
        );
        assert_failure(&output);
        assert!(!String::from_utf8_lossy(&output.stderr).contains("HTTP"));
    }
}

#[test]
fn token_stdin_verifies_and_stores_without_echoing_the_secret() {
    let env = GbTestEnv::new();
    let (port, server) =
        spawn_scripted_server(vec![response("GET", "user", json!({"login":"alice"}))]);
    let output = with_stdin(
        env.command().args([
            "auth",
            "login",
            "--hostname",
            &format!("127.0.0.1:{port}"),
            "--protocol",
            "http",
            "--with-token",
        ]),
        b"stdin-secret\r\n",
    );
    assert_success(&output);
    assert!(!String::from_utf8_lossy(&output.stdout).contains("stdin-secret"));
    assert!(!String::from_utf8_lossy(&output.stderr).contains("stdin-secret"));
    assert_eq!(
        server.join().unwrap()[0].headers["authorization"],
        "token stdin-secret"
    );
    assert!(std::fs::read_to_string(env.path().join("config.toml"))
        .unwrap()
        .contains("stdin-secret"));
    let (port, server) = spawn_scripted_server(vec![ScriptedResponse::json(
        "GET /api/v3/user HTTP/1.1",
        "401 Unauthorized",
        r#"{"message":"rejected stdin-secret"}"#,
    )]);
    let output = with_stdin(
        env.command().args([
            "--json-errors",
            "auth",
            "login",
            "--hostname",
            &format!("127.0.0.1:{port}"),
            "--protocol",
            "http",
            "--with-token",
        ]),
        b"stdin-secret",
    );
    assert_failure(&output);
    let error: Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(!error.to_string().contains("stdin-secret"));
    server.join().unwrap();
    for input in [
        b"".as_slice(),
        b"secret\nsecond",
        b"secret\0",
        b"secret\t",
        &[0xff],
    ] {
        let output = with_stdin(
            env.command().args([
                "--json-errors",
                "auth",
                "login",
                "--hostname",
                "127.0.0.1:1",
                "--with-token",
            ]),
            input,
        );
        assert_failure(&output);
        let error: Value = serde_json::from_slice(&output.stderr).unwrap();
        assert!(!error.to_string().contains("secret"));
    }
    let output = env
        .command()
        .args(["auth", "login", "--token", "old"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn login_tokens_are_redacted_from_error_context_for_stdin() {
    let secret = "private-login-value";
    for status in ["401 Unauthorized", "404 Not Found"] {
        for json_errors in [true, false] {
            let env = GbTestEnv::new();
            // The transport already redacts its request context. The
            // login command adds the configured URL to the final error.
            let (port, server) = spawn_scripted_server(vec![ScriptedResponse::json(
                &format!("GET /{secret}/api/v3/user HTTP/1.1"),
                status,
                r#"{"message":"rejected"}"#,
            )]);
            let host = format!("http://127.0.0.1:{port}/{secret}");
            let mut command = env.command();
            command
                .env_remove("GB_JSON_ERRORS")
                .args(["auth", "login", "--hostname", &host]);
            if json_errors {
                command.arg("--json-errors");
            }
            let output = with_stdin(command.arg("--with-token"), secret.as_bytes());
            assert_failure(&output);
            assert_eq!(server.join().unwrap().len(), 1);
            assert!(
                !String::from_utf8_lossy(&output.stderr).contains(secret),
                "json={json_errors}: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert!(!String::from_utf8_lossy(&output.stdout).contains(secret));
            if json_errors {
                let error: Value = serde_json::from_slice(&output.stderr).unwrap();
                assert_eq!(error["error"]["code"], "auth_error");
                assert_eq!(error["error"]["exit_code"], 1);
            }
            assert!(!env.path().join("config.toml").exists());
        }
    }
}

#[test]
fn edited_issue_titles_remain_one_status_line_without_changing_the_payload() {
    let env = GbTestEnv::new();
    let title = "title\nforged\tfield\r\x1b[2J";
    let before = json!({"number":1,"title":"before","state":"open"});
    let after = json!({"number":1,"title":title,"state":"open"});
    let path = "repos/alice/project/issues/1";
    let (port, server) = spawn_scripted_server(vec![
        response("GET", path, before),
        response("PATCH", path, after.clone()),
        response("GET", path, after),
    ]);
    let output = env
        .repo_api_command(format!("127.0.0.1:{port}"), "alice/project")
        .args(["issue", "edit", "1", "--title", title])
        .output()
        .unwrap();
    assert_success(&output);
    let requests = server.join().unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&requests[1].body).unwrap()["title"],
        title
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.lines().count(), 1, "{text:?}");
    assert!(text.contains("title\\nforged\\tfield\\r"));
    assert!(!text.contains(['\r', '\t', '\x1b']));
}

#[test]
fn milestone_view_create_edit_and_noop_titles_cannot_inject_lines() {
    for action in ["view", "create", "edit", "noop"] {
        let env = GbTestEnv::new();
        let title = "title\nforged\tfield\r\x1b[2J";
        let body = "first\n\tcode\n";
        let item = json!({"number":1,"title":title,"state":"open","description":body});
        let path = "repos/alice/project/milestones/1";
        let frames = match action {
            "create" => vec![response("POST", "repos/alice/project/milestones", item)],
            "edit" => vec![
                response("GET", path, item.clone()),
                response("PATCH", path, item),
            ],
            _ => vec![response("GET", path, item)],
        };
        let (port, server) = spawn_scripted_server(frames);
        let mut command = env.repo_api_command(format!("127.0.0.1:{port}"), "alice/project");
        command.args(["milestone", if action == "noop" { "edit" } else { action }]);
        if action == "create" {
            command.arg(title);
        } else {
            command.arg("1");
        }
        if action == "edit" {
            command.args(["--description", body]);
        } else if action == "noop" {
            command.args(["--state", "open"]);
        }
        let output = command.output().unwrap();
        assert_success(&output);
        let requests = server.join().unwrap();
        let text = String::from_utf8(output.stdout).unwrap();
        assert!(
            text.lines()
                .next()
                .unwrap()
                .contains("title\\nforged\\tfield\\r"),
            "{action}: {text:?}"
        );
        assert!(!text.contains(['\r', '\x1b']));
        if action == "view" {
            assert!(text.contains(body));
        } else {
            assert_eq!(text.lines().count(), 1);
            assert!(!text.contains('\t'));
        }
        if matches!(action, "create" | "edit") {
            let request = requests
                .iter()
                .find(|request| matches!(request.method.as_str(), "POST" | "PATCH"))
                .unwrap();
            assert_eq!(
                serde_json::from_str::<Value>(&request.body).unwrap()["title"],
                title
            );
        }
    }
}

#[test]
fn default_base_uses_server_metadata_and_never_guesses_main() {
    for base in [Some("master"), Some("develop"), None] {
        let env = GbTestEnv::new();
        let mut responses = vec![response(
            "GET",
            "repos/alice/project",
            json!({"name":"project","full_name":"alice/project","default_branch":base}),
        )];
        if base.is_some() {
            responses.push(response(
                "POST",
                "repos/alice/project/pulls",
                json!({"number":1,"title":"title","state":"open"}),
            ));
        }
        let (port, server) = spawn_scripted_server(responses);
        let output = env
            .repo_api_command(format!("127.0.0.1:{port}"), "alice/project")
            .args(["pr", "create", "--head", "topic", "--title", "title"])
            .output()
            .unwrap();
        let requests = server.join().unwrap();
        if let Some(base) = base {
            assert_success(&output);
            assert_eq!(
                serde_json::from_str::<Value>(&requests[1].body).unwrap()["base"],
                base
            );
        } else {
            assert_failure(&output);
            assert!(String::from_utf8_lossy(&output.stderr).contains("--base"));
        }
    }
}

#[test]
fn inferred_head_checks_live_ref_and_never_pushes_or_updates_tracking_refs() {
    for mode in [
        "published",
        "dirty",
        "ahead",
        "behind",
        "diverged",
        "missing",
    ] {
        let env = GbTestEnv::new();
        let local = env.path().join("local");
        let remote = env.path().join("remote.git");
        init_bare_repo(&remote);
        init_work_repo(&local);
        commit_readme(&local, "one\n", "one");
        run_git(&local, &["branch", "-M", "topic"]);
        run_git(
            &local,
            &["remote", "add", "origin", remote.to_str().unwrap()],
        );
        if mode != "missing" {
            run_git(&local, &["push", "-u", "origin", "topic"]);
        }
        if mode == "dirty" {
            std::fs::write(local.join("README.md"), "dirty\n").unwrap();
        }
        if matches!(mode, "ahead" | "behind" | "diverged") {
            let original = git_output(&local, &["rev-parse", "HEAD"]);
            commit_tracked_readme(&local, "two\n", "two");
            if mode != "ahead" {
                run_git(&local, &["push", "origin", "topic"]);
                // Preserve the local files, while moving only this disposable fixture's branch.
                run_git(&local, &["checkout", "-B", "topic", &original]);
                if mode == "diverged" {
                    commit_tracked_readme(&local, "three\n", "three");
                }
            }
        }
        let refs_before = git_output(&local, &["show-ref"]);
        let index_before = std::fs::read(local.join(".git/index")).unwrap();
        let published_before = git_output(&local, &["ls-remote", "origin"]);
        let succeeds = matches!(mode, "published" | "dirty");
        let mut responses = vec![response(
            "GET",
            "repos/alice/project",
            json!({"name":"project","full_name":"alice/project","default_branch":"develop","clone_url":remote.to_str().unwrap()}),
        )];
        if succeeds {
            responses.push(response(
                "POST",
                "repos/alice/project/pulls",
                json!({"number":1,"title":"title","state":"open"}),
            ));
        }
        let (port, server) = spawn_scripted_server(responses);
        let output = env
            .repo_api_command(format!("127.0.0.1:{port}"), "alice/project")
            .current_dir(&local)
            .args(["pr", "create", "--title", "title"])
            .output()
            .unwrap();
        if succeeds {
            assert_success(&output);
        } else {
            assert_failure(&output);
            assert!(String::from_utf8_lossy(&output.stderr).contains("No PR was created"));
        }
        if mode == "dirty" {
            assert!(String::from_utf8_lossy(&output.stderr).contains("Uncommitted changes"));
        }
        server.join().unwrap();
        assert_eq!(git_output(&local, &["show-ref"]), refs_before);
        assert_eq!(
            std::fs::read(local.join(".git/index")).unwrap(),
            index_before
        );
        assert_eq!(
            git_output(&local, &["ls-remote", "origin"]),
            published_before
        );
    }
}

#[test]
fn human_tables_views_and_success_lines_escape_controls_while_json_preserves_originals() {
    let title = "日本e\u{301}👩‍💻\n\x1b[2J\rspoof";
    let body = "first\n\tcode\r\x1b]8;;https://example.test\x07\u{202e}last\n";
    let item = json!({"number":1,"title":title,"body":body,"state":"open"});
    for (args, path, payload, is_json, list) in [
        (
            vec!["issue", "list"],
            "issues?state=open",
            json!([item]),
            false,
            true,
        ),
        (
            vec!["issue", "view", "1"],
            "issues/1",
            item.clone(),
            false,
            false,
        ),
        (
            vec!["issue", "view", "1", "--json"],
            "issues/1",
            item.clone(),
            true,
            false,
        ),
        (
            vec!["pr", "view", "1"],
            "pulls/1",
            item.clone(),
            false,
            false,
        ),
        (
            vec!["pr", "view", "1", "--json"],
            "pulls/1",
            item.clone(),
            true,
            false,
        ),
    ] {
        let env = GbTestEnv::new();
        let (port, server) = spawn_scripted_server(vec![response(
            "GET",
            &format!("repos/alice/project/{path}"),
            payload,
        )]);
        let output = env
            .repo_api_command(format!("127.0.0.1:{port}"), "alice/project")
            .args(args)
            .output()
            .unwrap();
        assert_success(&output);
        server.join().unwrap();
        if is_json {
            assert_eq!(
                serde_json::from_slice::<Value>(&output.stdout).unwrap(),
                item
            );
        } else {
            let out = String::from_utf8_lossy(&output.stdout);
            assert!(!out.contains(['\x1b', '\r', '\u{202e}']));
            if list {
                assert_eq!(out.lines().count(), 2);
            } else {
                assert!(out.lines().next().unwrap().contains("\\n"));
                assert!(out.contains("first\n\tcode\\r"));
            }
        }
    }
    let env = GbTestEnv::new();
    let (port, server) =
        spawn_scripted_server(vec![response("POST", "repos/alice/project/issues", item)]);
    let output = env
        .repo_api_command(format!("127.0.0.1:{port}"), "alice/project")
        .args(["issue", "create", "--title", "title"])
        .output()
        .unwrap();
    assert_success(&output);
    let out = String::from_utf8_lossy(&output.stdout);
    assert_eq!(out.lines().count(), 1);
    assert!(!out.contains(['\x1b', '\r']));
    server.join().unwrap();
}