Skip to main content

alint_rules/
no_case_conflicts.rs

1//! `no_case_conflicts` — flag two paths that differ only by
2//! case (e.g. `README.md` + `readme.md`). Such pairs cannot
3//! coexist on case-insensitive filesystems (macOS HFS+/APFS
4//! default, Windows NTFS in its default mode), so committing
5//! them breaks checkouts for those developers.
6//!
7//! Check-only — renaming which one to keep is a human decision.
8
9use std::collections::BTreeMap;
10use std::path::PathBuf;
11
12use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
13
14#[derive(Debug)]
15pub struct NoCaseConflictsRule {
16    id: String,
17    level: Level,
18    policy_url: Option<String>,
19    message: Option<String>,
20    scope: Scope,
21}
22
23impl Rule for NoCaseConflictsRule {
24    fn id(&self) -> &str {
25        &self.id
26    }
27    fn level(&self) -> Level {
28        self.level
29    }
30    fn policy_url(&self) -> Option<&str> {
31        self.policy_url.as_deref()
32    }
33
34    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
35        // Group paths by their lowercased form.
36        let mut groups: BTreeMap<String, Vec<PathBuf>> = BTreeMap::new();
37        for entry in ctx.index.files() {
38            if !self.scope.matches(&entry.path) {
39                continue;
40            }
41            let Some(as_str) = entry.path.to_str() else {
42                continue;
43            };
44            groups
45                .entry(as_str.to_ascii_lowercase())
46                .or_default()
47                .push(entry.path.clone());
48        }
49        let mut violations = Vec::new();
50        for (_lower, paths) in groups {
51            if paths.len() < 2 {
52                continue;
53            }
54            let names: Vec<String> = paths.iter().map(|p| p.display().to_string()).collect();
55            for p in &paths {
56                let msg = self.message.clone().unwrap_or_else(|| {
57                    format!(
58                        "case-insensitive collision: {} (collides with: {})",
59                        p.display(),
60                        names
61                            .iter()
62                            .filter(|n| *n != &p.display().to_string())
63                            .cloned()
64                            .collect::<Vec<_>>()
65                            .join(", ")
66                    )
67                });
68                violations.push(Violation::new(msg).with_path(p));
69            }
70        }
71        Ok(violations)
72    }
73}
74
75pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
76    let paths = spec.paths.as_ref().ok_or_else(|| {
77        Error::rule_config(
78            &spec.id,
79            "no_case_conflicts requires a `paths` field (often `\"**\"`)",
80        )
81    })?;
82    if spec.fix.is_some() {
83        return Err(Error::rule_config(
84            &spec.id,
85            "no_case_conflicts has no fix op — renaming which path to keep is a human decision",
86        ));
87    }
88    Ok(Box::new(NoCaseConflictsRule {
89        id: spec.id.clone(),
90        level: spec.level,
91        policy_url: spec.policy_url.clone(),
92        message: spec.message.clone(),
93        scope: Scope::from_paths_spec(paths)?,
94    }))
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::test_support::{ctx, index, spec_yaml};
101    use std::path::Path;
102
103    #[test]
104    fn build_rejects_missing_paths_field() {
105        let spec = spec_yaml(
106            "id: t\n\
107             kind: no_case_conflicts\n\
108             level: warning\n",
109        );
110        assert!(build(&spec).is_err());
111    }
112
113    #[test]
114    fn build_rejects_fix_block() {
115        let spec = spec_yaml(
116            "id: t\n\
117             kind: no_case_conflicts\n\
118             paths: \"**\"\n\
119             level: warning\n\
120             fix:\n  \
121               file_remove: {}\n",
122        );
123        assert!(build(&spec).is_err());
124    }
125
126    #[test]
127    fn evaluate_passes_when_paths_unique_after_lowercase() {
128        let spec = spec_yaml(
129            "id: t\n\
130             kind: no_case_conflicts\n\
131             paths: \"**\"\n\
132             level: warning\n",
133        );
134        let rule = build(&spec).unwrap();
135        let i = index(&["README.md", "src/main.rs", "Cargo.toml"]);
136        let v = rule.evaluate(&ctx(Path::new("/fake"), &i)).unwrap();
137        assert!(v.is_empty());
138    }
139
140    #[test]
141    fn evaluate_fires_one_violation_per_collision_member() {
142        let spec = spec_yaml(
143            "id: t\n\
144             kind: no_case_conflicts\n\
145             paths: \"**\"\n\
146             level: warning\n",
147        );
148        let rule = build(&spec).unwrap();
149        // README.md and readme.md collide → both emitted.
150        let i = index(&["README.md", "readme.md", "Cargo.toml"]);
151        let v = rule.evaluate(&ctx(Path::new("/fake"), &i)).unwrap();
152        assert_eq!(v.len(), 2, "two collision members should fire");
153    }
154
155    #[test]
156    fn evaluate_fires_on_three_way_collision() {
157        let spec = spec_yaml(
158            "id: t\n\
159             kind: no_case_conflicts\n\
160             paths: \"**\"\n\
161             level: warning\n",
162        );
163        let rule = build(&spec).unwrap();
164        let i = index(&["README.md", "readme.md", "ReadMe.md"]);
165        let v = rule.evaluate(&ctx(Path::new("/fake"), &i)).unwrap();
166        assert_eq!(v.len(), 3, "three collision members should fire");
167    }
168}