srgn 0.14.2

A grep-like tool which understands source code syntax and allows for manipulation in addition to search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
//! End-to-end tests for the CLI. Main purpose is exercising multiple combinations of
//! inputs/flags/options.

#[cfg(test)]
#[cfg(feature = "all")]
mod tests {
    use std::collections::VecDeque;
    use std::path::{Path, PathBuf};

    use anyhow::Context;
    use assert_cmd::Command;
    use assert_cmd::cargo::cargo_bin_cmd;
    use insta::with_settings;
    use itertools::Itertools;
    use rstest::rstest;
    use serde::Serialize;
    use tempfile::TempDir;

    #[derive(Debug, Serialize)]
    struct CommandSnap {
        args: Vec<String>,
        stdin: Option<Vec<String>>,
        stdout: Vec<String>,
        exit_code: i32, // `u8` would make sense but this is what the library returns 🤷‍♀️
    }

    #[derive(Debug, Serialize)]
    struct CommandInfo {
        stderr: Vec<String>,
    }

    impl CommandInfo {
        pub fn new(stderr: &str) -> Self {
            Self {
                stderr: stderr
                    .lines()
                    .filter(|l| !l.starts_with('[')) // Normal log lines
                    .map(ToOwned::to_owned)
                    .collect(),
            }
        }
    }

    #[rstest]
    #[case(
        "baseline-replacement",
        false,
        &[
            "A",
            "--",
            "B",
        ],
        Some(r"A;  B 😫"),
    )]
    #[case(
        "baseline-replacement-no-stdin",
        false,
        &[
            "A",
            "--",
            "B",
        ],
        None,
    )]
    #[case(
        "baseline-regex-replacement",
        false,
        &[
            r"\W",
            "--",
            "B",
        ],
        Some(r"A;  B 😫"),
    )]
    #[case(
        "german-symbols",
        false,
        &[
            "--german",
            "--symbols",
        ],
        Some(r"Duebel -> 1.5mm;  Wand != 3m²... UEBELTAETER! 😫"),
    )]
    #[case(
        "german-text",
        false,
        &[
            "--german",
        ],
        Some(r#"Zwei flinke Boxer jagen die quirlige Eva und ihren Mops durch Sylt.
Franz jagt im komplett verwahrlosten Taxi quer durch Bayern.
Zwoelf Boxkaempfer jagen Viktor quer ueber den grossen Sylter Deich.
Vogel Quax zwickt Johnys Pferd Bim.
Sylvia wagt quick den Jux bei Pforzheim.
Polyfon zwitschernd assen Maexchens Voegel Rueben, Joghurt und Quark.
"Fix, Schwyz!" quaekt Juergen bloed vom Pass.
Victor jagt zwoelf Boxkaempfer quer ueber den grossen Sylter Deich.
Falsches Ueben von Xylophonmusik quaelt jeden groesseren Zwerg.
Heizoelrueckstossabdaempfung.
"#),
    )]
    #[case(
        "deleting-emojis",
        false,
        &[
            "--delete",
            r"\p{Emoji_Presentation}",
        ],
        Some("Some text  :) :-) and emojis 🤩!\nMore: 👽"),
    )]
    #[case(
        "failing-on-anything-found-trigger",
        false,
        &[
            "--fail-any",
            "X",
        ],
        Some("XYZ"),
    )]
    #[case(
        "failing-on-anything-found-no-trigger",
        false,
        &[
            "--fail-any",
            "A",
        ],
        Some("XYZ"),
    )]
    #[case(
        "failing-on-nothing-found-trigger",
        false,
        &[
            "--fail-none",
            "A",
        ],
        Some("XYZ"),
    )]
    #[case(
        "failing-on-nothing-found-no-trigger",
        false,
        &[
            "--fail-none",
            "X",
        ],
        Some("XYZ"),
    )]
    #[case(
        "go-search",
        false,
        &[
            "--go",
            "comments",
            "[fF]izz",
        ],
        Some(include_str!("langs/go/fizzbuzz.go")),
    )]
    #[case(
        "go-replacement",
        false,
        &[
            "--go",
            "comments",
            "[fF]izz",
            "--",
            "🤡",
        ],
        Some(include_str!("langs/go/fizzbuzz.go")),
    )]
    #[case(
        "go-search-files",
        true, // Prints different file paths! (but thanks to `autocrlf = false` has identical line endings)
        &[
            "--sorted", // Need determinism
            "--go",
            "comments",
            "[fF]izz",
        ],
        None,
    )]
    #[case(
        "python-search-files", // searches all files, in all Python strings
        true, // Prints different file paths! (but thanks to `autocrlf = false` has identical line endings)
        &[
            "--sorted", // Need determinism
            "--python",
            "strings",
            "is",
        ],
        None,
    )]
    #[case(
        "python-search-stdin", // stdin takes precedence
        false,
        &[
            "--python",
            "strings",
            "is",
        ],
        Some(include_str!("langs/python/base.py")),
    )]
    #[case(
        "python-search-stdin-and-files", // stdin takes precedence
        false,
        &[
            "--python",
            "strings",
            "--glob",
            "**/*.py",
            "is",
        ],
        Some(include_str!("langs/python/base.py")),
    )]
    #[case(
        "python-search-stdin-across-lines",
        false,
        &[
            "--python",
            "class",
            r"(?s)@classmethod\n\s+def class_method", // ?s: include newline
        ],
        Some(include_str!("langs/python/base.py")),
    )]
    #[case(
        "python-multiple-scopes",
        false,
        &[
            "--python",
            "def",
            "--python",
            "strings",
            "A",
        ],
        Some("# A comment\nx = \"A string\"\ndef A(): return \"A string in a func\"\nclass A: pass"),
    )]
    //
    // Set up baseline for subsequent tests
    #[case(
        "only-matching-baseline-outside-search-mode",
        false,
        &[
            "A",
            "--",
            "X",
        ],
        Some("A\nB"),
    )]
    #[case(
        "only-matching-outside-search-mode",
        false,
        &[
            "--only-matching",
            "A",
            "--",
            "X",
        ],
        Some("A\nB"),
    )]
    #[case(
        "line-numbers-outside-search-mode",
        false,
        &[
            "--line-numbers",
            "A",
            "--",
            "X",
        ],
        Some("A\nB"),
    )]
    #[case(
        "only-matching-and-line-numbers-outside-search-mode",
        false,
        &[
            "--only-matching",
            "--line-numbers",
            "A",
            "--",
            "X",
        ],
        Some("A\nB"),
    )]
    // Taking no action etc., but sure enough prints line numbers...
    #[case(
        "only-matching-and-line-numbers-no-actions-outside-search-mode",
        false,
        &[
            "--only-matching",
            "--line-numbers",
        ],
        Some("A\nB"),
    )]
    fn test_cli(
        #[case] mut snapshot_name: String,
        #[case] os_dependent: bool,
        #[case] args: &[&str],
        #[case] stdin: Option<&str>,
    ) {
        if os_dependent {
            // Thanks to Windows, (some) snapshots are actually OS-dependent if they
            // involve file system paths :( Careful: `cargo insta test
            // --unreferenced=delete` will wipe snapshot of foreign OSes, but that'll
            // break in CI!
            snapshot_name.push('-');
            snapshot_name.push_str(std::env::consts::OS);
        }

        // Should rebuild the binary to `target/debug/<name>`. This works if running as
        // an integration test (insides `tests/`), but not if running as a unit test
        // (inside `src/main.rs` etc.).
        let mut cmd = get_cmd();

        let mut args: VecDeque<String> = args.iter().map(|&s| s.to_owned()).collect();

        // Be deterministic for testing purposes. We have to push this awkwardly, to not
        // override any potential positional arguments at the end.
        args.push_front("1".into());
        args.push_front("--threads".into());

        if let Some(stdin) = stdin {
            cmd.write_stdin(stdin);
        } else {
            // Override; `Command` is detected as providing stdin but we're working on
            // files here.
            args.push_front("force-unreadable".into());
            args.push_front("--stdin-detection".into());
        }

        cmd.args(args.clone());

        let output = cmd.output().expect("failed to execute process");

        let exit_code = output
            .status
            .code()
            .expect("Process unexpectedly terminated via signal, not `exit`.");
        let stdout = String::from_utf8(output.stdout).unwrap();
        let stderr = String::from_utf8(output.stderr).unwrap();

        // For debugging, include this, but do not rely on it for snapshot
        // validity/correctness. We do not want changes in error messages etc. break
        // tests, seems excessive.
        let info = CommandInfo::new(&stderr);

        with_settings!({
            info => &info,
        }, {
            insta::assert_yaml_snapshot!(
                snapshot_name,
                CommandSnap {
                    args: args.into(),
                    stdin: stdin.map(|s| s.split_inclusive('\n').map(ToOwned::to_owned).collect_vec()),
                    stdout: stdout.split_inclusive('\n').map(ToOwned::to_owned).collect_vec(),
                    exit_code,
                }
            );
        });
    }

    #[rstest]
    #[case::files_inplace_python(
        "files-inplace-python",
        "tests/files/files-python/in",
        &[
            "-vvvv", // Trigger logging lines, just for more coverage
            "--sorted",
            "--glob",
            "**/*.py",
            "foo",
            "--",
            "baz"
        ],
        false,
    )]
    #[case::language_scoping_inplace_python(
        "language-scoping-inplace-python",
        "tests/files/language-scoping-python/in",
        &[
            "-vvvv", // Trigger logging lines, just for more coverage
            "--sorted",
            "--python",
            "function-names",
            "foo",
            "--",
            "baz"
        ],
        false,
    )]
    #[case::language_scoping_and_files_inplace_python(
        "language-scoping-and-files-inplace-python",
        "tests/files/language-scoping-and-files-python/in",
        &[
            "-vvvv", // Trigger logging lines, just for more coverage
            "--sorted",
            "--python",
            "function-names",
            "--glob", // Will override language scoper
            "subdir/**/*.py",
            "foo",
            "--",
            "baz"
        ],
        false,
    )]
    #[case::language_scoping_and_files_inplace_python(
        "language-scoping-and-files-inplace-python",
        "tests/files/language-scoping-and-files-python/in",
        &[
            "-vvvv", // Trigger logging lines, just for more coverage
            "--python",
            "function-names",
            "--glob", // Will override language scoper
            "subdir/**/*.py",
            "foo",
            "--",
            "baz"
        ],
        // NOT `--sorted`, so not deterministic; use to test that directories are
        // equivalent even if running parallel, unsorted. Output will be random,
        // breaking snapshot testing.
        true,
    )]
    #[case::binary_data_sorted(
        "binary-data-sorted",
        "tests/files/binary-data/in",
        &[
            "-vvvv", // Trigger logging lines, just for more coverage
            "--sorted",
            "--glob",
            "**/*",
            "0a1a09c8-2995-4ac5-9d60-01a0f02920e8",
            "--",
            "gone"
        ],
        false,
    )]
    #[case::binary_data_unsorted(
        "binary-data-sorted",
        "tests/files/binary-data/in",
        &[
            "-vvvv", // Trigger logging lines, just for more coverage
            "--glob",
            "**/*",
            "0a1a09c8-2995-4ac5-9d60-01a0f02920e8",
            "--",
            "gone"
        ],
        // NOT `--sorted`, so not deterministic; use to test that directories are
        // equivalent even if running parallel, unsorted. Output will be random,
        // breaking snapshot testing.
        true,
    )]
    fn test_cli_files(
        #[case] mut snapshot_name: String,
        #[case] input: PathBuf,
        #[case] args: &[&str],
        #[case] skip_output_check: bool,
        #[values(true, false)] dry_run: bool, // Check all permutations for all inputs
    ) -> anyhow::Result<()> {
        let args = args.iter().map(ToString::to_string).collect_vec();

        // Arrange
        let mut cmd = get_cmd();

        let baseline = if dry_run {
            // Stays the same! In dry runs, we compare against the very same directory,
            // as it should not change.
            input.clone()
        } else {
            let mut baseline = input.clone();
            baseline.pop();
            baseline.push("out");
            baseline
        };

        let candidate = copy_to_tmp(&input);
        drop(input); // Prevent misuse

        cmd.current_dir(&candidate);
        cmd.args(
            // Override; `Command` is detected as providing stdin but we're working on
            // files here.
            ["--stdin-detection", "force-unreadable"],
        );
        if dry_run {
            cmd.arg("--dry-run");
        }
        cmd.args(&args);

        // Act
        let output = cmd.output().expect("failed to execute binary under test");

        // Assert

        // Thing itself works
        output.status.success().then_some(()).ok_or_else(|| {
            anyhow::anyhow!(
                "Binary execution itself failed: {}",
                String::from_utf8_lossy(&output.stderr).escape_debug()
            )
        })?;

        // Do not drop on panic, to keep tmpdir in place for manual inspection. Can then
        // diff directories.
        check_directories_equality(baseline, candidate.path().to_owned())?;

        // Test was successful: ok to drop. Caveat: fails test if deletion fails, which
        // is unwarranted coupling?
        candidate.close()?;

        // Let's look at command output now.
        if !skip_output_check {
            if dry_run {
                snapshot_name.push_str("-dry-run");
            }

            // These are inherently platform-specific, as they deal with file paths.
            snapshot_name.push('-');
            snapshot_name.push_str(std::env::consts::OS);

            let exit_code = output
                .status
                .code()
                .expect("Process unexpectedly terminated via signal, not `exit`.");
            let stdout = String::from_utf8(output.stdout).unwrap();
            let stderr = String::from_utf8(output.stderr).unwrap();

            let info = CommandInfo::new(&stderr);

            with_settings!({
                info => &info,
            }, {
                insta::assert_yaml_snapshot!(
                    snapshot_name,
                    CommandSnap {
                        args,
                        stdin: None,
                        stdout: stdout.split_inclusive('\n').map(ToOwned::to_owned).collect_vec(),
                        exit_code,
                    }
                );
            });
        }

        Ok(())
    }

    /// Tests various *expected* failure modes.
    #[rstest]
    //
    // stdin
    #[case(
        "fail-none-implicitly-in-search-mode-stdin",
        Some(r#"x = "y""#),
        &[
            "--python",
            "strings",
            "z",
        ],
        None,
    )]
    #[case(
        "fail-none-explicitly-in-search-mode-stdin",
        Some(r#"x = "y""#),
        &[
            "--fail-none",
            "--python",
            "strings",
            "z",
        ],
        None,
    )]
    #[case(
        "fail-any-in-search-mode-stdin",
        Some(r#"x = "y""#),
        &[
            "--fail-any",
            "--python",
            "strings",
            "y",
        ],
        None,
    )]
    //
    // Multiple files, sorted
    #[case(
        "fail-none-implicitly-in-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--python",
            "strings",
            "unfindable-string-dheuihiuhiulerfiuehrilufhiusdho438ryh9vuoih",
        ],
        None,
    )]
    #[case(
        "fail-none-explicitly-in-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--fail-none",
            "--python",
            "strings",
            "unfindable-string-dheuihiuhiulerfiuehrilufhiusdho438ryh9vuoih",
        ],
        None,
    )]
    #[case(
        "fail-none-explicitly-outside-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--fail-none",
            "--glob",
            "**/*.py",
            "unfindable-string-dheuihiuhiulerfiuehrilufhiusdho438ryh9vuoih",
        ],
        None,
    )]
    #[case(
        "fail-any-in-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--fail-any",
            "--python",
            "strings",
            r".",
        ],
        None,
    )]
    #[case(
        "fail-any-outside-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--fail-any",
            "--glob",
            "**/*.py",
            r".",
        ],
        None,
    )]
    #[case(
        "fail-no-files-in-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--fail-no-files",
            "--python",
            "strings",
            r".",
        ],
        Some(Path::new("tests/langs/go")), // No Python files here...
    )]
    #[case(
        "fail-no-files-outside-search-mode-sorted",
        None,
        &[
            "--sorted",
            "--fail-no-files",
            "--glob",
            "**/*.there-is-no-such-suffix",
            r".",
        ],
        None,
    )]
    //
    // Multiple files, not sorted aka multi-threaded
    #[case(
        "fail-none-implicitly-in-search-mode-multithreaded",
        None,
        &[
            "--python",
            "strings",
            "unfindable-string-dheuihiuhiulerfiuehrilufhiusdho438ryh9vuoih",
        ],
        None,
    )]
    #[case(
        "fail-none-explicitly-in-search-mode-multithreaded",
        None,
        &[
            "--fail-none",
            "--python",
            "strings",
            "unfindable-string-dheuihiuhiulerfiuehrilufhiusdho438ryh9vuoih",
        ],
        None,
    )]
    #[case(
        "fail-none-explicitly-outside-search-mode-multithreaded",
        None,
        &[
            "--fail-none",
            "--glob",
            "**/*.py",
            "unfindable-string-dheuihiuhiulerfiuehrilufhiusdho438ryh9vuoih",
        ],
        None,
    )]
    #[case(
        "fail-any-in-search-mode-multithreaded",
        None,
        &[
            "--fail-any",
            "--python",
            "strings",
            r".",
        ],
        None,
    )]
    #[case(
        "fail-any-outside-search-mode-multithreaded",
        None,
        &[
            "--fail-any",
            "--glob",
            "**/*.py",
            r".",
        ],
        None,
    )]
    #[case(
        "fail-no-files-in-search-mode-multithreaded",
        None,
        &[
            "--fail-no-files",
            "--python",
            "strings",
            r".",
        ],
        Some(Path::new("tests/langs/go")), // No Python files here...
    )]
    #[case(
        "fail-no-files-outside-search-mode-multithreaded",
        None,
        &[
            "--fail-no-files",
            "--glob",
            "**/*.there-is-no-such-suffix",
            r".",
        ],
        None,
    )]
    //
    //
    #[case(
        "fail-multiple-languages",
        None,
        &[
            // This should be stopped very early on, in CLI entry
            "--python",
            "strings",
            "--go",
            "strings",
        ],
        None,
    )]
    #[case(
        "go-ignores-vendor-directory",
        None,
        &[
            "--go",
            "comments",
        ],
        Some(Path::new("tests/langs/go/vendor-dir-test/")), // Contains vendor dir
    )]
    #[case(
        // tree-sitter regular expressions do not support `fancy_regex` features such as
        // lookaheads. This is validated during CLI arg parsing time, instead of failing
        // much later at runtime in the tree-sitter library, at which we point we lose
        // rich error messages.
        "tree-sitter-invalid-regex-validated-at-parse-time",
        None,
        &[
            "--rust",
            "struct~(?<=Foo)Bar",
        ],
        None,
    )]
    #[case(
        // Some grammar elements/node types do not support "namedness" - they are
        // anonymous. This should be caught and rejected at parse time.
        "unsupported-named-entities-validated-at-parse-time",
        None,
        &[
            "--rust",
            "comments~InherentlyHaveNoNames",
        ],
        None,
    )]
    fn test_cli_failure_modes(
        #[case] snapshot_name: String,
        #[case] stdin: Option<&str>,
        #[case] args: &[&str],
        #[case] cwd: Option<&Path>,
    ) {
        let args = args.iter().map(ToString::to_string).collect_vec();

        // Arrange
        let mut cmd = get_cmd();

        if let Some(stdin) = stdin {
            cmd.write_stdin(stdin);
        } else {
            cmd.args(
                // Override; `Command` is detected as providing stdin but we're working on
                // files here.
                ["--stdin-detection", "force-unreadable"],
            );
        }
        cmd.args(&args);

        if let Some(cwd) = cwd {
            cmd.current_dir(cwd);
        }

        // Act
        let output = cmd.output().expect("failed to execute binary under test");

        // Assert
        let exit_code = output
            .status
            .code()
            .expect("Process unexpectedly terminated via signal, not `exit`.");
        let stdout = String::from_utf8(output.stdout).unwrap();
        let stderr = String::from_utf8(output.stderr).unwrap();

        let info = CommandInfo::new(&stderr);

        with_settings!({
            info => &info,
        }, {
            insta::assert_yaml_snapshot!(
                snapshot_name,
                CommandSnap {
                    args,
                    stdin: None,
                    stdout: stdout.split_inclusive('\n').map(ToOwned::to_owned).collect_vec(),
                    exit_code,
                }
            );
        });
    }

    #[test]
    fn test_shell_completion() {
        use predicates::str::contains;

        let mut cmd = get_cmd();
        cmd.args(["--completions", "zsh"]);

        cmd.assert().success();
        // Let's just see if this prints something that could *roughly* make sense.
        cmd.assert().stdout(contains("python"));
    }

    #[test]
    fn test_cli_on_invalid_utf8() {
        let mut cmd = get_cmd();

        let input = b"invalid utf8 \xFF";

        #[expect(invalid_from_utf8)] // Attribute didn't work on `assert` macro?
        let check = std::str::from_utf8(input);
        assert!(check.is_err(), "Input is valid UTF8, test is broken");

        cmd.write_stdin(*input);

        cmd.assert().failure();
    }

    /// Tests the helper function itself.
    #[test]
    fn test_directory_comparison() -> anyhow::Result<()> {
        for result in ignore::WalkBuilder::new("./src")
            .add("./tests")
            .add("./data")
            .add("./docs")
            .build()
        {
            let entry = result.unwrap();
            let path = entry.path();
            if path.is_dir() {
                let path = path.to_owned();

                {
                    // Any directory compares to itself fine.
                    check_directories_equality(path.clone(), path.clone())?;
                }

                {
                    let parent = path
                        .clone()
                        .parent()
                        .expect("(our) directories under test always have parents")
                        .to_owned();

                    assert!(
                        check_directories_equality(
                            // Impossible: a directory always compares unequal to a subdirectory
                            // of itself.
                            parent, path
                        )
                        .is_err()
                    );
                }
            }
        }

        Ok(())
    }

    fn get_cmd() -> Command {
        cargo_bin_cmd!()
    }

    /// Same as [`compare_directories`], but checks in both directions.
    ///
    /// This ensures exact equality, instead of more loose 'superset' shenanigans.
    fn check_directories_equality<P: Into<PathBuf>>(
        baseline: P,
        candidate: P,
    ) -> anyhow::Result<()> {
        let baseline = baseline.into();
        let candidate = candidate.into();

        compare_directories(baseline.clone(), candidate.clone())?;
        compare_directories(candidate, baseline)
    }

    /// Recursively compares file contents of some `baseline` directory to some
    /// `candidate`.
    ///
    /// The `candidate` tree has to be a superset (not strict) of `baseline`: all files
    /// with their full paths, i.e. all intermediary directories, need to exist in
    /// `candidate` as they do in `baseline`, but extraneous files in `candidate` are
    /// allowed and ignored.
    ///
    /// **File contents are checked for exactly**. File metadata is not compared.
    ///
    /// Any failure fails the entire comparison.
    ///
    /// Lots of copying happens, so not efficient.
    fn compare_directories<P: Into<PathBuf>>(baseline: P, candidate: P) -> anyhow::Result<()> {
        let baseline: PathBuf = baseline.into();
        let mut candidate: PathBuf = candidate.into();

        for entry in baseline
            .read_dir()
            .with_context(|| format!("Failure reading left dir: {baseline:?}"))?
        {
            // This shadows on purpose: less risk of misuse
            let left = entry
                .with_context(|| format!("Failure reading left dir entry (left: {baseline:?})"))?;

            candidate.push(left.file_name());

            let metadata = left.metadata().context("Failure reading file metadata")?;

            if !candidate.exists() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!(
                        "Right counterpart does not exist: left: {:?}, right: {:?}, left meta: {:?}",
                        left.path(),
                        candidate,
                        metadata
                    ),
                )
                .into());
            }

            if metadata.is_file() {
                // Recursion end
                let left_contents = std::fs::read(left.path())
                    .with_context(|| format!("Failure reading left file: {:?}", left.path()))?;
                let right_contents = std::fs::read(&candidate)
                    .with_context(|| format!("Failure reading right file: {candidate:?}"))?;

                if left_contents != right_contents {
                    return Err(std::io::Error::other(format!(
                        r"File contents differ:
left path: {:?}
right path: {:?}
---------
left contents:
{}
---------
right contents:
{}
---------
",
                        left.path(),
                        candidate,
                        String::from_utf8_lossy(&left_contents).escape_debug(),
                        String::from_utf8_lossy(&right_contents).escape_debug()
                    ))
                    .into());
                }
            } else if metadata.is_dir() {
                // Recursion step
                compare_directories(left.path().clone(), candidate.clone())?;
            } else {
                // Do not silently ignore.
                return Err(std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    format!(
                        "Unsupported file type for testing, found: {:?}",
                        left.metadata().unwrap()
                    ),
                )
                .into());
            }

            candidate.pop();
        }

        Ok(())
    }

    /// Recursively copies a directory tree from `src` to `dst`.
    fn copy_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
        std::fs::create_dir_all(dst)?;

        for entry in std::fs::read_dir(src)? {
            let entry = entry?;

            if entry.file_type()?.is_dir() {
                copy_tree(&entry.path(), &dst.join(entry.file_name()))?;
            } else {
                std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
            }
        }

        Ok(())
    }

    /// Creates a temporary directory and copies the contents of `src` into it,
    /// returning the path to the newly created directory.
    fn copy_to_tmp(src: &Path) -> TempDir {
        let pkg = env!("CARGO_PKG_NAME");
        assert!(
            !pkg.contains(std::path::MAIN_SEPARATOR),
            // Not like this will ever happen, but always good to encode assumptions
            "Package name contains path separator, which is not advisable for path prefix"
        );

        let tmp_dir = tempfile::Builder::new()
            .prefix(pkg)
            .disable_cleanup(true) // Keep for manual inspection if needed
            .tempdir()
            .expect("Failed to create temporary directory");

        copy_tree(src, tmp_dir.path()).expect("Failed to copy test files to tempdir");

        // Important: transfer ownership out, else `drop` will delete created dir
        tmp_dir
    }
}