tldr-cli 0.1.5

CLI binary for TLDR code analysis tool
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
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
//! End-to-end integration tests for `bugbot check`
//!
//! Each test creates a real git repository in a temp directory, makes specific
//! changes (signature regressions, born-dead functions, etc.), runs the binary,
//! and verifies the JSON/text output and exit codes.

use std::path::{Path, PathBuf};
use std::process::Command;

// ---------------------------------------------------------------------------
// Test harness helpers
// ---------------------------------------------------------------------------

/// Get a `Command` pointing at the built `tldr` binary.
fn tldr_bin() -> Command {
    Command::new(env!("CARGO_BIN_EXE_tldr"))
}

/// Create a test git repo with an initial commit so HEAD exists.
fn create_test_repo() -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().to_path_buf();

    Command::new("git")
        .args(["init"])
        .current_dir(&path)
        .output()
        .unwrap();
    Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(&path)
        .output()
        .unwrap();
    Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(&path)
        .output()
        .unwrap();

    // Initial commit so HEAD exists
    std::fs::write(path.join("init.rs"), "fn _init() {}\n").unwrap();
    Command::new("git")
        .args(["add", "."])
        .current_dir(&path)
        .output()
        .unwrap();
    Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&path)
        .output()
        .unwrap();

    (dir, path)
}

/// Write a file into the repo directory.
fn write_file(dir: &Path, name: &str, content: &str) {
    std::fs::write(dir.join(name), content).unwrap();
}

/// Stage all files and commit with the given message.
fn git_add_commit(dir: &Path, message: &str) {
    Command::new("git")
        .args(["add", "."])
        .current_dir(dir)
        .output()
        .unwrap();
    Command::new("git")
        .args(["commit", "-m", message])
        .current_dir(dir)
        .output()
        .unwrap();
}

/// Run `tldr --lang rust --format json bugbot check <path> [extra_args...]`
fn run_bugbot_check(path: &Path, extra_args: &[&str]) -> std::process::Output {
    tldr_bin()
        .args(["--lang", "rust", "--format", "json", "bugbot", "check"])
        .arg(path)
        .args(extra_args)
        .output()
        .expect("bugbot check failed to run")
}

/// Run `tldr --lang rust --format text bugbot check <path> [extra_args...]`
fn run_bugbot_check_text(path: &Path, extra_args: &[&str]) -> std::process::Output {
    tldr_bin()
        .args(["--lang", "rust", "--format", "text", "bugbot", "check"])
        .arg(path)
        .args(extra_args)
        .output()
        .expect("bugbot check (text) failed to run")
}

/// Parse stdout as JSON, panicking with a helpful message on failure.
fn parse_json(output: &std::process::Output) -> serde_json::Value {
    serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "Failed to parse JSON: {}\nstdout: {}\nstderr: {}",
            e,
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Commit a 2-param function, then remove one param.
/// Expect a signature-regression finding with severity "high".
#[test]
fn test_e2e_signature_regression() {
    let (_dir, path) = create_test_repo();

    // Commit a function with two parameters
    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32, y: i32) -> i32 {\n    x + y\n}\n",
    );
    git_add_commit(&path, "add compute");

    // Remove parameter y (signature regression)
    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32) -> i32 {\n    x * 2\n}\n",
    );

    let output = run_bugbot_check(&path, &["--no-fail"]);
    assert!(
        output.status.success(),
        "bugbot check should exit 0 with --no-fail, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");

    let sig_findings: Vec<&serde_json::Value> = findings
        .iter()
        .filter(|f| f["finding_type"] == "signature-regression")
        .collect();

    assert!(
        !sig_findings.is_empty(),
        "expected at least 1 signature-regression finding, got 0.\nfull output: {}",
        serde_json::to_string_pretty(&json).unwrap()
    );

    let first = &sig_findings[0];
    assert_eq!(
        first["severity"], "high",
        "signature-regression should be severity high"
    );
    assert!(
        first["function"]
            .as_str()
            .unwrap_or("")
            .contains("compute"),
        "finding function should contain 'compute', got: {}",
        first["function"]
    );
}

/// Add a new function that is never called anywhere.
/// Expect a born-dead finding.
#[test]
fn test_e2e_born_dead() {
    let (_dir, path) = create_test_repo();

    // Commit a simple program
    write_file(
        &path,
        "lib.rs",
        "fn main() {\n    helper();\n}\n\nfn helper() -> i32 {\n    42\n}\n",
    );
    git_add_commit(&path, "add main and helper");

    // Add a new function that is never called
    write_file(
        &path,
        "lib.rs",
        "fn main() {\n    helper();\n}\n\nfn helper() -> i32 {\n    42\n}\n\nfn unused_func() -> bool {\n    true\n}\n",
    );

    let output = run_bugbot_check(&path, &["--no-fail"]);
    assert!(
        output.status.success(),
        "bugbot check should exit 0 with --no-fail, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");

    let dead_findings: Vec<&serde_json::Value> = findings
        .iter()
        .filter(|f| f["finding_type"] == "born-dead")
        .collect();

    assert!(
        !dead_findings.is_empty(),
        "expected at least 1 born-dead finding, got 0.\nfull output: {}",
        serde_json::to_string_pretty(&json).unwrap()
    );

    assert!(
        dead_findings[0]["function"]
            .as_str()
            .unwrap_or("")
            .contains("unused_func"),
        "born-dead finding should reference 'unused_func', got: {}",
        dead_findings[0]["function"]
    );
}

/// No uncommitted changes => empty findings, "no_changes_detected" note.
#[test]
fn test_e2e_no_changes() {
    let (_dir, path) = create_test_repo();

    // Commit some real code, then make NO further changes
    write_file(
        &path,
        "lib.rs",
        "pub fn stable(x: i32) -> i32 {\n    x\n}\n",
    );
    git_add_commit(&path, "add stable function");

    let output = run_bugbot_check(&path, &[]);
    assert!(
        output.status.success(),
        "bugbot check with no changes should exit 0, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");
    assert!(
        findings.is_empty(),
        "expected 0 findings when no changes, got {}",
        findings.len()
    );

    let notes = json["notes"].as_array().expect("notes should be array");
    assert!(
        notes.iter().any(|n| n == "no_changes_detected"),
        "notes should contain 'no_changes_detected', got: {:?}",
        notes
    );
}

/// Add a brand new file with functions. Should not crash and should report it
/// in changed_files. The file must be staged for git to detect it as a change.
#[test]
fn test_e2e_new_file() {
    let (_dir, path) = create_test_repo();

    // Commit initial state
    write_file(&path, "lib.rs", "fn existing() {}\n");
    git_add_commit(&path, "initial code");

    // Add a brand new file and stage it (git diff --staged will see it)
    write_file(
        &path,
        "extra.rs",
        "pub fn new_helper() -> u32 {\n    99\n}\n\nfn another() -> bool {\n    false\n}\n",
    );
    Command::new("git")
        .args(["add", "extra.rs"])
        .current_dir(&path)
        .output()
        .unwrap();

    let output = run_bugbot_check(&path, &["--no-fail", "--staged"]);
    assert!(
        output.status.success(),
        "bugbot check should not crash on new files, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);

    // Verify changed_files contains the new file
    let changed_files = json["changed_files"]
        .as_array()
        .expect("changed_files should be array");
    let has_extra = changed_files
        .iter()
        .any(|f| f.as_str().unwrap_or("").contains("extra.rs"));
    assert!(
        has_extra,
        "changed_files should contain extra.rs, got: {:?}",
        changed_files
    );
}

/// When findings exist and --no-fail is NOT set, exit code should be non-zero.
#[test]
fn test_e2e_exit_code_with_findings() {
    let (_dir, path) = create_test_repo();

    // Commit a function, then break its signature
    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32, y: i32) -> i32 {\n    x + y\n}\n",
    );
    git_add_commit(&path, "add compute");

    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32) -> i32 {\n    x * 2\n}\n",
    );

    // Run WITHOUT --no-fail
    let output = run_bugbot_check(&path, &[]);
    assert!(
        !output.status.success(),
        "bugbot check should exit non-zero when findings exist (without --no-fail)"
    );
}

/// When findings exist but --no-fail is set, exit code should be 0 and findings
/// should still be present.
#[test]
fn test_e2e_no_fail_flag() {
    let (_dir, path) = create_test_repo();

    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32, y: i32) -> i32 {\n    x + y\n}\n",
    );
    git_add_commit(&path, "add compute");

    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32) -> i32 {\n    x * 2\n}\n",
    );

    let output = run_bugbot_check(&path, &["--no-fail"]);
    assert!(
        output.status.success(),
        "bugbot check with --no-fail should exit 0, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");
    assert!(
        !findings.is_empty(),
        "findings should still be present with --no-fail"
    );
}

/// Verify that the JSON output has ALL required top-level fields.
#[test]
fn test_e2e_json_schema() {
    let (_dir, path) = create_test_repo();

    // Make a simple change so there is something to analyze
    write_file(
        &path,
        "lib.rs",
        "pub fn foo(x: i32) -> i32 {\n    x + 1\n}\n",
    );
    git_add_commit(&path, "add foo");

    write_file(
        &path,
        "lib.rs",
        "pub fn foo(x: i32) -> i32 {\n    x + 2\n}\n",
    );

    let output = run_bugbot_check(&path, &["--no-fail"]);
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);

    // All required top-level fields
    let required_fields = [
        "tool",
        "mode",
        "language",
        "base_ref",
        "detection_method",
        "timestamp",
        "changed_files",
        "findings",
        "summary",
        "elapsed_ms",
        "errors",
        "notes",
    ];

    for field in &required_fields {
        assert!(
            !json[field].is_null(),
            "required field '{}' is missing from output JSON.\nFull output: {}",
            field,
            serde_json::to_string_pretty(&json).unwrap()
        );
    }

    // Type checks
    assert_eq!(json["tool"], "bugbot");
    assert_eq!(json["mode"], "check");
    assert!(json["language"].is_string());
    assert!(json["base_ref"].is_string());
    assert!(json["detection_method"].is_string());
    assert!(json["timestamp"].is_string());
    assert!(json["changed_files"].is_array());
    assert!(json["findings"].is_array());
    assert!(json["summary"].is_object());
    assert!(json["elapsed_ms"].is_number());
    assert!(json["errors"].is_array());
    assert!(json["notes"].is_array());

    // Summary sub-fields
    let summary = &json["summary"];
    assert!(summary["total_findings"].is_number());
    assert!(summary["by_severity"].is_object());
    assert!(summary["by_type"].is_object());
    assert!(summary["files_analyzed"].is_number());
    assert!(summary["functions_analyzed"].is_number());
}

/// Create many functions with signature changes, then limit with --max-findings.
#[test]
fn test_e2e_max_findings() {
    let (_dir, path) = create_test_repo();

    // Commit many functions with 2 params each
    let mut original = String::new();
    for i in 0..10 {
        original.push_str(&format!(
            "pub fn func_{i}(a: i32, b: i32) -> i32 {{\n    a + b + {i}\n}}\n\n"
        ));
    }
    write_file(&path, "lib.rs", &original);
    git_add_commit(&path, "add many functions");

    // Change all signatures (remove param b)
    let mut modified = String::new();
    for i in 0..10 {
        modified.push_str(&format!(
            "pub fn func_{i}(a: i32) -> i32 {{\n    a + {i}\n}}\n\n"
        ));
    }
    write_file(&path, "lib.rs", &modified);

    let output = run_bugbot_check(&path, &["--no-fail", "--max-findings", "2"]);
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");

    assert!(
        findings.len() <= 2,
        "expected at most 2 findings with --max-findings 2, got {}",
        findings.len()
    );
}

/// Changing only the function body (not the signature) should NOT produce a
/// signature-regression finding.
#[test]
fn test_e2e_body_only_change_no_regression() {
    let (_dir, path) = create_test_repo();

    write_file(
        &path,
        "lib.rs",
        "fn foo(x: i32) -> bool {\n    x > 0\n}\n",
    );
    git_add_commit(&path, "add foo");

    // Only change the body, keep signature identical
    write_file(
        &path,
        "lib.rs",
        "fn foo(x: i32) -> bool {\n    x > 1\n}\n",
    );

    let output = run_bugbot_check(&path, &["--no-fail"]);
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");

    let sig_regression_findings: Vec<&serde_json::Value> = findings
        .iter()
        .filter(|f| f["finding_type"] == "signature-regression")
        .collect();

    assert!(
        sig_regression_findings.is_empty(),
        "body-only change should produce 0 signature-regression findings, got {}.\nfindings: {}",
        sig_regression_findings.len(),
        serde_json::to_string_pretty(findings).unwrap()
    );
}

/// With --format text, output should be human-readable text, not JSON.
#[test]
fn test_e2e_text_format() {
    let (_dir, path) = create_test_repo();

    write_file(&path, "lib.rs", "fn bar() -> i32 {\n    1\n}\n");
    git_add_commit(&path, "add bar");

    // Make a body-only change (just to have something to analyze)
    write_file(&path, "lib.rs", "fn bar() -> i32 {\n    2\n}\n");

    let output = run_bugbot_check_text(&path, &["--no-fail"]);
    assert!(
        output.status.success(),
        "text format should exit 0, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should contain the summary line
    assert!(
        stdout.contains("bugbot check --"),
        "text output should contain 'bugbot check --' summary line, got:\n{}",
        stdout
    );

    // Should NOT be valid JSON
    let json_result: Result<serde_json::Value, _> = serde_json::from_slice(&output.stdout);
    assert!(
        json_result.is_err(),
        "text format output should NOT be valid JSON"
    );
}

/// Run bugbot check against the actual tldr codebase.
/// This is a smoke test: it should not panic and should produce valid JSON.
#[test]
#[ignore] // slow and environment-dependent
fn test_e2e_dogfood_no_crash() {
    let codebase =
        PathBuf::from("/Users/cosimo/.opc-dev/opc/packages/tldr-code/tldr-rs-v2-canonical");

    let output = tldr_bin()
        .args([
            "--lang",
            "rust",
            "--format",
            "json",
            "bugbot",
            "check",
            "--no-fail",
        ])
        .arg(&codebase)
        .output()
        .expect("bugbot check on codebase failed to run");

    assert!(
        output.status.success(),
        "dogfood run should exit 0 with --no-fail, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    assert!(
        json["elapsed_ms"].is_number(),
        "elapsed_ms should be present and numeric"
    );
    assert!(
        json["findings"].is_array(),
        "findings should be an array in dogfood output"
    );
}

/// Exit code should be 1 (not 0, not other) when findings exist without --no-fail.
/// This verifies the process::exit(1) replacement with proper error propagation.
#[test]
fn test_e2e_exit_code_is_1_for_findings() {
    let (_dir, path) = create_test_repo();

    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32, y: i32) -> i32 {\n    x + y\n}\n",
    );
    git_add_commit(&path, "add compute");

    write_file(
        &path,
        "lib.rs",
        "pub fn compute(x: i32) -> i32 {\n    x * 2\n}\n",
    );

    let output = run_bugbot_check(&path, &[]);
    assert_eq!(
        output.status.code(),
        Some(1),
        "exit code should be exactly 1 when findings exist, got: {:?}",
        output.status.code()
    );
}

/// --max-findings 0 should report all findings (unlimited).
#[test]
fn test_e2e_max_findings_zero_unlimited() {
    let (_dir, path) = create_test_repo();

    // Commit 5 functions with 2 params each
    let mut original = String::new();
    for i in 0..5 {
        original.push_str(&format!(
            "pub fn func_{i}(a: i32, b: i32) -> i32 {{\n    a + b + {i}\n}}\n\n"
        ));
    }
    write_file(&path, "lib.rs", &original);
    git_add_commit(&path, "add functions");

    // Remove a parameter from all 5 functions
    let mut modified = String::new();
    for i in 0..5 {
        modified.push_str(&format!(
            "pub fn func_{i}(a: i32) -> i32 {{\n    a + {i}\n}}\n\n"
        ));
    }
    write_file(&path, "lib.rs", &modified);

    let output = run_bugbot_check(&path, &["--no-fail", "--max-findings", "0"]);
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json = parse_json(&output);
    let findings = json["findings"].as_array().expect("findings should be array");

    // All 5 signature regressions should be reported (no truncation)
    assert!(
        findings.len() >= 5,
        "expected at least 5 findings with --max-findings 0 (unlimited), got {}",
        findings.len()
    );

    // Should not have a truncation note
    let notes = json["notes"].as_array().expect("notes should be array");
    let has_truncation = notes.iter().any(|n| {
        n.as_str()
            .unwrap_or("")
            .starts_with("truncated_to_")
    });
    assert!(
        !has_truncation,
        "should not have truncation note with --max-findings 0, got: {:?}",
        notes
    );
}