OXYGENHUB
# acadb5ed28a1 oxygen / crates / oxy-core / src / repo / walk.rs
8.2 KiB · Rust · last changed Status: a lean parallel lister of the working copy, reused by the snapshot after a failed clean check (refs #41) 1 month ago source blame history raw
1
//! Listing the working copy (spec §12.3): every file and symlink under the
2
//! root, found in parallel. `.oxy` is skipped, and so is a nested
3
//! repository (a directory holding `.oxy` or `.git`), which is reported
4
//! instead. `.oxyignore` files (and `.ignore` files, as before) exclude
5
//! paths with gitignore syntax, the nearest file deciding.
6
//!
7
//! Each directory is read once; a file's stat comes from its directory
8
//! entry, and results are gathered a directory at a time, so a tree of
9
//! 100 000 files costs about what its system calls cost.
10
11
use super::*;
12
use ignore::gitignore::{Gitignore, GitignoreBuilder};
13
use ignore::Match;
14
use std::sync::{Arc, Mutex};
15
16
/// What a listing found.
17
#[derive(Default)]
18
pub(crate) struct Listing {
19
    /// Regular files: path relative to the root (with `/`), full path, stat.
20
    pub files: Vec<(String, PathBuf, fs::Metadata)>,
21
    /// Symbolic links and their targets.
22
    pub symlinks: Vec<(String, Vec<u8>)>,
23
    /// Directories holding a repository of their own.
24
    pub nested: Vec<PathBuf>,
25
}
26
27
/// The ignore files in force for a directory, innermost first.
28
#[derive(Clone, Default)]
29
struct Rules(Option<Arc<(Gitignore, Rules)>>);
30
31
impl Rules {
32
    /// The rules for `dir`, adding its own ignore files if it has any.
33
    fn enter(&self, dir: &Path, names: &[String]) -> Rules {
34
        let files: Vec<&str> = [".ignore", ".oxyignore"]
35
            .into_iter()
36
            .filter(|f| names.iter().any(|n| n == f))
37
            .collect();
38
        if files.is_empty() {
39
            return self.clone();
40
        }
41
        let mut b = GitignoreBuilder::new(dir);
42
        for f in files {
43
            // An unreadable or malformed ignore file excludes nothing.
44
            let _ = b.add(dir.join(f));
45
        }
46
        match b.build() {
47
            Ok(g) if !g.is_empty() => Rules(Some(Arc::new((g, self.clone())))),
48
            _ => self.clone(),
49
        }
50
    }
51
52
    fn ignored(&self, path: &Path, is_dir: bool) -> bool {
53
        let mut at = &self.0;
54
        while let Some(node) = at {
55
            match node.0.matched(path, is_dir) {
56
                Match::Ignore(_) => return true,
57
                Match::Whitelist(_) => return false,
58
                Match::None => {}
59
            }
60
            at = &(node.1).0;
61
        }
62
        false
63
    }
64
}
65
66
struct Ctx<'a> {
67
    in_scope: &'a (dyn Fn(&str) -> bool + Sync),
68
    out: Mutex<Listing>,
69
    failed: Mutex<Option<String>>,
70
}
71
72
/// List the working copy under `root`; files outside `in_scope` (a sparse
73
/// checkout's paths) are left out, though every directory is visited.
74
pub(crate) fn list(root: &Path, in_scope: &(dyn Fn(&str) -> bool + Sync)) -> Result<Listing> {
75
    let ctx = Ctx {
76
        in_scope,
77
        out: Mutex::new(Listing::default()),
78
        failed: Mutex::new(None),
79
    };
80
    rayon::scope(|s| {
81
        visit(
82
            s,
83
            root.to_path_buf(),
84
            String::new(),
85
            true,
86
            Rules::default(),
87
            &ctx,
88
        )
89
    });
90
    if let Some(e) = ctx.failed.into_inner().unwrap_or_else(|e| e.into_inner()) {
91
        return fail(e);
92
    }
93
    Ok(ctx.out.into_inner().unwrap_or_else(|e| e.into_inner()))
94
}
95
96
fn visit<'s>(
97
    s: &rayon::Scope<'s>,
98
    dir: PathBuf,
99
    rel: String,
100
    top: bool,
101
    rules: Rules,
102
    ctx: &'s Ctx<'s>,
103
) {
104
    let read = || -> std::io::Result<Vec<fs::DirEntry>> { fs::read_dir(&dir)?.collect() };
105
    let entries = match read() {
106
        Ok(e) => e,
107
        Err(e) => {
108
            ctx.failed
109
                .lock()
110
                .unwrap_or_else(|e| e.into_inner())
111
                .get_or_insert_with(|| format!("{}: {e}", dir.display()));
112
            return;
113
        }
114
    };
115
    let names: Vec<String> = entries
116
        .iter()
117
        .map(|e| e.file_name().to_string_lossy().into_owned())
118
        .collect();
119
    if !top && names.iter().any(|n| n == OXY_DIR || n == ".git") {
120
        ctx.out
121
            .lock()
122
            .unwrap_or_else(|e| e.into_inner())
123
            .nested
124
            .push(dir);
125
        return;
126
    }
127
    let rules = rules.enter(&dir, &names);
128
    let mut mine = Listing::default();
129
    for (e, name) in entries.into_iter().zip(names) {
130
        if name == OXY_DIR {
131
            continue;
132
        }
133
        let Ok(ft) = e.file_type() else { continue };
134
        let path = e.path();
135
        if rules.ignored(&path, ft.is_dir()) {
136
            continue;
137
        }
138
        let child = if rel.is_empty() {
139
            name
140
        } else {
141
            format!("{rel}/{name}")
142
        };
143
        if ft.is_dir() {
144
            let rules = rules.clone();
145
            s.spawn(move |s| visit(s, path, child, false, rules, ctx));
146
        } else if !(ctx.in_scope)(&child) {
147
        } else if ft.is_symlink() {
148
            match fs::read_link(&path) {
149
                Ok(t) => mine
150
                    .symlinks
151
                    .push((child, t.to_string_lossy().as_bytes().to_vec())),
152
                Err(e) => {
153
                    ctx.failed
154
                        .lock()
155
                        .unwrap_or_else(|e| e.into_inner())
156
                        .get_or_insert_with(|| format!("{}: {e}", path.display()));
157
                }
158
            }
159
        } else if ft.is_file() {
160
            match e.metadata() {
161
                Ok(m) => mine.files.push((child, path, m)),
162
                Err(e) => {
163
                    ctx.failed
164
                        .lock()
165
                        .unwrap_or_else(|e| e.into_inner())
166
                        .get_or_insert_with(|| format!("{}: {e}", path.display()));
167
                }
168
            }
169
        }
170
    }
171
    if !mine.files.is_empty() || !mine.symlinks.is_empty() {
172
        let mut out = ctx.out.lock().unwrap_or_else(|e| e.into_inner());
173
        out.files.append(&mut mine.files);
174
        out.symlinks.append(&mut mine.symlinks);
175
    }
176
}
177
178
#[cfg(test)]
179
mod tests {
180
    use super::*;
181
182
    fn write(root: &Path, rel: &str, text: &str) {
183
        let p = root.join(rel);
184
        fs::create_dir_all(p.parent().unwrap()).unwrap();
185
        fs::write(p, text).unwrap();
186
    }
187
188
    fn listed(root: &Path, in_scope: &(dyn Fn(&str) -> bool + Sync)) -> (Vec<String>, Vec<String>) {
189
        let l = list(root, in_scope).unwrap();
190
        let mut files: Vec<String> = l.files.into_iter().map(|(r, _, _)| r).collect();
191
        files.extend(l.symlinks.into_iter().map(|(r, _)| r));
192
        files.sort();
193
        let mut nested: Vec<String> = l
194
            .nested
195
            .iter()
196
            .map(|d| {
197
                d.strip_prefix(root)
198
                    .unwrap()
199
                    .to_string_lossy()
200
                    .replace('\\', "/")
201
            })
202
            .collect();
203
        nested.sort();
204
        (files, nested)
205
    }
206
207
    #[test]
208
    fn ignore_files_nested_repositories_and_scope() {
209
        let dir = tempfile::tempdir().unwrap();
210
        let root = dir.path();
211
        write(root, ".oxy/config", "");
212
        write(root, ".oxyignore", "*.log\nbuild/\n");
213
        write(root, ".hidden", "");
214
        write(root, "a.txt", "");
215
        write(root, "a.log", "");
216
        write(root, "build/out.o", "");
217
        write(root, "src/main.c", "");
218
        write(root, "src/deep/x.log", "");
219
        // A nearer file overrides an outer rule, and `.ignore` counts too.
220
        write(root, "keep/.oxyignore", "!*.log\n");
221
        write(root, "keep/k.log", "");
222
        write(root, "other/.ignore", "secret\n");
223
        write(root, "other/secret", "");
224
        write(root, "other/public", "");
225
        // Nested repositories are reported, not entered.
226
        write(root, "sub/.oxy/config", "");
227
        write(root, "sub/inner.txt", "");
228
        write(root, "vendor/g/.git/HEAD", "");
229
        #[cfg(unix)]
230
        std::os::unix::fs::symlink("a.txt", root.join("link")).unwrap();
231
232
        let (files, nested) = listed(root, &|_| true);
233
        let mut want = vec![
234
            ".hidden",
235
            ".oxyignore",
236
            "a.txt",
237
            "keep/.oxyignore",
238
            "keep/k.log",
239
            "other/.ignore",
240
            "other/public",
241
            "src/main.c",
242
        ];
243
        if cfg!(unix) {
244
            want.push("link");
245
        }
246
        want.sort();
247
        assert_eq!(files, want);
248
        assert_eq!(nested, vec!["sub", "vendor/g"]);
249
250
        // A sparse scope leaves files out but still visits directories.
251
        let (files, _) = listed(root, &|p: &str| p.starts_with("src/"));
252
        assert_eq!(files, vec!["src/main.c"]);
253
    }
254
}