rust-llm-tidy-cli 0.2.2

CLI for reordering and linting Rust source code. Intended for LLM use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Integration tests for the `--validate` mode and config-driven
//! exclusions of `rust-llm-tidy`.
//!
//! Mirrors the helper pattern from `fix.rs`/`doc_check.rs` (`run_command`,
//! `manifest_dir`; `binary` lives in the shared `common` module). Each test
//! writes a temp config and/or fixture and runs the built CLI binary with
//! `--config <path>`. Existing tests use `--no-config` (see `fix.rs`), so the
//! repo-root sample config never interferes here.

use common::binary;
use std::fs;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};

mod common;

static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Default pipeline with `exclude: [reorder]` fixes/vis/lints but does
/// not reorder (the input is reordered on a normal run; under `reorder` being
/// disabled it must remain in input order).
#[test]
fn all_excludes_reorder_rule() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    // Two top-level fns in NON-canonical order (canonical is caller before
    // callee, per the reorder phase); here callee precedes caller so a normal
    // run would reorder them.
    fs::write(&tmp, "fn callee() {}\nfn caller() { callee(); }\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        "exclude:\n  - paths: [\"lib.rs\"]\n    rules: [\"reorder\"]\n",
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap()])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "pipeline should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    // Default pipeline runs fix/reorder/vis/lints. With `reorder` disabled, the
    // non-canonical input order (callee before caller) must be preserved.
    // Without the disable, it would reorder to caller-before-callee.
    let actual = fs::read_to_string(&tmp).unwrap();
    assert!(
        actual.find("fn callee()").unwrap() < actual.find("fn caller()").unwrap(),
        "reorder disabled: non-canonical callee-before-caller must be preserved"
    );
    let _ = fs::remove_dir_all(&dir);
}

// ── auto-discovery ──

/// Placing `.rust-llm-tidy.yml` in a temp dir with a `.git` marker and running
/// from a subdir discovers the config.
#[test]
fn auto_discovery_walks_up_to_git_root() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join(".git"), "gitdir: placeholder\n").unwrap();
    fs::create_dir_all(dir.join("src")).unwrap();
    fs::write(dir.join("src").join("lib.rs"), "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files:\n  - \"src/lib.rs\"\n").unwrap();

    let sub = dir.join("src");
    let output = Command::new(binary())
        .current_dir(&sub)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "--validate should discover the config by walking up to .git: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Default pipeline with `exclude: [DOC001]` suppresses DOC001 findings.
#[test]
fn check_excludes_doc001_rule() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    // An undocumented pub fn triggers DOC001 + DOC002 (Result with no Errors).
    fs::write(&tmp, "pub fn load() -> Result<(), String> { Ok(()) }\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        "exclude:\n  - paths: [\"lib.rs\"]\n    rules: [\"DOC001\"]\n",
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap()])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("DOC001"),
        "DOC001 must be suppressed by exclude: {stderr:?}"
    );
    // A non-disabled diagnostic (DOC002) must still be reported, proving
    // the filter is selective, not clearing all diagnostics.
    assert!(
        stderr.contains("DOC002"),
        "non-disabled DOC002 must still appear: {stderr:?}"
    );
    let _ = fs::remove_dir_all(&dir);
}

// ── flag exclusivity ──

/// `--config` and `--no-config` are mutually exclusive; supplying both
/// causes a non-zero exit (clap `conflicts_with` enforcement).
#[test]
fn config_and_no_config_are_mutually_exclusive() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files: []\n").unwrap();

    let output = Command::new(binary())
        .args([
            "--config",
            cfg.to_str().unwrap(),
            "--no-config",
            "--validate",
        ])
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--config and --no-config must be mutually exclusive"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// --exclude additive: even with no config, --exclude lints skips lint failure.
#[test]
fn exclude_flag_additive_skips_lints() {
    let dir = temp_dir();
    fs::create_dir(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn undocumented() {}\n").unwrap();
    let output = Command::new(binary())
        .args(["--no-config", "--exclude", "lints"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "--exclude lints must skip the lint pass: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Blacklist mode: exclude: [{rules: [lints]}] suppresses all lint failure.
#[test]
fn exclude_lints_op_suppresses_all_lint_failure() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    // DOC001 + DOC002 would both fire on a normal run.
    fs::write(&tmp, "pub fn load() -> Result<(), String> { Ok(()) }\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude:\n  - rules: [\"lints\"]\n").unwrap();
    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap()])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "lints op disabled -> run must succeed despite doc gaps: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// --exclude lints suppresses all lint codes, including specifically included ones.
#[test]
fn exclude_lints_overrides_included_lint_code() {
    let dir = temp_dir();
    fs::create_dir(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn undocumented() {}\n").unwrap();
    let output = Command::new(binary())
        .args(["--no-config", "--include", "DOC001", "--exclude", "lints"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "--exclude lints must suppress included DOC001: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!String::from_utf8_lossy(&output.stderr).contains("DOC001"));
    let _ = fs::remove_dir_all(&dir);
}

/// An excluded file is NOT post-processed.
#[test]
fn excluded_file_not_post_processed() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    // Exclude the file AND run a failing post_process on .rs files. Excluded
    // files are skipped, so post_process never sees the file -> exit 0.
    fs::write(
        &cfg,
        format!(
            "exclude_files:\n  - \"lib.rs\"\npost_process:\n  - {}\n    extensions: [\"rs\"]\n",
            post_process_command(1)
        ),
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "tables"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "excluded file must not be post-processed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Default pipeline with `exclude_files` for the fixture leaves the file unchanged.
#[test]
fn fix_exclude_skips_file() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("in.md");
    let original = "| a | b |\n|---|---|\n| 1 | 2 |\n";
    fs::write(&tmp, original).unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files:\n  - \"in.md\"\n").unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap()])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "default pipeline should succeed even when the file is excluded: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let actual = fs::read_to_string(&tmp).unwrap();
    assert_eq!(actual, original, "excluded file must be unchanged");
    let _ = fs::remove_dir_all(&dir);
}

// ── exclude + exclude_rules on pipeline operations ──

/// Bare default pipeline with `exclude: [links]` does NOT hoist links on a
/// file that needs link hoisting, while tables/fences are still applied.
#[test]
fn fix_excludes_links_rule() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("in.md");
    // A markdown table with multi-char cells that `fix_tables` would pad-align,
    // plus a repeated inline link that `fix_links` would hoist.
    fs::write(
        &tmp,
        "| Name | Value |\n| --- | --- |\n| a | 1 |\n| longname | 200 |\n\nsee [A](http://x) and [A](http://x)\n",
    )
    .unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        "exclude:\n  - paths: [\"in.md\"]\n    rules: [\"links\"]\n",
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--dry-run"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "default pipeline should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Dry-run reports change records on stderr, never reconstructed source.
    assert!(
        output.stdout.is_empty(),
        "dry-run must not print reconstructed source to stdout"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("hoist link"),
        "links must NOT be hoisted when `links` is disabled: {stderr:?}"
    );
    // Tables are still applied (the `links` disable is selective, not blanket).
    assert!(
        stderr.contains("tables were aligned"),
        "tables must still be applied when only `links` is disabled: {stderr:?}"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// --include / --exclude with an unknown op errors.
#[test]
fn flags_reject_unknown_op() {
    let dir = temp_dir();
    fs::create_dir(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let output = Command::new(binary())
        .args(["--no-config", "--include", "BOGUS"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(!output.status.success(), "--include BOGUS must error");

    let output = Command::new(binary())
        .args(["--no-config", "--exclude", "BOGUS"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(!output.status.success(), "--exclude BOGUS must error");
    let _ = fs::remove_dir_all(&dir);
}

/// --include + --exclude combine in whitelist mode: --include vis,lints then
/// --exclude lints yields enabled={vis}. vis narrows the inner fn, but lints
/// does NOT run, so the bare `pub fn f` that would trigger DOC001 stays clean.
#[test]
fn include_and_exclude_cli_combine_in_whitelist_mode() {
    let dir = temp_dir();
    fs::create_dir(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    // vis would narrow `pub fn f`; lints/DOC001 would normally flag it.
    fs::write(&tmp, "pub(crate) mod m {\n    pub fn f() {}\n}\n").unwrap();
    let output = Command::new(binary())
        .args([
            "--no-config",
            "--include",
            "vis",
            "--include",
            "lints",
            "--exclude",
            "lints",
        ])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "whitelist {{vis,lints}} - {{lints}} = {{vis}}: vis runs, lints skipped (no DOC001): {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let actual = fs::read_to_string(&tmp).unwrap();
    assert!(
        actual.contains("pub(crate) fn f"),
        "vis must still narrow despite --exclude lints: {actual}"
    );
    let _ = fs::remove_dir_all(&dir);
}

// ── New tests: include/exclude modes, --include/--exclude flags ──

/// include + exclude both present -> config-load error.
#[test]
fn include_and_exclude_xor_errors() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("lib.rs"), "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        "include:\n  - rules: [tables]\nexclude:\n  - rules: [reorder]\n",
    )
    .unwrap();
    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--validate"])
        .output()
        .expect("failed to spawn");
    assert!(
        !output.status.success(),
        "include + exclude must hard-fail at config load: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// --include override: only run `vis`, no lint failure on an undocumented fn.
#[test]
fn include_flag_overrides_config_mode() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    // Bare pub fn -> vis would narrow; lints would error (DOC001). --include vis
    // must override the default mode so lints does NOT run.
    fs::write(&tmp, "pub(crate) mod m {\n    pub fn f() {}\n}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    // Config is blacklist mode (lints on); --include must override it.
    fs::write(&cfg, "exclude:\n  - rules: [vis]\n").unwrap();
    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "vis"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "--include vis must override config and skip lints: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let actual = fs::read_to_string(&tmp).unwrap();
    assert!(
        actual.contains("pub(crate) fn f"),
        "vis must narrow: {actual}"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// --include lints with --exclude DOC001 keeps DOC001 disabled in whitelist mode.
#[test]
fn include_lints_exclude_lint_code() {
    let dir = temp_dir();
    fs::create_dir(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn undocumented() {}\n").unwrap();
    let output = Command::new(binary())
        .args(["--no-config", "--include", "lints", "--exclude", "DOC001"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "--exclude DOC001 must suppress DOC001 with --include lints: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!String::from_utf8_lossy(&output.stderr).contains("DOC001"));
    let _ = fs::remove_dir_all(&dir);
}

/// Whitelist a single lint code: the lint pass runs scoped to DOC001 only,
/// no other ops/lints run, and the file is unmutated.
#[test]
fn include_single_lint_code_runs_only_that_code() {
    let dir = temp_dir();
    fs::create_dir(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    // Undocumented Result-returning pub fn triggers DOC001 and DOC002.
    fs::write(&tmp, "pub fn load() -> Result<(), String> { Ok(()) }\n").unwrap();
    let output = Command::new(binary())
        .args(["--no-config", "--include", "DOC001"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !output.status.success(),
        "--include DOC001 must surface DOC001 diagnostics: {}",
        stderr
    );
    assert!(
        stderr.contains("DOC001"),
        "--include DOC001 must report DOC001: {stderr:?}"
    );
    assert!(
        !stderr.contains("DOC002"),
        "--include DOC001 must not report DOC002: {stderr:?}"
    );
    // No fix/reorder/vis in the whitelist -> file untouched.
    let actual = fs::read_to_string(&tmp).unwrap();
    assert_eq!(
        actual, "pub fn load() -> Result<(), String> { Ok(()) }\n",
        "file must be unmutated by the DOC001-only lint pass"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Whitelist mode: a file matching NO include group runs nothing.
#[test]
fn include_whitelist_runs_nothing_for_unmatched_file() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    // Sibling file under `other/` so the include pattern matches at least
    // one file (preserved semantic check); the target `lib.rs` is outside it.
    fs::create_dir_all(dir.join("other")).unwrap();
    fs::write(dir.join("other").join("lib.rs"), "fn matched() {}\n").unwrap();
    let tmp = dir.join("lib.rs");
    // Bare `pub` that vis would narrow and lints would flag - neither runs.
    fs::write(&tmp, "pub fn undocumented() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    // Whitelist: only run `vis, lints` (ops that would affect a .rs file),
    // and crucially NOT on this path.
    fs::write(
        &cfg,
        "include:\n  - paths: [\"other/**/*.rs\"]\n    rules: [vis, lints]\n",
    )
    .unwrap();
    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap()])
        .arg(&tmp)
        .output()
        .expect("failed to spawn");
    assert!(
        output.status.success(),
        "unmatched file in whitelist mode must run nothing (no lint failure): {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let actual = fs::read_to_string(&tmp).unwrap();
    assert_eq!(
        actual, "pub fn undocumented() {}\n",
        "file must be unchanged"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Patterns are resolved relative to the config file's directory (config
/// placed in a temp subdir).
#[test]
fn patterns_resolved_relative_to_config_dir() {
    let dir = temp_dir();
    let sub = dir.join("cfg-dir");
    fs::create_dir_all(&sub).unwrap();
    let src = dir.join("src");
    fs::create_dir_all(&src).unwrap();
    fs::write(src.join("lib.rs"), "pub fn example() {}\n").unwrap();

    // Config in `cfg-dir/`, but the excluded path is `../src/lib.rs` relative
    // to the config dir. The config dir is canonicalized, so the relative path
    // must resolve against it.
    let cfg = sub.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files:\n  - \"../src/lib.rs\"\n").unwrap();

    let validate = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--validate"])
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        validate.status.success(),
        "--validate should succeed when the pattern matches relative to the config dir: {}",
        String::from_utf8_lossy(&validate.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Return platform-specific command YAML for a command with requested exit code.
/// `true` and `false` are not available as standalone commands on Windows.
fn post_process_command(exit_code: u8) -> String {
    if cfg!(windows) {
        format!("command: \"cmd.exe\"\n    args: [\"/C\", \"exit\", \"{exit_code}\"]")
    } else {
        let command = if exit_code == 0 { "true" } else { "false" };
        format!("command: \"{command}\"")
    }
}

/// A failing `post_process` command causes a non-zero exit.
#[test]
fn post_process_failure_exits_nonzero() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        format!(
            "post_process:\n  - {}\n    extensions: [\"rs\"]\n",
            post_process_command(1)
        ),
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "tables"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "a failing post_process command must exit non-zero"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `post_process` does not run on `lints` (read-only).
#[test]
fn post_process_not_run_on_check() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        format!(
            "post_process:\n  - {}\n    extensions: [\"rs\"]\n",
            post_process_command(1)
        ),
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "lints"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    // `lints` is read-only and has no post-process pass, so `false` never runs
    // and the only possible failure is error-severity diagnostics.
    // We assert the binary did not fail *because of post_process* by checking
    // stderr has no "post_process" mention.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("post_process"),
        "lints must not invoke post_process: {stderr:?}"
    );
    let _ = fs::remove_dir_all(&dir);
}

// ── post_process ──

/// A successful `post_process` step on a .rs file runs and exits 0.
#[test]
fn post_process_runs_on_matching_extension() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        format!(
            "post_process:\n  - {}\n    extensions: [\"rs\"]\n",
            post_process_command(0)
        ),
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "tables"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "successful post_process should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--dry-run` skips `post_process` entirely (a failing command does not run).
#[test]
fn post_process_skipped_under_dry_run() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        format!(
            "post_process:\n  - {}\n    extensions: [\"rs\"]\n",
            post_process_command(1)
        ),
    )
    .unwrap();

    let output = Command::new(binary())
        .args([
            "--config",
            cfg.to_str().unwrap(),
            "--include",
            "tables",
            "--dry-run",
        ])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "--dry-run must skip post_process so `false` never runs"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `post_process` with `extensions: [\"md\"]` does NOT run on a .rs file (no
/// failure reported).
#[test]
fn post_process_skips_non_matching_extension() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    // A failing command would fail if invoked; restricting to .md means it must
    // not run.
    fs::write(
        &cfg,
        format!(
            "post_process:\n  - {}\n    extensions: [\"md\"]\n",
            post_process_command(1)
        ),
    )
    .unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "tables"])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "post_process must NOT run on a .rs file when extensions=[md]: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

/// A non-matching-path config hard-fails a regular command (non-zero exit, not
/// a warning).
#[test]
fn regular_command_hard_fails_on_non_matching_path() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let tmp = dir.join("lib.rs");
    fs::write(&tmp, "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files:\n  - \"missing/**\"\n").unwrap();

    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap()])
        .arg(&tmp)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "non-matching-path config must hard-fail, not warn"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--validate` exits non-zero when `links.min_occurrences` is below 1.
#[test]
fn validate_fails_on_links_min_occurrences_zero() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "links:\n  min_occurrences: 0\n").unwrap();

    let output = Command::new(binary())
        .arg("--config")
        .arg(&cfg)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--validate should fail on min_occurrences: 0"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--validate` exits non-zero on malformed YAML.
#[test]
fn validate_fails_on_malformed_yaml() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files: [unclosed\n").unwrap();

    let output = Command::new(binary())
        .arg("--config")
        .arg(&cfg)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--validate should fail on bad YAML"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--validate` exits non-zero when a pattern matches zero files.
#[test]
fn validate_fails_on_non_matching_path() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files:\n  - \"does/not/exist/**\"\n").unwrap();

    let output = Command::new(binary())
        .arg("--config")
        .arg(&cfg)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--validate should fail on a non-matching path"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--validate` exits non-zero on an unknown rule name.
#[test]
fn validate_fails_on_unknown_rule() {
    let dir = temp_dir();
    fs::create_dir_all(dir.join("src")).unwrap();
    fs::write(dir.join("src").join("lib.rs"), "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(
        &cfg,
        "exclude:\n  - paths: [\"src/**\"]\n    rules: [\"NOPE\"]\n",
    )
    .unwrap();

    let output = Command::new(binary())
        .arg("--config")
        .arg(&cfg)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--validate should fail on an unknown rule"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--validate` exits non-zero when no config file is found.
#[test]
fn validate_fails_when_no_config_found() {
    // Run --validate from a temp dir with no .rust-llm-tidy.yml and no .git, and
    // pass neither --config nor --no-config. discover walks to fs root without
    // finding a config and returns None, which `--validate` treats as failure.
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let output = Command::new(binary())
        .current_dir(&dir)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--validate should fail when no config is found"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// `--validate --no-config` exits non-zero because there is no config to
/// validate.
#[test]
fn validate_fails_with_no_config_flag() {
    let output = Command::new(binary())
        .args(["--no-config", "--validate"])
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        !output.status.success(),
        "--validate --no-config must exit non-zero"
    );
}

// ── --validate ──

/// `--validate` exits 0 on a syntactically valid config with at least one match
/// per pattern.
#[test]
fn validate_ok_on_valid_config() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    fs::create_dir_all(dir.join("src")).unwrap();
    fs::write(dir.join("src").join("lib.rs"), "pub fn example() {}\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "exclude_files:\n  - \"src/lib.rs\"\n").unwrap();

    let output = Command::new(binary())
        .arg("--config")
        .arg(&cfg)
        .arg("--validate")
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "--validate should exit 0 on a valid config: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let _ = fs::remove_dir_all(&dir);
}

// -- Helpers (mirrors fix.rs) -----------------------------------

/// Create a numbered temporary directory.
fn temp_dir() -> std::path::PathBuf {
    let seq = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    std::env::temp_dir().join(format!("rust-llm-tidy-cfg-dir-{}-{}", pid, seq))
}