uncomment 3.10.1

A CLI tool to remove comments from code using tree-sitter for accurate parsing
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
//! The `[lint]` table: which tags mark tracked work, what a valid issue key looks like, and how
//! loudly each rule complains.
//!
//! Nothing here is hardcoded on purpose. The convention this was written for — `TODO(AMVP-12345):`,
//! with `FIXME`/`HACK`/`XXX` rewritten to `TODO` — is one convention among many, so every tag,
//! pattern and severity is configuration and `lint` does nothing at all until `enabled = true`.
//!
//! Both regexes are compiled and validated the moment the table is read, so an unparseable pattern
//! is a configuration error naming the key it came from rather than a panic partway through a run
//! that has already rewritten files.
//!
//! [`LintTable`] is the `lint` field of [`crate::config::Config`], so one config file serves both
//! readers and discovery happens once, in [`crate::config::ConfigManager`]. What is left here is the
//! table's own schema, its layering rule, and turning a resolved table into a validated
//! [`LintConfig`].

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use regex::Regex;
use serde::{Deserialize, Serialize};

use crate::config::ConfigManager;
use crate::paths::absolute_normalized;

pub const DEFAULT_TAGS: [&str; 4] = ["TODO", "FIXME", "HACK", "XXX"];
pub const DEFAULT_CANONICAL_TAG: &str = "TODO";

/// Matched against a comment's text from the tag onwards, so the leading `^\s*` absorbs nothing more
/// than the gap between the comment delimiter and the tag.
///
/// The tags are spelled in the canonical casing and the key half is anchored to upper case
/// deliberately: when `case_sensitive_tags` is false a miscased *tag* is reconciled before this runs
/// (see [`LintConfig::extract_key`]), while a miscased *key* stays no key at all.
pub const DEFAULT_KEY_PATTERN: &str = r"^\s*(?:TODO|FIXME|HACK|XXX)\((?<key>[A-Z][A-Z0-9]+-\d+)\)\s*:";

/// Matched against the current branch name. Deliberately unanchored: Armis branches are
/// `naaman.hirschfeld.AMVP-160815.description`, so the key sits in the middle.
pub const DEFAULT_BRANCH_PATTERN: &str = r"([A-Z][A-Z0-9]+-\d+)";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Counts towards a non-zero exit status.
    Error,
    /// Reported, but the run still succeeds.
    Warn,
    /// Not evaluated at all.
    Off,
}

impl Severity {
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warn => "warn",
            Severity::Off => "off",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Rule {
    /// A tag not written as configured: a different spelling (`FIXME`/`HACK`/`XXX`), or the
    /// canonical spelling in the wrong casing (`todo`, `Todo`).
    TagNotCanonical,
    /// A tag comment carrying no issue key at all — not in a group, not spelled out nearby.
    TodoMissingKey,
    /// An issue key was found, but not upper case: `TODO(amvp-12):`.
    TodoKeyNotUpperCase,
    /// A key was found near the tag, but the tag is not written as `TAG(KEY):` around it — a bare
    /// key in the surrounding text, a `[KEY]` bracket, a tag wrapped in its own `(...)`, or a
    /// leftover fragment such as `(TODO(AMVP-1):):`.
    TagFormNotCanonical,
    /// A tag comment naming the issue the current change is being made under.
    TodoSelfReference,
}

impl Rule {
    pub const ALL: [Rule; 5] = [
        Rule::TagNotCanonical,
        Rule::TodoMissingKey,
        Rule::TodoKeyNotUpperCase,
        Rule::TagFormNotCanonical,
        Rule::TodoSelfReference,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Rule::TagNotCanonical => "tag-not-canonical",
            Rule::TodoMissingKey => "todo-missing-key",
            Rule::TodoKeyNotUpperCase => "todo-key-not-upper-case",
            Rule::TagFormNotCanonical => "tag-form-not-canonical",
            Rule::TodoSelfReference => "todo-self-reference",
        }
    }

    fn index(self) -> usize {
        match self {
            Rule::TagNotCanonical => 0,
            Rule::TodoMissingKey => 1,
            Rule::TodoKeyNotUpperCase => 2,
            Rule::TagFormNotCanonical => 3,
            Rule::TodoSelfReference => 4,
        }
    }
}

/// `[lint.rules]` as written. Absent means "use the default severity", which lets a table that only
/// silences one rule leave the others alone.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RuleTable {
    #[serde(rename = "tag-not-canonical", skip_serializing_if = "Option::is_none")]
    pub tag_not_canonical: Option<Severity>,

    #[serde(rename = "todo-missing-key", skip_serializing_if = "Option::is_none")]
    pub todo_missing_key: Option<Severity>,

    #[serde(rename = "todo-key-not-upper-case", skip_serializing_if = "Option::is_none")]
    pub todo_key_not_upper_case: Option<Severity>,

    #[serde(rename = "tag-form-not-canonical", skip_serializing_if = "Option::is_none")]
    pub tag_form_not_canonical: Option<Severity>,

    #[serde(rename = "todo-self-reference", skip_serializing_if = "Option::is_none")]
    pub todo_self_reference: Option<Severity>,
}

impl RuleTable {
    /// `self` layered on top of `base`: a severity `self` names wins, one it omits is inherited.
    fn layer_over(&self, base: &RuleTable) -> RuleTable {
        RuleTable {
            tag_not_canonical: self.tag_not_canonical.or(base.tag_not_canonical),
            todo_missing_key: self.todo_missing_key.or(base.todo_missing_key),
            todo_key_not_upper_case: self.todo_key_not_upper_case.or(base.todo_key_not_upper_case),
            tag_form_not_canonical: self.tag_form_not_canonical.or(base.tag_form_not_canonical),
            todo_self_reference: self.todo_self_reference.or(base.todo_self_reference),
        }
    }
}

/// The `[lint]` table exactly as written, before any defaulting or regex compilation.
///
/// Every key is optional so that layering can tell "absent" from "set to the default", which is what
/// lets a nested `[lint]` override one key and inherit the rest.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LintTable {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub canonical_tag: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub case_sensitive_tags: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_pattern: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_issue_from_branch: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_doc_comments: Option<bool>,

    #[serde(default)]
    pub rules: RuleTable,
}

impl LintTable {
    /// `self` layered on top of `base`: every key `self` names wins, every key it omits — including
    /// each severity inside `[lint.rules]` — is inherited.
    ///
    /// Merging rather than replacing is what makes a nested `[lint]` a local amendment instead of a
    /// second, unrelated policy: a directory that only silences one rule keeps `enabled` and the tag
    /// vocabulary of the config above it.
    pub fn layer_over(&self, base: &LintTable) -> LintTable {
        LintTable {
            enabled: self.enabled.or(base.enabled),
            tags: self.tags.clone().or_else(|| base.tags.clone()),
            canonical_tag: self.canonical_tag.clone().or_else(|| base.canonical_tag.clone()),
            case_sensitive_tags: self.case_sensitive_tags.or(base.case_sensitive_tags),
            key_pattern: self.key_pattern.clone().or_else(|| base.key_pattern.clone()),
            current_issue_from_branch: self
                .current_issue_from_branch
                .clone()
                .or_else(|| base.current_issue_from_branch.clone()),
            include_doc_comments: self.include_doc_comments.or(base.include_doc_comments),
            rules: self.rules.layer_over(&base.rules),
        }
    }

    /// Reject what is wrong with this table on its own, before it is layered with any other.
    ///
    /// Only the keys this table actually names are judged, so [`crate::config::Config::validate`] can
    /// call it per file and report the file that carries the mistake. Cross-key rules that depend on
    /// the layered result — a canonical tag outside `tags` — are checked in
    /// [`LintConfig::from_table`] instead.
    pub fn validate(&self) -> Result<()> {
        if let Some(tags) = &self.tags {
            if tags.is_empty() {
                bail!("lint.tags is empty: there is nothing to lint for");
            }
            if let Some(blank) = tags.iter().find(|tag| tag.trim().is_empty()) {
                bail!("lint.tags contains a blank tag {blank:?}");
            }
        }
        if let Some(pattern) = &self.key_pattern {
            compile(pattern, "lint.key_pattern", "")?;
        }
        if let Some(pattern) = &self.current_issue_from_branch {
            compile(pattern, "lint.current_issue_from_branch", "")?;
        }

        Ok(())
    }
}

/// How a tag as written in a comment relates to the configured canonical tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TagSpelling {
    /// Written exactly as `canonical_tag`.
    Canonical,
    /// The canonical tag, written with different casing.
    CanonicalMiscased,
    /// A different tag, whatever its casing.
    NotCanonical,
}

/// A validated `[lint]` table with its regexes compiled.
#[derive(Debug)]
pub struct LintConfig {
    pub enabled: bool,
    pub tags: Vec<String>,
    pub canonical_tag: String,
    pub case_sensitive_tags: bool,
    pub key_pattern: Regex,
    /// `key_pattern`, matched case-insensitively in both its tag and key halves. Used only to
    /// *detect* a key written in lower case inside the canonical `TAG(KEY):` group — never to accept
    /// one, so a miscased key is still reported and normalized rather than silently passing.
    key_pattern_ci: Regex,
    pub branch_pattern: Regex,
    /// Locates configured tags inside a comment's text; derived from `tags`, never configured
    /// directly.
    pub tag_pattern: Regex,
    /// Whether doc comments and docstrings are inspected at all. Off by default: documentation
    /// describes an interface to its readers, and a tag word in it — `{"uuid": XXX}`, "returns the
    /// TODO list" — is far more often part of that description than tracked work.
    pub include_doc_comments: bool,
    severities: [Severity; 5],
    /// The config file this came from, for error messages. `None` for the built-in defaults.
    pub source: Option<PathBuf>,
}

impl LintConfig {
    /// Defaults with every rule at `error` — but `enabled = false`, so they do nothing.
    pub fn defaults() -> Result<Self> {
        Self::from_table(&LintTable::default(), None)
    }

    pub fn from_table(table: &LintTable, source: Option<PathBuf>) -> Result<Self> {
        let where_from = || match &source {
            Some(path) => format!(" in {}", path.display()),
            None => String::new(),
        };

        let case_sensitive_tags = table.case_sensitive_tags.unwrap_or(false);

        let tags: Vec<String> = table
            .tags
            .clone()
            .unwrap_or_else(|| DEFAULT_TAGS.iter().map(|tag| (*tag).to_string()).collect());
        if tags.is_empty() {
            bail!("lint.tags{} is empty: there is nothing to lint for", where_from());
        }
        if let Some(blank) = tags.iter().find(|tag| tag.trim().is_empty()) {
            bail!("lint.tags{} contains a blank tag {blank:?}", where_from());
        }
        // Two tags that differ only in casing are one tag once casing stops mattering, and which of
        // the two `--fix` should write is unanswerable. Judged here rather than in
        // `LintTable::validate` because the answer depends on the layered `case_sensitive_tags`,
        // which a table naming only `tags` does not carry.
        if !case_sensitive_tags {
            for (index, tag) in tags.iter().enumerate() {
                if let Some(other) = tags[index + 1..].iter().find(|later| later.eq_ignore_ascii_case(tag)) {
                    bail!(
                        "lint.tags{} lists {tag:?} and {other:?}, which differ only in casing: with \
                         lint.case_sensitive_tags = false they are the same tag",
                        where_from()
                    );
                }
            }
        }

        let canonical_tag = table
            .canonical_tag
            .clone()
            .unwrap_or_else(|| DEFAULT_CANONICAL_TAG.to_string());
        // A canonical tag outside `tags` would make `--fix` non-idempotent: the rewrite would
        // produce a tag no later run recognises.
        if !tags.iter().any(|tag| tag == &canonical_tag) {
            bail!(
                "lint.canonical_tag{} is {canonical_tag:?}, which is not one of lint.tags {tags:?}",
                where_from()
            );
        }

        let key_pattern_source = table.key_pattern.as_deref().unwrap_or(DEFAULT_KEY_PATTERN);
        let key_pattern = compile(key_pattern_source, "lint.key_pattern", &where_from())?;
        let key_pattern_ci = compile(&format!("(?i){key_pattern_source}"), "lint.key_pattern", &where_from())?;
        let branch_pattern = compile(
            table
                .current_issue_from_branch
                .as_deref()
                .unwrap_or(DEFAULT_BRANCH_PATTERN),
            "lint.current_issue_from_branch",
            &where_from(),
        )?;

        let mut alternation = String::new();
        // Casing is a `tag-not-canonical` defect, not a reason to miss the tag — so `fixme` and
        // `Todo` are found and then reported, rather than silently not being tags at all.
        if !case_sensitive_tags {
            alternation.push_str("(?i)");
        }
        alternation.push_str(r"\b(?:");
        // Longest first so `TODO` cannot claim the prefix of a longer configured tag.
        let mut ordered = tags.clone();
        ordered.sort_by(|a, b| b.len().cmp(&a.len()).then(a.cmp(b)));
        for (index, tag) in ordered.iter().enumerate() {
            if index > 0 {
                alternation.push('|');
            }
            alternation.push_str(&regex::escape(tag));
        }
        alternation.push_str(r")\b");
        let tag_pattern = compile(&alternation, "lint.tags", &where_from())?;

        let severities = [
            table.rules.tag_not_canonical.unwrap_or(Severity::Error),
            table.rules.todo_missing_key.unwrap_or(Severity::Error),
            table.rules.todo_key_not_upper_case.unwrap_or(Severity::Error),
            table.rules.tag_form_not_canonical.unwrap_or(Severity::Error),
            table.rules.todo_self_reference.unwrap_or(Severity::Error),
        ];

        Ok(Self {
            enabled: table.enabled.unwrap_or(false),
            tags,
            canonical_tag,
            case_sensitive_tags,
            key_pattern,
            key_pattern_ci,
            branch_pattern,
            tag_pattern,
            include_doc_comments: table.include_doc_comments.unwrap_or(false),
            severities,
            source,
        })
    }

    /// How `tag`, as written in a comment, relates to [`Self::canonical_tag`].
    pub fn classify_tag(&self, tag: &str) -> TagSpelling {
        if tag == self.canonical_tag {
            TagSpelling::Canonical
        } else if tag.eq_ignore_ascii_case(&self.canonical_tag) {
            TagSpelling::CanonicalMiscased
        } else {
            TagSpelling::NotCanonical
        }
    }

    /// The `tag-not-canonical` message for a tag written as `tag`.
    ///
    /// The rule covers two defects — a tag spelled differently from the canonical one, and the
    /// canonical tag spelled with the wrong casing — and they need different wording: "`TODO` should
    /// be written as `TODO`" states nothing at all.
    pub fn tag_not_canonical_message(&self, tag: &str) -> String {
        match self.classify_tag(tag) {
            TagSpelling::CanonicalMiscased => {
                format!("`{tag}` is `{}` written with the wrong casing", self.canonical_tag)
            }
            _ => format!("`{tag}` should be written as `{}`", self.canonical_tag),
        }
    }

    pub fn severity(&self, rule: Rule) -> Severity {
        self.severities[rule.index()]
    }

    pub fn is_on(&self, rule: Rule) -> bool {
        self.severity(rule) != Severity::Off
    }

    /// The issue key in `haystack`, which is a comment's text from a tag onwards.
    ///
    /// Prefers the `key` capture group, falls back to the first group and then to the whole match,
    /// so a pattern written without a named group still works.
    ///
    /// When casing does not decide what is a tag, a miscased tag must not hide the key behind it:
    /// `# todo(AMVP-1):` carries a key and reporting `todo-missing-key` for it would be wrong. But
    /// `key_pattern` is a user-supplied regex that spells the tags out itself, and it is opaque —
    /// there is no way to relax only the half that names the tag. Compiling the whole of it with
    /// `(?i)` would relax the key half too, silently accepting `todo(amvp-1)`. So the *haystack* is
    /// normalised instead: the tag token is rewritten to the casing the pattern expects and every
    /// other byte, the key included, is left exactly as written.
    pub fn extract_key<'t>(&self, haystack: &'t str) -> Option<&'t str> {
        if let Some(range) = self.key_range(haystack) {
            return haystack.get(range);
        }
        if self.case_sensitive_tags {
            return None;
        }

        let respelled = self.tag_respelled_as_configured(haystack)?;
        let range = self.key_range(&respelled)?;
        // Sliced out of the original: `tag_respelled_as_configured` only ever replaces the tag token
        // with a same-length spelling, so the two strings share every offset.
        haystack.get(range)
    }

    /// [`Self::extract_key`], but a key written in lower case is detected too — paired with the byte
    /// range it occupies in `haystack`, so a caller can normalize it in place.
    ///
    /// Still detection only: a lower-case key is returned exactly as written, not upper-cased here,
    /// so the caller can tell the two apart and report the miscased one rather than silently
    /// accepting it.
    pub fn extract_key_relaxed<'t>(&self, haystack: &'t str) -> Option<(&'t str, std::ops::Range<usize>)> {
        if let Some(range) = self.key_range(haystack) {
            return Some((&haystack[range.clone()], range));
        }
        if !self.case_sensitive_tags
            && let Some(respelled) = self.tag_respelled_as_configured(haystack)
            && let Some(range) = self.key_range(&respelled)
        {
            return Some((&haystack[range.clone()], range));
        }
        let range = self.key_range_ci(haystack)?;
        Some((&haystack[range.clone()], range))
    }

    /// Byte range of the key inside `haystack`, matching `key_pattern` case-insensitively in both its
    /// tag and key halves — used only to detect a lower-case key, never to accept one.
    fn key_range_ci(&self, haystack: &str) -> Option<std::ops::Range<usize>> {
        let captures = self.key_pattern_ci.captures(haystack)?;
        captures
            .name("key")
            .or_else(|| captures.get(1))
            .or_else(|| captures.get(0))
            .map(|matched| matched.range())
    }

    /// Byte range of the key inside `haystack`, by the same group preference as [`Self::extract_key`].
    fn key_range(&self, haystack: &str) -> Option<std::ops::Range<usize>> {
        let captures = self.key_pattern.captures(haystack)?;
        captures
            .name("key")
            .or_else(|| captures.get(1))
            .or_else(|| captures.get(0))
            .map(|matched| matched.range())
    }

    /// `haystack` with its first tag occurrence respelled as the configured tag it matches.
    ///
    /// `None` when there is nothing to do or when the rewrite would shift any other byte — the
    /// caller slices the original string at the rewritten one's offsets, so a length change would
    /// silently return the wrong text. Casing a tag is length-preserving for every ASCII tag; the
    /// guard is there for the Unicode ones, where a case fold can change the byte count.
    fn tag_respelled_as_configured(&self, haystack: &str) -> Option<String> {
        let found = self.tag_pattern.find(haystack)?;
        let written = found.as_str();
        let configured = self.tags.iter().find(|tag| tag.eq_ignore_ascii_case(written))?;
        if configured == written || configured.len() != written.len() {
            return None;
        }

        let mut respelled = String::with_capacity(haystack.len());
        respelled.push_str(&haystack[..found.start()]);
        respelled.push_str(configured);
        respelled.push_str(&haystack[found.end()..]);
        Some(respelled)
    }
}

fn compile(pattern: &str, key: &str, where_from: &str) -> Result<Regex> {
    Regex::new(pattern).with_context(|| format!("invalid regex for {key}{where_from}: {pattern}"))
}

/// Per-directory resolution of the `[lint]` table, memoized.
///
/// Discovery and layering belong to [`ConfigManager`], which reads each config file once for every
/// reader; this adds only the compiled, validated form and the memo. Resolution runs as a sequential
/// pre-pass over the files to lint, so the per-file lookup that follows is a map read and a bad
/// pattern is reported before anything is inspected — let alone rewritten.
#[derive(Debug)]
pub struct Resolver<'manager> {
    manager: &'manager ConfigManager,
    /// Relative paths resolve against this, so the cache key is canonical.
    base: PathBuf,
    cache: HashMap<PathBuf, Arc<LintConfig>>,
}

impl<'manager> Resolver<'manager> {
    pub fn new(base: &Path, manager: &'manager ConfigManager) -> Self {
        Self {
            manager,
            base: base.to_path_buf(),
            cache: HashMap::new(),
        }
    }

    /// The table in force for `file`, which need not exist yet.
    pub fn for_file(&mut self, file: &Path) -> Result<Arc<LintConfig>> {
        let absolute = absolute_normalized(&self.base, file);
        let dir = absolute.parent().unwrap_or(&absolute).to_path_buf();
        if let Some(cached) = self.cache.get(&dir) {
            return Ok(Arc::clone(cached));
        }

        let (table, source) = self.manager.lint_table_for_file(&absolute);
        let resolved = Arc::new(LintConfig::from_table(&table.unwrap_or_default(), source)?);
        self.cache.insert(dir, Arc::clone(&resolved));
        Ok(resolved)
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::TempDir;

    use super::*;

    use crate::config::Config;

    /// The `[lint]` table of a whole config document, compiled.
    fn table(toml: &str) -> Result<LintConfig> {
        let config: Config = toml::from_str(toml)?;
        LintConfig::from_table(&config.lint.unwrap_or_default(), None)
    }

    /// The table in force for `file` under `root`, resolved the way a lint run resolves it.
    fn resolve(root: &Path, file: &str) -> Result<Arc<LintConfig>> {
        let manager = ConfigManager::new(root)?;
        Resolver::new(root, &manager).for_file(&root.join(file))
    }

    fn repo() -> TempDir {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join(".git")).unwrap();
        temp
    }

    #[test]
    fn lint_is_inert_until_it_is_enabled() {
        let defaults = LintConfig::defaults().unwrap();
        assert!(!defaults.enabled);
        assert!(table("[lint]\n").unwrap().enabled_is(false));
        assert!(table("[lint]\nenabled = true\n").unwrap().enabled);
        assert!(!table("[lint]\nenabled = false\n").unwrap().enabled);
    }

    #[test]
    fn enabled_alone_is_enough_to_get_the_documented_defaults() {
        let config = table("[lint]\nenabled = true\n").unwrap();
        assert_eq!(config.tags, DEFAULT_TAGS);
        assert_eq!(config.canonical_tag, "TODO");
        for rule in Rule::ALL {
            assert_eq!(config.severity(rule), Severity::Error, "{}", rule.as_str());
        }
    }

    #[test]
    fn the_default_key_pattern_uses_a_named_group_and_the_crates_regex_accepts_it() {
        let config = table("[lint]\nenabled = true\n").unwrap();
        assert!(
            config.key_pattern.capture_names().any(|name| name == Some("key")),
            "the `key` group is what makes the pattern self-documenting"
        );
        assert_eq!(config.extract_key("TODO(AMVP-160815): migrate"), Some("AMVP-160815"));
        assert_eq!(config.extract_key("FIXME(PPSC-42): later"), Some("PPSC-42"));
        assert_eq!(config.extract_key("TODO: no key here"), None);
        assert_eq!(config.extract_key("TODO(lowercase-1): no"), None);
    }

    #[test]
    fn a_pattern_without_a_named_group_falls_back_to_the_first_group() {
        let config = table(
            r#"
[lint]
enabled = true
key_pattern = '^\s*(?:TODO)\[([A-Z]+-\d+)\]'
"#,
        )
        .unwrap();
        assert_eq!(config.extract_key("TODO[ABC-7] do it"), Some("ABC-7"));
    }

    #[test]
    fn both_armis_branch_shapes_yield_the_same_key_with_the_default_pattern() {
        let config = table("[lint]\nenabled = true\n").unwrap();
        for branch in [
            "naaman.hirschfeld.AMVP-160815.ai-rulez-migration",
            "naaman.AMVP-160815.ai-rulez-migration",
        ] {
            let captures = config.branch_pattern.captures(branch);
            let key = captures.as_ref().and_then(|c| c.get(1)).map(|m| m.as_str());
            assert_eq!(key, Some("AMVP-160815"), "branch {branch}");
        }

        assert!(config.branch_pattern.captures("master").is_none());
        assert!(config.branch_pattern.captures("feat/comment-inventory").is_none());
    }

    #[test]
    fn an_invalid_key_pattern_is_a_load_error_naming_the_key() {
        let err = table("[lint]\nenabled = true\nkey_pattern = '([unclosed'\n").unwrap_err();
        let message = format!("{err:#}");
        assert!(message.contains("lint.key_pattern"), "{message}");
    }

    #[test]
    fn an_invalid_branch_pattern_is_a_load_error_naming_the_key() {
        let err = table("[lint]\nenabled = true\ncurrent_issue_from_branch = '(?P<'\n").unwrap_err();
        let message = format!("{err:#}");
        assert!(message.contains("lint.current_issue_from_branch"), "{message}");
    }

    #[test]
    fn a_canonical_tag_outside_tags_is_rejected() {
        let err = table("[lint]\nenabled = true\ntags = ['TODO']\ncanonical_tag = 'NOTE'\n").unwrap_err();
        let message = format!("{err:#}");
        assert!(message.contains("lint.canonical_tag"), "{message}");
    }

    #[test]
    fn empty_or_blank_tags_are_rejected() {
        assert!(format!("{:#}", table("[lint]\ntags = []\n").unwrap_err()).contains("lint.tags"));
        assert!(format!("{:#}", table("[lint]\ntags = ['TODO', '  ']\n").unwrap_err()).contains("lint.tags"));
    }

    #[test]
    fn a_typo_inside_the_lint_table_is_rejected() {
        let err = toml::from_str::<Config>("[lint]\nenable = true\n").unwrap_err();
        assert!(err.to_string().contains("enable"), "{err}");
    }

    #[test]
    fn one_document_carries_the_removal_settings_and_the_lint_table() {
        // `Config` has `deny_unknown_fields`, so before `lint` became a field this document was
        // `unknown field `lint`` for every reader but this one.
        let config: Config = toml::from_str(
            r#"
[global]
remove_todos = true

[lint]
enabled = true
"#,
        )
        .unwrap();
        assert!(config.global.remove_todos);
        assert!(LintConfig::from_table(&config.lint.unwrap(), None).unwrap().enabled);
    }

    #[test]
    fn per_rule_severities_override_only_what_they_name() {
        let config = table(
            r#"
[lint]
enabled = true

[lint.rules]
tag-not-canonical = "warn"
todo-self-reference = "off"
"#,
        )
        .unwrap();
        assert_eq!(config.severity(Rule::TagNotCanonical), Severity::Warn);
        assert_eq!(config.severity(Rule::TodoMissingKey), Severity::Error);
        assert_eq!(config.severity(Rule::TodoSelfReference), Severity::Off);
        assert!(!config.is_on(Rule::TodoSelfReference));
    }

    #[test]
    fn tags_are_matched_longest_first_and_on_word_boundaries() {
        let config = table("[lint]\nenabled = true\ntags = ['TODO', 'TODOLATER']\n").unwrap();
        let found: Vec<&str> = config
            .tag_pattern
            .find_iter("TODOLATER and TODO and TODOS")
            .map(|m| m.as_str())
            .collect();
        assert_eq!(found, vec!["TODOLATER", "TODO"]);
    }

    #[test]
    fn a_tag_with_regex_metacharacters_is_matched_literally() {
        let config = table("[lint]\nenabled = true\ntags = ['TODO', 'T.DO']\n").unwrap();
        assert!(config.tag_pattern.is_match("T.DO: x"));
        assert!(!config.tag_pattern.is_match("TXDO: x"));
    }

    // --- tag casing ------------------------------------------------------------------------------

    #[test]
    fn tags_are_matched_regardless_of_casing_by_default() {
        let config = table("[lint]\nenabled = true\n").unwrap();
        assert!(!config.case_sensitive_tags, "case-insensitive is the default");

        for written in ["TODO", "todo", "Todo", "ToDo", "FIXME", "fixme", "Fixme", "hack", "xXx"] {
            assert!(config.tag_pattern.is_match(&format!("// {written}: x")), "{written}");
        }

        // Word boundaries still hold, so a longer word is not a tag in either casing.
        assert!(!config.tag_pattern.is_match("// TODOS are tracked in Jira"));
        assert!(!config.tag_pattern.is_match("// todos are tracked in Jira"));
    }

    #[test]
    fn case_sensitive_tags_restores_literal_matching() {
        let config = table("[lint]\nenabled = true\ncase_sensitive_tags = true\n").unwrap();
        assert!(config.case_sensitive_tags);
        assert!(config.tag_pattern.is_match("// TODO: x"));
        for written in ["todo", "Todo", "fixme", "xXx"] {
            assert!(!config.tag_pattern.is_match(&format!("// {written}: x")), "{written}");
        }
    }

    #[test]
    fn a_miscased_tag_is_classified_apart_from_a_differently_spelled_one() {
        let config = table("[lint]\nenabled = true\n").unwrap();
        assert_eq!(config.classify_tag("TODO"), TagSpelling::Canonical);
        assert_eq!(config.classify_tag("todo"), TagSpelling::CanonicalMiscased);
        assert_eq!(config.classify_tag("Todo"), TagSpelling::CanonicalMiscased);
        assert_eq!(config.classify_tag("FIXME"), TagSpelling::NotCanonical);
        assert_eq!(config.classify_tag("fixme"), TagSpelling::NotCanonical);
    }

    #[test]
    fn a_casing_only_violation_does_not_read_as_a_tautology() {
        let config = table("[lint]\nenabled = true\n").unwrap();

        // The defect is the casing, so the message cannot be "`TODO` should be written as `TODO`".
        let miscased = config.tag_not_canonical_message("todo");
        assert!(miscased.contains("casing"), "{miscased}");
        assert!(miscased.contains("`todo`") && miscased.contains("`TODO`"), "{miscased}");

        // A differently spelled tag keeps the wording it has always had.
        assert_eq!(
            config.tag_not_canonical_message("FIXME"),
            "`FIXME` should be written as `TODO`"
        );
        assert_eq!(
            config.tag_not_canonical_message("fixme"),
            "`fixme` should be written as `TODO`"
        );
    }

    #[test]
    fn a_miscased_tag_does_not_hide_its_key_but_a_miscased_key_is_still_rejected() {
        let config = table("[lint]\nenabled = true\n").unwrap();

        // The tag half of `key_pattern` has to tolerate the casing the tag was written in …
        assert_eq!(config.extract_key("todo(AMVP-1): x"), Some("AMVP-1"));
        assert_eq!(config.extract_key("Todo(AMVP-1): x"), Some("AMVP-1"));
        assert_eq!(config.extract_key("fixme(PPSC-42): x"), Some("PPSC-42"));

        // … while the key half must not, or `todo(amvp-123)` silently counts as keyed.
        assert_eq!(config.extract_key("todo(amvp-1): x"), None);
        assert_eq!(config.extract_key("TODO(amvp-1): x"), None);
        assert_eq!(config.extract_key("fixme(ppsc-42): x"), None);
    }

    #[test]
    fn case_sensitive_tags_keeps_the_key_pattern_exactly_as_strict_as_it_is_written() {
        let config = table("[lint]\nenabled = true\ncase_sensitive_tags = true\n").unwrap();
        assert_eq!(config.extract_key("TODO(AMVP-1): x"), Some("AMVP-1"));
        assert_eq!(config.extract_key("todo(AMVP-1): x"), None);
    }

    #[test]
    fn tags_differing_only_in_casing_are_rejected_unless_matching_is_case_sensitive() {
        let error = table("[lint]\nenabled = true\ntags = ['TODO', 'todo']\n").unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("lint.tags"), "{message}");
        assert!(message.contains("casing"), "{message}");

        // With literal matching the two really are separate tags, so the pair is legitimate.
        let config = table("[lint]\nenabled = true\ntags = ['TODO', 'todo']\ncase_sensitive_tags = true\n").unwrap();
        assert_eq!(config.tags, vec!["TODO", "todo"]);
    }

    #[test]
    fn a_canonical_tag_that_only_differs_from_tags_in_casing_is_still_rejected() {
        // Case-insensitive *matching* does not make the two spellings interchangeable in the
        // configuration: `--fix` writes `canonical_tag` verbatim, so it has to be in `tags` verbatim.
        let error = table("[lint]\nenabled = true\ntags = ['TODO']\ncanonical_tag = 'todo'\n").unwrap_err();
        assert!(format!("{error:#}").contains("lint.canonical_tag"));
    }

    #[test]
    fn case_sensitive_tags_layers_key_by_key_and_absent_is_not_false() {
        let temp = repo();
        let root = temp.path();
        fs::create_dir_all(root.join("nested")).unwrap();

        fs::write(
            root.join(".uncomment.toml"),
            "[lint]\nenabled = true\ncase_sensitive_tags = true\n",
        )
        .unwrap();
        // Does not name `case_sensitive_tags`, so the outer `true` has to survive — and `['NOTE',
        // 'note']` is only a legal pair of tags because it did.
        fs::write(
            root.join("nested/.uncomment.toml"),
            "[lint]\ntags = ['NOTE', 'note']\ncanonical_tag = 'NOTE'\n",
        )
        .unwrap();

        assert!(resolve(root, "a.rs").unwrap().case_sensitive_tags);
        let below = resolve(root, "nested/b.rs").unwrap();
        assert!(
            below.case_sensitive_tags,
            "an absent key must inherit, not reset to the default"
        );
        assert_eq!(below.tags, vec!["NOTE", "note"]);

        // And a nested table that names it explicitly wins.
        fs::write(
            root.join("nested/.uncomment.toml"),
            "[lint]\ncase_sensitive_tags = false\n",
        )
        .unwrap();
        assert!(!resolve(root, "nested/b.rs").unwrap().case_sensitive_tags);
    }

    #[test]
    fn a_table_naming_only_case_sensitive_tags_is_valid_on_its_own() {
        let table: LintTable = toml::from_str("case_sensitive_tags = true\n").unwrap();
        assert!(table.validate().is_ok());
        assert_eq!(table.case_sensitive_tags, Some(true));

        // And a typo in it is refused like any other key.
        let error = toml::from_str::<LintTable>("case_sensitive_tag = true\n").unwrap_err();
        assert!(error.to_string().contains("case_sensitive_tag"), "{error}");
    }

    // --- documentation ---------------------------------------------------------------------------

    #[test]
    fn doc_comments_are_out_of_scope_unless_include_doc_comments_is_set() {
        assert!(!table("[lint]\nenabled = true\n").unwrap().include_doc_comments);
        assert!(
            table("[lint]\nenabled = true\ninclude_doc_comments = true\n")
                .unwrap()
                .include_doc_comments
        );
        assert!(
            !table("[lint]\nenabled = true\ninclude_doc_comments = false\n")
                .unwrap()
                .include_doc_comments
        );
    }

    #[test]
    fn include_doc_comments_layers_key_by_key_and_absent_is_not_false() {
        let temp = repo();
        let root = temp.path();
        fs::create_dir_all(root.join("nested")).unwrap();

        fs::write(
            root.join(".uncomment.toml"),
            "[lint]\nenabled = true\ninclude_doc_comments = true\n",
        )
        .unwrap();
        fs::write(
            root.join("nested/.uncomment.toml"),
            "[lint.rules]\ntag-not-canonical = 'off'\n",
        )
        .unwrap();

        assert!(resolve(root, "a.rs").unwrap().include_doc_comments);
        assert!(
            resolve(root, "nested/b.rs").unwrap().include_doc_comments,
            "an absent key must inherit, not reset to the default"
        );

        fs::write(
            root.join("nested/.uncomment.toml"),
            "[lint]\ninclude_doc_comments = false\n",
        )
        .unwrap();
        assert!(!resolve(root, "nested/b.rs").unwrap().include_doc_comments);
    }

    #[test]
    fn a_table_naming_only_include_doc_comments_is_valid_and_a_typo_in_it_is_not() {
        let table: LintTable = toml::from_str("include_doc_comments = true\n").unwrap();
        assert!(table.validate().is_ok());
        assert_eq!(table.include_doc_comments, Some(true));

        let error = toml::from_str::<LintTable>("include_doc_comment = true\n").unwrap_err();
        assert!(error.to_string().contains("include_doc_comment"), "{error}");
    }

    #[test]
    fn a_nested_table_overrides_only_the_keys_it_names() {
        let temp = repo();
        let root = temp.path();
        fs::create_dir_all(root.join("nested/deeper")).unwrap();

        fs::write(
            root.join(".uncomment.toml"),
            "[lint]\nenabled = true\ntags = ['TODO']\n\n[lint.rules]\ntag-not-canonical = 'warn'\n",
        )
        .unwrap();
        fs::write(
            root.join("nested/.uncomment.toml"),
            "[lint]\ntags = ['NOTE']\ncanonical_tag = 'NOTE'\n",
        )
        .unwrap();

        let above = resolve(root, "a.rs").unwrap();
        assert_eq!(above.tags, vec!["TODO"]);
        assert_eq!(above.canonical_tag, "TODO");

        let below = resolve(root, "nested/b.rs").unwrap();
        assert_eq!(below.tags, vec!["NOTE"]);
        // Named by neither the nested table nor a default: inherited from the root.
        assert!(below.enabled, "`enabled` must come from the config above");
        assert_eq!(below.severity(Rule::TagNotCanonical), Severity::Warn);
        assert_eq!(below.severity(Rule::TodoMissingKey), Severity::Error);

        // And the nested table keeps applying further down, where no config of its own exists.
        assert_eq!(resolve(root, "nested/deeper/c.rs").unwrap().tags, vec!["NOTE"]);
    }

    #[test]
    fn a_config_without_a_lint_table_leaves_the_one_above_it_in_force() {
        let temp = repo();
        let root = temp.path();
        fs::create_dir_all(root.join("nested")).unwrap();

        fs::write(root.join(".uncomment.toml"), "[lint]\nenabled = true\n").unwrap();
        fs::write(root.join("nested/.uncomment.toml"), "[global]\nremove_todos = true\n").unwrap();

        assert!(resolve(root, "nested/b.rs").unwrap().enabled);
    }

    #[test]
    fn discovery_stops_at_the_git_root() {
        let temp = TempDir::new().unwrap();
        let outside = temp.path();
        let repo = outside.join("repo");
        fs::create_dir_all(repo.join(".git")).unwrap();

        fs::write(outside.join(".uncomment.toml"), "[lint]\nenabled = true\n").unwrap();

        assert!(
            !resolve(&repo, "a.rs").unwrap().enabled,
            "a config above the repository root must not apply"
        );
    }

    #[test]
    fn a_forced_config_file_skips_discovery_entirely() {
        let temp = repo();
        let root = temp.path();
        fs::create_dir_all(root.join("nested")).unwrap();
        fs::write(root.join(".uncomment.toml"), "[lint]\nenabled = false\n").unwrap();
        fs::write(root.join("nested/.uncomment.toml"), "[lint]\ntags = ['XXX']\n").unwrap();

        let forced = root.join("forced.toml");
        fs::write(
            &forced,
            "[lint]\nenabled = true\ntags = ['NOTE']\ncanonical_tag = 'NOTE'\n",
        )
        .unwrap();

        let manager = ConfigManager::from_config_file(root, &forced).unwrap();
        let mut resolver = Resolver::new(root, &manager);
        for file in ["a.rs", "nested/b.rs"] {
            let config = resolver.for_file(&root.join(file)).unwrap();
            assert!(config.enabled, "{file}");
            assert_eq!(config.tags, vec!["NOTE"], "{file}");
        }
    }

    #[test]
    fn an_invalid_pattern_in_a_discovered_file_names_that_file() {
        let temp = repo();
        let root = temp.path();
        fs::write(
            root.join(".uncomment.toml"),
            "[lint]\nenabled = true\nkey_pattern = '([unclosed'\n",
        )
        .unwrap();

        // A config on the invocation directory's own chain is loaded eagerly, so this is refused
        // before any resolution happens at all.
        let error = ConfigManager::new(root).unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("lint.key_pattern"), "{message}");
        assert!(message.contains(".uncomment.toml"), "{message}");
    }

    #[test]
    fn an_invalid_pattern_below_the_invocation_directory_names_that_file() {
        let temp = repo();
        let root = temp.path();
        fs::create_dir_all(root.join("nested")).unwrap();
        fs::write(root.join(".uncomment.toml"), "[lint]\nenabled = true\n").unwrap();
        fs::write(
            root.join("nested/.uncomment.toml"),
            "[lint]\nkey_pattern = '([unclosed'\n",
        )
        .unwrap();

        // Below the invocation directory a config is discovered from a call that cannot fail, so the
        // failure is recorded rather than returned — and the run has to check for it.
        let manager = ConfigManager::new(root).unwrap();
        Resolver::new(root, &manager)
            .for_file(&root.join("nested/b.rs"))
            .unwrap();
        let recorded = manager.deferred_config_error().expect("the broken config was rejected");
        assert!(recorded.contains("lint.key_pattern"), "{recorded}");
        assert!(recorded.contains("nested"), "{recorded}");
    }

    #[test]
    fn a_table_is_validated_on_its_own_before_it_is_layered() {
        let broken: LintTable = toml::from_str("key_pattern = '([unclosed'\n").unwrap();
        let message = format!("{:#}", broken.validate().unwrap_err());
        assert!(message.contains("lint.key_pattern"), "{message}");

        // Only the keys the table names are judged: a table that sets `tags` alone must not be
        // rejected for the canonical tag it inherits.
        let partial: LintTable = toml::from_str("tags = ['NOTE']\n").unwrap();
        assert!(partial.validate().is_ok());
        assert!(toml::from_str::<LintTable>("tags = []\n").unwrap().validate().is_err());
    }

    impl LintConfig {
        fn enabled_is(&self, expected: bool) -> bool {
            self.enabled == expected
        }
    }
}