OXYGENHUB

Coverage / crates/oxy-core/src/repo/walk.rs 87.6%

211 of 241 lines run, 38 of 61 functions · run #266 on main · run missed

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 {
2916263×
    pub(crate) fn of(m: &fs::Metadata) -> Stat {
3016263×
        Stat {
3116263×
            size: m.len(),
3216263×
            mtime_ns: super::prompt::mtime_ns(m),
3316263×
            exec: super::is_executable(m),
3416263×
        }
3516263×
    }
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.
602446×
    fn enter(&self, dir: &Path, names: &[String]) -> Rules {
61
        // Later files win: .oxyignore over .ignore over .gitignore.
622446×
        let files: Vec<&str> = [".gitignore", ".ignore", ".oxyignore"]
632446×
            .into_iter()
6456396×
            .filter(|f| names.iter().any(|n| n == f))
652446×
            .collect();
662446×
        if files.is_empty() {
672407×
            return self.clone();
6839×
        }
6939×
        let mut b = GitignoreBuilder::new(dir);
7041×
        for f in files {
7141×
            // An unreadable or malformed ignore file excludes nothing.
7241×
            let _ = b.add(dir.join(f));
7341×
        }
7439×
        match b.build() {
7539×
            Ok(g) if !g.is_empty() => Rules(Some(Arc::new((g, self.clone())))),
760×
            _ => self.clone(),
77
        }
782446×
    }
79
803983×
    fn ignored(&self, path: &Path, is_dir: bool) -> bool {
813983×
        let mut at = &self.0;
824081×
        while let Some(node) = at {
83164×
            match node.0.matched(path, is_dir) {
8460×
                Match::Ignore(_) => return true,
856×
                Match::Whitelist(_) => return false,
8698×
                Match::None => {}
87
            }
8898×
            at = &(node.1).0;
89
        }
903917×
        false
913983×
    }
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.
1034×
pub(crate) fn list(root: &Path, in_scope: &(dyn Fn(&str) -> bool + Sync)) -> Result<Listing> {
1044×
    list_knowing(root, in_scope, &|_| false)
1054×
}
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.
1111674×
pub(crate) fn list_knowing(
1121674×
    root: &Path,
1131674×
    in_scope: &(dyn Fn(&str) -> bool + Sync),
1141674×
    known: &(dyn Fn(&str) -> bool + Sync),
1151674×
) -> Result<Listing> {
1161674×
    let ctx = Ctx {
1171674×
        in_scope,
1181674×
        known,
1191674×
        out: Mutex::new(Listing::default()),
1201674×
        failed: Mutex::new(None),
1211674×
    };
1221674×
    let root_time = fs::metadata(root)
1231674×
        .map(|m| super::prompt::mtime_ns(&m))
1241674×
        .unwrap_or(0);
1251674×
    rayon::scope(|s| {
1261674×
        visit(
1271674×
            s,
1281674×
            root.to_path_buf(),
1291674×
            String::new(),
1301674×
            root_time,
131
            true,
1321674×
            Rules::default(),
1331674×
            &ctx,
134
        )
1351674×
    });
1361674×
    if let Some(e) = ctx.failed.into_inner().unwrap_or_else(|e| e.into_inner()) {
1370×
        return fail(e);
1381674×
    }
1391674×
    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::*;
14367372×
        out.files.par_sort_unstable_by(|a, b| a.0.cmp(&b.0));
1441674×
        out.symlinks.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1451674×
        out.dirs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1461674×
        out.nested.sort_unstable();
147
    }
1481674×
    Ok(out)
1491674×
}
150
151
#[allow(clippy::too_many_arguments)]
1522485×
fn visit<'s>(
1532485×
    s: &rayon::Scope<'s>,
1542485×
    dir: PathBuf,
1552485×
    rel: String,
1562485×
    mtime: u128,
1572485×
    top: bool,
1582485×
    rules: Rules,
1592485×
    ctx: &'s Ctx<'s>,
1602485×
) {
1612485×
    let read = || -> std::io::Result<Vec<fs::DirEntry>> { fs::read_dir(&dir)?.collect() };
1622485×
    let entries = match read() {
1632485×
        Ok(e) => e,
1640×
        Err(e) => {
1650×
            ctx.failed
1660×
                .lock()
1670×
                .unwrap_or_else(|e| e.into_inner())
1680×
                .get_or_insert_with(|| format!("{}: {e}", dir.display()));
1690×
            return;
170
        }
171
    };
1722485×
    let names: Vec<String> = entries
1732485×
        .iter()
17418912×
        .map(|e| e.file_name().to_string_lossy().into_owned())
1752485×
        .collect();
17613417×
    if !top && names.iter().any(|n| n == OXY_DIR || n == ".git") {
17739×
        ctx.out
17839×
            .lock()
17939×
            .unwrap_or_else(|e| e.into_inner())
180
            .nested
18139×
            .push(dir);
18239×
        return;
1832446×
    }
1842446×
    let rules = rules.enter(&dir, &names);
1852446×
    let mut mine = Listing::default();
1862446×
    mine.dirs.push((rel.clone(), mtime));
18718830×
    for (e, name) in entries.into_iter().zip(names) {
18818830×
        if name == OXY_DIR {
1891674×
            continue;
19017156×
        }
19117156×
        let Ok(ft) = e.file_type() else { continue };
19217156×
        let path = e.path();
19317156×
        let child = if rel.is_empty() {
1943818×
            name
195
        } else {
19613338×
            format!("{rel}/{name}")
197
        };
19817156×
        if (ft.is_dir() || !(ctx.known)(&child)) && rules.ignored(&path, ft.is_dir()) {
19960×
            continue;
20017096×
        }
20117096×
        if ft.is_dir() {
202811×
            let rules = rules.clone();
203
            // The directory's time now, before it is read.
204811×
            let time = e
205811×
                .metadata()
206811×
                .map(|m| super::prompt::mtime_ns(&m))
207811×
                .unwrap_or(0);
208811×
            s.spawn(move |s| visit(s, path, child, time, false, rules, ctx));
20916285×
        } else if !(ctx.in_scope)(&child) {
21016266×
        } else if ft.is_symlink() {
2113×
            match fs::read_link(&path) {
2123×
                Ok(t) => mine
2133×
                    .symlinks
2143×
                    .push((child, t.to_string_lossy().as_bytes().to_vec())),
2150×
                Err(e) => {
2160×
                    ctx.failed
2170×
                        .lock()
2180×
                        .unwrap_or_else(|e| e.into_inner())
2190×
                        .get_or_insert_with(|| format!("{}: {e}", path.display()));
220
                }
221
            }
22216263×
        } else if ft.is_file() {
22316263×
            match e.metadata() {
22416263×
                Ok(m) => mine.files.push((child, path, Stat::of(&m))),
2250×
                Err(e) => {
2260×
                    ctx.failed
2270×
                        .lock()
2280×
                        .unwrap_or_else(|e| e.into_inner())
2290×
                        .get_or_insert_with(|| format!("{}: {e}", path.display()));
230
                }
231
            }
2320×
        }
233
    }
2342446×
    let mut out = ctx.out.lock().unwrap_or_else(|e| e.into_inner());
2352446×
    out.files.append(&mut mine.files);
2362446×
    out.symlinks.append(&mut mine.symlinks);
2372446×
    out.dirs.append(&mut mine.dirs);
2382485×
}
239
240
#[cfg(test)]
241
mod tests {
242
    use super::*;
243
24422×
    fn write(root: &Path, rel: &str, text: &str) {
24522×
        let p = root.join(rel);
24622×
        fs::create_dir_all(p.parent().unwrap()).unwrap();
24722×
        fs::write(p, text).unwrap();
24822×
    }
249
2502×
    fn listed(root: &Path, in_scope: &(dyn Fn(&str) -> bool + Sync)) -> (Vec<String>, Vec<String>) {
2512×
        let l = list(root, in_scope).unwrap();
2522×
        let mut files: Vec<String> = l.files.into_iter().map(|(r, _, _)| r).collect();
2532×
        files.extend(l.symlinks.into_iter().map(|(r, _)| r));
2542×
        files.sort();
2552×
        let mut nested: Vec<String> = l
2562×
            .nested
2572×
            .iter()
2584×
            .map(|d| {
2594×
                d.strip_prefix(root)
2604×
                    .unwrap()
2614×
                    .to_string_lossy()
2624×
                    .replace('\\', "/")
2634×
            })
2642×
            .collect();
2652×
        nested.sort();
2662×
        (files, nested)
2672×
    }
268
269
    #[test]
2701×
    fn ignore_files_nested_repositories_and_scope() {
2711×
        let dir = tempfile::tempdir().unwrap();
2721×
        let root = dir.path();
2731×
        write(root, ".oxy/config", "");
2741×
        write(root, ".oxyignore", "*.log\nbuild/\n");
2751×
        write(root, ".hidden", "");
2761×
        write(root, "a.txt", "");
2771×
        write(root, "a.log", "");
2781×
        write(root, "build/out.o", "");
2791×
        write(root, "src/main.c", "");
2801×
        write(root, "src/deep/x.log", "");
281
        // A nearer file overrides an outer rule, and `.ignore` counts too.
2821×
        write(root, "keep/.oxyignore", "!*.log\n");
2831×
        write(root, "keep/k.log", "");
2841×
        write(root, "other/.ignore", "secret\n");
2851×
        write(root, "other/secret", "");
2861×
        write(root, "other/public", "");
287
        // .gitignore counts, below .oxyignore in the same directory.
2881×
        write(root, "gitproj/.gitignore", "build/\n*.tmp\nkeep.tmp\n");
2891×
        write(root, "gitproj/.oxyignore", "!keep.tmp\n");
2901×
        write(root, "gitproj/build/out.bin", "");
2911×
        write(root, "gitproj/x.tmp", "");
2921×
        write(root, "gitproj/keep.tmp", "");
2931×
        write(root, "gitproj/src.c", "");
294
        // Nested repositories are reported, not entered.
2951×
        write(root, "sub/.oxy/config", "");
2961×
        write(root, "sub/inner.txt", "");
2971×
        write(root, "vendor/g/.git/HEAD", "");
298
        #[cfg(unix)]
2991×
        std::os::unix::fs::symlink("a.txt", root.join("link")).unwrap();
300
3011×
        let (files, nested) = listed(root, &|_| true);
3021×
        let mut want = vec![
303
            ".hidden",
3041×
            ".oxyignore",
3051×
            "a.txt",
3061×
            "gitproj/.gitignore",
3071×
            "gitproj/.oxyignore",
3081×
            "gitproj/keep.tmp",
3091×
            "gitproj/src.c",
3101×
            "keep/.oxyignore",
3111×
            "keep/k.log",
3121×
            "other/.ignore",
3131×
            "other/public",
3141×
            "src/main.c",
315
        ];
3161×
        if cfg!(unix) {
3171×
            want.push("link");
3181×
        }
3191×
        want.sort();
3201×
        assert_eq!(files, want);
3211×
        assert_eq!(nested, vec!["sub", "vendor/g"]);
322
323
        // A sparse scope leaves files out but still visits directories.
32413×
        let (files, _) = listed(root, &|p: &str| p.starts_with("src/"));
3251×
        assert_eq!(files, vec!["src/main.c"]);
3261×
    }
327
}