Skip to main content

mago_database/
git.rs

1//! Git's ignore rules for a work tree, read without running `git`.
2//!
3//! [`GitIgnores`] collects the `.gitignore` files Git would read, plus each
4//! repository's `info/exclude` and `core.excludesFile`, and answers whether
5//! Git ignores a path. Files below an ignored directory stay ignored, as in Git.
6//! Matching follows the patterns only: tracked files and `core.ignoreCase` are
7//! not consulted.
8
9use std::env::home_dir;
10use std::fs;
11use std::path::Path;
12use std::path::PathBuf;
13use std::sync::Arc;
14
15use foldhash::HashMap;
16use ignore::Match;
17use ignore::gitignore::Gitignore;
18use ignore::gitignore::GitignoreBuilder;
19use ignore::gitignore::gitconfig_excludes_path;
20use walkdir::WalkDir;
21
22/// The ignore rules of the Git work tree that contains a workspace.
23#[derive(Debug)]
24pub struct GitIgnores {
25    root: PathBuf,
26    workspace: PathBuf,
27    /// Every directory the rules were read from: the work tree root, the
28    /// ancestors of the workspace, and the workspace directories Git does not ignore.
29    directories: HashMap<PathBuf, Directory>,
30    rules: Vec<Gitignore>,
31    /// Each repository's `info/exclude`, then its excludes file, in descending precedence.
32    repositories: Vec<Vec<Gitignore>>,
33    /// The exclude files each repository reads, whether or not they exist.
34    excludes: Vec<PathBuf>,
35    configs: Vec<RepositoryConfig>,
36}
37
38/// A repository configuration and the excludes file it named.
39#[derive(Debug)]
40struct RepositoryConfig {
41    root: PathBuf,
42    path: PathBuf,
43    excludes: Option<PathBuf>,
44}
45
46/// The rules that apply to a directory's entries.
47#[derive(Debug, Clone)]
48struct Directory {
49    /// `.gitignore` files from this directory up to its repository root, deepest first.
50    chain: Arc<[u32]>,
51    repository: u32,
52}
53
54impl GitIgnores {
55    /// Read the rules for the work tree that contains `workspace`.
56    ///
57    /// Returns `None` outside a work tree, or when Git ignores `workspace` itself.
58    #[must_use]
59    pub fn discover(workspace: &Path) -> Option<Self> {
60        Self::discover_with_global(workspace, gitconfig_excludes_path().as_deref())
61    }
62
63    pub(crate) fn discover_with_global(workspace: &Path, global: Option<&Path>) -> Option<Self> {
64        let workspace = workspace.canonicalize().ok()?;
65        let root = workspace.ancestors().find(|directory| directory.join(".git").exists())?.to_path_buf();
66        let mut ignores = Self {
67            root,
68            workspace: workspace.clone(),
69            directories: HashMap::default(),
70            rules: Vec::new(),
71            repositories: Vec::new(),
72            excludes: Vec::new(),
73            configs: Vec::new(),
74        };
75
76        let chain: Vec<_> =
77            workspace.ancestors().take_while(|directory| directory.starts_with(&ignores.root)).collect();
78        let mut parent = None;
79        for directory in chain.into_iter().rev() {
80            if let Some(parent) = &parent
81                && ignores.decide(directory, true, parent)
82            {
83                return None;
84            }
85
86            parent = Some(ignores.visit(directory, parent.as_ref(), global));
87        }
88
89        let walker = WalkDir::new(&workspace).into_iter().filter_entry(|entry| {
90            if entry.depth() == 0 {
91                return true;
92            }
93
94            if !entry.file_type().is_dir() || entry.file_name() == ".git" {
95                return false;
96            }
97
98            let Some(parent) = entry.path().parent().and_then(|parent| ignores.directories.get(parent)).cloned() else {
99                return false;
100            };
101
102            if ignores.decide(entry.path(), true, &parent) {
103                return false;
104            }
105
106            ignores.visit(entry.path(), Some(&parent), global);
107            true
108        });
109
110        for _ in walker {}
111
112        Some(ignores)
113    }
114
115    /// Whether Git ignores `path`, an absolute path below the work tree.
116    #[must_use]
117    pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
118        let Ok(relative) = path.strip_prefix(&self.root) else { return false };
119        if relative.as_os_str().is_empty() {
120            return false;
121        }
122
123        if relative.components().any(|component| component.as_os_str() == ".git") {
124            return true;
125        }
126
127        let Some((read, directory)) =
128            path.ancestors().skip(1).find_map(|directory| Some((directory, self.directories.get(directory)?)))
129        else {
130            return false;
131        };
132
133        path.ancestors()
134            .take_while(|level| *level != read)
135            .enumerate()
136            .any(|(depth, level)| self.decide(level, depth > 0 || is_dir, directory))
137    }
138
139    /// Whether a change at `path` can change these rules: a `.gitignore` Git reads for the
140    /// workspace, an exclude file, or a repository configuration that now names another one.
141    #[must_use]
142    pub fn depends_on(&self, path: &Path) -> bool {
143        if self.excludes.iter().any(|file| file == path) {
144            return true;
145        }
146
147        if let Some(config) = self.configs.iter().find(|config| config.path == path) {
148            return configured_excludes_file(&config.root, &config.path) != config.excludes;
149        }
150
151        path.file_name().is_some_and(|name| name == ".gitignore")
152            && path.parent().is_some_and(|directory| {
153                self.directories.contains_key(directory)
154                    || (directory.starts_with(&self.workspace) && !self.is_ignored(directory, true))
155            })
156    }
157
158    /// The files the rules depend on outside the workspace directory.
159    pub fn sources_outside(&self) -> impl Iterator<Item = PathBuf> + '_ {
160        let ancestors = self
161            .workspace
162            .ancestors()
163            .skip(1)
164            .take_while(|directory| directory.starts_with(&self.root))
165            .map(|directory| directory.join(".gitignore"));
166        let files = self.excludes.iter().chain(self.configs.iter().map(|config| &config.path)).cloned();
167        ancestors.chain(files.filter(|file| !file.starts_with(&self.workspace)))
168    }
169
170    /// Match `path` against the rules that apply inside `directory`, an already read
171    /// ancestor: the deepest `.gitignore` first, then the repository's excludes.
172    fn decide(&self, path: &Path, is_dir: bool, directory: &Directory) -> bool {
173        for &rules in directory.chain.iter() {
174            match self.rules[rules as usize].matched(path, is_dir) {
175                Match::None => {}
176                decided => return decided.is_ignore(),
177            }
178        }
179
180        self.repositories[directory.repository as usize]
181            .iter()
182            .map(|rules| rules.matched(path, is_dir))
183            .find(|decided| !decided.is_none())
184            .is_some_and(|decided| decided.is_ignore())
185    }
186
187    /// Record `directory` below `parent`, or as the work tree root without one.
188    fn visit(&mut self, directory: &Path, parent: Option<&Directory>, global: Option<&Path>) -> Directory {
189        let nested = parent.filter(|_| !directory.join(".git").exists());
190        let repository = match nested {
191            Some(parent) => parent.repository,
192            None => {
193                let excludes = self.repository_excludes(directory, global);
194                self.repositories.push(excludes);
195                (self.repositories.len() - 1) as u32
196            }
197        };
198        let inherited = nested.map(|parent| Arc::clone(&parent.chain));
199        let chain = match read(directory, &directory.join(".gitignore")) {
200            Some(rules) => {
201                self.rules.push(rules);
202                let own = (self.rules.len() - 1) as u32;
203                std::iter::once(own).chain(inherited.iter().flat_map(|chain| chain.iter().copied())).collect()
204            }
205            None => inherited.unwrap_or_else(|| Arc::from([])),
206        };
207
208        let entry = Directory { chain, repository };
209        self.directories.insert(directory.to_path_buf(), entry.clone());
210        entry
211    }
212
213    /// A repository's own `core.excludesFile` takes precedence over the global one.
214    fn repository_excludes(&mut self, root: &Path, global: Option<&Path>) -> Vec<Gitignore> {
215        let common = git_directory(root).map(|git| resolved(&common_directory(&git)));
216        let config = common.as_ref().map(|common| common.join("config"));
217        let configured = config.as_deref().and_then(|config| configured_excludes_file(root, config));
218        let info = common.map(|common| common.join("info").join("exclude"));
219        let file = configured.as_deref().or(global).filter(|file| !file.as_os_str().is_empty()).map(Path::to_path_buf);
220        let mut excludes = Vec::new();
221        excludes.extend(info.as_deref().and_then(|info| read(root, info)));
222        excludes.extend(file.as_deref().and_then(|file| read(root, file)));
223        for source in info.into_iter().chain(file) {
224            let target = resolved(&source);
225            if target != source {
226                self.excludes.push(target);
227            }
228            self.excludes.push(source);
229        }
230        if let Some(path) = config {
231            self.configs.push(RepositoryConfig { root: root.to_path_buf(), path, excludes: configured });
232        }
233
234        excludes
235    }
236}
237
238/// A file's target, resolved through its directory when the file does not exist yet.
239fn resolved(path: &Path) -> PathBuf {
240    if let Ok(path) = path.canonicalize() {
241        return path;
242    }
243
244    match (path.parent().and_then(|parent| parent.canonicalize().ok()), path.file_name()) {
245        (Some(parent), Some(name)) => parent.join(name),
246        _ => path.to_path_buf(),
247    }
248}
249
250fn read(root: &Path, file: &Path) -> Option<Gitignore> {
251    if !file.is_file() {
252        return None;
253    }
254
255    let mut builder = GitignoreBuilder::new(root);
256    builder.add(file);
257    builder.build().ok().filter(|rules| !rules.is_empty())
258}
259
260/// The repository directory: `.git` itself, or the target of a worktree's `.git` file.
261fn git_directory(root: &Path) -> Option<PathBuf> {
262    let dot_git = root.join(".git");
263    if dot_git.is_dir() {
264        return Some(dot_git);
265    }
266
267    let contents = fs::read_to_string(&dot_git).ok()?;
268    let target = Path::new(contents.strip_prefix("gitdir:")?.trim());
269    Some(if target.is_absolute() { target.to_path_buf() } else { root.join(target) })
270}
271
272/// Linked worktrees keep `info/exclude` and the repository configuration in the main repository.
273fn common_directory(git: &Path) -> PathBuf {
274    match fs::read_to_string(git.join("commondir")) {
275        Ok(common) => {
276            let common = Path::new(common.trim());
277            if common.is_absolute() { common.to_path_buf() } else { git.join(common) }
278        }
279        Err(_) => git.to_path_buf(),
280    }
281}
282
283/// The last `core.excludesFile` in a repository configuration file. An empty
284/// value yields an empty path, which turns the global file off.
285fn configured_excludes_file(root: &Path, config: &Path) -> Option<PathBuf> {
286    let contents = fs::read_to_string(config).ok()?;
287    let mut core = false;
288    let mut file = None;
289    for line in contents.lines() {
290        let mut entry = line.trim_start();
291        if let Some(header) = entry.strip_prefix('[') {
292            let Some((section, rest)) = header.split_once(']') else { continue };
293            core = section.trim().eq_ignore_ascii_case("core");
294            entry = rest;
295        }
296        if core
297            && let Some((key, value)) = entry.split_once('=')
298            && key.trim().eq_ignore_ascii_case("excludesfile")
299        {
300            file = Some(config_value(value));
301        }
302    }
303
304    let file = file?;
305    if file.is_empty() {
306        return Some(PathBuf::new());
307    }
308    Some(match file.strip_prefix("~/") {
309        Some(relative) => home_dir()?.join(relative),
310        None => root.join(file),
311    })
312}
313
314/// A Git configuration value: quotes and escapes resolved, a comment dropped, and
315/// the whitespace around the value trimmed unless it is quoted.
316fn config_value(raw: &str) -> String {
317    let mut value = String::new();
318    let mut kept = 0;
319    let mut quoted = false;
320    let mut characters = raw.chars();
321    while let Some(character) = characters.next() {
322        match character {
323            '"' => {
324                quoted = !quoted;
325                kept = value.len();
326            }
327            '\\' => {
328                match characters.next() {
329                    Some('n') => value.push('\n'),
330                    Some('t') => value.push('\t'),
331                    Some('b') => value.push('\u{8}'),
332                    Some(escaped) => value.push(escaped),
333                    None => break,
334                }
335                kept = value.len();
336            }
337            '#' | ';' if !quoted => break,
338            character if !quoted && character.is_whitespace() => {
339                if !value.is_empty() {
340                    value.push(character);
341                }
342            }
343            character => {
344                value.push(character);
345                kept = value.len();
346            }
347        }
348    }
349
350    value.truncate(kept);
351    value
352}
353
354#[cfg(test)]
355#[allow(clippy::unwrap_used)]
356mod tests {
357    use tempfile::TempDir;
358
359    use super::*;
360
361    fn write(root: &Path, relative: &str, contents: &str) {
362        let path = root.join(relative);
363        fs::create_dir_all(path.parent().unwrap()).unwrap();
364        fs::write(path, contents).unwrap();
365    }
366
367    fn repository(files: &[(&str, &str)]) -> TempDir {
368        let directory = TempDir::new().unwrap();
369        fs::create_dir_all(directory.path().join(".git/info")).unwrap();
370        for (relative, contents) in files {
371            write(directory.path(), relative, contents);
372        }
373        directory
374    }
375
376    fn ignored(ignores: &GitIgnores, root: &Path, relative: &str) -> bool {
377        ignores.is_ignored(&root.canonicalize().unwrap().join(relative), false)
378    }
379
380    #[test]
381    fn nested_rules_negations_and_info_exclude_follow_git_precedence() {
382        let directory = repository(&[
383            (".gitignore", "/vendor/\n*.log.php\ncache/\n!keep.log.php\n/build/*\n!/build/keep/\n"),
384            (".git/info/exclude", "local.php\n"),
385            ("src/.gitignore", "generated/\n!cache/\n"),
386            ("vendor/package/src/Library.php", "<?php"),
387            ("src/generated/Proxy.php", "<?php"),
388            ("src/cache/Kept.php", "<?php"),
389            ("build/keep/Kept.php", "<?php"),
390            ("build/other/Dropped.php", "<?php"),
391        ]);
392        let root = directory.path();
393        let global = root.join("global-ignore");
394        fs::write(&global, "*.swp.php\n").unwrap();
395        let ignores = GitIgnores::discover_with_global(root, Some(&global)).unwrap();
396
397        assert!(ignored(&ignores, root, "src/Editor.swp.php"));
398        assert!(ignored(&ignores, root, "vendor/package/src/Library.php"));
399        assert!(ignored(&ignores, root, "src/generated/Proxy.php"));
400        assert!(ignored(&ignores, root, "var/cache/Container.php"));
401        assert!(ignored(&ignores, root, "src/debug.log.php"));
402        assert!(ignored(&ignores, root, "config/local.php"));
403        assert!(ignored(&ignores, root, ".git/hooks/pre-commit.php"));
404        assert!(ignored(&ignores, root, "build/other/Dropped.php"));
405        assert!(!ignored(&ignores, root, "build/keep/Kept.php"));
406        assert!(!ignored(&ignores, root, "src/keep.log.php"));
407        assert!(!ignored(&ignores, root, "src/cache/Kept.php"));
408        assert!(!ignored(&ignores, root, "src/Service.php"));
409        assert!(!ignored(&ignores, root, "vendor.php"));
410    }
411
412    #[test]
413    fn rules_inside_ignored_directories_are_never_read() {
414        let directory = repository(&[(".gitignore", "build/\n"), ("build/.gitignore", "!*.php\n")]);
415        let root = directory.path();
416        let ignores = GitIgnores::discover_with_global(root, None).unwrap();
417
418        assert!(ignored(&ignores, root, "build/Kept.php"));
419        assert!(!ignores.directories.contains_key(&root.canonicalize().unwrap().join("build")));
420    }
421
422    #[test]
423    fn workspaces_below_the_root_inherit_parent_rules_and_skip_ignored_roots() {
424        let directory = repository(&[
425            (".gitignore", "copies/\n"),
426            ("app/.gitignore", "/var/\n"),
427            ("app/src/Service.php", "<?php"),
428            ("copies/app/src/Service.php", "<?php"),
429        ]);
430        let root = directory.path();
431        let ignores = GitIgnores::discover_with_global(&root.join("app"), None).unwrap();
432
433        assert!(ignored(&ignores, root, "app/var/Cache.php"));
434        assert!(!ignored(&ignores, root, "app/src/Service.php"));
435        assert!(GitIgnores::discover_with_global(&root.join("copies/app"), None).is_none());
436    }
437
438    #[test]
439    fn nested_repositories_use_their_own_rules_inside_their_root() {
440        let directory = repository(&[
441            (".gitignore", "*.local.php\npackages/ignored/\n"),
442            ("packages/tool/.git/info/exclude", "scratch/\n"),
443            ("packages/tool/src/Service.php", "<?php"),
444            ("packages/ignored/.git/HEAD", "ref: refs/heads/main\n"),
445        ]);
446        let root = directory.path();
447        let ignores = GitIgnores::discover_with_global(root, None).unwrap();
448
449        assert!(ignored(&ignores, root, "packages/tool/scratch/Notes.php"));
450        assert!(!ignored(&ignores, root, "packages/tool/config.local.php"));
451        assert!(!ignored(&ignores, root, "packages/tool/src/Service.php"));
452        assert!(ignored(&ignores, root, "packages/ignored/src/Service.php"));
453        assert!(ignored(&ignores, root, "app.local.php"));
454        assert!(!ignored(&ignores, root, "scratch/Notes.php"));
455    }
456
457    #[test]
458    fn repository_excludes_files_replace_the_global_one() {
459        let directory = repository(&[
460            (
461                ".git/config",
462                "[user]\n\texcludesFile = user-ignore\n[core] # local settings\n\texcludesFile = \"repository-ignore\" # local rules\n",
463            ),
464            ("repository-ignore", ".claude/worktrees/\n"),
465            ("user-ignore", "src/\n"),
466        ]);
467        let root = directory.path();
468        let global = root.join("global-ignore");
469        fs::write(&global, "*.php\n").unwrap();
470        let ignores = GitIgnores::discover_with_global(root, Some(&global)).unwrap();
471
472        assert!(ignored(&ignores, root, ".claude/worktrees/copy/src/Service.php"));
473        assert!(!ignored(&ignores, root, "src/Service.php"));
474
475        fs::write(root.join(".git/config"), "[core]\n\texcludesFile = repository-ignore\n\texcludesFile = \"\"\n")
476            .unwrap();
477        let ignores = GitIgnores::discover_with_global(root, Some(&global)).unwrap();
478        assert!(!ignored(&ignores, root, "src/Service.php"));
479        assert!(!ignored(&ignores, root, ".claude/worktrees/copy/src/Service.php"));
480    }
481
482    #[test]
483    fn rules_depend_on_read_gitignores_new_ones_git_would_read_and_exclude_sources() {
484        let directory = repository(&[
485            (".gitignore", "/vendor/\n"),
486            (".git/config", "[core]\n\texcludesFile = repository-ignore\n"),
487            ("app/.gitignore", "/var/\n"),
488            ("app/src/Service.php", "<?php"),
489            ("other/.gitignore", "*.php\n"),
490        ]);
491        let root = directory.path().canonicalize().unwrap();
492        let ignores = GitIgnores::discover_with_global(&root.join("app"), Some(&root.join("global-ignore"))).unwrap();
493        for (relative, expected) in [
494            (".gitignore", true),
495            ("app/.gitignore", true),
496            ("app/src/.gitignore", true),
497            ("app/new/deep/.gitignore", true),
498            ("app/var/.gitignore", false),
499            ("other/.gitignore", false),
500            ("vendor/.gitignore", false),
501            (".git/info/exclude", true),
502            ("repository-ignore", true),
503            ("global-ignore", false),
504            ("app/src/Service.php", false),
505        ] {
506            assert_eq!(ignores.depends_on(&root.join(relative)), expected, "{relative}");
507        }
508
509        let config = root.join(".git/config");
510        assert!(!ignores.depends_on(&config));
511        fs::write(&config, "[core]\n\texcludesFile = other-ignore\n").unwrap();
512        assert!(ignores.depends_on(&config));
513
514        let mut sources: Vec<_> = ignores.sources_outside().collect();
515        sources.sort_unstable();
516        let expected = [".git/config", ".git/info/exclude", ".gitignore", "repository-ignore"];
517        assert_eq!(sources, expected.map(|relative| root.join(relative)));
518    }
519
520    #[test]
521    fn config_values_follow_git_quoting_and_comments() {
522        for (raw, expected) in [
523            (" plain ", "plain"),
524            ("\"with # hash\" # comment", "with # hash"),
525            ("two words ; comment", "two words"),
526            ("\" padded \"", " padded "),
527            (r#"escaped\"quote"#, "escaped\"quote"),
528            ("\"\"", ""),
529            (r"ab\bcd", "ab\u{8}cd"),
530        ] {
531            assert_eq!(config_value(raw), expected, "{raw}");
532        }
533    }
534
535    #[test]
536    fn deep_paths_created_after_discovery_use_their_nearest_read_directory() {
537        let directory = repository(&[(".gitignore", "*.cache.php\n"), ("src/.gitignore", "!kept.cache.php\n")]);
538        let root = directory.path();
539        let ignores = GitIgnores::discover_with_global(root, None).unwrap();
540        let src = root.canonicalize().unwrap().join("src");
541        assert_eq!(ignores.directories[&src].chain.len(), 2);
542
543        assert!(ignored(&ignores, root, "src/a/b/c/d/e/drop.cache.php"));
544        assert!(!ignored(&ignores, root, "src/a/b/c/d/e/kept.cache.php"));
545        assert!(!ignored(&ignores, root, "src/a/b/c/d/e/Service.php"));
546    }
547
548    #[test]
549    fn worktree_files_resolve_info_exclude_from_the_common_directory() {
550        let directory = repository(&[(".git/info/exclude", "scratch/\n")]);
551        let main = directory.path();
552        fs::create_dir_all(main.join(".git/worktrees/feature")).unwrap();
553        fs::write(main.join(".git/worktrees/feature/commondir"), "../..\n").unwrap();
554        let worktree = TempDir::new().unwrap();
555        let link = main.canonicalize().unwrap().join(".git/worktrees/feature");
556        fs::write(worktree.path().join(".git"), format!("gitdir: {}\n", link.display())).unwrap();
557
558        let ignores = GitIgnores::discover_with_global(worktree.path(), None).unwrap();
559        assert!(ignored(&ignores, worktree.path(), "scratch/Notes.php"));
560        assert!(!ignored(&ignores, worktree.path(), "src/Service.php"));
561        let exclude = main.canonicalize().unwrap().join(".git/info/exclude");
562        assert!(ignores.depends_on(&exclude));
563        assert!(ignores.sources_outside().any(|source| source == exclude));
564    }
565
566    #[cfg(unix)]
567    #[test]
568    fn symlinked_excludes_files_depend_on_the_link_and_its_target() {
569        let directory = repository(&[]);
570        let home = TempDir::new().unwrap();
571        let home = home.path().canonicalize().unwrap();
572        let target = home.join("dotfiles/ignore");
573        fs::create_dir_all(target.parent().unwrap()).unwrap();
574        fs::write(&target, "*.log\n").unwrap();
575        let link = home.join(".gitignore_global");
576        std::os::unix::fs::symlink(&target, &link).unwrap();
577        let ignores = GitIgnores::discover_with_global(directory.path(), Some(&link)).unwrap();
578        assert!(ignores.depends_on(&link));
579        assert!(ignores.depends_on(&target));
580    }
581
582    #[test]
583    fn excludes_files_named_gitignore_outside_the_workspace_are_sources() {
584        let directory = repository(&[]);
585        let home = TempDir::new().unwrap();
586        let global = home.path().canonicalize().unwrap().join(".gitignore");
587        fs::write(&global, "*.log\n").unwrap();
588        let ignores = GitIgnores::discover_with_global(directory.path(), Some(&global)).unwrap();
589        assert!(ignores.depends_on(&global));
590        assert!(ignores.sources_outside().any(|source| source == global));
591    }
592
593    #[test]
594    fn paths_outside_a_work_tree_have_no_rules() {
595        let directory = TempDir::new().unwrap();
596        write(directory.path(), ".gitignore", "*\n");
597        assert!(GitIgnores::discover_with_global(directory.path(), None).is_none());
598    }
599}