rust-doctor 0.5.0

Local-first health audit for Cargo workspaces: curated Clippy lints and native detectors, scored out of 100
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
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]

mod support;

use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::AtomicUsize;

use rust_doctor::{
    BlockingLevel, ExecutionScope, GateStatus, InspectRequest, ScopeMode, Status, inspect,
};
use serde_json::Value;
use support::rule_scaling::{oracle, project_legacy_report};

static NEXT_WORKSPACE: AtomicUsize = AtomicUsize::new(0);

fn fixture() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/configuration-kernel/workspace")
}

fn successful(command: &mut Command) -> Output {
    let output = command.output().unwrap();
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    output
}

fn git(root: &Path, arguments: &[&str]) -> Output {
    successful(Command::new("git").args(arguments).current_dir(root))
}

fn repository(scope: &str) -> PathBuf {
    let root = support::temporary_target(scope, &NEXT_WORKSPACE);
    if root.exists() {
        fs::remove_dir_all(&root).unwrap();
    }
    support::copy_tree(&fixture(), &root);
    fs::write(root.join(".gitignore"), "/target\n").unwrap();
    successful(
        Command::new(env!("CARGO"))
            .args(["generate-lockfile", "--offline"])
            .current_dir(&root),
    );
    git(&root, &["init", "--quiet"]);
    git(&root, &["config", "user.name", "Rust Doctor"]);
    git(
        &root,
        &["config", "user.email", "rust-doctor@example.invalid"],
    );
    git(&root, &["add", "."]);
    git(&root, &["commit", "--quiet", "-m", "base"]);
    git(&root, &["branch", "baseline"]);
    fs::write(
        root.join("member/src/lib.rs"),
        // The module declaration is kept: dropping it would leave
        // `member/src/nested/mod.rs` reached by nothing, which is a structural
        // finding of its own and not the change this fixture is about.
        "pub mod nested;\n\npub fn configuration_kernel_fixture() -> bool {\n    false\n}\n",
    )
    .unwrap();
    root
}

fn cli(path: &Path, arguments: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_rust-doctor"))
        .arg("inspect")
        .arg("--json")
        .args(arguments)
        .arg(path)
        .env("CARGO_NET_OFFLINE", "true")
        .output()
        .unwrap()
}

fn json(output: &Output) -> Value {
    assert_eq!(output.stdout.last(), Some(&b'\n'));
    serde_json::from_slice(&output.stdout).unwrap()
}

fn compact_json_fixture(input: &str) -> Vec<u8> {
    let mut compact = Vec::with_capacity(input.len());
    let mut in_string = false;
    let mut escaped = false;
    for byte in input.bytes() {
        if in_string {
            compact.push(byte);
            if escaped {
                escaped = false;
            } else if byte == b'\\' {
                escaped = true;
            } else if byte == b'"' {
                in_string = false;
            }
        } else if byte == b'"' {
            in_string = true;
            compact.push(byte);
        } else if !byte.is_ascii_whitespace() {
            compact.push(byte);
        }
    }
    compact.push(b'\n');
    compact
}

fn project_v9_value_to_v7(report: &mut Value) {
    report["schema_version"] = Value::from(7);
    report
        .as_object_mut()
        .expect("report should be an object")
        .remove("audit");
    for added in ["distinct", "occurrences"] {
        report["summary"]
            .as_object_mut()
            .expect("summary should be an object")
            .remove(added)
            .expect("schema v9 should publish both magnitudes");
    }
    for rule in report["policy"]["rules"]
        .as_array_mut()
        .expect("policy rules should be an array")
    {
        rule.as_object_mut()
            .expect("a rule should be an object")
            .remove("tier")
            .expect("schema v9 should publish a tier per rule");
    }
}

fn snapshot(root: &Path) -> Vec<Vec<u8>> {
    [
        vec!["rev-parse", "HEAD"],
        vec!["show-ref"],
        vec!["hash-object", ".git/index"],
        vec!["status", "--porcelain=v1", "-z"],
    ]
    .into_iter()
    .map(|arguments| git(root, &arguments).stdout)
    .collect()
}

#[cfg(unix)]
fn instrumented_cli(root: &Path, arguments: &[&str], scope: &str) -> (Output, Vec<String>) {
    let harness_root = support::temporary_target(scope, &NEXT_WORKSPACE);
    let processes = support::ProcessHarness::install_with_git(&harness_root);
    let real_git = support::resolve_program("git");
    let output = Command::new(env!("CARGO_BIN_EXE_rust-doctor"))
        .arg("inspect")
        .arg("--json")
        .args(arguments)
        .arg(root)
        .env("PATH", processes.command_path())
        .env("RUST_DOCTOR_REAL_GIT", real_git)
        .env("RUST_DOCTOR_REAL_CARGO", env!("CARGO"))
        .env("RUST_DOCTOR_REAL_RUSTC", support::resolve_program("rustc"))
        .env("RUST_DOCTOR_PROCESS_LOG", processes.log_path())
        .env("CARGO_NET_OFFLINE", "true")
        .env("GIT_DIR", "/private/hostile/repository")
        .env("GIT_WORK_TREE", "/private/hostile/worktree")
        .env("GIT_INDEX_FILE", "/private/hostile/index")
        .env("GIT_OBJECT_DIRECTORY", "/private/hostile/objects")
        .env(
            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
            "/private/hostile/alternates",
        )
        .env("GIT_COMMON_DIR", "/private/hostile/common")
        .env("GIT_CONFIG", "/private/hostile/config")
        .env("GIT_CONFIG_COUNT", "1")
        .env("GIT_CONFIG_KEY_0", "core.pager")
        .env("GIT_CONFIG_VALUE_0", "/private/hostile/pager")
        .env("GIT_EXTERNAL_DIFF", "/private/hostile/diff")
        .env("GIT_PAGER", "/private/hostile/pager")
        .output()
        .unwrap();
    let git_processes = processes
        .events()
        .into_iter()
        .filter_map(|event| event.strip_prefix("git-").map(str::to_owned))
        .collect();
    (output, git_processes)
}

#[test]
fn api_full_and_files_resolve_one_workspace_without_mutating_git() {
    let root = repository("git-scope-api");
    let before = snapshot(&root);
    let full = inspect(InspectRequest::new(&root));
    assert_eq!(full.status, Status::Complete, "{:?}", full.errors);
    assert_eq!(full.schema_version, 15);
    let full_scope = full.scope.unwrap();
    assert_eq!(full_scope.mode(), ScopeMode::Full);
    assert_eq!(full_scope.execution_scope(), ExecutionScope::Workspace);
    assert_eq!(full_scope.comparison_base(), None);
    assert_eq!(full_scope.files(), None);

    let entries = [
        root.clone(),
        root.join("member/Cargo.toml"),
        root.join("member/src/nested"),
    ];
    let mut expected_scope = None;
    for entry in entries {
        let report = inspect(InspectRequest::new(entry).with_files_scope("baseline"));
        assert_eq!(report.status, Status::Complete, "{:?}", report.errors);
        let scope = report.scope.unwrap();
        assert_eq!(scope.mode(), ScopeMode::Files);
        assert_eq!(scope.execution_scope(), ExecutionScope::Workspace);
        assert_eq!(scope.files(), Some(&["member/src/lib.rs".to_owned()][..]));
        assert_eq!(scope.comparison_base().map(str::len), Some(40));
        if let Some(expected) = &expected_scope {
            assert_eq!(&scope, expected);
        } else {
            expected_scope = Some(scope);
        }
    }
    assert_eq!(snapshot(&root), before);
}

#[test]
fn full_v8_preserves_the_frozen_v7_bytes_and_v6_projection() {
    let report = inspect(InspectRequest::new(fixture()));
    assert_eq!(report.status, Status::Complete, "{:?}", report.errors);
    let scope = report.scope.as_ref().unwrap();
    assert_eq!(scope.mode(), ScopeMode::Full);
    assert_eq!(scope.execution_scope(), ExecutionScope::Workspace);
    assert!(scope.comparison_base().is_none());
    assert!(scope.files().is_none());

    let mut current_wire = Vec::new();
    rust_doctor::render::render_json(&report, &mut current_wire).unwrap();
    // The command is compared separately: it deliberately lost `--all-targets`,
    // and it gains a `-W` with every rule admitted into the catalog. The rest
    // of the v7 bytes must stay identical.
    let frozen = compact_json_fixture(include_str!(
        "fixtures/rule-scaling-kernel/v7-full-report.json"
    ));
    assert_ne!(support::project_v11_wire_to_v7(&current_wire), frozen);
    assert_eq!(
        support::project_v11_wire_to_v7(&current_wire),
        support::drop_scan_command(&frozen)
    );

    let frozen_v7_source = include_str!("fixtures/git-scope/v7-full-report.json");
    let mut current = serde_json::to_value(report).unwrap();
    project_v9_value_to_v7(&mut current);
    let current = project_legacy_report(current, &oracle());
    assert_eq!(current["schema_version"], 7);
    assert!(current["delta"].is_null());
    let mut frozen_v7: Value =
        serde_json::from_str(include_str!("fixtures/git-scope/v7-full-report.json")).unwrap();
    // Same rule as for the bytes: the command is the record of what ran, not a
    // clause of the schema contract.
    assert_ne!(current["scan"]["command"], frozen_v7["scan"]["command"]);
    let mut current = current;
    current["scan"].as_object_mut().unwrap().remove("command");
    frozen_v7["scan"].as_object_mut().unwrap().remove("command");
    assert_eq!(current, frozen_v7);

    let mut compatible_v6 = current.clone();
    compatible_v6["schema_version"] = Value::from(6);
    compatible_v6.as_object_mut().unwrap().remove("delta");
    let mut frozen_v6: Value =
        serde_json::from_str(include_str!("fixtures/git-scope/v6-full-report.json")).unwrap();
    frozen_v6["scan"].as_object_mut().unwrap().remove("command");
    assert_eq!(compatible_v6, frozen_v6);
    let projected_v6 = frozen_v7_source
        .replacen("\"schema_version\": 7", "\"schema_version\": 6", 1)
        .replace(
            "  \"diagnostics\": [],\n  \"delta\": null,\n",
            "  \"diagnostics\": [],\n",
        );
    assert_eq!(
        projected_v6,
        include_str!("fixtures/git-scope/v6-full-report.json"),
        "the frozen v6 bytes may only gain schema v7 and delta",
    );

    let mut compatible = compatible_v6;
    compatible["schema_version"] = Value::from(5);
    compatible.as_object_mut().unwrap().remove("scope");
    let mut frozen: Value =
        serde_json::from_str(include_str!("fixtures/git-scope/v5-full-report.json")).unwrap();
    frozen["scan"].as_object_mut().unwrap().remove("command");

    assert_eq!(compatible, frozen);
}

#[test]
fn frozen_v7_baseline_fixture_has_the_unambiguous_delta_shape() {
    let root = repository("git-scope-v7-baseline-fixture");
    let output = cli(&root, &["--scope", "baseline", "--base", "baseline"]);
    assert_eq!(
        output.status.code(),
        Some(0),
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let production = json(&output);
    let comparison_base = production["scope"]["comparison_base"].as_str().unwrap();
    let normalized_wire = String::from_utf8(output.stdout)
        .unwrap()
        .replace(comparison_base, "0123456789abcdef0123456789abcdef01234567");
    let frozen_baseline = compact_json_fixture(include_str!(
        "fixtures/rule-scaling-kernel/v7-baseline-report.json"
    ));
    assert_ne!(
        support::project_v11_wire_to_v7(normalized_wire.as_bytes()),
        frozen_baseline
    );
    assert_eq!(
        support::project_v11_wire_to_v7(normalized_wire.as_bytes()),
        support::drop_scan_command(&frozen_baseline),
    );

    let mut normalized = production;
    normalized["scope"]["comparison_base"] =
        Value::String("0123456789abcdef0123456789abcdef01234567".to_owned());
    project_v9_value_to_v7(&mut normalized);
    let normalized = project_legacy_report(normalized, &oracle());

    let mut baseline: Value =
        serde_json::from_str(include_str!("fixtures/baseline/v7-baseline-report.json")).unwrap();
    let mut normalized = normalized;
    assert_ne!(normalized["scan"]["command"], baseline["scan"]["command"]);
    normalized["scan"].as_object_mut().unwrap().remove("command");
    baseline["scan"].as_object_mut().unwrap().remove("command");
    assert_eq!(normalized, baseline);
    assert_eq!(baseline["schema_version"], 7);
    assert_eq!(baseline["scope"]["mode"], "baseline");
    assert_eq!(
        baseline["scope"]["comparison_base"],
        "0123456789abcdef0123456789abcdef01234567"
    );
    let keys = baseline["delta"]
        .as_object()
        .unwrap()
        .keys()
        .map(String::as_str)
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(
        keys,
        std::collections::BTreeSet::from([
            "base_diagnostics",
            "current_diagnostics",
            "fingerprint_version",
            "fixed",
            "introduced",
            "pre_existing",
            "summary",
        ])
    );
    fs::remove_dir_all(root).unwrap();
}

#[test]
fn files_scope_projects_diagnostics_through_the_canonical_path_representation() {
    let root = repository("git-scope-canonical-path");
    let manifest = root.join("member/Cargo.toml");
    let source = root.join("member/src/100%.rs");
    git(&root, &["mv", "member/src/lib.rs", "member/src/100%.rs"]);
    fs::write(
        &manifest,
        format!(
            "{}\n[lib]\npath = \"src/100%.rs\"\n",
            fs::read_to_string(&manifest).unwrap()
        ),
    )
    .unwrap();
    git(&root, &["add", "."]);
    git(
        &root,
        &["commit", "--quiet", "-m", "canonical path baseline"],
    );
    git(&root, &["branch", "-f", "baseline", "HEAD"]);
    fs::write(
        &source,
        "pub fn canonical_path_fixture() -> bool { todo!() }\n",
    )
    .unwrap();

    let report = inspect(InspectRequest::new(&root).with_files_scope("baseline"));

    assert_eq!(report.status, Status::Complete, "{:?}", report.errors);
    assert_eq!(
        report.scope.as_ref().and_then(|scope| scope.files()),
        Some(&["member/src/100%25.rs".to_owned()][..])
    );
    assert!(report.diagnostics.iter().any(|diagnostic| {
        diagnostic.code.as_deref() == Some("clippy::todo")
            && diagnostic.path.as_deref() == Some("member/src/100%25.rs")
    }));
}

#[cfg(unix)]
#[test]
fn cli_and_api_share_scope_while_full_runs_zero_git_and_files_runs_three() {
    let root = repository("git-scope-cli");
    let api = inspect(
        InspectRequest::new(&root)
            .with_files_scope("baseline")
            .with_blocking(BlockingLevel::Warning),
    );
    let expected_report = serde_json::to_value(&api).unwrap();
    let expected_scope = api.scope.unwrap();

    let (full, full_processes) = instrumented_cli(&root, &[], "git-scope-full-processes");
    assert!(
        full.status.success(),
        "{}",
        String::from_utf8_lossy(&full.stderr)
    );
    assert!(full_processes.is_empty());

    let (files, files_processes) = instrumented_cli(
        &root,
        &[
            "--scope",
            "files",
            "--base",
            "baseline",
            "--blocking",
            "warning",
        ],
        "git-scope-files-processes",
    );
    assert!(
        files.status.success(),
        "{}",
        String::from_utf8_lossy(&files.stderr)
    );
    assert_eq!(files_processes, ["rev-parse", "merge-base", "diff"]);
    let report = json(&files);
    assert_eq!(
        report["scope"],
        serde_json::to_value(expected_scope).unwrap()
    );
    for field in [
        "status",
        "complete",
        "policy",
        "scope",
        "project",
        "toolchain",
        "scan",
        "diagnostics",
        "errors",
        "summary",
        "gate",
    ] {
        assert_eq!(report[field], expected_report[field], "{field}");
    }
    let rendered = String::from_utf8(files.stdout).unwrap();
    for hostile in [
        "/private/hostile",
        "credential=secret",
        "https://secret",
        "\u{1b}",
    ] {
        assert!(!rendered.contains(hostile));
    }
}

#[cfg(unix)]
#[test]
fn policy_discovery_and_metadata_failures_precede_every_git_process() {
    let missing = support::temporary_target("git-scope-missing-entry", &NEXT_WORKSPACE);
    if missing.exists() {
        fs::remove_dir_all(&missing).unwrap();
    }
    let (policy, policy_processes) = instrumented_cli(
        &missing,
        &[
            "--scope",
            "files",
            "--base",
            "main",
            "--rule",
            "unknown::rule=warn",
        ],
        "git-scope-policy-order",
    );
    assert_eq!(policy.status.code(), Some(2));
    assert!(policy_processes.is_empty());
    let policy = json(&policy);
    assert_eq!(policy["errors"][0]["stage"], "policy");
    assert_eq!(policy["scope"], Value::Null);

    let (discovery, discovery_processes) = instrumented_cli(
        &missing,
        &["--scope", "files", "--base", "main"],
        "git-scope-discovery-order",
    );
    assert_eq!(discovery.status.code(), Some(2));
    assert!(discovery_processes.is_empty());
    let discovery = json(&discovery);
    assert_eq!(discovery["errors"][0]["stage"], "discovery");
    assert_eq!(discovery["scope"], Value::Null);

    let invalid_metadata = support::temporary_target("git-scope-metadata-entry", &NEXT_WORKSPACE);
    if invalid_metadata.exists() {
        fs::remove_dir_all(&invalid_metadata).unwrap();
    }
    fs::create_dir_all(&invalid_metadata).unwrap();
    fs::write(
        invalid_metadata.join("Cargo.toml"),
        "[package]\nname = \"invalid-metadata\"\n",
    )
    .unwrap();
    let (metadata, metadata_processes) = instrumented_cli(
        &invalid_metadata,
        &["--scope", "files", "--base", "main"],
        "git-scope-metadata-order",
    );
    assert_eq!(metadata.status.code(), Some(2));
    assert!(metadata_processes.is_empty());
    let metadata = json(&metadata);
    assert_eq!(metadata["errors"][0]["stage"], "metadata");
    assert_eq!(metadata["scope"], Value::Null);
}

#[test]
fn invalid_api_base_stops_before_discovery_without_disclosing_input() {
    let hostile = "--secret^{commit}";
    for request in [
        InspectRequest::new("/path/that/must/not/be/inspected").with_files_scope(hostile),
        InspectRequest::new("/path/that/must/not/be/inspected").with_baseline_scope(hostile),
    ] {
        assert!(!format!("{request:?}").contains(hostile));
        let report = inspect(request);

        assert_eq!(report.schema_version, 15);
        assert_eq!(report.status, Status::Failed);
        assert!(report.project.is_none());
        assert!(report.policy.is_none());
        assert!(report.scope.is_none());
        assert!(report.toolchain.cargo.is_none());
        assert!(report.toolchain.rustc.is_none());
        assert!(report.toolchain.clippy.is_none());
        assert!(report.scan.command.is_none());
        assert_eq!(report.gate.status, GateStatus::NotEvaluated);
        assert_eq!(report.exit_code(), 2);
        assert_eq!(report.errors.len(), 1);
        assert_eq!(report.errors[0].stage, "scope");
        assert_eq!(report.errors[0].code, "invalid-base");
        assert!(!format!("{report:?}").contains(hostile));
    }
}

#[test]
fn git_failure_after_configuration_keeps_only_project_and_closed_scope_error() {
    let root = support::temporary_target("git-scope-no-repository", &NEXT_WORKSPACE);
    if root.exists() {
        fs::remove_dir_all(&root).unwrap();
    }
    support::copy_tree(&fixture(), &root);
    fs::write(root.join(".git"), "gitdir: missing\n").unwrap();

    let report = inspect(InspectRequest::new(&root).with_files_scope("main"));

    assert_eq!(report.status, Status::Failed);
    assert!(report.project.is_some());
    assert!(report.policy.is_none());
    assert!(report.scope.is_none());
    assert!(report.toolchain.cargo.is_none());
    assert!(report.toolchain.rustc.is_none());
    assert!(report.toolchain.clippy.is_none());
    assert!(report.scan.command.is_none());
    assert_eq!(report.errors.len(), 1);
    assert_eq!(report.errors[0].stage, "scope");
    assert_eq!(report.errors[0].code, "base-unavailable");
    assert!(!format!("{report:?}").contains(&root.display().to_string()));
}

#[test]
fn missing_base_is_closed_and_never_reaches_tool_execution() {
    let root = repository("git-scope-missing-base");
    let selector = "missing-private-base";
    let report = inspect(InspectRequest::new(&root).with_files_scope(selector));
    assert_eq!(report.status, Status::Failed);
    assert_eq!(report.errors.len(), 1);
    assert_eq!(report.errors[0].code, "base-unavailable");
    assert!(report.scope.is_none());
    assert!(report.toolchain.cargo.is_none());
    assert!(report.scan.command.is_none());
    assert!(!format!("{report:?}").contains(selector));
}

#[test]
fn terminal_scope_failure_exposes_only_the_closed_code() {
    let root = repository("git-scope-terminal-error");
    let selector = "missing-private-base";
    let output = Command::new(env!("CARGO_BIN_EXE_rust-doctor"))
        .arg("inspect")
        .args(["--scope", "files", "--base", selector])
        .arg(&root)
        .env("CARGO_NET_OFFLINE", "true")
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(2));
    let mut rendered = String::from_utf8_lossy(&output.stdout).into_owned();
    rendered.push_str(&String::from_utf8_lossy(&output.stderr));
    assert!(rendered.contains("scope/base-unavailable"));
    for forbidden in [
        selector,
        root.to_string_lossy().as_ref(),
        "credential=secret",
        "https://",
        "\u{1b}",
    ] {
        assert!(!rendered.contains(forbidden), "leaked {forbidden:?}");
    }
}

#[test]
fn clap_rejects_invalid_scope_combinations_without_a_report_or_inspection() {
    for arguments in [
        vec!["--scope", "files"],
        vec!["--scope", "baseline"],
        vec!["--scope", "baseline", "--scope", "files", "--base", "main"],
        vec!["--scope", "full", "--base", "main"],
        vec!["--base", "main"],
        vec!["--scope", "unknown"],
    ] {
        let output = cli(Path::new("/path/that/must/not/be/inspected"), &arguments);
        assert_eq!(output.status.code(), Some(2), "{arguments:?}");
        assert!(output.stdout.is_empty(), "{arguments:?}");
        let stderr = String::from_utf8(output.stderr).unwrap();
        assert!(
            !stderr.contains("Inspecting Cargo workspace"),
            "{arguments:?}"
        );
    }
}

#[test]
fn closed_configuration_rejects_scope_fields_before_git() {
    for document in ["scope = \"files\"\n", "base = \"main\"\n"] {
        let root = support::temporary_target("git-scope-closed-configuration", &NEXT_WORKSPACE);
        if root.exists() {
            fs::remove_dir_all(&root).unwrap();
        }
        support::copy_tree(&fixture(), &root);
        fs::write(root.join("rust-doctor.toml"), document).unwrap();
        fs::write(root.join(".git"), "gitdir: missing\n").unwrap();

        let report = inspect(InspectRequest::new(&root).with_files_scope("main"));
        assert_eq!(report.status, Status::Failed);
        assert_eq!(report.errors.len(), 1);
        assert_eq!(report.errors[0].stage, "configuration");
        assert_eq!(report.errors[0].code, "config-invalid");
        assert!(report.scope.is_none());
    }
}

#[test]
fn request_debug_never_contains_a_files_base() {
    for request in [
        InspectRequest::new(".").with_files_scope("credential-secret-ref"),
        InspectRequest::new(".").with_baseline_scope("credential-secret-ref"),
    ] {
        let debug = format!("{request:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("credential-secret-ref"));
    }
}