Skip to main content

alint_rules/
no_submodules.rs

1//! `no_submodules` — flag the presence of a `.gitmodules` file at
2//! the repo root.
3//!
4//! Submodules introduce a second source of truth (the submodule's
5//! commit pointer) that drifts silently, complicates CI, and
6//! surprises users who `git clone` without `--recurse-submodules`.
7//! Many projects have adopted vendoring or package managers and
8//! want to keep submodules banned forever.
9//!
10//! This rule is intentionally *not* configurable by `paths` —
11//! `.gitmodules` at the repo root is what actually enables git
12//! submodules, and letting users override that would invite
13//! footguns. For more general "file X must not exist" checks,
14//! use `file_absent` instead.
15//!
16//! Fixable via `file_remove`, which deletes `.gitmodules`. Note
17//! this is the surface-level fix — the user still needs to run
18//! `git submodule deinit` and clean up `.git/modules/` themselves.
19
20use alint_core::{
21    Context, Error, FixSpec, Fixer, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation,
22    reject_scope_filter_with_reason,
23};
24
25use crate::fixers::FileRemoveFixer;
26
27#[derive(Debug)]
28pub struct NoSubmodulesRule {
29    id: String,
30    level: Level,
31    policy_url: Option<String>,
32    message: Option<String>,
33    scope: Scope,
34    fixer: Option<FileRemoveFixer>,
35}
36
37impl Rule for NoSubmodulesRule {
38    fn id(&self) -> &str {
39        &self.id
40    }
41    fn level(&self) -> Level {
42        self.level
43    }
44    fn policy_url(&self) -> Option<&str> {
45        self.policy_url.as_deref()
46    }
47
48    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
49        let mut violations = Vec::new();
50        for entry in ctx.index.files() {
51            if !self.scope.matches(&entry.path, ctx.index) {
52                continue;
53            }
54            let msg = self.message.clone().unwrap_or_else(|| {
55                "`.gitmodules` present — git submodules are forbidden".to_string()
56            });
57            violations.push(Violation::new(msg).with_path(entry.path.clone()));
58        }
59        Ok(violations)
60    }
61
62    fn fixer(&self) -> Option<&dyn Fixer> {
63        self.fixer.as_ref().map(|f| f as &dyn Fixer)
64    }
65}
66
67pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
68    if spec.paths.is_some() {
69        return Err(Error::rule_config(
70            &spec.id,
71            "no_submodules does not accept a `paths` field; it always targets `.gitmodules` at \
72             the repo root. Use `file_absent` for more general patterns.",
73        ));
74    }
75    reject_scope_filter_with_reason(
76        spec,
77        "no_submodules",
78        "this rule is hardcoded to inspect `.gitmodules` at the repo root and does not iterate \
79         the file index",
80    )?;
81    let fixer = match &spec.fix {
82        Some(FixSpec::FileRemove { .. }) => Some(FileRemoveFixer),
83        Some(other) => {
84            return Err(Error::rule_config(
85                &spec.id,
86                format!(
87                    "fix.{} is not compatible with no_submodules",
88                    other.op_name()
89                ),
90            ));
91        }
92        None => None,
93    };
94    let pinned = PathsSpec::Single(".gitmodules".to_string());
95    Ok(Box::new(NoSubmodulesRule {
96        id: spec.id.clone(),
97        level: spec.level,
98        policy_url: spec.policy_url.clone(),
99        message: spec.message.clone(),
100        scope: Scope::from_paths_spec(&pinned)?,
101        fixer,
102    }))
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use crate::test_support::{ctx, index, spec_yaml};
109    use std::path::Path;
110
111    #[test]
112    fn build_rejects_paths_field() {
113        let spec = spec_yaml(
114            "id: t\n\
115             kind: no_submodules\n\
116             paths: \"**\"\n\
117             level: warning\n",
118        );
119        let err = build(&spec).unwrap_err().to_string();
120        assert!(err.contains("paths"), "unexpected: {err}");
121    }
122
123    #[test]
124    fn build_accepts_minimal_config() {
125        let spec = spec_yaml(
126            "id: t\n\
127             kind: no_submodules\n\
128             level: warning\n",
129        );
130        assert!(build(&spec).is_ok());
131    }
132
133    #[test]
134    fn build_accepts_file_remove_fix() {
135        let spec = spec_yaml(
136            "id: t\n\
137             kind: no_submodules\n\
138             level: warning\n\
139             fix:\n  \
140               file_remove: {}\n",
141        );
142        let rule = build(&spec).unwrap();
143        assert!(rule.fixer().is_some());
144    }
145
146    #[test]
147    fn build_rejects_incompatible_fix() {
148        let spec = spec_yaml(
149            "id: t\n\
150             kind: no_submodules\n\
151             level: warning\n\
152             fix:\n  \
153               file_create:\n    \
154                 content: \"x\"\n",
155        );
156        assert!(build(&spec).is_err());
157    }
158
159    #[test]
160    fn evaluate_passes_without_gitmodules() {
161        let spec = spec_yaml(
162            "id: t\n\
163             kind: no_submodules\n\
164             level: warning\n",
165        );
166        let rule = build(&spec).unwrap();
167        let idx = index(&["README.md", ".gitignore"]);
168        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
169        assert!(v.is_empty());
170    }
171
172    #[test]
173    fn evaluate_fires_when_gitmodules_present() {
174        let spec = spec_yaml(
175            "id: t\n\
176             kind: no_submodules\n\
177             level: warning\n",
178        );
179        let rule = build(&spec).unwrap();
180        let idx = index(&[".gitmodules", "README.md"]);
181        let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
182        assert_eq!(v.len(), 1);
183    }
184
185    #[test]
186    fn build_rejects_scope_filter() {
187        // no_submodules is a fixed-target rule; scope_filter is
188        // semantically meaningless and silently ignoring it
189        // would surprise users. Build must reject it loudly.
190        let spec = spec_yaml(
191            "id: t\n\
192             kind: no_submodules\n\
193             scope_filter:\n  \
194               has_ancestor: marker.lock\n\
195             level: warning\n",
196        );
197        let err = build(&spec).unwrap_err().to_string();
198        assert!(
199            err.contains("scope_filter is not supported on no_submodules"),
200            "unexpected error: {err}"
201        );
202    }
203}