tga 2.16.0

Developer productivity analytics — git commit collection, classification, and reporting
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
678
679
680
681
682
683
684
685
//! Tests for the AUDIT sweep and the `tga audit` clap wiring.

use std::time::Instant;

use clap::{Args as _, FromArgMatches, Parser};

use crate::audit::{run_full_sweep, AuditSweepStats, StageStatus, SweepOptions, SweepStage};
use crate::commands::audit::AuditArgs;
use crate::core::config::Config;
use crate::core::db::Database;
use crate::core::progress::{ProgressBus, Stage};

/// The order `run_full_sweep` is contracted to execute in.
///
/// Data-flow order, not DOC-67 §5's prose order — deployments and incidents
/// populate what dora reduces, and report renders what everything else wrote.
const EXPECTED_ORDER: [SweepStage; 8] = [
    SweepStage::Collect,
    SweepStage::Classify,
    SweepStage::JiraSync,
    SweepStage::Deployments,
    SweepStage::Incidents,
    SweepStage::Dora,
    SweepStage::PrMetrics,
    SweepStage::Report,
];

// ---------------------------------------------------------------------------
// AuditSweepStats — per-stage outcome reporting, including a failing stage
// ---------------------------------------------------------------------------

#[test]
fn failed_stage_is_recorded_and_does_not_stop_the_sweep() {
    let mut stats = AuditSweepStats::default();

    stats.record(SweepStage::Collect, Instant::now(), Ok(()));
    stats.record(
        SweepStage::JiraSync,
        Instant::now(),
        Err(anyhow::anyhow!("no JIRA project configured")),
    );
    stats.record(SweepStage::Report, Instant::now(), Ok(()));

    // Every stage recorded, in call order — the failure did not truncate the run.
    let stages: Vec<_> = stats.outcomes.iter().map(|o| o.stage).collect();
    assert_eq!(
        stages,
        vec![
            SweepStage::Collect,
            SweepStage::JiraSync,
            SweepStage::Report
        ]
    );

    // The failure is individually observable, with its message intact.
    let failures: Vec<_> = stats.failures().collect();
    assert_eq!(failures.len(), 1);
    assert_eq!(failures[0].stage, SweepStage::JiraSync);
    assert_eq!(
        failures[0].status,
        StageStatus::Failed("no JIRA project configured".to_string())
    );
    assert!(stats.any_failed());
}

#[test]
fn error_cause_chain_is_preserved_in_the_stage_record() {
    let mut stats = AuditSweepStats::default();
    let err = anyhow::anyhow!("connection refused").context("fetching deploy events");

    stats.record(SweepStage::Deployments, Instant::now(), Err(err));

    let StageStatus::Failed(msg) = &stats.outcomes[0].status else {
        panic!("expected a failed status");
    };
    assert!(
        msg.contains("fetching deploy events") && msg.contains("connection refused"),
        "cause chain lost: {msg}"
    );
}

#[test]
fn summary_counts_successes_and_failures() {
    let mut stats = AuditSweepStats::default();
    assert_eq!(stats.summary(), "0 of 0 stage(s) succeeded");
    assert!(!stats.any_failed());

    stats.record(SweepStage::Collect, Instant::now(), Ok(()));
    stats.record(
        SweepStage::Dora,
        Instant::now(),
        Err(anyhow::anyhow!("boom")),
    );
    assert_eq!(stats.summary(), "1 of 2 stage(s) succeeded");
}

#[test]
fn stage_names_match_their_subcommands() {
    assert_eq!(SweepStage::JiraSync.as_str(), "jira sync");
    assert_eq!(SweepStage::PrMetrics.to_string(), "pr-metrics");
    assert_eq!(SweepStage::Deployments.as_str(), "deployments collect");
}

// ---------------------------------------------------------------------------
// run_full_sweep — sequencing over a real (empty) database
// ---------------------------------------------------------------------------

/// An empty config has no repositories, no JIRA, and no DORA sources, so no
/// stage touches the network. Stages that need configuration that is absent
/// fail — which is the point: the sweep must record them and keep going.
#[tokio::test]
async fn sweep_runs_every_stage_in_order_and_survives_failures() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };

    let stats = run_full_sweep(&Config::default(), &mut db, &options, None)
        .await
        .expect("sequencing itself must not fail");

    let stages: Vec<_> = stats.outcomes.iter().map(|o| o.stage).collect();
    assert_eq!(stages, EXPECTED_ORDER.to_vec());
    // The "stage N of 8" denominator in the progress start events is this
    // constant; a stage added without updating it would lie to the operator.
    assert_eq!(stages.len(), super::sweep::TOTAL_STAGES);

    // JIRA is unconfigured here, so that stage must have failed — and the
    // seven stages after it must still have run.
    assert!(
        stats.any_failed(),
        "an unconfigured JIRA sync should have been recorded as a failure"
    );
    assert!(
        stats.failures().any(|o| o.stage == SweepStage::JiraSync),
        "expected the jira sync stage among the failures, got {:?}",
        stats.failures().map(|o| o.stage).collect::<Vec<_>>()
    );
    let jira_index = stages
        .iter()
        .position(|s| *s == SweepStage::JiraSync)
        .expect("jira stage present");
    assert_eq!(
        &stages[jira_index + 1..],
        &EXPECTED_ORDER[jira_index + 1..],
        "stages after the failing jira-sync stage should still have run, but were missing"
    );
}

#[tokio::test]
async fn sweep_writes_reports_into_the_requested_directory() {
    let dir = tempfile::tempdir().expect("tempdir");
    let out = dir.path().join("audit-out");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(out.clone()),
        weeks: None,
    };

    let stats = run_full_sweep(&Config::default(), &mut db, &options, None)
        .await
        .expect("sweep");

    let report = stats
        .outcomes
        .iter()
        .find(|o| o.stage == SweepStage::Report)
        .expect("report stage ran");
    assert_eq!(
        report.status,
        StageStatus::Succeeded,
        "report stage failed: {:?}",
        report.status
    );
    assert!(
        out.is_dir(),
        "report stage did not create {}",
        out.display()
    );

    // `is_dir()` alone would pass for a sweep that creates the directory and
    // writes nothing, so assert the artifacts themselves. `summary.csv` and
    // `report.json` are fixed names from the CSV and JSON formatters, and
    // `pr-metrics.csv` is the name the sweep hands `pr-metrics --output`.
    let written: Vec<String> = std::fs::read_dir(&out)
        .expect("read report dir")
        .map(|e| {
            e.expect("dir entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .collect();
    assert!(
        written.len() > 1,
        "report stage wrote {} file(s) into {}: {written:?}",
        written.len(),
        out.display()
    );
    for expected in [
        crate::report::formatters::csv::SUMMARY_CSV,
        crate::report::formatters::json::REPORT_JSON,
        "pr-metrics.csv",
    ] {
        assert!(
            out.join(expected).is_file(),
            "expected artifact {expected} missing from {}: {written:?}",
            out.display()
        );
    }
}

// ---------------------------------------------------------------------------
// Progress reporting from every stage, not just collection (#5361)
// ---------------------------------------------------------------------------

/// #5361: `run_full_sweep` used to bind and discard its `progress` parameter,
/// so a caller that supplied a bus saw nothing for classify, report, pr-metrics,
/// jira sync, dora, deployments, or incidents — a ~10-minute sweep behind a
/// frozen screen. This asserts the non-collection stages reach the bus the
/// caller passed in; before the fix the drained event list is empty.
#[tokio::test]
async fn sweep_emits_progress_for_non_collection_stages() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };
    let bus = ProgressBus::new();

    let stats = run_full_sweep(&Config::default(), &mut db, &options, Some(&bus))
        .await
        .expect("sweep");

    let events = bus.drain();
    assert_eq!(bus.dropped(), 0, "the run must fit in the default ring");
    assert!(
        !events.is_empty(),
        "a bus handed to run_full_sweep received nothing at all"
    );

    // Report and classify are the stages furthest from collection: neither has
    // any instrumentation of its own, so if the parameter is not threaded they
    // are silent no matter what the collection pipeline does.
    for stage in [SweepStage::Classify, SweepStage::Report] {
        let mine: Vec<_> = events
            .iter()
            .filter(|e| e.stage == Stage::Audit && e.target == stage.as_str())
            .collect();
        assert!(
            mine.iter().any(|e| !e.is_terminal()),
            "no start event for the {stage} stage: {events:#?}"
        );
        assert!(
            mine.iter().any(|e| e.is_terminal()),
            "no completion event for the {stage} stage: {events:#?}"
        );
    }

    // Every stage, not just those two — and the bus's verdict agrees with the
    // recorded one, so a stage cannot report green on screen and red in stats.
    for outcome in &stats.outcomes {
        let terminal = events
            .iter()
            .find(|e| {
                e.stage == Stage::Audit && e.target == outcome.stage.as_str() && e.is_terminal()
            })
            .unwrap_or_else(|| panic!("no terminal event for {}", outcome.stage));
        let announced_failure = terminal
            .outcome
            .as_ref()
            .is_some_and(|o| matches!(o, crate::core::progress::Outcome::Failed { .. }));
        assert_eq!(
            announced_failure,
            outcome.status.is_failure(),
            "{} announced and recorded different verdicts",
            outcome.stage
        );
    }
}

/// An inactive bus must change nothing — the `None` caller's contract, proved
/// through the one shape that is observable from outside.
#[tokio::test]
async fn a_disabled_bus_stays_a_no_op() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };
    let bus = ProgressBus::disabled();

    let stats = run_full_sweep(&Config::default(), &mut db, &options, Some(&bus))
        .await
        .expect("sweep");

    assert!(bus.drain().is_empty(), "a disabled bus queued events");
    assert_eq!(bus.dropped(), 0);
    let stages: Vec<_> = stats.outcomes.iter().map(|o| o.stage).collect();
    assert_eq!(
        stages,
        EXPECTED_ORDER.to_vec(),
        "sequencing must not depend on whether anybody is watching"
    );
}

// ---------------------------------------------------------------------------
// clap wiring — `tga audit` parses its flags and dispatches
// ---------------------------------------------------------------------------

/// Standalone parser so the wiring can be asserted without building the whole
/// `tga` CLI, which the binary target owns.
#[derive(Parser, Debug)]
struct AuditOnly {
    #[command(flatten)]
    args: AuditArgs,
}

#[test]
fn audit_args_parse_every_flag() {
    let parsed = AuditOnly::try_parse_from([
        "tga-audit",
        "--org",
        "acme",
        "--title",
        "Acme DD",
        "--analyst",
        "J. Reviewer",
        "--client",
        "Acme Holdings",
        "--output",
        "/tmp/acme-dd",
        "--weeks",
        "26",
    ])
    .expect("flags must parse");

    assert_eq!(parsed.args.org.as_deref(), Some("acme"));
    assert_eq!(parsed.args.title.as_deref(), Some("Acme DD"));
    assert_eq!(parsed.args.analyst.as_deref(), Some("J. Reviewer"));
    assert_eq!(parsed.args.client.as_deref(), Some("Acme Holdings"));
    assert_eq!(
        parsed.args.output.as_deref(),
        Some(std::path::Path::new("/tmp/acme-dd"))
    );
    assert_eq!(parsed.args.weeks, Some(26));
}

#[test]
fn audit_runs_with_no_flags_at_all() {
    // DOC-67 §2: `tga audit` must be runnable as one shot with no operator
    // input, so no flag may be required.
    let parsed = AuditOnly::try_parse_from(["tga-audit"]).expect("bare invocation must parse");
    assert!(parsed.args.org.is_none());
    assert!(parsed.args.output.is_none());
}

#[test]
fn audit_takes_no_positional_arguments() {
    // A positional would be a place for an operator to be asked for something.
    // Which `ErrorKind` clap picks for an unexpected positional depends on the
    // command shape and the clap version, so assert the observable contract —
    // the parse fails and the message names the rejected argument — instead of
    // pinning the discriminant.
    let err = AuditOnly::try_parse_from(["tga-audit", "acme"])
        .expect_err("a positional argument must be rejected");
    let rendered = err.to_string();
    assert!(
        rendered.contains("acme"),
        "rejection must name the offending argument, got: {rendered}"
    );
}

#[test]
fn audit_args_expose_a_complete_clap_command() {
    // Guards the derive itself: every declared flag must reach the command.
    let cmd = AuditArgs::augment_args(clap::Command::new("audit"));
    let names: Vec<_> = cmd.get_arguments().map(|a| a.get_id().as_str()).collect();
    for expected in ["org", "title", "analyst", "client", "output", "weeks"] {
        assert!(
            names.contains(&expected),
            "missing --{expected} in {names:?}"
        );
    }

    let matches = cmd
        .try_get_matches_from(["audit", "--analyst", "me"])
        .expect("parse");
    let args = AuditArgs::from_arg_matches(&matches).expect("from_arg_matches");
    assert_eq!(args.analyst.as_deref(), Some("me"));
}

// ---------------------------------------------------------------------------
// Gaps & Caveats lines from the sweep's own record (#5239, #5244)
// ---------------------------------------------------------------------------

/// A config holding no credentials. The redaction path itself is proved end to
/// end against a real token in
/// `crate::report::dd_manifest_tests::a_token_straddling_the_excerpt_boundary_leaves_no_fragment`;
/// these tests are about the wording and ordering of the lines.
const NO_SECRETS: &[&str] = &[];

#[test]
fn sweep_gap_lines_name_each_failed_stage() {
    let mut stats = AuditSweepStats::default();
    stats.record(SweepStage::Collect, Instant::now(), Ok(()));
    stats.record(
        SweepStage::JiraSync,
        Instant::now(),
        Err(anyhow::anyhow!("no JIRA project configured")),
    );
    stats.record(
        SweepStage::Dora,
        Instant::now(),
        Err(anyhow::anyhow!("fact_deployments is empty")),
    );

    let lines = crate::audit::sweep_gap_lines(&stats, NO_SECRETS);

    assert_eq!(lines.len(), 2, "one line per failure, none for success");
    assert!(lines[0].contains("`jira sync`"), "{}", lines[0]);
    assert!(
        lines[0].contains("no JIRA project configured"),
        "{}",
        lines[0]
    );
    assert!(lines[1].contains("`dora`"), "{}", lines[1]);
    // DOC-67 §9: the line must refuse to read as a clean result.
    for line in &lines {
        assert!(line.contains("not assessed"), "{line}");
    }
    // Execution order, so two runs over the same failures read identically.
    assert_eq!(lines, crate::audit::sweep_gap_lines(&stats, NO_SECRETS));
}

/// #5321: a `collect` stage that fell back to stale local refs used to reach
/// the report as nothing at all.
///
/// The sweep hard-codes `--allow-stale` (DOC-67 §9), so an unreachable remote
/// is not an error: the pipeline walks whatever the local clone already had and
/// the stage records `Succeeded`. `sweep_gap_lines` only reads
/// [`AuditSweepStats::failures`], so a succeeded stage contributed no line and
/// the manifest carried no note — the reader could not tell "no stale refs" from
/// "the data may be months behind". Before the fix this test fails on the final
/// assertion: the gap lines name the failed `jira sync` stage and nothing else.
#[tokio::test]
async fn a_repo_that_fell_back_to_stale_local_refs_is_named_in_the_gap_lines() {
    let dir = tempfile::tempdir().expect("tempdir");
    let repo_path = dir.path().join("acme-service");
    // An `origin` whose scheme has no transport: the fetch fails without
    // touching the network, exactly as the reported run's SSH remote did
    // ("unsupported URL protocol"), so the test is offline and deterministic.
    init_repo_with_dead_origin(
        &repo_path,
        "sshx://git@example.invalid/acme/acme-service.git",
    );

    let mut config = Config::default();
    config
        .repositories
        .push(crate::core::config::RepositoryConfig {
            name: Some("acme-service".to_string()),
            path: repo_path,
            branch: None,
            since_date: None,
            until_date: None,
            org: None,
            head_only: false,
            fetch_timeout_secs: None,
        });

    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };
    let stats = run_full_sweep(&config, &mut db, &options, None)
        .await
        .expect("sweep");

    // The defect's own shape: the stage reports `ok`. That is correct — the
    // sweep must not abort — which is exactly why the degradation needs its own
    // channel to the report.
    let collect = stats
        .outcomes
        .iter()
        .find(|o| o.stage == SweepStage::Collect)
        .expect("collect stage ran");
    assert_eq!(
        collect.status,
        StageStatus::Succeeded,
        "collect should still report ok under --allow-stale: {:?}",
        collect.status
    );

    let lines = crate::audit::sweep_gap_lines(&stats, NO_SECRETS);
    let stale = lines
        .iter()
        .find(|l| l.contains("acme-service"))
        .unwrap_or_else(|| {
            panic!("no Gaps & Caveats line names the repo that fell back to stale refs: {lines:#?}")
        });
    assert!(
        stale.contains("origin"),
        "the line must name the affected remote: {stale}"
    );
    assert!(
        stale.contains("behind the true remote state"),
        "the line must say the data may be out of date: {stale}"
    );
}

/// A git repository with one commit and an `origin` that cannot be fetched.
fn init_repo_with_dead_origin(path: &std::path::Path, remote_url: &str) {
    std::fs::create_dir_all(path).expect("mkdir");
    let repo = git2::Repository::init(path).expect("git init");
    repo.remote("origin", remote_url).expect("add origin");

    std::fs::write(path.join("README.md"), "acme").expect("write file");
    let mut index = repo.index().expect("index");
    index
        .add_path(std::path::Path::new("README.md"))
        .expect("index add");
    index.write().expect("index write");
    let tree = repo
        .find_tree(index.write_tree().expect("write_tree"))
        .expect("find_tree");
    let sig = git2::Signature::now("Test", "t@example.com").expect("signature");
    repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
        .expect("commit");
}

/// The stale-refs line travels the same redaction path a stage message does,
/// and it needs to: git2 quotes the remote URL back in the error, so an HTTPS
/// remote with an embedded token puts that token in the manifest and the
/// delivered report. Also pins the ordering — failed stages first, then the
/// repositories that were collected anyway.
#[test]
fn a_credential_in_a_fetch_error_never_reaches_the_gap_line() {
    let mut stats = AuditSweepStats::default();
    stats.record(
        SweepStage::Dora,
        Instant::now(),
        Err(anyhow::anyhow!("fact_deployments is empty")),
    );
    stats.record_stale_fetch(crate::audit::StaleFetch {
        repo: "acme-service".to_string(),
        remote: "origin".to_string(),
        error: "failed to connect to https://x-access-token:ghp_SECRETVALUE@github.com/acme/svc"
            .to_string(),
    });

    let lines = crate::audit::sweep_gap_lines(&stats, &["ghp_SECRETVALUE"]);

    assert_eq!(lines.len(), 2, "{lines:#?}");
    assert!(lines[0].contains("`dora`"), "{}", lines[0]);
    assert!(lines[1].contains("acme-service"), "{}", lines[1]);
    assert!(
        !lines[1].contains("ghp_SECRETVALUE"),
        "the token survived into the report: {}",
        lines[1]
    );
}

#[test]
fn sweep_gap_lines_are_empty_for_a_clean_run() {
    let mut stats = AuditSweepStats::default();
    for stage in EXPECTED_ORDER {
        stats.record(stage, Instant::now(), Ok(()));
    }
    assert!(crate::audit::sweep_gap_lines(&stats, NO_SECRETS).is_empty());
}

#[test]
fn long_stage_reasons_are_truncated() {
    let mut stats = AuditSweepStats::default();
    stats.record(
        SweepStage::Collect,
        Instant::now(),
        Err(anyhow::anyhow!("x".repeat(4000))),
    );

    let line = crate::audit::sweep_gap_lines(&stats, NO_SECRETS).remove(0);

    assert!(line.contains('…'), "a long reason is excerpted: {line}");
    assert!(
        line.chars().count() < 400,
        "one verbose error must not dominate the Gaps section ({} chars)",
        line.chars().count()
    );
}

#[test]
fn data_handling_note_is_a_pending_claim() {
    let note = crate::audit::DATA_HANDLING_NOTE;
    // DOC-67 §10: pending, never asserted — and #5218 is where the real one comes from.
    assert!(note.contains("pending"), "{note}");
    assert!(note.contains("#5218"), "{note}");
    // §10's exact scope claim; the broader "no code" claim is wrong and must
    // not appear, because free-text columns can carry pasted snippets.
    assert!(note.contains("no file content, diffs, patches, hunks, or blobs"));
    assert!(!note.contains("no code"), "{note}");
}

// ---------------------------------------------------------------------------
// Invoking trusty-review as a subprocess (#5238)
// ---------------------------------------------------------------------------

#[test]
fn artifact_paths_are_parsed_from_stdout() {
    // trusty-review prints one written path per line on stdout; blank lines and
    // trailing whitespace must not become phantom artifacts.
    let stdout = "  /out/acme.md\n\n/out/acme.json\n";
    let paths = crate::audit::artifact_paths(stdout);
    assert_eq!(
        paths,
        vec![
            std::path::PathBuf::from("/out/acme.md"),
            std::path::PathBuf::from("/out/acme.json")
        ]
    );
    assert!(crate::audit::artifact_paths("").is_empty());
}

#[tokio::test]
async fn missing_binary_is_a_named_actionable_error() {
    // A renderer that is not installed must produce a message an operator can
    // act on — never a panic, and never a silent skip that leaves the run
    // looking successful with no report.
    let dir = tempfile::tempdir().expect("tempdir");
    let manifest = dir.path().join("manifest.toml");
    std::fs::write(&manifest, "[report]\ntitle = \"T\"\n").expect("write");

    // The binary is passed in, never installed through the environment: this is
    // the same path `run_review_report` takes once resolution has happened, and
    // it stays sound under the parallel harness (#5308 review).
    let missing = dir.path().join("definitely-not-installed");
    let err =
        super::review::run_review_report_with(missing.display().to_string(), &manifest, dir.path())
            .await
            .expect_err("a missing binary must be an error");

    let msg = err.to_string();
    assert!(
        matches!(err, crate::audit::ReviewRunError::BinaryNotFound { .. }),
        "{msg}"
    );
    assert!(
        msg.contains("TRUSTY_REVIEW_BIN"),
        "names the override: {msg}"
    );
    assert!(msg.contains("cargo install"), "names the fix: {msg}");
    assert!(
        msg.contains(&manifest.display().to_string()),
        "the written manifest is still usable and must be named: {msg}"
    );
}

/// The rule is exercised as a pure function over the override value, which is
/// what `resolve_review_binary` reads `TRUSTY_REVIEW_BIN` into. Mutating the
/// process environment to test it would be unsound under the parallel test
/// harness, and no `unsafe` block can make it sound (#5308 review).
#[test]
fn binary_resolution_prefers_the_env_override() {
    use super::review::binary_from_override;

    assert_eq!(
        binary_from_override(Some("/opt/bin/trusty-review")),
        "/opt/bin/trusty-review"
    );
    assert_eq!(
        binary_from_override(Some("")),
        crate::audit::DEFAULT_REVIEW_BIN,
        "an empty override falls back to the PATH lookup"
    );
    assert_eq!(binary_from_override(None), crate::audit::DEFAULT_REVIEW_BIN);
    // The public entry point returns one of the two, whatever this machine's
    // environment happens to hold — read only, never written.
    let resolved = crate::audit::resolve_review_binary();
    assert!(!resolved.is_empty(), "{resolved}");
}