Skip to main content

grit_lib/
submodule_ignore.rs

1//! Submodule ignore policy (`diff.ignoreSubmodules`, `submodule.<name>.ignore`, `.gitmodules`).
2//!
3//! Matches Git's `submodule-config` precedence for worktree diffs used by `status` and `diff`.
4
5use std::path::Path;
6
7use crate::config::{ConfigEntry, ConfigFile, ConfigScope, ConfigSet};
8
9/// Submodule ignore mode for worktree gitlink comparisons (Git `--ignore-submodules`,
10/// `diff.ignoreSubmodules`, `submodule.<name>.ignore`).
11#[non_exhaustive]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum SubmoduleIgnoreMode {
14    /// Report new submodule commits and dirty tracked content inside the checkout.
15    #[default]
16    None,
17    /// Ignore untracked paths inside the submodule only.
18    Untracked,
19    /// Ignore dirty worktrees when the recorded gitlink commit matches the checkout HEAD.
20    Dirty,
21    /// Omit gitlink worktree drift when the checkout HEAD matches the recorded gitlink, and also
22    /// omit a moved submodule HEAD (Git `ignore=all`).
23    All,
24}
25
26/// Parse `none|untracked|dirty|all`. Unknown values fall back to [`SubmoduleIgnoreMode::None`].
27#[must_use]
28pub fn parse_submodule_ignore_value(raw: &str) -> SubmoduleIgnoreMode {
29    match raw.trim().to_ascii_lowercase().as_str() {
30        "untracked" => SubmoduleIgnoreMode::Untracked,
31        "dirty" => SubmoduleIgnoreMode::Dirty,
32        "all" => SubmoduleIgnoreMode::All,
33        _ => SubmoduleIgnoreMode::None,
34    }
35}
36
37/// Parsed `.gitmodules` entries for path→name mapping and per-name fields.
38struct GitmodulesFile {
39    entries: Vec<ConfigEntry>,
40}
41
42impl GitmodulesFile {
43    fn load(work_tree: &Path) -> Option<Self> {
44        let gitmodules = work_tree.join(".gitmodules");
45        let content = std::fs::read_to_string(&gitmodules).ok()?;
46        let (entries, _) =
47            ConfigFile::parse_gitmodules_best_effort(&gitmodules, &content, ConfigScope::Local);
48        Some(Self { entries })
49    }
50
51    fn name_for_path(&self, path: &str) -> Option<String> {
52        for e in &self.entries {
53            let key = &e.key;
54            let Some(rest) = key.strip_prefix("submodule.") else {
55                continue;
56            };
57            let Some(name) = rest.strip_suffix(".path") else {
58                continue;
59            };
60            if e.value
61                .as_deref()
62                .is_some_and(|p| p.replace('\\', "/") == path)
63            {
64                return Some(name.to_owned());
65            }
66        }
67        None
68    }
69
70    fn field_value(&self, name: &str, field: &str) -> Option<String> {
71        let key = format!("submodule.{name}.{field}");
72        // Git config uses last value wins for duplicate keys in one file.
73        self.entries
74            .iter()
75            .rev()
76            .find(|e| e.key == key)
77            .and_then(|e| e.value.clone())
78    }
79}
80
81fn submodule_name_from_config_paths(cfg: &ConfigSet, path: &str) -> Option<String> {
82    for e in cfg.entries() {
83        let key = &e.key;
84        if let Some(rest) = key.strip_prefix("submodule.") {
85            if let Some(name) = rest.strip_suffix(".path") {
86                if e.value
87                    .as_deref()
88                    .is_some_and(|p| p.replace('\\', "/") == path)
89                {
90                    return Some(name.to_owned());
91                }
92            }
93        }
94    }
95    None
96}
97
98/// Submodule logical name for a gitlink path (defaults to the path when unregistered).
99#[must_use]
100pub fn submodule_name_for_gitlink_path(
101    cfg: &ConfigSet,
102    work_tree: &Path,
103    gitlink_path: &str,
104) -> String {
105    let path_norm = gitlink_path.replace('\\', "/");
106    submodule_name_from_config_paths(cfg, &path_norm)
107        .or_else(|| GitmodulesFile::load(work_tree).and_then(|gm| gm.name_for_path(&path_norm)))
108        .unwrap_or(path_norm)
109}
110
111/// Effective ignore mode for `gitlink_path` in the superproject work tree.
112///
113/// Precedence: `submodule.<name>.ignore` in the loaded [`ConfigSet`], then the same key from
114/// `.gitmodules`, then `diff.ignoreSubmodules`, default [`SubmoduleIgnoreMode::None`].
115#[must_use]
116pub fn submodule_ignore_for_path(
117    cfg: &ConfigSet,
118    work_tree: &Path,
119    gitlink_path: &str,
120) -> SubmoduleIgnoreMode {
121    let name = submodule_name_for_gitlink_path(cfg, work_tree, gitlink_path);
122    let per_name_key = format!("submodule.{name}.ignore");
123    if let Some(v) = cfg.value(&per_name_key) {
124        return parse_submodule_ignore_value(&v);
125    }
126    if let Some(gm) = GitmodulesFile::load(work_tree) {
127        if let Some(v) = gm.field_value(&name, "ignore") {
128            return parse_submodule_ignore_value(&v);
129        }
130    }
131    if let Some(v) = cfg.value("diff.ignoreSubmodules") {
132        return parse_submodule_ignore_value(&v);
133    }
134    SubmoduleIgnoreMode::None
135}
136
137/// Whether staged index-vs-`HEAD` diffs should omit this gitlink (`git diff --cached` with ignore=all).
138#[must_use]
139pub fn staged_gitlink_omitted_in_diff(
140    cfg: &ConfigSet,
141    work_tree: &Path,
142    gitlink_path: &str,
143) -> bool {
144    submodule_ignore_for_path(cfg, work_tree, gitlink_path) == SubmoduleIgnoreMode::All
145}
146
147/// Whether a gitlink worktree diff entry should be omitted given ignore policy.
148///
149/// `ref_matches` is true when the submodule checkout HEAD equals the parent index gitlink OID.
150#[must_use]
151pub fn gitlink_worktree_change_suppressed(
152    ignore: SubmoduleIgnoreMode,
153    ref_matches: bool,
154    flags: crate::diff::SubmodulePorcelainFlags,
155) -> bool {
156    match ignore {
157        SubmoduleIgnoreMode::All => true,
158        _ if !ref_matches => false,
159        SubmoduleIgnoreMode::None => false,
160        SubmoduleIgnoreMode::Untracked => !flags.modified && flags.untracked,
161        SubmoduleIgnoreMode::Dirty => flags.modified || flags.untracked,
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::diff::SubmodulePorcelainFlags;
169    use std::fs;
170    use tempfile::tempdir;
171
172    #[test]
173    fn parse_submodule_ignore_rejects_unknown() {
174        assert_eq!(
175            parse_submodule_ignore_value("bogus"),
176            SubmoduleIgnoreMode::None
177        );
178        assert_eq!(
179            parse_submodule_ignore_value("all"),
180            SubmoduleIgnoreMode::All
181        );
182    }
183
184    #[test]
185    fn gitlink_suppressed_for_dirty_and_all_when_ref_matches() {
186        let flags = SubmodulePorcelainFlags {
187            modified: true,
188            ..Default::default()
189        };
190        assert!(gitlink_worktree_change_suppressed(
191            SubmoduleIgnoreMode::Dirty,
192            true,
193            flags
194        ));
195        assert!(gitlink_worktree_change_suppressed(
196            SubmoduleIgnoreMode::All,
197            true,
198            flags
199        ));
200        assert!(!gitlink_worktree_change_suppressed(
201            SubmoduleIgnoreMode::Dirty,
202            false,
203            flags
204        ));
205        assert!(gitlink_worktree_change_suppressed(
206            SubmoduleIgnoreMode::All,
207            false,
208            flags
209        ));
210    }
211
212    #[test]
213    fn gitlink_untracked_only_honors_untracked_mode() {
214        let flags = SubmodulePorcelainFlags {
215            untracked: true,
216            ..Default::default()
217        };
218        assert!(gitlink_worktree_change_suppressed(
219            SubmoduleIgnoreMode::Untracked,
220            true,
221            flags
222        ));
223        assert!(!gitlink_worktree_change_suppressed(
224            SubmoduleIgnoreMode::None,
225            true,
226            flags
227        ));
228    }
229
230    #[test]
231    fn gitmodules_logical_name_resolves_ignore_key() {
232        let dir = tempdir().expect("tempdir");
233        fs::write(
234            dir.path().join(".gitmodules"),
235            "[submodule \"logical\"]\n\tpath = vendor/lib\n\tignore = all\n",
236        )
237        .expect("gitmodules");
238        let cfg = ConfigSet::new();
239        assert_eq!(
240            submodule_name_for_gitlink_path(&cfg, dir.path(), "vendor/lib"),
241            "logical"
242        );
243        assert_eq!(
244            submodule_ignore_for_path(&cfg, dir.path(), "vendor/lib"),
245            SubmoduleIgnoreMode::All
246        );
247    }
248
249    #[test]
250    fn gitmodules_field_keys_do_not_prefix_match_longer_names() {
251        let dir = tempdir().expect("tempdir");
252        fs::write(
253            dir.path().join(".gitmodules"),
254            "[submodule \"foo\"]\n\tpath = a\n\tignore = dirty\n[submodule \"foobar\"]\n\tpath = b\n\tignore = all\n",
255        )
256        .expect("gitmodules");
257        let cfg = ConfigSet::new();
258        assert_eq!(
259            submodule_ignore_for_path(&cfg, dir.path(), "a"),
260            SubmoduleIgnoreMode::Dirty
261        );
262        assert_eq!(
263            submodule_ignore_for_path(&cfg, dir.path(), "b"),
264            SubmoduleIgnoreMode::All
265        );
266    }
267
268    #[test]
269    fn gitmodules_duplicate_ignore_uses_last_value() {
270        let dir = tempdir().expect("tempdir");
271        fs::write(
272            dir.path().join(".gitmodules"),
273            "[submodule \"logical\"]\n\tpath = vendor/lib\n\tignore = all\n\tignore = none\n",
274        )
275        .expect("gitmodules");
276        let cfg = ConfigSet::new();
277        assert_eq!(
278            submodule_ignore_for_path(&cfg, dir.path(), "vendor/lib"),
279            SubmoduleIgnoreMode::None
280        );
281    }
282}