OXYGENHUB
# 3a4b3e018326 oxygen / crates / oxy-core / src / repo / walk.rs
11.0 KiB · Rust · last changed Stat tracked files relative to their directories (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 exclude paths with gitignore syntax, the
5
//! nearest file deciding; `.gitignore` and `.ignore` files count too, below
6
//! `.oxyignore` in the same directory (oxygen#44), so a project coming from
7
//! Git does not commit what Git ignored, and `.oxyignore` can still say
8
//! otherwise with `!`.
9
//!
10
//! Each directory is read once; a file's stat comes from its directory
11
//! entry, and results are gathered a directory at a time, so a tree of
12
//! 100 000 files costs about what its system calls cost.
13
14
use super::*;
15
use ignore::gitignore::{Gitignore, GitignoreBuilder};
16
use ignore::Match;
17
use std::sync::{Arc, Mutex};
18
19
/// What a stat says about a file that the working copy needs: its size,
20
/// modification time and executable bit.
21
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22
pub(crate) struct Stat {
23
    pub size: u64,
24
    pub mtime_ns: u128,
25
    pub exec: bool,
26
}
27
28
impl Stat {
29
    pub(crate) fn of(m: &fs::Metadata) -> Stat {
30
        Stat {
31
            size: m.len(),
32
            mtime_ns: super::prompt::mtime_ns(m),
33
            exec: super::is_executable(m),
34
        }
35
    }
36
}
37
38
/// What a listing found, each list in path order.
39
#[derive(Default)]
40
pub(crate) struct Listing {
41
    /// Regular files: path relative to the root (with `/`), full path, stat.
42
    pub files: Vec<(String, PathBuf, Stat)>,
43
    /// Symbolic links and their targets.
44
    pub symlinks: Vec<(String, Vec<u8>)>,
45
    /// Directories holding a repository of their own.
46
    pub nested: Vec<PathBuf>,
47
    /// Every directory listed (the root as ""), with its modification time
48
    /// read before its entries were: a later change to its entries moves
49
    /// the time, so a manifest that keeps these can skip reading a
50
    /// directory whose time has not moved.
51
    pub dirs: Vec<(String, u128)>,
52
}
53
54
/// The ignore files in force for a directory, innermost first.
55
#[derive(Clone, Default)]
56
struct Rules(Option<Arc<(Gitignore, Rules)>>);
57
58
impl Rules {
59
    /// The rules for `dir`, adding its own ignore files if it has any.
60
    fn enter(&self, dir: &Path, names: &[String]) -> Rules {
61
        // Later files win: .oxyignore over .ignore over .gitignore.
62
        let files: Vec<&str> = [".gitignore", ".ignore", ".oxyignore"]
63
            .into_iter()
64
            .filter(|f| names.iter().any(|n| n == f))
65
            .collect();
66
        if files.is_empty() {
67
            return self.clone();
68
        }
69
        let mut b = GitignoreBuilder::new(dir);
70
        for f in files {
71
            // An unreadable or malformed ignore file excludes nothing.
72
            let _ = b.add(dir.join(f));
73
        }
74
        match b.build() {
75
            Ok(g) if !g.is_empty() => Rules(Some(Arc::new((g, self.clone())))),
76
            _ => self.clone(),
77
        }
78
    }
79
80
    fn ignored(&self, path: &Path, is_dir: bool) -> bool {
81
        let mut at = &self.0;
82
        while let Some(node) = at {
83
            match node.0.matched(path, is_dir) {
84
                Match::Ignore(_) => return true,
85
                Match::Whitelist(_) => return false,
86
                Match::None => {}
87
            }
88
            at = &(node.1).0;
89
        }
90
        false
91
    }
92
}
93
94
struct Ctx<'a> {
95
    in_scope: &'a (dyn Fn(&str) -> bool + Sync),
96
    known: &'a (dyn Fn(&str) -> bool + Sync),
97
    out: Mutex<Listing>,
98
    failed: Mutex<Option<String>>,
99
}
100
101
/// List the working copy under `root`; files outside `in_scope` (a sparse
102
/// checkout's paths) are left out, though every directory is visited.
103
pub(crate) fn list(root: &Path, in_scope: &(dyn Fn(&str) -> bool + Sync)) -> Result<Listing> {
104
    list_knowing(root, in_scope, &|_| false)
105
}
106
107
/// [`list`], taking files `known` says are tracked without asking the
108
/// ignore rules, which apply to untracked paths only: on the Linux tree,
109
/// matching every file against its 400 `.gitignore` files cost more than
110
/// a manifest lookup.
111
pub(crate) fn list_knowing(
112
    root: &Path,
113
    in_scope: &(dyn Fn(&str) -> bool + Sync),
114
    known: &(dyn Fn(&str) -> bool + Sync),
115
) -> Result<Listing> {
116
    let ctx = Ctx {
117
        in_scope,
118
        known,
119
        out: Mutex::new(Listing::default()),
120
        failed: Mutex::new(None),
121
    };
122
    let root_time = fs::metadata(root)
123
        .map(|m| super::prompt::mtime_ns(&m))
124
        .unwrap_or(0);
125
    rayon::scope(|s| {
126
        visit(
127
            s,
128
            root.to_path_buf(),
129
            String::new(),
130
            root_time,
131
            true,
132
            Rules::default(),
133
            &ctx,
134
        )
135
    });
136
    if let Some(e) = ctx.failed.into_inner().unwrap_or_else(|e| e.into_inner()) {
137
        return fail(e);
138
    }
139
    let mut out = ctx.out.into_inner().unwrap_or_else(|e| e.into_inner());
140
    // In path order, as the maps built from it want.
141
    {
142
        use rayon::prelude::*;
143
        out.files.par_sort_unstable_by(|a, b| a.0.cmp(&b.0));
144
        out.symlinks.sort_unstable_by(|a, b| a.0.cmp(&b.0));
145
        out.dirs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
146
        out.nested.sort_unstable();
147
    }
148
    Ok(out)
149
}
150
151
#[allow(clippy::too_many_arguments)]
152
fn visit<'s>(
153
    s: &rayon::Scope<'s>,
154
    dir: PathBuf,
155
    rel: String,
156
    mtime: u128,
157
    top: bool,
158
    rules: Rules,
159
    ctx: &'s Ctx<'s>,
160
) {
161
    let read = || -> std::io::Result<Vec<fs::DirEntry>> { fs::read_dir(&dir)?.collect() };
162
    let entries = match read() {
163
        Ok(e) => e,
164
        Err(e) => {
165
            ctx.failed
166
                .lock()
167
                .unwrap_or_else(|e| e.into_inner())
168
                .get_or_insert_with(|| format!("{}: {e}", dir.display()));
169
            return;
170
        }
171
    };
172
    let names: Vec<String> = entries
173
        .iter()
174
        .map(|e| e.file_name().to_string_lossy().into_owned())
175
        .collect();
176
    if !top && names.iter().any(|n| n == OXY_DIR || n == ".git") {
177
        ctx.out
178
            .lock()
179
            .unwrap_or_else(|e| e.into_inner())
180
            .nested
181
            .push(dir);
182
        return;
183
    }
184
    let rules = rules.enter(&dir, &names);
185
    let mut mine = Listing::default();
186
    mine.dirs.push((rel.clone(), mtime));
187
    for (e, name) in entries.into_iter().zip(names) {
188
        if name == OXY_DIR {
189
            continue;
190
        }
191
        let Ok(ft) = e.file_type() else { continue };
192
        let path = e.path();
193
        let child = if rel.is_empty() {
194
            name
195
        } else {
196
            format!("{rel}/{name}")
197
        };
198
        if (ft.is_dir() || !(ctx.known)(&child)) && rules.ignored(&path, ft.is_dir()) {
199
            continue;
200
        }
201
        if ft.is_dir() {
202
            let rules = rules.clone();
203
            // The directory's time now, before it is read.
204
            let time = e
205
                .metadata()
206
                .map(|m| super::prompt::mtime_ns(&m))
207
                .unwrap_or(0);
208
            s.spawn(move |s| visit(s, path, child, time, false, rules, ctx));
209
        } else if !(ctx.in_scope)(&child) {
210
        } else if ft.is_symlink() {
211
            match fs::read_link(&path) {
212
                Ok(t) => mine
213
                    .symlinks
214
                    .push((child, t.to_string_lossy().as_bytes().to_vec())),
215
                Err(e) => {
216
                    ctx.failed
217
                        .lock()
218
                        .unwrap_or_else(|e| e.into_inner())
219
                        .get_or_insert_with(|| format!("{}: {e}", path.display()));
220
                }
221
            }
222
        } else if ft.is_file() {
223
            match e.metadata() {
224
                Ok(m) => mine.files.push((child, path, Stat::of(&m))),
225
                Err(e) => {
226
                    ctx.failed
227
                        .lock()
228
                        .unwrap_or_else(|e| e.into_inner())
229
                        .get_or_insert_with(|| format!("{}: {e}", path.display()));
230
                }
231
            }
232
        }
233
    }
234
    let mut out = ctx.out.lock().unwrap_or_else(|e| e.into_inner());
235
    out.files.append(&mut mine.files);
236
    out.symlinks.append(&mut mine.symlinks);
237
    out.dirs.append(&mut mine.dirs);
238
}
239
240
#[cfg(test)]
241
mod tests {
242
    use super::*;
243
244
    fn write(root: &Path, rel: &str, text: &str) {
245
        let p = root.join(rel);
246
        fs::create_dir_all(p.parent().unwrap()).unwrap();
247
        fs::write(p, text).unwrap();
248
    }
249
250
    fn listed(root: &Path, in_scope: &(dyn Fn(&str) -> bool + Sync)) -> (Vec<String>, Vec<String>) {
251
        let l = list(root, in_scope).unwrap();
252
        let mut files: Vec<String> = l.files.into_iter().map(|(r, _, _)| r).collect();
253
        files.extend(l.symlinks.into_iter().map(|(r, _)| r));
254
        files.sort();
255
        let mut nested: Vec<String> = l
256
            .nested
257
            .iter()
258
            .map(|d| {
259
                d.strip_prefix(root)
260
                    .unwrap()
261
                    .to_string_lossy()
262
                    .replace('\\', "/")
263
            })
264
            .collect();
265
        nested.sort();
266
        (files, nested)
267
    }
268
269
    #[test]
270
    fn ignore_files_nested_repositories_and_scope() {
271
        let dir = tempfile::tempdir().unwrap();
272
        let root = dir.path();
273
        write(root, ".oxy/config", "");
274
        write(root, ".oxyignore", "*.log\nbuild/\n");
275
        write(root, ".hidden", "");
276
        write(root, "a.txt", "");
277
        write(root, "a.log", "");
278
        write(root, "build/out.o", "");
279
        write(root, "src/main.c", "");
280
        write(root, "src/deep/x.log", "");
281
        // A nearer file overrides an outer rule, and `.ignore` counts too.
282
        write(root, "keep/.oxyignore", "!*.log\n");
283
        write(root, "keep/k.log", "");
284
        write(root, "other/.ignore", "secret\n");
285
        write(root, "other/secret", "");
286
        write(root, "other/public", "");
287
        // .gitignore counts, below .oxyignore in the same directory.
288
        write(root, "gitproj/.gitignore", "build/\n*.tmp\nkeep.tmp\n");
289
        write(root, "gitproj/.oxyignore", "!keep.tmp\n");
290
        write(root, "gitproj/build/out.bin", "");
291
        write(root, "gitproj/x.tmp", "");
292
        write(root, "gitproj/keep.tmp", "");
293
        write(root, "gitproj/src.c", "");
294
        // Nested repositories are reported, not entered.
295
        write(root, "sub/.oxy/config", "");
296
        write(root, "sub/inner.txt", "");
297
        write(root, "vendor/g/.git/HEAD", "");
298
        #[cfg(unix)]
299
        std::os::unix::fs::symlink("a.txt", root.join("link")).unwrap();
300
301
        let (files, nested) = listed(root, &|_| true);
302
        let mut want = vec![
303
            ".hidden",
304
            ".oxyignore",
305
            "a.txt",
306
            "gitproj/.gitignore",
307
            "gitproj/.oxyignore",
308
            "gitproj/keep.tmp",
309
            "gitproj/src.c",
310
            "keep/.oxyignore",
311
            "keep/k.log",
312
            "other/.ignore",
313
            "other/public",
314
            "src/main.c",
315
        ];
316
        if cfg!(unix) {
317
            want.push("link");
318
        }
319
        want.sort();
320
        assert_eq!(files, want);
321
        assert_eq!(nested, vec!["sub", "vendor/g"]);
322
323
        // A sparse scope leaves files out but still visits directories.
324
        let (files, _) = listed(root, &|p: &str| p.starts_with("src/"));
325
        assert_eq!(files, vec!["src/main.c"]);
326
    }
327
}