Skip to main content

aft_base/
project_walk.rs

1//! Shared project-walk ignore policy without request-local state.
2
3use std::path::Path;
4
5/// Whether a traversal may open ignore files for the current request.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum IgnoreFileAccess {
8    Allowed,
9    Fenced,
10}
11
12/// True when `entry` is a directory below the walk root that is itself a
13/// nested linked worktree of this repository, which the walk must prune.
14/// Shared by every walker built on the project walk; the depth check keeps
15/// an explicitly named root (depth 0) admitted.
16pub fn is_nested_worktree_entry(
17    entry: &ignore::DirEntry,
18    worktrees: &crate::project_content::NestedWorktreeBoundary,
19) -> bool {
20    entry.depth() > 0
21        && entry
22            .file_type()
23            .as_ref()
24            .is_some_and(std::fs::FileType::is_dir)
25        && worktrees.is_nested_worktree_root(entry.path())
26}
27
28/// Apply the ignore rules every AFT project traversal honours to `builder`.
29///
30/// This is the one definition the project walkers share (search index build
31/// and refresh, semantic collection, grep/glob fallback, call graph, inspect
32/// scans, views membership, LSP applicability and ignore-file discovery), so
33/// a folder is indexed the same way whether or not it is a git repository:
34///
35/// - `.gitignore` files at the walk root, below it, and in its ancestors;
36/// - `.aftignore` files, layered on top with higher precedence;
37/// - Git's global excludes file (`core.excludesFile`);
38/// - `.git/info/exclude`, which only exists inside a repository.
39///
40/// The `ignore` crate applies the git-family sources only inside a repository
41/// unless `require_git` is off. Inside a git or jj work tree the crate default
42/// is kept, so git roots walk exactly as they always have (including where a
43/// nested repository starts its own rule scope). In a folder that is not a
44/// repository it is switched off so `.gitignore` files and the global excludes
45/// file still apply, matching the shared matcher that filters watcher events
46/// (the shared ignore-input matcher), which reads both regardless of
47/// git. `.git/info/exclude` has nothing to contribute there.
48///
49/// Call it after `standard_filters`, which would otherwise reset these flags.
50pub fn apply_project_ignore_rules<'a>(
51    builder: &'a mut ignore::WalkBuilder,
52    walk_root: &Path,
53    access: IgnoreFileAccess,
54) -> &'a mut ignore::WalkBuilder {
55    if access == IgnoreFileAccess::Fenced {
56        // Ignore files can themselves be symlinks to another checkout. A
57        // confined walk must not read those files, even to filter its results.
58        return builder
59            .ignore(false)
60            .git_ignore(false)
61            .git_global(false)
62            .git_exclude(false)
63            .parents(false)
64            .require_git(false);
65    }
66    builder
67        .git_ignore(true)
68        .git_global(true)
69        .git_exclude(true)
70        .add_custom_ignore_filename(".aftignore")
71        .require_git(is_inside_vcs_work_tree(walk_root))
72}
73
74/// Whether `path` or one of its ancestors holds `.git` (a directory, or the
75/// file a linked worktree or submodule uses) or `.jj`. This is the same test
76/// the `ignore` crate uses to decide that git rules apply, run on the same
77/// canonical ancestors it inspects, so keeping `require_git` on exactly when
78/// this is true leaves the crate's own decision unchanged for git roots.
79fn is_inside_vcs_work_tree(path: &Path) -> bool {
80    let absolute = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
81    absolute
82        .ancestors()
83        .any(|dir| dir.join(".git").exists() || dir.join(".jj").exists())
84}
85
86#[cfg(all(test, target_os = "linux"))]
87mod tests {
88    use super::*;
89    use std::ffi::CString;
90    use std::io::Read;
91    use std::os::fd::FromRawFd;
92    use std::os::unix::ffi::OsStrExt;
93
94    #[test]
95    fn fenced_walk_does_not_open_ignore_files() {
96        let root = tempfile::tempdir().unwrap();
97        std::fs::create_dir(root.path().join(".git")).unwrap();
98        std::fs::write(root.path().join("visible.rs"), "fn visible() {}\n").unwrap();
99        // Kernel open notifications distinguish not reading an ignore file from
100        // reading it and then disregarding its rules.
101        let fd = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) };
102        assert!(fd >= 0, "{}", std::io::Error::last_os_error());
103        let mut events = unsafe { std::fs::File::from_raw_fd(fd) };
104        for name in [".ignore", ".gitignore", ".aftignore"] {
105            let path = root.path().join(name);
106            std::fs::write(&path, "visible.rs\n").unwrap();
107            let path = CString::new(path.as_os_str().as_bytes()).unwrap();
108            let watch = unsafe { libc::inotify_add_watch(fd, path.as_ptr(), libc::IN_OPEN) };
109            assert!(watch >= 0, "{}", std::io::Error::last_os_error());
110        }
111        let mut builder = ignore::WalkBuilder::new(root.path());
112        let paths = apply_project_ignore_rules(&mut builder, root.path(), IgnoreFileAccess::Fenced)
113            .build()
114            .map(|entry| entry.unwrap().into_path())
115            .collect::<Vec<_>>();
116        assert!(paths.contains(&root.path().join("visible.rs")));
117        let mut buffer = [0_u8; 1024];
118        assert_eq!(
119            events.read(&mut buffer).unwrap_err().kind(),
120            std::io::ErrorKind::WouldBlock
121        );
122        // Check the observer itself: a deliberate open must produce an event.
123        drop(std::fs::File::open(root.path().join(".gitignore")).unwrap());
124        assert!(events.read(&mut buffer).unwrap() > 0);
125    }
126}