rust-llm-tidy-cli 0.6.0

CLI for linting and tidying Rust, C#, and documentation source.
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
//! Integration tests for the `fix` subcommand of `rust-llm-tidy`.
//!
//! Mirrors the helper pattern from `doc_check/mod.rs` (`run_command`,
//! `manifest_dir`, `fixture_dir`; `binary` lives in the shared `common`
//! module). Each test runs the built CLI binary against fixture files in
//! `tests/fixtures/fix/`.

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

mod common;

/// The byte-exact output of the fix on [`INTRA_DOC_REPRO_SOURCE`]: every link
/// is hoisted and a `[text]: url` definition is duplicated inside each comment
/// that uses it, never at EOF, with a blank comment line before the
/// definitions.
const INTRA_DOC_REPRO_FIXED: &str = "\
/// Assembles the final value by driving [the Builder].
///
/// [the Builder]: crate::Builder
pub struct Builder;

impl Builder {
    /// Produces [the Config] and hands it to
    /// [the Builder].
    ///
    /// [the Config]: crate::Config
    /// [the Builder]: crate::Builder
    pub fn build(&self) -> Config {
        Config
    }

    /// Resets the builder before [the build].
    ///
    /// [the build]: Self::build
    pub fn reset(&mut self) {}
}

/// The assembled value; see [the Builder].
///
/// [the Builder]: crate::Builder
pub struct Config;
";
/// Reported multi-comment intra-doc repro (`Self::`/`crate::`-style links used
/// across several doc comments) with resolvable targets, so it is doc-build
/// clean both before and after the fix.
const INTRA_DOC_REPRO_SOURCE: &str = "\
/// Assembles the final value by driving [the Builder](crate::Builder).
pub struct Builder;

impl Builder {
    /// Produces [the Config](crate::Config) and hands it to
    /// [the Builder](crate::Builder).
    pub fn build(&self) -> Config {
        Config
    }

    /// Resets the builder before [the build](Self::build).
    pub fn reset(&mut self) {}
}

/// The assembled value; see [the Builder](crate::Builder).
pub struct Config;
";
static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Default all-pass `fix` on a file where only the table changes: the later
/// fence/link passes are no-ops and restore `prior`, so the earlier table fix
/// must survive and produce one record plus a byte-identical write.
#[test]
fn fix_default_passes_borrowed_restore_preserves_earlier_change() {
    let before = fixture_dir().join("table_md_before.md");
    let expected = fs::read_to_string(fixture_dir().join("table_md_after.md")).unwrap();
    let tmp = temp_file("md");
    fs::write(&tmp, fs::read_to_string(&before).unwrap()).unwrap();

    let output = run_command(&[], &tmp); // default: tables, fences, links
    assert!(
        output.status.success(),
        "default fix should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let actual = fs::read_to_string(&tmp).unwrap();
    let _ = fs::remove_file(&tmp);
    assert_eq!(
        actual, expected,
        "fences/links no-op restore must keep the table fix"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("success[FIX]").count(),
        1,
        "only the realigned table reports a record: {stderr}"
    );
}

/// `fix --dry-run` on `table_doc_comment_before.rs` reports a change record on
/// stderr and leaves stdout empty.
#[test]
fn fix_doc_comment_dry_run_reports_change() {
    let before = fixture_dir().join("table_doc_comment_before.rs");
    let output = run_command(&["--include", "tables", "--dry-run"], &before);

    assert!(
        output.status.success(),
        "fix --dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    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("success[FIX]"),
        "dry-run must report a fix change line on stderr: {stderr}"
    );
}

/// In-place `fix --include fences` on `fence_md_before.md` produces
/// `fence_md_after.md` byte-for-byte (the fences transform's content output).
#[test]
fn fix_fence_in_place_matches_after() {
    let expected = fs::read_to_string(fixture_dir().join("fence_md_after.md")).unwrap();
    let tmp = temp_file("md");
    fs::write(
        &tmp,
        fs::read_to_string(fixture_dir().join("fence_md_before.md")).unwrap(),
    )
    .unwrap();

    let output = run_command(&["--include", "fences"], &tmp);
    assert!(
        output.status.success(),
        "fence fix in-place should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let actual = fs::read_to_string(&tmp).unwrap();
    let _ = fs::remove_file(&tmp);
    assert_eq!(actual, expected, "fence fix must match fence_md_after.md");
}

/// `fix --dry-run` on `fence_md_before.md` reports a change record on stderr.
#[test]
fn fix_fence_md_dry_run_reports_change() {
    let before = fixture_dir().join("fence_md_before.md");
    let output = run_command(&["--include", "fences", "--dry-run"], &before);

    assert!(
        output.status.success(),
        "fix --dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    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("success[FIX]"),
        "dry-run must report a fix change line on stderr: {stderr}"
    );
}

/// Idempotency: running `fix --dry-run` on an `_after` fixture is a no-op with
/// zero change records.
#[test]
fn fix_idempotent_on_after_fixtures() {
    for name in ["table_md_after.md", "table_doc_comment_after.rs"] {
        let path = fixture_dir().join(name);
        let output = run_command(&["--include", "tables", "--dry-run"], &path);
        assert!(
            output.status.success(),
            "fix --dry-run on {name} should succeed"
        );
        assert!(
            output.stdout.is_empty(),
            "{name} dry-run must not print source to stdout"
        );
        assert!(
            output.stderr.is_empty(),
            "{name} is already tidy: dry-run must emit zero change records"
        );
    }
    // Fence fixture uses --include fences.
    {
        let path = fixture_dir().join("fence_md_after.md");
        let output = run_command(&["--include", "fences", "--dry-run"], &path);
        assert!(
            output.status.success(),
            "fix --dry-run on fence_md_after.md should succeed"
        );
        assert!(
            output.stdout.is_empty(),
            "fence_md_after.md dry-run must not print source to stdout"
        );
        assert!(
            output.stderr.is_empty(),
            "fence_md_after.md is already tidy: dry-run must emit zero change records"
        );
    }
}

/// An in-place fix run reports the same change records as its dry-run twin and
/// writes the file, so identical stderr change lines accompany a modified file.
#[test]
fn fix_in_place_reports_same_records_and_writes() {
    let before = fixture_dir().join("multi_md_before.md");
    let dry_run = run_command(&["--include", "tables", "--dry-run"], &before);
    let dry_stderr = String::from_utf8_lossy(&dry_run.stderr);

    let tmp = temp_file("md");
    fs::write(&tmp, fs::read_to_string(&before).unwrap()).unwrap();
    let output = run_command(&["--include", "tables"], &tmp);
    assert!(
        output.status.success(),
        "fix in-place should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let actual = fs::read_to_string(&tmp).unwrap();
    let _ = fs::remove_file(&tmp);

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("success[FIX]").count(),
        1,
        "in-place run reports the same record: {stderr}"
    );
    assert!(
        stderr.contains("tables were aligned"),
        "in-place change line matches dry-run: {stderr}"
    );
    assert_eq!(
        stderr.matches("success[FIX]").count(),
        dry_stderr.matches("success[FIX]").count(),
        "in-place reports the same change lines as its dry-run twin"
    );
    assert_ne!(
        actual,
        fs::read_to_string(&before).unwrap(),
        "in-place run must write the fixed file"
    );
}

/// In-place write: copy before.md to a temp file, run `fix`, assert content.
#[test]
fn fix_in_place_write() {
    let expected = fs::read_to_string(fixture_dir().join("table_md_after.md")).unwrap();
    let tmp = temp_file("md");
    fs::write(
        &tmp,
        fs::read_to_string(fixture_dir().join("table_md_before.md")).unwrap(),
    )
    .unwrap();

    let output = run_command(&["--include", "tables"], &tmp);
    assert!(
        output.status.success(),
        "fix in-place should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let actual = fs::read_to_string(&tmp).unwrap();
    let _ = fs::remove_file(&tmp);
    assert_eq!(actual, expected, "in-place file must match _after fixture");
}

/// In-place `fix` on a CRLF markdown file with a repeated inline link
/// preserves `\r\n` in the hoisted `[text]: url` definition. CRLF input is
/// built in-memory (committed fixtures would be git-normalized on checkout).
#[test]
fn fix_links_in_place_preserves_crlf() {
    let tmp = temp_file("md");
    let input = "see [A](http://x) and [A](http://x)\r\n";
    fs::write(&tmp, input).unwrap();

    let output = run_command(&["--include", "links"], &tmp);
    assert!(
        output.status.success(),
        "fix in-place should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let actual = fs::read_to_string(&tmp).unwrap();
    let _ = fs::remove_file(&tmp);

    // The hoisted definition must be present and use `\r\n`.
    assert!(
        actual.contains("[A]: http://x"),
        "definition hoisted: {actual:?}"
    );
    assert!(
        actual.contains("[A]: http://x\r\n"),
        "hoisted definition must end with CRLF: {actual:?}"
    );
    // No bare LF: every `\n` is part of `\r\n`.
    assert_eq!(
        actual.matches('\n').count(),
        actual.matches("\r\n").count(),
        "every newline must be CRLF after fix: {actual:?}"
    );
}

/// `fix --include links --dry-run` over a `.rs` file with intra-doc links in
/// several doc comments reports one link record per hoisted pair on stderr and
/// leaves the file untouched.
#[test]
fn fix_links_rs_dry_run_reports_intra_doc_records() {
    let tmp = temp_file("rs");
    fs::write(&tmp, INTRA_DOC_REPRO_SOURCE).unwrap();

    let output = run_command(&["--include", "links", "--dry-run"], &tmp);
    let _ = fs::remove_file(&tmp);
    assert!(
        output.status.success(),
        "fix --dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        output.stdout.is_empty(),
        "dry-run must not print reconstructed source to stdout"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("success[FIX]").count(),
        3,
        "one record per hoisted pair: {stderr}"
    );
    assert!(
        stderr.contains("`[the Builder](crate::Builder)` -> `[the Builder]`"),
        "Builder hoist reported: {stderr}"
    );
    assert!(
        stderr.contains("`[the Config](crate::Config)` -> `[the Config]`"),
        "Config hoist reported: {stderr}"
    );
    assert!(
        stderr.contains("`[the build](Self::build)` -> `[the build]`"),
        "Self:: build hoist reported: {stderr}"
    );
}

/// In-place `fix --include links` on the intra-doc repro produces the
/// byte-exact per-comment definitions: no definition is emitted at EOF or on a
/// non-doc-comment line.
#[test]
fn fix_links_rs_in_place_produces_per_comment_defs() {
    let tmp = temp_file("rs");
    fs::write(&tmp, INTRA_DOC_REPRO_SOURCE).unwrap();

    let output = run_command(&["--include", "links"], &tmp);
    assert!(
        output.status.success(),
        "fix in-place should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let actual = fs::read_to_string(&tmp).unwrap();
    let _ = fs::remove_file(&tmp);
    assert_eq!(
        actual, INTRA_DOC_REPRO_FIXED,
        "in-place output must match the per-comment reference form"
    );
}

/// A scratch crate embedding the intra-doc repro passes
/// `cargo doc --document-private-items` with `RUSTDOCFLAGS="-D warnings"` after
/// the fix, proving the per-comment rewritten output is doc-build clean.
#[test]
fn fix_links_rs_output_is_doc_build_clean() {
    let dir = temp_dir();
    let src = dir.join("src");
    fs::create_dir_all(&src).unwrap();
    fs::write(
        dir.join("Cargo.toml"),
        "[package]\nname = \"intradoc_repro\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
    )
    .unwrap();
    // Embed the fixed (post-op) output so the scratch crate documents the exact
    // bytes the fix produces.
    fs::write(src.join("lib.rs"), INTRA_DOC_REPRO_FIXED).unwrap();

    let output = Command::new("cargo")
        .current_dir(&dir)
        .env("RUSTDOCFLAGS", "-D warnings")
        .args(["doc", "--document-private-items"])
        .output()
        .unwrap_or_else(|e| panic!("failed to spawn cargo doc: {e}"));

    let _ = fs::remove_dir_all(&dir);
    assert!(
        output.status.success(),
        "cargo doc must be clean on the fixed output:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// `fix --dry-run` on `table_md_before.md` reports a change record on stderr
/// and leaves stdout empty.
#[test]
fn fix_md_dry_run_reports_change() {
    let before = fixture_dir().join("table_md_before.md");
    let output = run_command(&["--include", "tables", "--dry-run"], &before);

    assert!(
        output.status.success(),
        "fix --dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    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("success[FIX]"),
        "dry-run must report a fix change line on stderr: {stderr}"
    );
}

/// `fix --include tables --dry-run` on a fixture with two misaligned tables
/// reports one per-file record, not one per table.
#[test]
fn fix_multi_entity_dry_run_reports_one_record_per_file() {
    let before = fixture_dir().join("multi_md_before.md");
    let output = run_command(&["--include", "tables", "--dry-run"], &before);

    assert!(
        output.status.success(),
        "fix --dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        output.stdout.is_empty(),
        "dry-run must not print reconstructed source to stdout"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("success[FIX]").count(),
        1,
        "one record for the whole file: {stderr}"
    );
    assert!(
        stderr.contains("tables were aligned"),
        "record covers both tables with no line: {stderr}"
    );
}

/// A non-existent path is rejected.
#[test]
fn fix_nonexistent_path_fails() {
    let nonexistent = std::env::temp_dir().join(format!(
        "rust-llm-tidy-fix-missing-{}-{}.md",
        std::process::id(),
        TEST_COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    let output = run_command(&["--include", "tables"], &nonexistent);
    assert!(
        !output.status.success(),
        "non-existent path should exit non-zero"
    );
}

// -- Helpers (mirrors doc_check/mod.rs) -------------------------------

/// Recursive directory: `fix` collects both `.rs` and `.md` files.
#[test]
fn fix_recursive_directory_collects_md_and_rs() {
    let dir = temp_dir();
    let sub = dir.join("sub");
    fs::create_dir_all(&sub).unwrap();

    fs::write(
        dir.join("readme.md"),
        fs::read_to_string(fixture_dir().join("table_md_before.md")).unwrap(),
    )
    .unwrap();
    fs::write(
        sub.join("code.rs"),
        fs::read_to_string(fixture_dir().join("table_doc_comment_before.rs")).unwrap(),
    )
    .unwrap();

    let output = run_command(&["--include", "tables"], &dir);
    assert!(
        output.status.success(),
        "fix directory should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let md_expected = fs::read_to_string(fixture_dir().join("table_md_after.md")).unwrap();
    let rs_expected = fs::read_to_string(fixture_dir().join("table_doc_comment_after.rs")).unwrap();

    assert_eq!(
        fs::read_to_string(dir.join("readme.md")).unwrap(),
        md_expected,
        ".md file should be fixed"
    );
    assert_eq!(
        fs::read_to_string(sub.join("code.rs")).unwrap(),
        rs_expected,
        ".rs file should be fixed"
    );

    let _ = fs::remove_dir_all(&dir);
}

/// A JavaScript indexed call `items[i](count)` reads like an inline link but
/// is call syntax: even an explicit `--include links` leaves the file
/// byte-unchanged with zero records.
#[test]
fn js_indexed_call_stays_unchanged_even_with_links_included() {
    let original =
        fs::read_to_string(fixture_dir().join("links_js_indexed_call_untouched.js")).unwrap();
    let arg_sets: [&[&str]; 2] = [&[], &["--include", "links"]];

    for args in arg_sets {
        let tmp = temp_file("js");
        fs::write(&tmp, &original).unwrap();

        let output = run_command(args, &tmp);
        assert!(
            output.status.success(),
            "run with {args:?} should succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            fs::read_to_string(&tmp).unwrap(),
            original,
            "indexed calls must stay byte-unchanged under {args:?}"
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            !stderr.contains("success["),
            "the links op must not rewrite call syntax: {stderr}"
        );
        let _ = fs::remove_file(&tmp);
    }
}

/// With `links.by_extension: { rs: 2 }`, a single-use doc-comment link in a
/// `.rs` file is below the threshold: it stays byte-unchanged with no link
/// record (dry-run), while a `.md` file at the default threshold 1 hoists.
#[test]
fn links_by_extension_rs_two_leaves_single_use_rs_unchanged() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let rs = dir.join("lib.rs");
    let rs_source = "/// see [A](http://x) once\npub fn f() {}\n";
    fs::write(&rs, rs_source).unwrap();
    let md = dir.join("doc.md");
    fs::write(&md, "only [A](http://x) once\n").unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "links:\n  by_extension:\n    rs: 2\n").unwrap();

    // The .rs single use is below the rs threshold of 2: no record, unchanged.
    let output = Command::new(binary())
        .args([
            "--config",
            cfg.to_str().unwrap(),
            "--include",
            "links",
            "--dry-run",
        ])
        .arg(&rs)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("`[A](http://x)` -> `[A]`"),
        "single-use .rs link below threshold must not hoist: {stderr:?}"
    );
    assert_eq!(
        fs::read_to_string(&rs).unwrap(),
        rs_source,
        "single-use .rs file must stay byte-unchanged"
    );

    // The .md file has no rs override, so the default threshold 1 applies and
    // hoists the single use with a trailing definition.
    let output = Command::new(binary())
        .args(["--config", cfg.to_str().unwrap(), "--include", "links"])
        .arg(&md)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "md in-place should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        fs::read_to_string(&md).unwrap(),
        "only [A] once\n\n[A]: http://x\n",
        ".md at threshold 1 must hoist the single use"
    );

    let _ = fs::remove_dir_all(&dir);
}

/// A global `links.min_occurrences: 2` suppresses a single-use `.rs` link.
#[test]
fn links_global_min_two_suppresses_single_use_rs() {
    let dir = temp_dir();
    fs::create_dir_all(&dir).unwrap();
    let rs = dir.join("lib.rs");
    let rs_source = "/// see [A](http://x) once\npub fn f() {}\n";
    fs::write(&rs, rs_source).unwrap();
    let cfg = dir.join(".rust-llm-tidy.yml");
    fs::write(&cfg, "links:\n  min_occurrences: 2\n").unwrap();

    let output = Command::new(binary())
        .args([
            "--config",
            cfg.to_str().unwrap(),
            "--include",
            "links",
            "--dry-run",
        ])
        .arg(&rs)
        .output()
        .expect("failed to spawn rust-llm-tidy");
    assert!(
        output.status.success(),
        "dry-run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("`[A](http://x)` -> `[A]`"),
        "single-use .rs link below threshold 2 must not hoist: {stderr:?}"
    );
    assert_eq!(
        fs::read_to_string(&rs).unwrap(),
        rs_source,
        "single-use .rs file must stay byte-unchanged under min_occurrences: 2"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Pipe-bearing lines that never form a GFM table stay byte-unchanged under
/// the default run: Haskell guard runs, SQL `||` concatenation, and Lua
/// comment notes without a delimiter row.
#[test]
fn non_table_pipe_lines_stay_byte_unchanged() {
    for name in [
        "table_hs_guards_untouched.hs",
        "table_sql_concat_untouched.sql",
        "table_lua_dash_notes_untouched.lua",
    ] {
        let ext = name.rsplit_once('.').unwrap().1;
        let original = fs::read_to_string(fixture_dir().join(name)).unwrap();
        let tmp = temp_file(ext);
        fs::write(&tmp, &original).unwrap();

        let output = run_command(&[], &tmp);
        let after = fs::read_to_string(&tmp).unwrap();
        let stderr = String::from_utf8_lossy(&output.stderr);
        let _ = fs::remove_file(&tmp);
        assert!(
            output.status.success(),
            "{name}: default run should succeed: {stderr}"
        );
        assert_eq!(
            after, original,
            "{name}: non-table pipe lines must stay byte-unchanged"
        );
        assert!(
            !stderr.contains("success["),
            "{name}: a non-table file must report zero change records: {stderr}"
        );
    }
}

// ── Per-language table fixtures ────────────────────────────────────

/// One before/after pair per comment-prefix family, the C# `///`/`//`
/// profile, and a markdown-family `.txt`: the default run realigns each
/// table with its marker and indent kept, reports one record, and a second
/// run emits zero records.
#[test]
fn table_fixtures_realign_with_marker_and_indent_kept() {
    let pairs = [
        (
            "table_slash_comment_before.go",
            "table_slash_comment_after.go",
        ),
        (
            "table_xml_doc_comment_before.cs",
            "table_xml_doc_comment_after.cs",
        ),
        (
            "table_hash_comment_before.py",
            "table_hash_comment_after.py",
        ),
        (
            "table_dash_comment_before.sql",
            "table_dash_comment_after.sql",
        ),
        (
            "table_semi_comment_before.el",
            "table_semi_comment_after.el",
        ),
        (
            "table_percent_comment_before.tex",
            "table_percent_comment_after.tex",
        ),
        // Markdown-family sibling: full default ops, `.md`-identical bytes.
        ("table_txt_before.txt", "table_txt_after.txt"),
    ];

    for (before_name, after_name) in pairs {
        let ext = before_name.rsplit_once('.').unwrap().1;
        let expected = fs::read_to_string(fixture_dir().join(after_name)).unwrap();
        let tmp = temp_file(ext);
        fs::write(
            &tmp,
            fs::read_to_string(fixture_dir().join(before_name)).unwrap(),
        )
        .unwrap();

        let output = run_command(&[], &tmp);
        assert!(
            output.status.success(),
            "{before_name}: default run should succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            fs::read_to_string(&tmp).unwrap(),
            expected,
            "{before_name}: default run must produce {after_name} byte-for-byte"
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(
            stderr.matches("success[FIX]").count(),
            1,
            "{before_name}: only the realigned table reports a record: {stderr}"
        );

        let second = run_command(&["--include", "tables", "--dry-run"], &tmp);
        let _ = fs::remove_file(&tmp);
        assert!(
            second.status.success(),
            "{before_name}: second run should succeed"
        );
        assert!(
            String::from_utf8_lossy(&second.stderr).is_empty(),
            "{before_name}: second run must emit zero change records"
        );
    }
}

/// A GFM table inside a Python string literal is re-padded by the default
/// run: a whitespace-only change inside the literal (the words and the
/// quotes stay identical), one record, and a second run is a no-op.
#[test]
fn table_inside_a_python_string_literal_is_repadded() {
    let expected = fs::read_to_string(fixture_dir().join("table_string_literal_after.py")).unwrap();
    let tmp = temp_file("py");
    fs::write(
        &tmp,
        fs::read_to_string(fixture_dir().join("table_string_literal_before.py")).unwrap(),
    )
    .unwrap();

    let output = run_command(&[], &tmp);
    assert!(
        output.status.success(),
        "default run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        fs::read_to_string(&tmp).unwrap(),
        expected,
        "the string-embedded table must be re-padded to the after fixture"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("success[FIX]").count(),
        1,
        "exactly the re-padded table reports a record: {stderr}"
    );

    let second = run_command(&["--include", "tables", "--dry-run"], &tmp);
    let _ = fs::remove_file(&tmp);
    assert!(
        second.status.success(),
        "second run on the re-padded file should succeed"
    );
    assert!(
        String::from_utf8_lossy(&second.stderr).is_empty(),
        "second run must emit zero change records"
    );
}

/// The directory holding `fix` fixtures.
fn fixture_dir() -> std::path::PathBuf {
    manifest_dir().join("tests").join("fixtures").join("fix")
}

/// Build `rust-llm-tidy <args> <path>` and run it, returning captured output.
fn run_command(args: &[&str], path: &std::path::Path) -> std::process::Output {
    let mut cmd = Command::new(binary());
    cmd.args(["--no-config"]).args(args).arg(path);
    cmd.output()
        .unwrap_or_else(|e| panic!("failed to spawn rust-llm-tidy on {}: {e}", path.display()))
}

/// 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-fix-dir-{}-{}", pid, seq))
}

/// Create a numbered temporary file path.
fn temp_file(ext: &str) -> 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-fix-{}-{}.{}", pid, seq, ext))
}

/// Return `CARGO_MANIFEST_DIR` for resolving fixture paths.
fn manifest_dir() -> std::path::PathBuf {
    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}