TODO §45 (docs/features/small-items-4). Closes topo §2.9-17, 29, 30 and
adds the delay-list bar to §2.9-22.
45.1 `settings::rules` records every dropped `lucisv.lint.select`/`ignore`
name as `lucisv.lint.<setting>: unknown rule: <name>`; `apply_settings`
logs what the previous settings value did not already say — once per
(setting, name), re-armed by a changed list.
45.2 `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink: an
unreadable directory, an unreadable `.gitignore` and a dangling source
link are warned about and the walk continues; the CLI prints
`warning: <path>: <message>` on stderr before the report with the exit
code unchanged, the server logs once per scan through `report_scope`.
45.3 `parse_expr_or_type` accepts a `struct`/`union`/`enum` head as a
type argument, so `m #(.T(struct packed { logic a; })) u ();` parses and
`instantiation_plan` emits a one-line `parameter type` aggregate default.
45.4 Comment slots for `#(1:2:3)` and gate delay lists
(`MinTypMaxComments`, `DelayValue`, `ContAssign`/`GateInstantiation`/
`GateInstance` slots); `EXPECTED_RTL_GAPS` 374 → 419 at zero failures.
Review rework (QA's MEDIUM): a line comment after a gate instance's `,`
now ends the line, the next instance one level in.
Byte-identity vs 0.43.0: 0 of 820 corpus files and 0 opentitan outcomes
differ.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
693 lines
26 KiB
Rust
693 lines
26 KiB
Rust
//! File discovery: directory walking, `--exclude` matching and the
|
|
//! `.gitignore` subset documented in
|
|
//! `docs/features/parallel-files/README.md`.
|
|
|
|
use std::collections::HashSet;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
/// File extensions lucisv formats when walking a directory.
|
|
pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
|
|
|
/// The name of the per-directory ignore file that is honoured by default.
|
|
const GITIGNORE: &str = ".gitignore";
|
|
|
|
/// Something the walk could not do and went on regardless: a directory it
|
|
/// could not read, an ignore file it could not open, a source file that is
|
|
/// only a broken link.
|
|
///
|
|
/// The walk's warning channel exists because none of these is worth failing a
|
|
/// run over — one unreadable directory used to drop every file already found
|
|
/// — and because a silent skip loses the user the fact entirely. Rendering is
|
|
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
|
|
/// the server logs the same text once per scan.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Warning {
|
|
/// What could not be used.
|
|
pub path: PathBuf,
|
|
/// Why, in the operating system's own words where there are any.
|
|
pub message: String,
|
|
}
|
|
|
|
impl std::fmt::Display for Warning {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "{}: {}", self.path.display(), self.message)
|
|
}
|
|
}
|
|
|
|
/// Adds `input` to `files`: the file itself, or every Verilog file under
|
|
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
|
|
/// to directory walks only — a path named on the command line is always
|
|
/// formatted.
|
|
///
|
|
/// `warn` is called once for everything the walk skipped and wants said; see
|
|
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
|
|
/// user's own typo, and the run has nothing to do.
|
|
pub fn collect_files(
|
|
input: &str,
|
|
exclude: &[String],
|
|
gitignore: bool,
|
|
files: &mut Vec<PathBuf>,
|
|
warn: &mut dyn FnMut(Warning),
|
|
) -> Result<(), String> {
|
|
let path = Path::new(input);
|
|
if path.is_dir() {
|
|
let mut walk = Walk {
|
|
exclude,
|
|
gitignore,
|
|
ignores: Vec::new(),
|
|
rel: Vec::new(),
|
|
visited: HashSet::new(),
|
|
files,
|
|
warn,
|
|
};
|
|
walk.dir(path);
|
|
} else if path.is_file() {
|
|
files.push(path.to_path_buf());
|
|
} else {
|
|
return Err(format!("{input}: no such file or directory"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// How a directory is recognised as one the walk has already entered. Two
|
|
/// names for the same directory — a symlink and its target, or two symlinks
|
|
/// pointing at one place — must map to the same identity, or a cycle has no
|
|
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
|
|
/// elsewhere it is the canonical path, which resolves symlinks the same way
|
|
/// at the cost of a real path lookup.
|
|
#[cfg(unix)]
|
|
type DirId = (u64, u64);
|
|
#[cfg(not(unix))]
|
|
type DirId = PathBuf;
|
|
|
|
/// The identity of the directory at `path`, or `None` when it cannot be
|
|
/// read — a dangling symlink, or a directory that vanished mid-walk.
|
|
#[cfg(unix)]
|
|
fn dir_id(path: &Path) -> Option<DirId> {
|
|
use std::os::unix::fs::MetadataExt;
|
|
let meta = std::fs::metadata(path).ok()?;
|
|
Some((meta.dev(), meta.ino()))
|
|
}
|
|
|
|
#[cfg(not(unix))]
|
|
fn dir_id(path: &Path) -> Option<DirId> {
|
|
std::fs::canonicalize(path).ok()
|
|
}
|
|
|
|
/// True when `path` names one of the source files lucisv formats.
|
|
fn is_source(path: &Path) -> bool {
|
|
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
|
|
}
|
|
|
|
/// One directory walk. `rel` is the path of the directory currently being
|
|
/// read, in components relative to the walk root, which is what
|
|
/// `.gitignore` rules are matched against; `ignores` is the stack of
|
|
/// ignore files seen from the root down to it; `visited` is every directory
|
|
/// already entered, by identity rather than by spelling.
|
|
struct Walk<'a> {
|
|
exclude: &'a [String],
|
|
gitignore: bool,
|
|
ignores: Vec<Ignore>,
|
|
rel: Vec<String>,
|
|
visited: HashSet<DirId>,
|
|
files: &'a mut Vec<PathBuf>,
|
|
warn: &'a mut dyn FnMut(Warning),
|
|
}
|
|
|
|
impl Walk<'_> {
|
|
fn dir(&mut self, dir: &Path) {
|
|
if !self.enter(dir) {
|
|
return;
|
|
}
|
|
let pushed = self.push_ignore(dir);
|
|
self.entries(dir);
|
|
if pushed {
|
|
self.ignores.pop();
|
|
}
|
|
}
|
|
|
|
/// One directory's entries, in name order. A directory that cannot be read
|
|
/// — the permission-denied one somewhere under the start — is said and
|
|
/// skipped: everything already found stays found and the walk goes on,
|
|
/// which is the whole reason this channel exists.
|
|
fn entries(&mut self, dir: &Path) {
|
|
let read = match std::fs::read_dir(dir) {
|
|
Ok(read) => read,
|
|
Err(e) => return self.say(dir, e.to_string()),
|
|
};
|
|
let mut entries = Vec::new();
|
|
for entry in read {
|
|
match entry {
|
|
Ok(entry) => entries.push(entry),
|
|
Err(e) => self.say(dir, e.to_string()),
|
|
}
|
|
}
|
|
entries.sort_by_key(|e| e.path());
|
|
for entry in entries {
|
|
let path = entry.path();
|
|
if is_excluded(&path, self.exclude) {
|
|
continue;
|
|
}
|
|
// One `metadata` call per entry, exactly as before — it follows
|
|
// symlinks, so it answers "directory?" for a symlinked directory
|
|
// the way `is_dir()` did. A dangling symlink has no metadata at
|
|
// all. One that *names a source file* is warned about and dropped:
|
|
// §43's QA was right that a silent skip loses the user the fact,
|
|
// and §45.2 gives that fact a home of its own rather than handing
|
|
// the path on to fail as "no such file" in the front end. One that
|
|
// names anything else was never going to be read, and is skipped
|
|
// as quietly as it always was.
|
|
let Ok(meta) = std::fs::metadata(&path) else {
|
|
if is_source(&path) {
|
|
let why = broken_link_reason(&path);
|
|
self.say(&path, why);
|
|
}
|
|
continue;
|
|
};
|
|
self.rel.push(entry.file_name().to_string_lossy().into_owned());
|
|
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
|
|
if meta.is_dir() {
|
|
self.dir(&path);
|
|
} else if meta.is_file() && is_source(&path) {
|
|
self.files.push(path);
|
|
}
|
|
}
|
|
self.rel.pop();
|
|
}
|
|
}
|
|
|
|
/// Hand one warning to the front end.
|
|
fn say(&mut self, path: &Path, message: String) {
|
|
(self.warn)(Warning { path: path.to_path_buf(), message });
|
|
}
|
|
|
|
/// Records `dir` as entered, and answers whether it had not been entered
|
|
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
|
|
/// a directory the walk is already inside, and following either is the
|
|
/// cycle that only ends when the OS refuses a path. A symlink to a
|
|
/// directory the walk has *not* seen is followed once, so
|
|
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
|
|
/// one target contributes nothing further, and the files are reported
|
|
/// under the first spelling that reached them.
|
|
///
|
|
/// A directory whose identity cannot be read is not entered.
|
|
fn enter(&mut self, dir: &Path) -> bool {
|
|
dir_id(dir).is_some_and(|id| self.visited.insert(id))
|
|
}
|
|
|
|
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
|
/// Returns whether anything was pushed, so `dir` can pop it again.
|
|
///
|
|
/// An ignore file that cannot be read is said and ignored, for the same
|
|
/// reason an unreadable directory is: the walk that finds too much is a
|
|
/// better failure than the walk that finds nothing.
|
|
fn push_ignore(&mut self, dir: &Path) -> bool {
|
|
let path = dir.join(GITIGNORE);
|
|
if !self.gitignore || !path.is_file() {
|
|
return false;
|
|
}
|
|
match std::fs::read_to_string(&path) {
|
|
Ok(text) => {
|
|
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
|
|
true
|
|
}
|
|
Err(e) => {
|
|
self.say(&path, e.to_string());
|
|
false
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Why a directory entry has no metadata, said the way a person would.
|
|
///
|
|
/// A broken symbolic link is what this is nearly always about, and naming it
|
|
/// as one is worth more than the bare `No such file or directory` the follow
|
|
/// produced; anything else keeps the operating system's own words.
|
|
fn broken_link_reason(path: &Path) -> String {
|
|
match std::fs::symlink_metadata(path) {
|
|
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
|
|
Ok(_) => "cannot be read".to_string(),
|
|
Err(e) => e.to_string(),
|
|
}
|
|
}
|
|
|
|
/// One `.gitignore` file's rules, plus how deep in the walk the directory
|
|
/// holding it was, so its patterns can be matched relative to it.
|
|
struct Ignore {
|
|
base: usize,
|
|
rules: Vec<Rule>,
|
|
}
|
|
|
|
/// One `.gitignore` line, already stripped of its prefix and suffix
|
|
/// markers. The remaining pattern uses the `--exclude` glob semantics.
|
|
struct Rule {
|
|
/// `!pattern`: a match re-includes instead of ignoring.
|
|
negated: bool,
|
|
/// `pattern/`: matches directories only.
|
|
dir_only: bool,
|
|
/// The pattern had a `/` at its start or in its middle, so it is
|
|
/// matched from the `.gitignore`'s own directory instead of at any
|
|
/// depth below it.
|
|
anchored: bool,
|
|
pattern: String,
|
|
}
|
|
|
|
/// Parses the supported `.gitignore` subset; unsupported metacharacters
|
|
/// are left to match literally rather than rejected. Grammar and the
|
|
/// explicit list of what git does that this does not:
|
|
/// `docs/features/parallel-files/README.md`.
|
|
fn parse_gitignore(text: &str) -> Vec<Rule> {
|
|
let mut rules = Vec::new();
|
|
for raw in text.lines() {
|
|
// Git strips trailing whitespace but not leading whitespace.
|
|
let line = raw.trim_end();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
continue;
|
|
}
|
|
let (negated, line) = match line.strip_prefix('!') {
|
|
Some(rest) => (true, rest),
|
|
None => (false, line),
|
|
};
|
|
let (dir_only, line) = match line.strip_suffix('/') {
|
|
Some(rest) => (true, rest),
|
|
None => (false, line),
|
|
};
|
|
let anchored = line.contains('/');
|
|
let pattern = line.strip_prefix('/').unwrap_or(line);
|
|
if pattern.is_empty() {
|
|
continue;
|
|
}
|
|
rules.push(Rule { negated, dir_only, anchored, pattern: pattern.to_string() });
|
|
}
|
|
rules
|
|
}
|
|
|
|
/// True if the ignore stack ignores the entry at `rel` (components
|
|
/// relative to the walk root). Later rules win, so a deeper `.gitignore`
|
|
/// overrides a shallower one and a later line overrides an earlier one —
|
|
/// git's own precedence, which is what makes `!` useful.
|
|
fn is_ignored(ignores: &[Ignore], rel: &[String], is_dir: bool) -> bool {
|
|
let mut ignored = false;
|
|
for ignore in ignores {
|
|
let Some(tail) = rel.get(ignore.base..) else { continue };
|
|
for rule in &ignore.rules {
|
|
if rule_matches(rule, tail, is_dir) {
|
|
ignored = !rule.negated;
|
|
}
|
|
}
|
|
}
|
|
ignored
|
|
}
|
|
|
|
fn rule_matches(rule: &Rule, tail: &[String], is_dir: bool) -> bool {
|
|
if rule.dir_only && !is_dir {
|
|
return false;
|
|
}
|
|
if !rule.anchored {
|
|
// No `/` in the pattern: it matches an entry's name at any depth.
|
|
return tail.last().is_some_and(|name| glob_component(&rule.pattern, name));
|
|
}
|
|
let pattern: Vec<&str> = rule.pattern.split('/').collect();
|
|
pattern.len() == tail.len()
|
|
&& pattern.iter().zip(tail).all(|(p, c)| glob_component(p, c.as_str()))
|
|
}
|
|
|
|
/// True if `path` matches any exclude pattern. A pattern containing `/`
|
|
/// is matched against the path's trailing components; one without is
|
|
/// matched against the final component only.
|
|
pub fn is_excluded(path: &Path, exclude: &[String]) -> bool {
|
|
let components: Vec<&str> = path.iter().filter_map(|c| c.to_str()).collect();
|
|
exclude.iter().any(|pattern| matches(pattern, &components))
|
|
}
|
|
|
|
fn matches(pattern: &str, components: &[&str]) -> bool {
|
|
let pattern: Vec<&str> = pattern.split('/').filter(|p| !p.is_empty()).collect();
|
|
if pattern.is_empty() || pattern.len() > components.len() {
|
|
return false;
|
|
}
|
|
let tail = &components[components.len() - pattern.len()..];
|
|
pattern.iter().zip(tail).all(|(p, c)| glob_component(p, c))
|
|
}
|
|
|
|
/// Matches one path component against a pattern in which `*` stands for
|
|
/// any run of characters (including none). No other metacharacters.
|
|
fn glob_component(pattern: &str, name: &str) -> bool {
|
|
let (pattern, name) = (pattern.as_bytes(), name.as_bytes());
|
|
let (mut p, mut n) = (0, 0);
|
|
// Position of the last `*` seen, and how much of `name` it had
|
|
// consumed at that point, so a failed match can backtrack into it.
|
|
let (mut star, mut consumed) = (None, 0);
|
|
while n < name.len() {
|
|
if p < pattern.len() && pattern[p] == b'*' {
|
|
star = Some(p);
|
|
consumed = n;
|
|
p += 1;
|
|
} else if p < pattern.len() && pattern[p] == name[n] {
|
|
p += 1;
|
|
n += 1;
|
|
} else if let Some(s) = star {
|
|
p = s + 1;
|
|
consumed += 1;
|
|
n = consumed;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
pattern[p..].iter().all(|&b| b == b'*')
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[cfg(unix)]
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
fn excluded(path: &str, pattern: &str) -> bool {
|
|
is_excluded(Path::new(path), &[pattern.to_string()])
|
|
}
|
|
|
|
#[test]
|
|
fn name_patterns_match_at_any_depth() {
|
|
assert!(excluded("rtl/build", "build"));
|
|
assert!(excluded("rtl/a/b/gen.sv", "gen.sv"));
|
|
assert!(!excluded("rtl/building", "build"));
|
|
assert!(!excluded("build/rtl", "rtl.sv"));
|
|
}
|
|
|
|
#[test]
|
|
fn star_stays_inside_one_component() {
|
|
assert!(excluded("rtl/foo_gen.sv", "*_gen.sv"));
|
|
assert!(excluded("rtl/foo_gen.sv", "*"));
|
|
assert!(!excluded("rtl/foo_gen.sv", "rtl*sv"));
|
|
assert!(excluded("rtl/foo_gen.sv", "rtl/*sv"));
|
|
}
|
|
|
|
#[test]
|
|
fn slash_patterns_match_a_path_suffix() {
|
|
assert!(excluded("a/b/gen/rtl", "gen/rtl"));
|
|
assert!(excluded("a/b/gen/rtl/x.sv", "gen/*/x.sv"));
|
|
assert!(!excluded("a/b/gen/other", "gen/rtl"));
|
|
assert!(!excluded("gen/rtl", "b/gen/rtl"));
|
|
}
|
|
|
|
#[test]
|
|
fn star_handles_repeats_and_empty_matches() {
|
|
assert!(excluded("a/xxxy", "*y"));
|
|
assert!(excluded("a/y", "*y"));
|
|
assert!(excluded("a/ab", "a*b*"));
|
|
assert!(!excluded("a/xxx", "*y"));
|
|
}
|
|
|
|
/// Builds a one-level ignore stack rooted at the walk root and asks it
|
|
/// about `rel` (a `/`-joined path, trailing `/` meaning a directory).
|
|
fn ignored(text: &str, rel: &str) -> bool {
|
|
ignored_at(&[(0, text)], rel)
|
|
}
|
|
|
|
/// The same, with several `.gitignore` files at the given depths.
|
|
fn ignored_at(files: &[(usize, &str)], rel: &str) -> bool {
|
|
let ignores: Vec<Ignore> = files
|
|
.iter()
|
|
.map(|(base, text)| Ignore { base: *base, rules: parse_gitignore(text) })
|
|
.collect();
|
|
let is_dir = rel.ends_with('/');
|
|
let parts: Vec<String> =
|
|
rel.trim_end_matches('/').split('/').map(|s| s.to_string()).collect();
|
|
is_ignored(&ignores, &parts, is_dir)
|
|
}
|
|
|
|
#[test]
|
|
fn comments_and_blank_lines_are_skipped() {
|
|
assert_eq!(parse_gitignore("\n# build\n\n \nbuild\n").len(), 1);
|
|
assert!(!ignored("# build", "build"));
|
|
assert!(ignored("build", "build"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_bare_name_matches_at_any_depth() {
|
|
assert!(ignored("build", "build"));
|
|
assert!(ignored("build", "a/b/build"));
|
|
assert!(ignored("*.log", "a/b/c.log"));
|
|
assert!(!ignored("build", "a/building"));
|
|
assert!(!ignored("build", "build/x.sv"), "the walk prunes the directory instead");
|
|
}
|
|
|
|
#[test]
|
|
fn a_slash_anchors_the_pattern_to_the_ignore_files_directory() {
|
|
assert!(ignored("/build", "build"));
|
|
assert!(!ignored("/build", "a/build"), "a leading slash anchors");
|
|
assert!(ignored("gen/rtl", "gen/rtl"));
|
|
assert!(!ignored("gen/rtl", "a/gen/rtl"), "a slash in the middle anchors too");
|
|
assert!(ignored("gen/*.sv", "gen/x.sv"));
|
|
assert!(!ignored("gen/*.sv", "gen/a/x.sv"), "`*` never crosses a separator");
|
|
}
|
|
|
|
#[test]
|
|
fn a_trailing_slash_matches_directories_only() {
|
|
assert!(ignored("build/", "build/"));
|
|
assert!(!ignored("build/", "build"));
|
|
assert!(ignored("build", "build/"), "without the slash both kinds match");
|
|
}
|
|
|
|
#[test]
|
|
fn negation_re_includes_and_the_last_match_wins() {
|
|
assert!(!ignored("*.sv\n!keep.sv", "keep.sv"));
|
|
assert!(ignored("*.sv\n!keep.sv", "drop.sv"));
|
|
assert!(ignored("!keep.sv\n*.sv", "keep.sv"), "order matters: the last match wins");
|
|
// A deeper .gitignore is consulted after a shallower one, so it wins.
|
|
assert!(!ignored_at(&[(0, "*.sv"), (1, "!keep.sv")], "sub/keep.sv"));
|
|
assert!(ignored_at(&[(0, "!keep.sv"), (1, "*.sv")], "sub/keep.sv"));
|
|
}
|
|
|
|
#[test]
|
|
fn an_anchored_pattern_is_relative_to_its_own_gitignore() {
|
|
// `/x.sv` in sub/.gitignore (base 1) means sub/x.sv, not x.sv.
|
|
assert!(ignored_at(&[(1, "/x.sv")], "sub/x.sv"));
|
|
assert!(!ignored_at(&[(1, "/x.sv")], "sub/deep/x.sv"));
|
|
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// Symlink cycles — `docs/features/walk-cycles/README.md`
|
|
//
|
|
// Every test below builds a real tree with real symlinks, because the
|
|
// question is what the filesystem answers, not what a mock does. Each
|
|
// one would run until the OS refused a path before the visited set.
|
|
// ------------------------------------------------------------------
|
|
|
|
/// A throwaway directory tree under the system temp dir, removed on
|
|
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
|
|
/// a tree with a cycle in it is cleaned up like any other.
|
|
#[cfg(unix)]
|
|
struct TempTree {
|
|
path: PathBuf,
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
impl TempTree {
|
|
fn new(tag: &str) -> TempTree {
|
|
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
|
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
let path =
|
|
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&path);
|
|
std::fs::create_dir_all(&path).expect("create temp dir");
|
|
TempTree { path }
|
|
}
|
|
|
|
fn write(&self, rel: &str, text: &str) {
|
|
let path = self.path.join(rel);
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).expect("create parent");
|
|
}
|
|
std::fs::write(&path, text).expect("write");
|
|
}
|
|
|
|
/// A source file with enough in it to be worth finding.
|
|
fn source(&self, rel: &str) {
|
|
self.write(rel, "module m;\nendmodule\n");
|
|
}
|
|
|
|
/// Set `rel`'s permission bits. `0o000` is how a test builds the
|
|
/// directory the walk cannot read; the test puts them back so the
|
|
/// temp tree can be removed.
|
|
fn chmod(&self, rel: &str, mode: u32) {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let path = self.path.join(rel);
|
|
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
|
|
.expect("set permissions");
|
|
}
|
|
|
|
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
|
|
/// directory — the spelling a checked-in symlink actually uses.
|
|
fn link(&self, rel: &str, target: &str) {
|
|
let path = self.path.join(rel);
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).expect("create parent");
|
|
}
|
|
std::os::unix::fs::symlink(target, &path).expect("symlink");
|
|
}
|
|
|
|
/// The walk from `rel` (empty for the root), as sorted paths
|
|
/// relative to the tree root. Warnings are dropped; the tests that
|
|
/// care about them call [`TempTree::warned`].
|
|
fn walk(&self, rel: &str) -> Vec<String> {
|
|
self.walked(rel).0
|
|
}
|
|
|
|
/// The same, plus what the walk said, each warning's path made
|
|
/// relative to the tree root so the assertions read.
|
|
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
|
self.walked(rel)
|
|
}
|
|
|
|
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
|
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
|
|
let mut files = Vec::new();
|
|
let mut warnings = Vec::new();
|
|
collect_files(
|
|
start.to_str().expect("utf-8 temp path"),
|
|
&[],
|
|
true,
|
|
&mut files,
|
|
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
|
|
)
|
|
.expect("the walk finishes");
|
|
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
|
|
out.sort();
|
|
warnings.sort();
|
|
(out, warnings)
|
|
}
|
|
|
|
fn rel_of(&self, path: &Path) -> String {
|
|
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn a_directory_linking_to_itself_is_entered_once() {
|
|
let tree = TempTree::new("selfloop");
|
|
tree.source("a/x.sv");
|
|
tree.link("a/loop", "../a");
|
|
assert_eq!(tree.walk(""), ["a/x.sv"]);
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
|
|
let tree = TempTree::new("uplink");
|
|
tree.source("root.sv");
|
|
tree.source("a/x.sv");
|
|
tree.link("a/up", "..");
|
|
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
|
|
// root, which the walk has not seen yet and so does enter — once.
|
|
// Its own `a` is the directory already being walked, and stops.
|
|
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn two_links_to_one_directory_yield_its_files_once() {
|
|
let tree = TempTree::new("twolinks");
|
|
tree.source("shared/x.sv");
|
|
// Sorted after `shared`, so the real directory is the spelling that
|
|
// reaches the file first; whichever name wins, the file is reported
|
|
// exactly once.
|
|
tree.link("z1", "shared");
|
|
tree.link("z2", "shared");
|
|
assert_eq!(tree.walk(""), ["shared/x.sv"]);
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
|
|
let tree = TempTree::new("sibling");
|
|
tree.source("shared/rtl/x.sv");
|
|
tree.link("proj/rtl", "../shared/rtl");
|
|
// The `rtl -> ../shared/rtl` of a real checkout: the target is
|
|
// outside the walk, so the link is the only way to it.
|
|
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
|
|
// §43's review kept the dangling source link in the file list so the
|
|
// front end's "no such file" error survived. TODO §45.2 reverses that
|
|
// on purpose: the warning is now the error's home, so the link is said
|
|
// once here and never reaches the formatter. A dangling link that
|
|
// names no source file was never going to be read and stays silent.
|
|
let tree = TempTree::new("dangling");
|
|
tree.source("a/x.sv");
|
|
tree.link("a/gone.sv", "nowhere.sv");
|
|
tree.link("a/gonedir", "nowhere");
|
|
let (files, warnings) = tree.warned("");
|
|
assert_eq!(files, ["a/x.sv"]);
|
|
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
|
|
// The finding this channel exists for: one permission-denied directory
|
|
// used to propagate `read_dir`'s error out of the whole walk, dropping
|
|
// every file already found and failing the run.
|
|
let tree = TempTree::new("unreadable");
|
|
tree.source("a.sv");
|
|
tree.source("locked/hidden.sv");
|
|
tree.source("z/late.sv");
|
|
tree.chmod("locked", 0o000);
|
|
let (files, warnings) = tree.warned("");
|
|
tree.chmod("locked", 0o755);
|
|
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
|
|
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
|
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
|
|
let tree = TempTree::new("lockedignore");
|
|
tree.write(".gitignore", "build\n");
|
|
tree.source("keep.sv");
|
|
tree.chmod(".gitignore", 0o000);
|
|
let (files, warnings) = tree.warned("");
|
|
tree.chmod(".gitignore", 0o644);
|
|
assert_eq!(files, ["keep.sv"]);
|
|
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
|
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn a_clean_walk_says_nothing() {
|
|
let tree = TempTree::new("quiet");
|
|
tree.source("a/x.sv");
|
|
tree.source("b/y.sv");
|
|
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
|
|
}
|
|
|
|
#[test]
|
|
#[cfg(unix)]
|
|
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
|
|
let tree = TempTree::new("ignoredcycle");
|
|
tree.write(".gitignore", "build\n");
|
|
tree.source("keep.sv");
|
|
tree.source("build/y.sv");
|
|
tree.link("build/loop", "../build");
|
|
assert_eq!(tree.walk(""), ["keep.sv"]);
|
|
}
|
|
|
|
#[test]
|
|
fn unsupported_syntax_degrades_to_plain_globbing() {
|
|
// `**` is just two stars inside one component; documented.
|
|
assert!(ignored("a/**/z.sv", "a/b/z.sv"));
|
|
assert!(!ignored("a/**/z.sv", "a/b/c/z.sv"));
|
|
// `?` is a literal character, not a single-character wildcard.
|
|
assert!(ignored("x?.sv", "x?.sv"));
|
|
assert!(!ignored("x?.sv", "xa.sv"));
|
|
}
|
|
}
|