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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
//! The main entrypoint to `srgn` as a CLI application.
//!
//! It mainly draws from `srgn`, the library, for actual implementations. This file then
//! deals with CLI argument handling, I/O, threading, and more.

use std::error::Error;
use std::fmt::Write as _; // import without risk of name clashing
use std::fs::{self, File};
use std::io::{self, IsTerminal, Read, Write, stdout};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fmt};

use anyhow::{Context, Result};
use colored::Colorize;
use ignore::{WalkBuilder, WalkState};
use itertools::Itertools;
use log::{LevelFilter, debug, error, info, trace, warn};
use pathdiff::diff_paths;
#[cfg(feature = "german")]
use srgn::actions::German;
use srgn::actions::{
    Action, ActionError, Deletion, Lower, Normalization, Replacement, Style, Titlecase, Upper,
};
#[cfg(feature = "symbols")]
use srgn::actions::{Symbols, SymbolsInversion};
use srgn::iterext::ParallelZipExt;
use srgn::scoping::Scoper;
use srgn::scoping::langs::LanguageScoper;
use srgn::scoping::literal::Literal;
use srgn::scoping::regex::Regex;
use srgn::scoping::scope::Scope;
use srgn::scoping::view::ScopedViewBuilder;
use tree_sitter::QueryError as TSQueryError;

// We have `LanguageScoper: Scoper`, but we cannot upcast
// (https://github.com/rust-lang/rust/issues/65991), so hack around the limitation
// by providing both.
type ScoperList = Vec<Box<dyn LanguageScoper>>;

#[expect(clippy::too_many_lines)] // Only slightly above.
#[expect(clippy::cognitive_complexity)]
fn main() -> Result<()> {
    let args = cli::Args::init();

    let level_filter = level_filter_from_env_and_verbosity(args.options.additional_verbosity);
    env_logger::Builder::new()
        .filter_level(level_filter)
        .format_timestamp_micros() // High precision is nice for benchmarks
        .init();

    info!("Launching app with args: {args:?}");

    let cli::Args {
        scope,
        shell,
        composable_actions,
        standalone_actions,
        mut options,
        languages_scopes,
        #[cfg(feature = "german")]
        german_options,
    } = args;

    if let Some(shell) = shell {
        debug!("Generating completions file for {shell:?}.");
        cli::print_completions(shell, &mut cli::Args::command());
        debug!("Done generating completions file, exiting.");

        return Ok(());
    }

    let standalone_action = standalone_actions.into();

    debug!("Assembling scopers.");
    let general_scoper = get_general_scoper(&options, scope)?;
    // Will be sent across threads and might (the borrow checker is convinced at least)
    // outlive the main one. Scoped threads would work here, `ignore` uses them
    // internally even, but we have no access here.

    let language_scopers = languages_scopes
        .compile_query_sources_to_scopes()?
        .map(Arc::new);
    debug!("Done assembling scopers.");

    let mut actions = {
        debug!("Assembling actions.");
        let mut actions = assemble_common_actions(&composable_actions, standalone_action)?;

        #[cfg(feature = "symbols")]
        if composable_actions.symbols {
            if options.invert {
                actions.push(Box::<SymbolsInversion>::default());
                debug!("Loaded action: SymbolsInversion");
            } else {
                actions.push(Box::<Symbols>::default());
                debug!("Loaded action: Symbols");
            }
        }

        #[cfg(feature = "german")]
        if composable_actions.german {
            actions.push(Box::new(German::new(
                // Smell? Bug if bools swapped.
                german_options.german_prefer_original,
                german_options.german_naive,
            )));
            debug!("Loaded action: German");
        }

        debug!("Done assembling actions.");
        actions
    };

    let is_stdout_tty = match options.stdout_detection {
        cli::StdoutDetection::Auto => {
            debug!("Detecting if stdout is a TTY");
            stdout().is_terminal()
        }
        cli::StdoutDetection::ForceTTY => true,
        cli::StdoutDetection::ForcePipe => false,
    };
    info!("Treating stdout as tty: {is_stdout_tty}.");

    let is_stdin_readable = match options.stdin_detection {
        cli::StdinDetection::Auto => {
            debug!("Detecting if stdin is readable");
            grep_cli::is_readable_stdin()
        }
        cli::StdinDetection::ForceReadable => true,
        cli::StdinDetection::ForceUnreadable => false,
    };
    info!("Treating stdin as readable: {is_stdin_readable}.");

    // See where we're reading from
    let input = match (
        is_stdin_readable,
        options.glob.clone(),
        &language_scopers,
    ) {
        // stdin considered viable: always use it.
        (true, None, _)
        // Nothing explicitly available: this should open an interactive stdin prompt.
        | (false, None, None) => Input::Stdin,
        (true, Some(..), _) => {
            // Usage error... warn loudly, the user is likely interested.
            error!("Detected stdin, and request for files: will use stdin and ignore files.");
            Input::Stdin
        }

        // When a pattern is specified, it takes precedence.
        (false, Some(pattern), _) => Input::WalkOn(Box::new(move |path| {
            let res = pattern.matches_path(path);
            trace!("Path '{}' matches: {}.", path.display(), res);
            res
        })),

        // If pattern wasn't manually overridden, consult the language scoper itself, if
        // any.
        (false, None, Some(language_scopers)) => {
            let language_scopers = Arc::clone(language_scopers);
            Input::WalkOn(Box::new(move |path| {
                // TODO: perform this work only once (it's super fast but in the hot
                // path).
                let res = language_scopers
                    .iter()
                    .map(|s| s.is_valid_path(path))
                    .all_equal_value()
                    .expect("all language scopers to agree on path validity");

                trace!(
                    "Language scoper considers path '{}' valid: {}",
                    path.display(),
                    res
                );
                res
            }))
        },
    };

    // Only have this kick in if a language scoper is in play; otherwise, we'd just be a
    // poor imitation of ripgrep itself. Plus, this retains the `tr`-like behavior,
    // setting it apart from other utilities.
    let search_mode = actions.is_empty() && language_scopers.is_some() || options.dry_run;

    if search_mode {
        info!("Will use search mode."); // Modelled after ripgrep!

        let style = if options.dry_run {
            Style::green_bold() // "Would change to this", like git diff
        } else {
            Style::red_bold() // "Found!", like ripgrep
        };

        if is_stdout_tty {
            // For human consumption, we style - otherwise, none needed (in fact, color
            // codes would mess with column positions, so omit).
            actions.push(Box::new(style));
        }

        options.only_matching = true;
        options.line_numbers = true;
        options.fail_none = true;
    }

    if actions.is_empty() && !search_mode {
        // Also kind of an error users will likely want to know about.
        error!(
            "No actions specified, and not in search mode. Will return input unchanged, if any."
        );
    }

    let pipeline = if options.dry_run {
        let action: Box<dyn Action> = Box::new(Style::red_bold());
        let color_only = vec![action];
        vec![color_only, actions]
    } else {
        vec![actions]
    };

    let pipeline: Vec<&[Box<dyn Action>]> = pipeline.iter().map(Vec::as_slice).collect();
    let language_scopers = language_scopers.unwrap_or_default();

    // Now write out
    match (input, options.sorted) {
        (Input::Stdin, _ /* no effect */) => {
            info!("Will read from stdin and write to stdout, applying actions.");
            handle_actions_on_stdin(
                &options,
                standalone_action,
                general_scoper.as_ref(),
                &language_scopers,
                &pipeline,
                is_stdout_tty,
            )?;
        }
        (Input::WalkOn(validator), false) => {
            info!("Will walk file tree, applying actions.");
            handle_actions_on_many_files_threaded(
                &options,
                standalone_action,
                &validator,
                general_scoper.as_ref(),
                &language_scopers,
                &pipeline,
                search_mode,
                options.threads.map_or_else(
                    || std::thread::available_parallelism().map_or(1, std::num::NonZero::get),
                    std::num::NonZero::get,
                ),
                is_stdout_tty,
            )?;
        }
        (Input::WalkOn(validator), true) => {
            info!("Will walk file tree, applying actions.");
            handle_actions_on_many_files_sorted(
                &options,
                standalone_action,
                &validator,
                general_scoper.as_ref(),
                &language_scopers,
                &pipeline,
                search_mode,
                is_stdout_tty,
            )?;
        }
    }

    info!("Done, exiting");
    Ok(())
}

/// Indicates whether a filesystem path is valid according to some criteria (glob
/// pattern, ...).
type Validator = Box<dyn Fn(&Path) -> bool + Send + Sync>;

/// The input to read from.
enum Input {
    /// Standard input.
    Stdin,
    /// Use a recursive directory walker, and apply the contained validator, which
    /// indicates valid filesystem entries. This is similar to globbing, but more
    /// flexible.
    WalkOn(Validator),
}

/// A standalone action to perform on the results of applying a scope.
#[derive(Clone, Copy, Debug)]
enum StandaloneAction {
    /// Delete anything in scope.
    ///
    /// Cannot be used with any other action: there is no point in deleting and
    /// performing any other processing. Sibling actions would either receive empty
    /// input or have their work wiped.
    Delete,
    /// Squeeze consecutive occurrences of scope into one.
    Squeeze,
    /// No stand alone action is set.
    None,
}

/// A "pipeline" in that there's not just a single sequence (== slice) of actions, but
/// instead multiple. These can be used in parallel (on the same or different views),
/// and the different results then used for advanced use cases. For example, diffing
/// different results against one another.
type Pipeline<'a> = &'a [&'a [Box<dyn Action>]];

/// Main entrypoint for simple `stdin` -> `stdout` processing.
fn handle_actions_on_stdin(
    global_options: &cli::GlobalOptions,
    standalone_action: StandaloneAction,
    general_scoper: &dyn Scoper,
    language_scopers: &[Box<dyn LanguageScoper>],
    pipeline: Pipeline<'_>,
    is_stdout_tty: bool,
) -> Result<(), ProgramError> {
    info!("Will use stdin to stdout.");
    let mut source = String::new();
    io::stdin().lock().read_to_string(&mut source)?;
    let mut destination = String::with_capacity(source.len());

    apply(
        global_options,
        standalone_action,
        &source,
        &mut destination,
        general_scoper,
        language_scopers,
        pipeline,
        None, // No filename for stdin
        is_stdout_tty,
    )?;

    stdout().lock().write_all(destination.as_bytes())?;

    Ok(())
}

/// Main entrypoint for processing using strictly sequential, *single-threaded*
/// processing.
///
/// If it's good enough for [ripgrep], it's good enough for us :-). Main benefit it full
/// control of output for testing anyway.
///
/// [ripgrep]:
///     https://github.com/BurntSushi/ripgrep/blob/71d71d2d98964653cdfcfa315802f518664759d7/GUIDE.md#L1016-L1017
#[expect(clippy::too_many_arguments)] // Yes :-(
fn handle_actions_on_many_files_sorted(
    global_options: &cli::GlobalOptions,
    standalone_action: StandaloneAction,
    validator: &Validator,
    general_scoper: &dyn Scoper,
    language_scopers: &[Box<dyn LanguageScoper>],
    pipeline: Pipeline<'_>,
    search_mode: bool,
    is_stdout_tty: bool,
) -> Result<(), ProgramError> {
    let root = env::current_dir()?;
    info!(
        "Will walk file tree sequentially, in sorted order, starting from: {:?}",
        root.canonicalize()
    );

    let mut n_files_processed: usize = 0;
    let mut n_files_seen: usize = 0;
    for entry in WalkBuilder::new(&root)
        .hidden(!global_options.hidden)
        .git_ignore(!global_options.gitignored)
        .sort_by_file_path(Ord::cmp)
        .build()
    {
        match entry {
            Ok(entry) => {
                let path = entry.path();
                let res = process_path(
                    global_options,
                    standalone_action,
                    path,
                    &root,
                    validator,
                    general_scoper,
                    language_scopers,
                    pipeline,
                    search_mode,
                    is_stdout_tty,
                );

                n_files_seen += match res {
                    Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => 0,
                    _ => 1,
                };

                n_files_processed += match res {
                    Ok(()) => 1,

                    // Soft errors with reasonable handling available:
                    Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => 0,
                    Err(PathProcessingError::ApplicationError(ApplicationError::SomeInScope))
                        if global_options.fail_any =>
                    {
                        // Early-out
                        info!("Match at {}, exiting early", path.display());
                        return Err(ProgramError::SomethingProcessed);
                    }
                    #[expect(clippy::match_same_arms)]
                    Err(PathProcessingError::ApplicationError(
                        ApplicationError::NoneInScope | ApplicationError::SomeInScope,
                    )) => 0,
                    Err(PathProcessingError::IoError(e, _))
                        if e.kind() == io::ErrorKind::BrokenPipe && search_mode =>
                    {
                        trace!("Detected broken pipe, stopping search.");
                        break;
                    }
                    Err(PathProcessingError::IoError(e, _))
                        // `InvalidData` does NOT equal "invalid utf-8", but that's how
                        // it's _effectively_ used in the "read to string" type of
                        // functions we use throughout.
                        // https://github.com/rust-lang/rust/blob/096277e989d6de11c3077472fc05778e261e7b8e/library/std/src/io/error.rs#L78-L79
                        if e.kind() == io::ErrorKind::InvalidData =>
                    {
                        warn!("File contains unreadable data (binary? invalid utf-8?), skipped: {}", path.display());
                        0
                    }

                    // Hard errors we should do something about:
                    Err(
                        e @ (PathProcessingError::ApplicationError(ApplicationError::ActionError(
                            ..,
                        ))
                        | PathProcessingError::IoError(..)),
                    ) => {
                        if search_mode {
                            error!("Error walking at {}: {}", path.display(), e);
                            0
                        } else {
                            error!("Aborting walk at {} due to: {}", path.display(), e);
                            return Err(e.into());
                        }
                    }
                }
            }
            Err(e) => {
                if search_mode {
                    error!("Error walking: {e}");
                } else {
                    error!("Aborting walk due to: {e}");
                    return Err(e.into());
                }
            }
        }
    }

    info!("Saw {n_files_seen} items");
    info!("Processed {n_files_processed} files");

    if n_files_seen == 0 && global_options.fail_no_files {
        Err(ProgramError::NoFilesFound)
    } else if n_files_processed == 0 && global_options.fail_none {
        Err(ProgramError::NothingProcessed)
    } else {
        Ok(())
    }
}

/// Main entrypoint for processing using at least 1 thread.
#[expect(clippy::too_many_lines)]
#[expect(clippy::too_many_arguments)]
fn handle_actions_on_many_files_threaded(
    global_options: &cli::GlobalOptions,
    standalone_action: StandaloneAction,
    validator: &Validator,
    general_scoper: &dyn Scoper,
    language_scopers: &[Box<dyn LanguageScoper>],
    pipeline: Pipeline<'_>,
    search_mode: bool,
    n_threads: usize,
    is_stdout_tty: bool,
) -> Result<(), ProgramError> {
    let root = env::current_dir()?;
    info!(
        "Will walk file tree using {:?} thread(s), processing in arbitrary order, starting from: {:?}",
        n_threads,
        root.canonicalize()
    );

    let n_files_processed = Arc::new(Mutex::new(0usize));
    let n_files_seen = Arc::new(Mutex::new(0usize));
    let err: Arc<Mutex<Option<ProgramError>>> = Arc::new(Mutex::new(None));

    WalkBuilder::new(&root)
        .threads(
            // https://github.com/BurntSushi/ripgrep/issues/2854
            n_threads,
        )
        .hidden(!global_options.hidden)
        .git_ignore(!global_options.gitignored)
        .build_parallel()
        .run(|| {
            Box::new(|entry| match entry {
                Ok(entry) => {
                    let path = entry.path();
                    let res = process_path(
                        global_options,
                        standalone_action,
                        path,
                        &root,
                        validator,
                        general_scoper,
                        language_scopers,
                        pipeline,
                        search_mode,
                        is_stdout_tty,
                    );

                    match res {
                        Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => (),
                        _ => *n_files_seen.lock().unwrap() += 1,
                    }

                    match res {
                        Ok(()) => {
                            *n_files_processed.lock().unwrap() += 1;
                            WalkState::Continue
                        }

                        // Soft errors with reasonable handling available:
                        Err(PathProcessingError::NotAFile | PathProcessingError::InvalidFile) => {
                            WalkState::Continue
                        }
                        Err(
                            e
                            @ PathProcessingError::ApplicationError(ApplicationError::SomeInScope),
                        ) if global_options.fail_any => {
                            // Early-out
                            info!("Match at {}, exiting early", path.display());
                            *err.lock().unwrap() = Some(e.into());
                            WalkState::Quit
                        }
                        Err(PathProcessingError::ApplicationError(
                            ApplicationError::NoneInScope | ApplicationError::SomeInScope,
                        )) => WalkState::Continue,
                        Err(PathProcessingError::IoError(e, _))
                            if e.kind() == io::ErrorKind::BrokenPipe && search_mode =>
                        {
                            trace!("Detected broken pipe, stopping search.");
                            WalkState::Quit
                        }
                        Err(PathProcessingError::IoError(e, _))
                            // `InvalidData` does NOT equal "invalid utf-8", but that's
                            // how it's _effectively_ used in the "read to string" type
                            // of functions we use throughout.
                            // https://github.com/rust-lang/rust/blob/096277e989d6de11c3077472fc05778e261e7b8e/library/std/src/io/error.rs#L78-L79
                            if e.kind() == io::ErrorKind::InvalidData =>
                        {
                            warn!("File contains unreadable data (binary? invalid utf-8?), skipped: {}", path.display());
                            WalkState::Continue
                        }

                        // Hard errors we should do something about:
                        Err(
                            e @ (PathProcessingError::ApplicationError(..)
                            | PathProcessingError::IoError(..)),
                        ) => {
                            error!("Error walking at {} due to: {}", path.display(), e);

                            if search_mode {
                                WalkState::Continue
                            } else {
                                // Chances are something bad and/or unintended happened;
                                // bail out to limit any potential damage.
                                error!("Aborting walk for safety");
                                *err.lock().unwrap() = Some(e.into());
                                WalkState::Quit
                            }
                        }
                    }
                }
                Err(e) => {
                    if search_mode {
                        error!("Error walking: {e}");
                        WalkState::Continue
                    } else {
                        error!("Aborting walk due to: {e}");
                        *err.lock().unwrap() = Some(e.into());
                        WalkState::Quit
                    }
                }
            })
        });

    let error = err.lock().unwrap().take();
    if let Some(e) = error {
        return Err(e);
    }

    let n_files_seen = *n_files_seen.lock().unwrap();
    info!("Saw {n_files_seen} items");
    let n_files_processed = *n_files_processed.lock().unwrap();
    info!("Processed {n_files_processed} files");

    if n_files_seen == 0 && global_options.fail_no_files {
        Err(ProgramError::NoFilesFound)
    } else if n_files_processed == 0 && global_options.fail_none {
        Err(ProgramError::NothingProcessed)
    } else {
        Ok(())
    }
}

#[expect(clippy::too_many_arguments)]
fn process_path(
    global_options: &cli::GlobalOptions,
    standalone_action: StandaloneAction,
    path: &Path,
    root: &Path,
    validator: &Validator,
    general_scoper: &dyn Scoper,
    language_scopers: &[Box<dyn LanguageScoper>],
    pipeline: Pipeline<'_>,
    search_mode: bool,
    is_stdout_tty: bool,
) -> std::result::Result<(), PathProcessingError> {
    if !path.is_file() {
        trace!("Skipping path (not a file): {}", path.display());
        return Err(PathProcessingError::NotAFile);
    }

    let path = diff_paths(path, root).expect("started walk at root, so relative to root works");

    if !validator(&path) {
        trace!("Skipping path (invalid): {}", path.display());
        return Err(PathProcessingError::InvalidFile);
    }

    debug!("Processing path: {}", path.display());

    let (new_contents, filesize, changed) = {
        let mut file = File::open(&path)?;

        let filesize = file.metadata().map_or(0, |m| m.len());
        let mut source =
            String::with_capacity(filesize.try_into().unwrap_or(/* no perf gains for you */ 0));
        file.read_to_string(&mut source)?;

        let mut destination = String::with_capacity(source.len());

        let changed = apply(
            global_options,
            standalone_action,
            &source,
            &mut destination,
            general_scoper,
            language_scopers,
            pipeline,
            Some(&path),
            is_stdout_tty,
        )?;

        (destination, filesize, changed)
    };

    // Hold the lock so results aren't intertwined
    let mut stdout = stdout().lock();

    if search_mode {
        if !new_contents.is_empty() {
            if is_stdout_tty {
                // TTY format: colored filename with empty line separator
                writeln!(
                    stdout,
                    "{}\n{}",
                    path.display().to_string().magenta(),
                    &new_contents
                )?;
            } else {
                // Machine-parseable format: the content should already be formatted
                // with filename:line_number: prefix by the apply function
                write!(stdout, "{}", &new_contents)?;
            }
        }
    } else {
        if filesize > 0 && new_contents.is_empty() {
            error!(
                "Failsafe triggered: file {} is nonempty ({} bytes), but new contents are empty. Will not wipe file.",
                path.display(),
                filesize
            );
            return Err(io::Error::other("attempt to wipe non-empty file (failsafe guard)").into());
        }

        if changed {
            debug!("Got new file contents, writing to file: {}", path.display());
            assert!(
                !global_options.dry_run,
                // Dry run leverages search mode, so should never get here. Assert for
                // extra safety.
                "Dry running, but attempted to write file!"
            );
            fs::write(&path, new_contents.as_bytes())?;

            // Confirm after successful processing.
            writeln!(stdout, "{}", path.display())?;
        } else {
            debug!(
                "Skipping writing file anew (nothing changed): {}",
                path.display()
            );
        }

        debug!("Done processing file: {}", path.display());
    }

    Ok(())
}

/// Runs the actual core processing, returning whether anything changed in the output
/// compared to the input.
///
/// TODO: The way this interacts with [`process_path`] etc. is just **awful** spaghetti
/// of the most imperative, procedural kind. Refactor needed.
#[expect(clippy::too_many_arguments)] // Yes :-(
fn apply(
    global_options: &cli::GlobalOptions,
    standalone_action: StandaloneAction,
    source: &str,
    // Use a string to avoid repeated and unnecessary bytes -> utf8 conversions and
    // corresponding checks.
    destination: &mut String,
    general_scoper: &dyn Scoper,
    language_scopers: &[Box<dyn LanguageScoper>],
    pipeline: Pipeline<'_>,
    file_path: Option<&Path>,
    is_stdout_tty: bool,
) -> std::result::Result<bool, ApplicationError> {
    debug!("Building view.");
    let mut builder = ScopedViewBuilder::new(source);

    if global_options.join_language_scopes {
        // All at once, as a slice: hits a specific, 'joining' `impl`
        builder.explode(&language_scopers);
    } else {
        // One by one: hits a different, 'intersecting' `impl`
        for scoper in language_scopers {
            builder.explode(scoper);
        }
    }

    builder.explode(general_scoper);
    let mut view = builder.build();
    debug!("Done building view: {view:?}");

    if global_options.fail_none && !view.has_any_in_scope() {
        return Err(ApplicationError::NoneInScope);
    }

    if global_options.fail_any && view.has_any_in_scope() {
        return Err(ApplicationError::SomeInScope);
    }

    debug!("Applying actions to view.");
    if matches!(standalone_action, StandaloneAction::Squeeze) {
        view.squeeze();
    }

    // Give each pipeline its own fresh view
    let mut views = vec![view; pipeline.len()];

    for (actions, view) in pipeline.iter().zip_eq(&mut views) {
        for action in *actions {
            view.map_with_context(action)?;
        }
    }

    debug!("Writing to destination.");
    let line_based = global_options.only_matching || global_options.line_numbers;
    if line_based {
        let line_based_views = views.iter().map(|v| v.lines().into_iter()).collect_vec();

        for (i, lines) in line_based_views.into_iter().parallel_zip().enumerate() {
            let i = i + 1;
            for line in lines {
                if global_options.only_matching && !line.has_any_in_scope() {
                    continue;
                }

                let sep = ":";

                if !is_stdout_tty {
                    // Machine-parseable format
                    if let Some(path) = file_path {
                        write!(destination, "{}{sep}", path.display())
                            .expect("infallible on String (are we OOM?)");
                    } else {
                        write!(destination, "(stdin){sep}")
                            .expect("infallible on String (are we OOM?)");
                    }
                }

                if global_options.line_numbers {
                    write!(
                        destination,
                        "{}{sep}",
                        if is_stdout_tty {
                            i.to_string().green().to_string()
                        } else {
                            i.to_string()
                        }
                    )
                    .expect("infallible on String (are we OOM?)");
                }

                if !is_stdout_tty {
                    // This is for programmatic use: column positions are 0-indexed.
                    let mut col = 0;

                    let mut ranges = Vec::new();

                    // NB: this manual column position computation should not live at
                    // this layer; ideally a `Scope` knows how to serialize itself,
                    // which would generalize to CLI output, JSON, ...
                    for scope in &line.scopes().0 {
                        let s: &str = scope.into();

                        // This is for programmatic use: ranges are half-open, [from,
                        // to).
                        let end = col + s.len();

                        if let Scope::In(..) = scope.0 {
                            ranges.push(format!("{col}-{end}"));
                        }

                        col = end;
                    }

                    write!(destination, "{ranges}{sep}", ranges = ranges.join(";"))
                        .expect("infallible on String (are we OOM?)");
                }

                destination.push_str(&line.to_string());
            }
        }
    } else {
        assert_eq!(
            views.len(),
            1,
            // Multiple views are useful for e.g. diffing, which works line-based (see
            // `dry_run`). When not line-based, they *currently* do not make sense, as
            // there's neither any code path where there *would* be multiple views at
            // this point, *nor* a valid use case. Printing multiple views here would
            // probably wreak havoc.
            "Multiple views at this stage make no sense."
        );

        for view in views {
            destination.push_str(&view.to_string());
        }
    }
    debug!("Done writing to destination.");

    Ok(source != *destination)
}

/// Top-level, user-facing errors, affecting and possibly terminating program execution
/// as a whole.
#[derive(Debug)]
enum ProgramError {
    /// Error when handling a path.
    PathProcessingError(PathProcessingError),
    /// Error when applying.
    ApplicationError(ApplicationError),
    /// No files were found, unexpectedly.
    NoFilesFound,
    /// Files were found but nothing ended up being processed, unexpectedly.
    NothingProcessed,
    /// Files were found but some input ended up being processed, unexpectedly.
    SomethingProcessed,
    /// I/O error.
    IoError(io::Error),
    /// Error while processing files for walking.
    IgnoreError(ignore::Error),
    /// The given query failed to parse
    QueryError(TSQueryError),
}

impl fmt::Display for ProgramError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PathProcessingError(e) => write!(f, "Error processing path: {e}"),
            Self::ApplicationError(e) => write!(f, "Error applying: {e}"),
            Self::NoFilesFound => write!(f, "No files found"),
            Self::NothingProcessed => write!(f, "No input was in scope"),
            Self::SomethingProcessed => write!(f, "Some input was in scope"),
            Self::IoError(e) => write!(f, "I/O error: {e}"),
            Self::IgnoreError(e) => write!(f, "Error walking files: {e}"),
            Self::QueryError(e) => {
                write!(f, "Error occurred while creating a tree-sitter query: {e}")
            }
        }
    }
}

impl From<ApplicationError> for ProgramError {
    fn from(err: ApplicationError) -> Self {
        Self::ApplicationError(err)
    }
}

impl From<PathProcessingError> for ProgramError {
    fn from(err: PathProcessingError) -> Self {
        Self::PathProcessingError(err)
    }
}

impl From<io::Error> for ProgramError {
    fn from(err: io::Error) -> Self {
        Self::IoError(err)
    }
}

impl From<ignore::Error> for ProgramError {
    fn from(err: ignore::Error) -> Self {
        Self::IgnoreError(err)
    }
}

impl From<TSQueryError> for ProgramError {
    fn from(err: TSQueryError) -> Self {
        Self::QueryError(err)
    }
}

impl Error for ProgramError {}

/// Errors when applying actions to scoped views.
#[derive(Debug)]
enum ApplicationError {
    /// Something was *unexpectedly* in scope.
    SomeInScope,
    /// Nothing was in scope, *unexpectedly*.
    NoneInScope,
    /// Error with an [`Action`].
    ActionError(ActionError),
}

impl fmt::Display for ApplicationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SomeInScope => write!(f, "Some input was in scope"),
            Self::NoneInScope => write!(f, "No input was in scope"),
            Self::ActionError(e) => write!(f, "Error in an action: {e}"),
        }
    }
}

impl From<ActionError> for ApplicationError {
    fn from(err: ActionError) -> Self {
        Self::ActionError(err)
    }
}

impl Error for ApplicationError {}

/// Errors when processing a (file) path.
#[derive(Debug)]
enum PathProcessingError {
    /// I/O error.
    IoError(io::Error, Option<PathBuf>),
    /// Item was not a file (directory, symlink, ...).
    NotAFile,
    /// Item is a file but is unsuitable for processing.
    InvalidFile,
    /// Error when applying.
    ApplicationError(ApplicationError),
}

impl fmt::Display for PathProcessingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IoError(e, None) => write!(f, "I/O error: {e}"),
            Self::IoError(e, Some(path)) => write!(f, "I/O error at path {}: {e}", path.display()),
            Self::NotAFile => write!(f, "Item is not a file"),
            Self::InvalidFile => write!(f, "Item is not a valid file"),
            Self::ApplicationError(e) => write!(f, "Error applying: {e}"),
        }
    }
}

impl From<io::Error> for PathProcessingError {
    fn from(err: io::Error) -> Self {
        Self::IoError(err, None)
    }
}

impl From<ApplicationError> for PathProcessingError {
    fn from(err: ApplicationError) -> Self {
        Self::ApplicationError(err)
    }
}

impl Error for PathProcessingError {}

fn get_general_scoper(options: &cli::GlobalOptions, scope: String) -> Result<Box<dyn Scoper>> {
    Ok(if options.literal_string {
        Box::new(Literal::try_from(scope).context("Failed building literal string")?)
    } else {
        Box::new(Regex::try_from(scope).context("Failed building regex")?)
    })
}

fn assemble_common_actions(
    composable_actions: &cli::ComposableActions,
    standalone_actions: StandaloneAction,
) -> Result<Vec<Box<dyn Action>>> {
    let mut actions: Vec<Box<dyn Action>> = Vec::new();

    if let Some(replacement) = composable_actions.replace.clone() {
        actions.push(Box::new(
            Replacement::try_from(replacement).context("Failed building replacement string")?,
        ));
        debug!("Loaded action: Replacement");
    }

    if matches!(standalone_actions, StandaloneAction::Delete) {
        actions.push(Box::<Deletion>::default());
        debug!("Loaded action: Deletion");
    }

    if composable_actions.upper {
        actions.push(Box::<Upper>::default());
        debug!("Loaded action: Upper");
    }

    if composable_actions.lower {
        actions.push(Box::<Lower>::default());
        debug!("Loaded action: Lower");
    }

    if composable_actions.titlecase {
        actions.push(Box::<Titlecase>::default());
        debug!("Loaded action: Titlecase");
    }

    if composable_actions.normalize {
        actions.push(Box::<Normalization>::default());
        debug!("Loaded action: Normalization");
    }

    Ok(actions)
}

/// To the default log level found in the environment, adds the requested additional
/// verbosity level, clamped to the maximum available.
///
/// See also
/// <https://docs.rs/env_logger/latest/env_logger/struct.Env.html#default-environment-variables>
/// and <https://docs.rs/env_logger/latest/env_logger/#enabling-logging>
fn level_filter_from_env_and_verbosity(additional_verbosity: u8) -> LevelFilter {
    let available = LevelFilter::iter().collect::<Vec<_>>();
    let default = env_logger::Builder::from_default_env().build().filter();

    let mut level = default as usize; // Implementation detail of `log` crate
    level += additional_verbosity as usize;

    available.get(level).copied().unwrap_or_else(|| {
        eprintln!(
            "Requested additional verbosity on top of env default exceeds maximum, will use maximum"
        );

        available
            .last()
            .copied()
            .expect("At least one level must be available")
    })
}

mod cli {
    use std::ffi::OsStr;
    use std::fmt::Write;
    use std::num::NonZero;
    use std::path::PathBuf;
    use std::{fs, io};

    use clap::builder::{ArgPredicate, StyledStr};
    use clap::error::ErrorKind;
    use clap::{ArgAction, Command, CommandFactory, Parser, ValueEnum};
    use clap_complete::{Generator, Shell, generate};
    use log::info;
    use regex::bytes::Regex;
    use srgn::GLOBAL_SCOPE;
    use srgn::scoping::langs::{
        LanguageScoper, QuerySource, TreeSitterRegex, c, csharp, go, hcl, python, rust, typescript,
    };
    use tree_sitter::QueryError as TSQueryError;

    use crate::{ProgramError, StandaloneAction};

    /// Main CLI entrypoint.
    ///
    /// Using `verbatim_doc_comment` a lot as otherwise lines wouldn't wrap neatly. I
    /// format them narrowly manually anyway, so can just use them verbatim.
    #[derive(Parser, Debug)]
    #[command(
        author,
        version,
        about,
        long_about = None,
        // Really dumb to hard-code, but we need deterministic output for README tests
        // to remain stable, and this is probably both a solid default *and* plays with
        // this very source file which is wrapped at *below* that, so it fits and clap
        // doesn't touch our manually formatted doc strings anymore.
        term_width = 90,
    )]
    pub struct Args {
        /// Scope to apply to, as a regular expression pattern.
        ///
        /// If string literal mode is requested, will be interpreted as a literal
        /// string.
        ///
        /// Actions will apply their transformations within this scope only.
        ///
        /// The default is the global scope, matching the entire input. Where that
        /// default is meaningless or dangerous (e.g., deletion), this argument is
        /// required.
        #[arg(
            value_name = "SCOPE",
            default_value = GLOBAL_SCOPE,
            verbatim_doc_comment,
            default_value_if("literal_string", ArgPredicate::IsPresent, None)
        )]
        pub(super) scope: String,

        /// Print shell completions for the given shell.
        #[arg(long = "completions", value_enum, verbatim_doc_comment)]
        // This thing needs to live up here to show up within `Options` next to `--help`
        // and `--version`. Further down, it'd show up in the wrong section because we
        // alter `next_help_heading`.
        pub(super) shell: Option<Shell>,

        #[command(flatten)]
        pub(super) composable_actions: ComposableActions,

        #[command(flatten)]
        pub(super) standalone_actions: StandaloneActions,

        #[command(flatten)]
        pub(super) options: GlobalOptions,

        #[command(flatten)]
        pub(super) languages_scopes: LanguageScopes,

        #[cfg(feature = "german")]
        #[command(flatten)]
        pub(super) german_options: GermanOptions,
    }

    /// <https://github.com/clap-rs/clap/blob/f65d421607ba16c3175ffe76a20820f123b6c4cb/clap_complete/examples/completion-derive.rs#L69>
    pub fn print_completions<G: Generator>(generator: G, cmd: &mut Command) {
        generate(
            generator,
            cmd,
            cmd.get_name().to_string(),
            &mut io::stdout(),
        );
    }

    /// Controls for stdin readability detection.
    #[derive(Debug, Clone, ValueEnum)]
    pub enum StdinDetection {
        /// Automatically detect if stdin is readable.
        Auto,
        /// Act as if stdin is readable.
        ForceReadable,
        /// Act as if stdin is not readable.
        ForceUnreadable,
    }

    /// Controls for stdout detection.
    #[derive(Debug, Clone, ValueEnum)]
    pub enum StdoutDetection {
        /// Automatically detect if stdout is a TTY and act accordingly.
        Auto,
        /// Act as if stdout is a TTY.
        ForceTTY,
        /// Act as if stdout is not a TTY, e.g. a pipe, redirect.
        ForcePipe,
    }

    #[derive(Parser, Debug)]
    #[group(required = false, multiple = true)]
    #[command(next_help_heading = "Options (global)")]
    #[expect(clippy::struct_excessive_bools)]
    pub struct GlobalOptions {
        /// Glob of files to work on (instead of reading stdin).
        ///
        /// If actions are applied, they overwrite files in-place.
        ///
        /// For supported glob syntax, see:
        /// <https://docs.rs/glob/0.3.1/glob/struct.Pattern.html>
        ///
        /// Names of processed files are written to stdout.
        #[arg(short('G'), long, verbatim_doc_comment, alias = "files")]
        pub glob: Option<glob::Pattern>,
        /// Fail if working on files (e.g. globbing is requested) but none are found.
        ///
        /// Processing no files is not an error condition in itself, but might be an
        /// unexpected outcome in some contexts. This flag makes the condition explicit.
        #[arg(long, verbatim_doc_comment, alias = "fail-empty-glob")]
        pub fail_no_files: bool,
        /// Do not destructively overwrite files, instead print rich diff only.
        ///
        /// The diff details the names of files which would be modified, alongside all
        /// changes inside those files which would be performed outside of dry running.
        /// It is similar to git diff with word diffing enabled.
        #[arg(long, verbatim_doc_comment)]
        pub dry_run: bool,
        /// Undo the effects of passed actions, where applicable.
        ///
        /// Requires a 1:1 mapping between replacements and original, which is currently
        /// available only for:
        ///
        /// - symbols: '≠' <-> '!=' etc.
        ///
        /// Other actions:
        ///
        /// - german: inverting e.g. 'Ä' is ambiguous (can be 'Ae' or 'AE')
        ///
        /// - upper, lower, deletion, squeeze: inversion is impossible as information is
        ///   lost
        ///
        /// These may still be passed, but will be ignored for inversion and applied
        /// normally.
        #[cfg(feature = "symbols")]
        #[arg(short, long, env, requires = "symbols", verbatim_doc_comment)]
        pub invert: bool,
        /// Do not interpret the scope as a regex. Instead, interpret it as a literal
        /// string. Will require a scope to be passed.
        #[arg(short('L'), long, env, verbatim_doc_comment)]
        pub literal_string: bool,
        /// If anything at all is found to be in scope, fail.
        ///
        /// The default is to continue processing normally.
        #[arg(long, verbatim_doc_comment)]
        pub fail_any: bool,
        /// If nothing is found to be in scope, fail.
        ///
        /// The default is to return the input unchanged (without failure).
        #[arg(long, verbatim_doc_comment)]
        pub fail_none: bool,
        /// Join (logical 'OR') multiple language scopes, instead of intersecting them.
        ///
        /// The default when multiple language scopes are given is to intersect their
        /// scopes, left to right. For example, `--go func --go strings` will first
        /// scope down to `func` bodies, then look for strings only within those. This
        /// flag instead joins (in the set logic sense) all scopes. The example would
        /// then scope any `func` bodies, and any strings, anywhere. Language scopers
        /// can then also be given in any order.
        ///
        /// No effect if only a single language scope is given. Also does not affect
        /// non-language scopers (regex pattern etc.), which always intersect.
        #[arg(short('j'), long, verbatim_doc_comment)]
        pub join_language_scopes: bool,
        /// Prepend line numbers to output.
        #[arg(long, hide(true), verbatim_doc_comment)]
        // Hidden: internal use. Not really useful to expose.
        pub line_numbers: bool,
        /// Print only matching lines.
        #[arg(long, hide(true), verbatim_doc_comment)]
        // Hidden: internal use. Not really useful to expose.
        pub only_matching: bool,
        /// Do not ignore hidden files and directories.
        #[arg(short('H'), long, verbatim_doc_comment)]
        pub hidden: bool,
        /// Do not ignore `.gitignore`d files and directories.
        #[arg(long, verbatim_doc_comment)]
        pub gitignored: bool,
        /// Process files in lexicographically sorted order, by file path.
        ///
        /// In search mode, this emits results in sorted order. Otherwise, it processes
        /// files in sorted order.
        ///
        /// Sorted processing disables parallel processing.
        #[arg(long, verbatim_doc_comment)]
        pub sorted: bool,
        /// Control heuristics for stdin readability detection, and force to value.
        #[arg(
            long,
            value_enum,
            default_value_t=StdinDetection::Auto,
            verbatim_doc_comment
        )]
        pub stdin_detection: StdinDetection,
        /// Control heuristics for stdout detection, and potentially force to value.
        #[arg(
            long,
            value_enum,
            default_value_t=StdoutDetection::Auto,
            verbatim_doc_comment
        )]
        pub stdout_detection: StdoutDetection,
        /// Number of threads to run processing on, when working with files.
        ///
        /// If not specified, will default to available parallelism. Set to 1 for
        /// sequential, deterministic (but not sorted) output.
        #[arg(long, verbatim_doc_comment)]
        pub threads: Option<NonZero<usize>>,
        /// Increase log verbosity level.
        ///
        /// The base log level to use is read from the `RUST_LOG` environment variable
        /// (if unspecified, defaults to 'error'), and increased according to the number
        /// of times this flag is given, maxing out at 'trace' verbosity.
        #[arg(
            short = 'v',
            long = "verbose",
            action = ArgAction::Count,
            verbatim_doc_comment
        )]
        pub additional_verbosity: u8,
    }

    #[derive(Parser, Debug)]
    #[group(required = false, multiple = true)]
    #[command(next_help_heading = "Composable Actions")]
    #[expect(clippy::struct_excessive_bools)]
    pub struct ComposableActions {
        /// Replace anything in scope with this value.
        ///
        /// Variables are supported: if a regex pattern was used for scoping and
        /// captured content in named or numbered capture groups, access these in the
        /// replacement value using `$1` etc. for numbered, `$NAME` etc. for named
        /// capture groups.
        ///
        /// This action is specially treated as a positional argument for ergonomics and
        /// compatibility with `tr`.
        ///
        /// If given, will run before any other action.
        #[arg(value_name = "REPLACEMENT", env, verbatim_doc_comment, last = true)]
        pub replace: Option<String>,
        /// Uppercase anything in scope.
        #[arg(short, long, env, verbatim_doc_comment)]
        pub upper: bool,
        /// Lowercase anything in scope.
        #[arg(short, long, env, verbatim_doc_comment)]
        pub lower: bool,
        /// Titlecase anything in scope.
        #[arg(short, long, env, verbatim_doc_comment)]
        pub titlecase: bool,
        /// Normalize (Normalization Form D) anything in scope, and throw away marks.
        #[arg(short, long, env, verbatim_doc_comment)]
        pub normalize: bool,
        /// Perform substitutions on German words, such as 'Abenteuergruesse' to
        /// 'Abenteuergrüße', for anything in scope.
        ///
        /// ASCII spellings for Umlauts (ae, oe, ue) and Eszett (ss) are replaced by
        /// their respective native Unicode (ä, ö, ü, ß).
        ///
        /// Arbitrary compound words are supported.
        ///
        /// Words legally containing alternative spellings are not modified.
        ///
        /// Words require correct spelling to be detected.
        #[cfg(feature = "german")]
        #[arg(
            short,
            long,
            verbatim_doc_comment,
            // `true` as string is very ugly, but there's no other way?
            default_value_if("german-opts", ArgPredicate::IsPresent, "true")
        )]
        pub german: bool,
        /// Perform substitutions on symbols, such as '!=' to '≠', '->' to '→', on
        /// anything in scope.
        ///
        /// Helps translate 'ASCII art' into native Unicode representations.
        #[cfg(feature = "symbols")]
        #[arg(short = 'S', long, verbatim_doc_comment)]
        pub symbols: bool,
    }

    #[derive(Parser, Debug)]
    #[group(required = false, multiple = false)]
    #[command(next_help_heading = "Standalone Actions (only usable alone)")]
    pub struct StandaloneActions {
        /// Delete anything in scope.
        ///
        /// Cannot be used with any other action: there is no point in deleting and
        /// performing any other processing. Sibling actions would either receive empty
        /// input or have their work wiped.
        #[arg(
            short,
            long,
            requires = "scope",
            conflicts_with = stringify!(ComposableActions),
            verbatim_doc_comment
        )]
        pub delete: bool,
        /// Squeeze consecutive occurrences of scope into one.
        #[arg(
            short,
            long,
            visible_alias("squeeze-repeats"),
            env,
            requires = "scope",
            verbatim_doc_comment
        )]
        pub squeeze: bool,
    }

    impl From<StandaloneActions> for StandaloneAction {
        fn from(value: StandaloneActions) -> Self {
            if value.delete {
                Self::Delete
            } else if value.squeeze {
                Self::Squeeze
            } else {
                Self::None
            }
        }
    }

    /// For use as <https://docs.rs/clap/latest/clap/struct.Arg.html#method.value_name>
    const TREE_SITTER_QUERY_VALUE: &str = "TREE-SITTER-QUERY-VALUE";
    const TREE_SITTER_QUERY_FILENAME: &str = "TREE-SITTER-QUERY-FILENAME";

    /// For grammar items supporting the concept of "namedness", like structs, enums,
    /// modules, classes and more, this is the separator used to separate the name from
    /// the pattern itself, when passed as a single argument.
    const NAMED_ITEM_PATTERN_SEPARATOR: &str = "~";

    macro_rules! impl_lang_scopes {
        ($(($lang_flag:ident, $lang_query_flag:ident, $lang_query_file_flag:ident, $lang_scope:ident),)+) => {
            #[derive(Parser, Debug)]
            #[group(required = false, multiple = false)]
            #[command(next_help_heading = "Language scopes")]
            pub struct LanguageScopes {
                $(
                    #[command(flatten)]
                    $lang_flag: Option<$lang_scope>,
                )+
            }

            impl LanguageScopes {
                /// Finds the first language field set, if any, and compiles the `QuerySourceOrPath`'s into a list of `LanguageScoper`'s.
                pub(super) fn compile_query_sources_to_scopes(self) -> Result<Option<crate::ScoperList>, ProgramError> {
                    assert_exclusive_lang_scope(&[
                        $(self.$lang_flag.is_some(),)+
                    ]);

                    $(
                        if let Some(s) = self.$lang_flag {
                            let s = accumulate_scopes::<$lang_flag::CompiledQuery, _>(s.$lang_flag, s.$lang_query_flag, s.$lang_query_file_flag,)?;
                            return Ok(Some(s));
                        }
                    )+

                    Ok(None)
                }
            }
        };
    }

    impl_lang_scopes!(
        (c, c_query, c_query_file, CScope),
        (csharp, csharp_query, csharp_query_file, CSharpScope),
        (go, go_query, go_query_file, GoScope),
        (hcl, hcl_query, hcl_query_file, HclScope),
        (python, python_query, python_query_file, PythonScope),
        (rust, rust_query, rust_query_file, RustScope),
        (
            typescript,
            typescript_query,
            typescript_query_file,
            TypeScriptScope
        ),
    );

    /// Assert that either zero or one lang field is set.
    ///
    /// If the assertion fails, exit with an error message.
    fn assert_exclusive_lang_scope(fields_set: &[bool]) {
        let set_fields_count = fields_set.iter().filter(|b| **b).count();

        if set_fields_count > 1 {
            let mut cmd = Args::command();
            cmd.error(
                ErrorKind::ArgumentConflict,
                "Can only use one language at a time.",
            )
            .exit();
        }
    }

    /// Convert the prepared queries and the literal queries into `CompiledQuery`'s
    fn accumulate_scopes<CQ, PQ>(
        prepared_queries: Vec<PQ>,
        literal_queries: Vec<QueryLiteral>,
        file_queries: Vec<PathBuf>,
    ) -> Result<super::ScoperList, ProgramError>
    where
        CQ: LanguageScoper + TryFrom<QuerySource, Error = TSQueryError> + 'static,
        PQ: Into<CQ>,
    {
        let mut scopers: crate::ScoperList = Vec::new();

        for prepared_query in prepared_queries {
            let compiled_query = prepared_query.into();
            scopers.push(Box::new(compiled_query));
        }

        for query_literal in literal_queries {
            let query_source = query_literal.into();
            let compiled_query = CQ::try_from(query_source)?;
            scopers.push(Box::new(compiled_query));
        }

        for file_query in file_queries {
            let query_source = read_query_from_file(file_query)?;
            let compiled_query = CQ::try_from(query_source)?;
            scopers.push(Box::new(compiled_query));
        }

        Ok(scopers)
    }

    /// Read a literal query as a file.
    fn read_query_from_file(path: PathBuf) -> io::Result<QuerySource> {
        info!("Reading query from file at '{}'", path.display());
        let s = fs::read_to_string(path)?;
        Ok(QuerySource::from(s))
    }

    /// Macro to create a `PreparedQueryParser` for a specific language.
    macro_rules! define_prepared_query_parser {
        (
            $parser_name:ident,
            $query_type:path,
            variants = [$(($variant:ident, $named_variant:ident)),*],
            separator = $separator:expr
        ) => {
            /// A dedicated type to implement `TypedValueParser` for.
            ///
            /// We need a full-blown, dedicated type as we leverage the `inner` parser
            /// of existing types, for which `ValueEnum` is implemented. That way, the
            /// enum variants etc. do not  need to be repeated manually. Only the select
            /// entries where we have a mapping to a named variant need to be listed.
            ///
            /// In essence, this allows us to have enums with only unit variants,
            /// `derive(ValueEnum)` on it, and benefit from that implementation.
            /// Non-unit variant enums are [not supported
            /// yet](https://github.com/clap-rs/clap/issues/2621). We then layer this
            /// parser on top, which just maps CLI args to the **full** enum (which
            /// *does* have some non-unit variants, which just were `skip`ped so they're
            /// compatible with `clap`) surface. Currently, this means splitting args to
            /// support grammar items with the concept of "namedness".
            ///
            /// Some items like structs, classes, functions, modules etc. are naturally
            /// named. Others like comments, literal strings, expression are not - they
            /// are anonymous. Supplying patterns to scope down to individual names of
            /// items makes usage more ergonomic - it allows the pattern to apply to
            /// *just* the names, not the entire scope (which requires multi-line regex
            /// contortions otherwise).
            #[derive(Clone)]
            struct $parser_name;

            impl clap::builder::TypedValueParser for $parser_name {
                type Value = $query_type;

                fn parse_ref(
                    &self,
                    cmd: &Command,
                    arg: Option<&clap::Arg>,
                    value: &OsStr,
                ) -> Result<Self::Value, clap::Error> {
                    let inner = clap::value_parser!($query_type);
                    let val = if let Some(Some((name, pattern))) =
                        value.to_str().map(|s| s.split_once($separator))
                    {
                        // Found a separator! Parse the value as a pattern.
                        let pattern = TreeSitterRegex(Regex::new(pattern).map_err(|e| {
                            let mut err = clap::Error::new(ErrorKind::ValueValidation).with_cmd(cmd);
                            err.insert(
                                clap::error::ContextKind::InvalidValue,
                                clap::error::ContextValue::String(pattern.to_string()),
                            );
                            err.insert(
                                clap::error::ContextKind::Suggested,
                                clap::error::ContextValue::StyledStrs({
                                    // Need `StyledStrs` here - anything else will not print via
                                    // `RichFormatter` (which is the default):
                                    // https://github.com/clap-rs/clap/blob/f046ca6a2b2da2ee0a46cb46544cebaba9f9a45a/clap_builder/src/error/format.rs#L110
                                    let mut s = StyledStr::new();
                                    write!(s, "error was: {e}").unwrap();
                                    vec![s]
                                }),
                            );
                            err.insert(
                                clap::error::ContextKind::InvalidArg,
                                clap::error::ContextValue::String(name.into()),
                            );
                            err
                        })?);

                        let parsed = inner.parse_ref(cmd, arg, OsStr::new(name))?;

                        match parsed {
                            // Is it any of the known variants we have a mapping to a
                            // named variant for?
                            $(
                                <$query_type>::$variant => <$query_type>::$named_variant(pattern),
                            )*

                            // It is not, so using a separator and thus a pattern is not
                            // supported.
                            _ => {
                                let mut err = clap::Error::new(ErrorKind::ArgumentConflict).with_cmd(cmd);

                                // Add some context for user feedback.

                                // A bit hacky - relies on internal implementation, and is
                                // misusing it to a degree:
                                // https://github.com/clap-rs/clap/blob/f046ca6a2b2da2ee0a46cb46544cebaba9f9a45a/clap_builder/src/error/format.rs#L176-L191
                                err.insert(
                                    clap::error::ContextKind::PriorArg,
                                    clap::error::ContextValue::String(format!("a pattern ('{pattern}')")),
                                );
                                err.insert(
                                    clap::error::ContextKind::InvalidArg,
                                    clap::error::ContextValue::String(name.into()),
                                );

                                return Err(err);
                            }
                        }
                    } else {
                        // No separator found, just parse the value as-is using existing
                        // base implementation.
                        inner.parse_ref(cmd, arg, value)?
                    };

                    Ok(val)
                }

                /// Provide possible values for the parser.
                ///
                /// This mainly dispatches on the underlying, existing [`ValueEnum`]
                /// implementation and its value variants/possible values. This manual
                /// step is necessary as the default impl returns `None`. Additionally,
                /// we add the pattern variants.
                fn possible_values(
                    &self,
                ) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
                    // Get all the variant possible values
                    let variants = <$query_type>::value_variants()
                        .iter()
                        .map(|v|
                            v.to_possible_value().expect(
                                "all value variants have a possible mapping, as `ValueEnum` is derived",
                            )
                        )
                        .collect::<Vec<_>>();

                    // Create the pattern values, to be inserted after their base variants
                    let pattern_values = vec![
                        $(
                            (
                                stringify!($variant).to_lowercase(),
                                clap::builder::PossibleValue::new(format!(
                                    "{}{}{}",
                                    stringify!($variant).to_lowercase(),
                                    $separator,
                                    "<PATTERN>"
                                ))
                                .help(format!(
                                    "Like {}, but only considers items whose name matches PATTERN.",
                                    stringify!($variant).to_lowercase()
                                ))
                            ),
                        )*
                    ];

                    // Create a new vector with patterns inserted after their variants
                    let mut result = Vec::with_capacity(variants.len() + pattern_values.len());

                    for val in variants {
                        // Add the base variant
                        result.push(val.clone());

                        // Find and add any matching pattern variant. This ensures
                        // pattern variants are slotted in right after their base
                        // variant, instead of e.g. at the end. Improves docs &
                        // discoverability.
                        for (name, pattern_val) in &pattern_values {
                            if val.get_name() == name {
                                result.push(pattern_val.clone());
                            }
                        }
                    }

                    Some(Box::new(result.into_iter()))
                }
            }
        };
    }

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct CScope {
        /// Scope C code using a prepared query.
        #[arg(long, env, verbatim_doc_comment)]
        c: Vec<c::PreparedQuery>,

        /// Scope C code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        c_query: Vec<QueryLiteral>,

        /// Scope C code using a custom tree-sitter query from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        c_query_file: Vec<PathBuf>,
    }

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct CSharpScope {
        /// Scope C# code using a prepared query.
        #[arg(long, env, verbatim_doc_comment, visible_alias = "cs")]
        csharp: Vec<csharp::PreparedQuery>,

        /// Scope C# code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        csharp_query: Vec<QueryLiteral>,

        /// Scope C# code using a custom tree-sitter query from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        csharp_query_file: Vec<PathBuf>,
    }

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct HclScope {
        #[expect(clippy::doc_markdown)] // CamelCase detected as 'needs backticks'
        /// Scope HashiCorp Configuration Language code using a prepared query.
        #[arg(long, env, verbatim_doc_comment, value_parser = HclPreparedQueryParser)]
        hcl: Vec<hcl::PreparedQuery>,

        #[expect(clippy::doc_markdown)] // CamelCase detected as 'needs backticks'
        /// Scope HashiCorp Configuration Language code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        hcl_query: Vec<QueryLiteral>,

        #[expect(clippy::doc_markdown)] // CamelCase detected as 'needs backticks'
        /// Scope HashiCorp Configuration Language code using a custom tree-sitter query
        /// from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        hcl_query_file: Vec<PathBuf>,
    }

    define_prepared_query_parser!(
        HclPreparedQueryParser,
        hcl::PreparedQuery,
        variants = [
            (RequiredProviders, RequiredProvidersNamed) //
        ],
        separator = NAMED_ITEM_PATTERN_SEPARATOR
    );

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct GoScope {
        /// Scope Go code using a prepared query.
        #[arg(long, env, verbatim_doc_comment, value_parser = GoPreparedQueryParser)]
        go: Vec<go::PreparedQuery>,

        /// Scope Go code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        go_query: Vec<QueryLiteral>,

        /// Scope Go code using a custom tree-sitter query from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        go_query_file: Vec<PathBuf>,
    }

    define_prepared_query_parser!(
        GoPreparedQueryParser,
        go::PreparedQuery,
        variants = [
            (Struct, StructNamed),
            (Interface, InterfaceNamed),
            (Func, FuncNamed)
        ],
        separator = NAMED_ITEM_PATTERN_SEPARATOR
    );

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct PythonScope {
        /// Scope Python code using a prepared query.
        #[arg(long, env, verbatim_doc_comment, visible_alias = "py")]
        python: Vec<python::PreparedQuery>,

        /// Scope Python code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        python_query: Vec<QueryLiteral>,

        /// Scope Python code using a custom tree-sitter query from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        python_query_file: Vec<PathBuf>,
    }

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct RustScope {
        /// Scope Rust code using a prepared query.
        #[arg(long, env, verbatim_doc_comment, visible_alias = "rs", value_parser = RustPreparedQueryParser)]
        rust: Vec<rust::PreparedQuery>,

        /// Scope Rust code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        rust_query: Vec<QueryLiteral>,

        /// Scope Rust code using a custom tree-sitter query from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        rust_query_file: Vec<PathBuf>,
    }

    define_prepared_query_parser!(
        RustPreparedQueryParser,
        rust::PreparedQuery,
        variants = [
            (Struct, StructNamed),
            (Enum, EnumNamed),
            (Fn, FnNamed),
            (Trait, TraitNamed),
            (Mod, ModNamed)
        ],
        separator = NAMED_ITEM_PATTERN_SEPARATOR
    );

    #[derive(Parser, Debug, Clone)]
    #[group(required = false, multiple = false)]
    struct TypeScriptScope {
        /// Scope TypeScript code using a prepared query.
        #[arg(long, env, verbatim_doc_comment, visible_alias = "ts")]
        typescript: Vec<typescript::PreparedQuery>,

        /// Scope TypeScript code using a custom tree-sitter query.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_VALUE)]
        typescript_query: Vec<QueryLiteral>,

        /// Scope TypeScript code using a custom tree-sitter query from file.
        #[arg(long, env, verbatim_doc_comment, value_name = TREE_SITTER_QUERY_FILENAME)]
        typescript_query_file: Vec<PathBuf>,
    }

    #[cfg(feature = "german")]
    #[derive(Parser, Debug)]
    #[group(required = false, multiple = true, id("german-opts"))]
    #[command(next_help_heading = "Options (german)")]
    pub struct GermanOptions {
        /// When some original version and its replacement are equally legal, prefer the
        /// original and do not modify.
        ///
        /// For example, "Busse" (original) and "Buße" (replacement) are equally legal
        /// words: by default, the tool would prefer the latter.
        #[arg(long, env, verbatim_doc_comment)]
        // More fine-grained control is not available. We are not in the business of
        // natural language processing or LLMs, so that's all we can offer...
        pub german_prefer_original: bool,
        /// Always perform any possible replacement ('ae' -> 'ä', 'ss' -> 'ß', etc.),
        /// regardless of legality of the resulting word
        ///
        /// Useful for names, which are otherwise not modifiable as they do not occur in
        /// dictionaries. Called 'naive' as this does not perform legal checks.
        #[arg(long, env, verbatim_doc_comment)]
        pub german_naive: bool,
    }

    /// The literal query as read in from the CLI.
    #[derive(Clone, Debug)]
    struct QueryLiteral(String);

    impl From<String> for QueryLiteral {
        fn from(s: String) -> Self {
            Self(s)
        }
    }

    impl From<QueryLiteral> for QuerySource {
        fn from(query: QueryLiteral) -> Self {
            query.0.into()
        }
    }

    impl Args {
        pub(super) fn init() -> Self {
            Self::parse()
        }

        pub(super) fn command() -> Command {
            <Self as CommandFactory>::command()
        }
    }
}

#[cfg(test)]
mod tests {
    use std::env;
    use std::sync::LazyLock;

    use env_logger::DEFAULT_FILTER_ENV;
    use log::LevelFilter;
    use rstest::rstest;

    use super::*;

    static ENV_MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

    #[rstest]
    #[case(None, 0, LevelFilter::Error)]
    #[case(None, 1, LevelFilter::Warn)]
    #[case(None, 2, LevelFilter::Info)]
    #[case(None, 3, LevelFilter::Debug)]
    #[case(None, 4, LevelFilter::Trace)]
    #[case(None, 5, LevelFilter::Trace)]
    #[case(None, 128, LevelFilter::Trace)]
    #[case(Some("off"), 0, LevelFilter::Off)]
    #[case(Some("off"), 1, LevelFilter::Error)]
    #[case(Some("off"), 2, LevelFilter::Warn)]
    #[case(Some("off"), 3, LevelFilter::Info)]
    #[case(Some("off"), 4, LevelFilter::Debug)]
    #[case(Some("off"), 5, LevelFilter::Trace)]
    #[case(Some("off"), 6, LevelFilter::Trace)]
    #[case(Some("off"), 128, LevelFilter::Trace)]
    #[case(Some("error"), 0, LevelFilter::Error)]
    #[case(Some("error"), 1, LevelFilter::Warn)]
    #[case(Some("error"), 2, LevelFilter::Info)]
    #[case(Some("error"), 3, LevelFilter::Debug)]
    #[case(Some("error"), 4, LevelFilter::Trace)]
    #[case(Some("error"), 5, LevelFilter::Trace)]
    #[case(Some("error"), 128, LevelFilter::Trace)]
    #[case(Some("warn"), 0, LevelFilter::Warn)]
    #[case(Some("warn"), 1, LevelFilter::Info)]
    #[case(Some("warn"), 2, LevelFilter::Debug)]
    #[case(Some("warn"), 3, LevelFilter::Trace)]
    #[case(Some("warn"), 4, LevelFilter::Trace)]
    #[case(Some("warn"), 128, LevelFilter::Trace)]
    #[case(Some("info"), 0, LevelFilter::Info)]
    #[case(Some("info"), 1, LevelFilter::Debug)]
    #[case(Some("info"), 2, LevelFilter::Trace)]
    #[case(Some("info"), 3, LevelFilter::Trace)]
    #[case(Some("info"), 128, LevelFilter::Trace)]
    #[case(Some("debug"), 0, LevelFilter::Debug)]
    #[case(Some("debug"), 1, LevelFilter::Trace)]
    #[case(Some("debug"), 2, LevelFilter::Trace)]
    #[case(Some("debug"), 128, LevelFilter::Trace)]
    #[case(Some("trace"), 0, LevelFilter::Trace)]
    #[case(Some("trace"), 1, LevelFilter::Trace)]
    #[case(Some("trace"), 128, LevelFilter::Trace)]
    fn test_level_filter_from_env_and_verbosity(
        #[case] env_value: Option<&str>,
        #[case] additional_verbosity: u8,
        #[case] expected: LevelFilter,
    ) {
        let _guard = ENV_MUTEX.lock().unwrap();

        #[expect(unsafe_code)]
        if let Some(env_value) = env_value {
            unsafe {
                env::set_var(DEFAULT_FILTER_ENV, env_value);
            }
        } else {
            unsafe {
                // Might be set on parent and fork()ed down
                env::remove_var(DEFAULT_FILTER_ENV);
            }
        }

        let result = level_filter_from_env_and_verbosity(additional_verbosity);
        assert_eq!(result, expected);
    }
}