Skip to main content

rust_anything/
walk.rs

1//! Directory walks that read `.gitignore` the way git does: from the repository root down to the
2//! scanned folder and below it, never from folders above the repository (a `*` in a home-folder
3//! `.gitignore` would otherwise hide every file).
4
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use ignore::gitignore::Gitignore;
9use ignore::{DirEntry, WalkBuilder};
10
11/// `.gitignore` files in the folders between the repository root and the scanned folder.
12struct Outer {
13    root: PathBuf,
14    base: PathBuf,
15    matchers: Vec<Gitignore>,
16}
17
18impl Outer {
19    fn new(root: &Path) -> Option<Self> {
20        let base = root.canonical().ok()?;
21        if base.join(".git").exists() {
22            return None;
23        }
24        let repo = base.ancestors().skip(1).find(|d| d.join(".git").exists())?;
25        let mut matchers: Vec<Gitignore> = base
26            .ancestors()
27            .skip(1)
28            .take_while(|d| d.starts_with(repo))
29            .filter_map(|d| {
30                let file = d.join(".gitignore");
31                file.is_file().then(|| Gitignore::new(file).0)
32            })
33            .collect();
34        matchers.reverse();
35        (!matchers.is_empty()).then(|| Self {
36            root: root.to_path_buf(),
37            base,
38            matchers,
39        })
40    }
41
42    fn ignores(&self, entry: &DirEntry) -> bool {
43        if entry.depth() == 0 {
44            return false;
45        }
46        let rel = entry
47            .path()
48            .strip_prefix(&self.root)
49            .unwrap_or(entry.path());
50        let path = self.base.join(rel);
51        let is_dir = entry.file_type().is_some_and(|t| t.is_dir());
52        for m in self.matchers.iter().rev() {
53            let found = m.matched(&path, is_dir);
54            if found.is_ignore() {
55                return true;
56            }
57            if found.is_whitelist() {
58                return false;
59            }
60        }
61        false
62    }
63}
64
65/// `canonicalize` without Windows' `\\?\` verbatim prefix, which `java -cp`, `-D` library
66/// paths and other tools reject. Elsewhere it is `canonicalize` itself.
67pub trait Canonical {
68    fn canonical(&self) -> std::io::Result<PathBuf>;
69}
70
71impl Canonical for Path {
72    fn canonical(&self) -> std::io::Result<PathBuf> {
73        let path = self.canonicalize()?;
74        Ok(match path.to_str().and_then(|s| s.strip_prefix(r"\\?\")) {
75            Some(rest) if !rest.starts_with(r"UNC\") => PathBuf::from(rest),
76            _ => path,
77        })
78    }
79}
80
81/// The path a `file://` URL names, percent-decoded. On Windows the URL is `file:///C:/...`; when
82/// `root` is a drive path the slash before the drive letter is dropped so the path compares with
83/// it. Under a Unix root `/C:/repo` the slash is part of the path and stays.
84pub fn file_url_path(url: &str, root: &Path) -> Option<String> {
85    let path =
86        percent_encoding::percent_decode_str(url.strip_prefix("file://")?).decode_utf8_lossy();
87    Some(match path.strip_prefix('/') {
88        Some(rest) if has_drive(rest) && has_drive(&root.to_string_lossy()) => rest.to_string(),
89        _ => path.into_owned(),
90    })
91}
92
93/// Whether a path starts with a Windows drive: `C:/` or `C:\`.
94pub fn has_drive(path: &str) -> bool {
95    let b = path.as_bytes();
96    b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'/' | b'\\')
97}
98
99/// A crate `bridge` generated inside the project: its wrappers reuse the original's names, so a
100/// source walk that entered it would find every class or module twice.
101fn bridge_crate(entry: &DirEntry) -> bool {
102    entry.depth() > 0
103        && entry.file_type().is_some_and(|t| t.is_dir())
104        && entry.path().join(crate::bridge::MANIFEST).is_file()
105}
106
107/// A walk of `root` that keeps an entry when `keep` says so and git would not ignore it.
108pub fn filtered<F>(root: &Path, keep: F) -> WalkBuilder
109where
110    F: Fn(&DirEntry) -> bool + Send + Sync + 'static,
111{
112    let mut walk = WalkBuilder::new(root);
113    walk.parents(false);
114    let outer = Outer::new(root).map(Arc::new);
115    walk.filter_entry(move |e| {
116        keep(e) && !bridge_crate(e) && !outer.as_ref().is_some_and(|o| o.ignores(e))
117    });
118    walk
119}
120
121/// A walk of `root` that skips only what git would ignore.
122pub fn builder(root: &Path) -> WalkBuilder {
123    filtered(root, |_| true)
124}
125
126/// Files with one of `extensions` under `root` that ignore rules exclude, outside folders that
127/// never hold source (dependencies, build output, version control).
128pub fn ignored_files(root: &Path, extensions: &[&str]) -> usize {
129    const SKIP: [&str; 6] = ["node_modules", "target", "vendor", ".git", "dist", "build"];
130    let has_ext = |p: &Path| {
131        p.extension()
132            .and_then(|e| e.to_str())
133            .is_some_and(|e| extensions.contains(&e))
134    };
135    let all = WalkBuilder::new(root)
136        .standard_filters(false)
137        .hidden(true)
138        .filter_entry(|e| !SKIP.contains(&e.file_name().to_string_lossy().as_ref()))
139        .build()
140        .flatten()
141        .filter(|e| e.file_type().is_some_and(|t| t.is_file()) && has_ext(e.path()))
142        .count();
143    let kept = builder(root)
144        .hidden(true)
145        .require_git(false)
146        .build()
147        .flatten()
148        .filter(|e| e.file_type().is_some_and(|t| t.is_file()) && has_ext(e.path()))
149        .filter(|e| {
150            !e.path()
151                .components()
152                .any(|c| SKIP.contains(&c.as_os_str().to_string_lossy().as_ref()))
153        })
154        .count();
155    all.saturating_sub(kept)
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    fn files(root: &Path) -> Vec<String> {
163        let mut out: Vec<String> = builder(root)
164            .hidden(true)
165            .require_git(false)
166            .build()
167            .flatten()
168            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
169            .map(|e| {
170                e.path()
171                    .strip_prefix(root)
172                    .unwrap()
173                    .to_string_lossy()
174                    .replace('\\', "/")
175            })
176            .collect();
177        out.sort();
178        out
179    }
180
181    #[test]
182    fn ignore_files_above_the_repository_are_not_read() {
183        let tmp = std::env::temp_dir().join(format!("ra-walk-{}", std::process::id()));
184        let _ = std::fs::remove_dir_all(&tmp);
185        let repo = tmp.join("home/proj");
186        std::fs::create_dir_all(repo.join("src/gen")).unwrap();
187        std::fs::write(tmp.join("home/.gitignore"), "*\n").unwrap();
188        std::fs::write(repo.join("src/a.ts"), "").unwrap();
189        std::fs::write(repo.join("src/gen/b.ts"), "").unwrap();
190        assert_eq!(
191            files(&repo),
192            ["src/a.ts", "src/gen/b.ts"],
193            "not a repository"
194        );
195
196        std::fs::create_dir(repo.join(".git")).unwrap();
197        std::fs::write(repo.join(".gitignore"), "/src/gen/\n").unwrap();
198        assert_eq!(files(&repo), ["src/a.ts"], "repository root");
199        assert_eq!(
200            files(&repo.join("src")),
201            ["a.ts"],
202            "folder inside the repository"
203        );
204
205        std::fs::remove_dir_all(&tmp).unwrap();
206    }
207
208    #[test]
209    fn bridge_crates_inside_the_project_are_not_source() {
210        let tmp = std::env::temp_dir().join(format!("ra-walk-bridge-{}", std::process::id()));
211        let _ = std::fs::remove_dir_all(&tmp);
212        std::fs::create_dir_all(tmp.join("src")).unwrap();
213        std::fs::create_dir_all(tmp.join("rust/x-rs/java")).unwrap();
214        std::fs::write(tmp.join("src/A.java"), "").unwrap();
215        std::fs::write(tmp.join("rust/x-rs/rust-anything.json"), "{}").unwrap();
216        std::fs::write(tmp.join("rust/x-rs/java/A.java"), "").unwrap();
217        assert_eq!(files(&tmp), ["src/A.java"]);
218        assert!(
219            files(&tmp.join("rust/x-rs")).contains(&"java/A.java".to_string()),
220            "a walk of the crate itself still sees its files"
221        );
222        std::fs::remove_dir_all(&tmp).unwrap();
223    }
224}