clove/code4dyslexia
src/discovery.rs
// src/discovery.rs
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use regex::Regex;
use crate::language;
const EXCLUDED: &[&str] = &[
".git",
".c4d",
".cache",
".deno",
".next",
".nuxt",
".output",
".svelte-kit",
".turbo",
".wrangler",
"bower_components",
"build",
"coverage",
"dist",
"node_modules",
"out",
"target",
"vendor",
];
fn excluded(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| EXCLUDED.contains(&name))
}
pub fn generated_name(path: &Path) -> bool {
let name = path
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.to_ascii_lowercase();
[".generated", ".gen", ".min"]
.iter()
.any(|suffix| name.ends_with(suffix))
}
struct Pattern {
regex: Regex,
ignored: bool,
directories_only: bool,
}
fn trim_pattern(mut line: &str) -> &str {
while let Some(before) = line.strip_suffix(' ') {
let escapes = before
.bytes()
.rev()
.take_while(|&byte| byte == b'\\')
.count();
if escapes % 2 == 1 {
break;
}
line = before;
}
line
}
impl Pattern {
fn parse(line: &str) -> Result<Option<Self>, regex::Error> {
let line = trim_pattern(line);
if line.is_empty() || line.starts_with('#') {
return Ok(None);
}
let (ignored, pattern) = line
.strip_prefix('!')
.map_or((true, line), |rest| (false, rest));
let (directories_only, pattern) = pattern
.strip_suffix('/')
.map_or((false, pattern), |rest| (true, rest));
let anchored = pattern.contains('/');
let pattern = pattern.strip_prefix('/').unwrap_or(pattern);
if pattern.is_empty() {
return Ok(None);
}
let mut expression = String::from(if anchored { "^" } else { "(?:^|/)" });
let mut characters = pattern.char_indices().peekable();
while let Some((offset, character)) = characters.next() {
match character {
'\\' => {
let escaped = characters.next().map_or('\\', |(_, escaped)| escaped);
expression.push_str(®ex::escape(&escaped.to_string()));
}
'?' => expression.push_str("[^/]"),
'*' => {
let mut count = 1;
while matches!(characters.peek(), Some((_, '*'))) {
characters.next();
count += 1;
}
let boundary = offset == 0 || pattern.as_bytes()[offset - 1] == b'/';
match characters.peek() {
Some((_, '/')) if count == 2 && boundary => {
characters.next();
expression.push_str("(?s:.*/)?");
}
None if count == 2 && boundary => expression.push_str("(?s:.*)"),
_ => expression.push_str("[^/]*"),
}
}
'[' => {
let interior = &pattern[offset + 1..];
if let Some(end) = interior.find(']').filter(|&end| end > 0) {
let class = &interior[..end];
for _ in 0..=class.chars().count() {
characters.next();
}
expression.push_str("[[^/]&&[");
if let Some(negative) = class.strip_prefix('!') {
expression.push('^');
expression.push_str(negative);
} else {
if class.starts_with('^') {
expression.push('\\');
}
expression.push_str(class);
}
expression.push_str("]]");
} else {
expression.push_str("\\[");
}
}
_ => expression.push_str(®ex::escape(&character.to_string())),
}
}
expression.push('$');
Ok(Some(Self {
regex: Regex::new(&expression)?,
ignored,
directories_only,
}))
}
}
struct IgnoreRules {
directory: PathBuf,
patterns: Vec<Pattern>,
}
pub struct Discovery {
working_directory: PathBuf,
rules: HashMap<PathBuf, Arc<IgnoreRules>>,
visited: HashSet<PathBuf>,
}
impl Discovery {
pub fn new(working_directory: PathBuf) -> Self {
Self {
working_directory,
rules: HashMap::new(),
visited: HashSet::new(),
}
}
pub fn explicit(&self, input: &Path) -> Result<Option<PathBuf>, String> {
let absolute = self.working_directory.join(input);
let mut current = PathBuf::new();
for part in absolute.components() {
match part {
Component::ParentDir => {
current.pop();
}
Component::Normal(_) => {
current.push(part);
let metadata = current
.symlink_metadata()
.map_err(|error| format!("{}: {error}", current.display()))?;
if metadata.file_type().is_symlink()
|| (metadata.is_dir() && excluded(¤t))
{
eprintln!(
"{}: skipped (symbolic link or excluded directory)",
input.display()
);
return Ok(None);
}
}
_ => current.push(part),
}
}
Ok(Some(current))
}
fn extend(
&mut self,
directory: &Path,
layers: &mut Vec<Arc<IgnoreRules>>,
) -> Result<(), String> {
if let Some(cached) = self.rules.get(directory) {
if !cached.patterns.is_empty() {
layers.push(Arc::clone(cached));
}
return Ok(());
}
let mut patterns = Vec::new();
for name in [".gitignore", ".c4dignore"] {
let path = directory.join(name);
let source = match fs::read_to_string(&path) {
Ok(source) => source,
Err(error) if error.kind() == ErrorKind::NotFound => continue,
Err(error) => return Err(format!("{}: {error}", path.display())),
};
for (index, line) in source.lines().enumerate() {
let pattern = Pattern::parse(line).map_err(|error| {
format!(
"{}:{}: invalid ignore pattern: {error}",
path.display(),
index + 1
)
})?;
patterns.extend(pattern);
}
}
let rules = Arc::new(IgnoreRules {
directory: directory.to_owned(),
patterns,
});
if !rules.patterns.is_empty() {
layers.push(Arc::clone(&rules));
}
self.rules.insert(directory.to_owned(), rules);
Ok(())
}
fn ignored(path: &Path, directory: bool, layers: &[Arc<IgnoreRules>]) -> bool {
for layer in layers.iter().rev() {
let Ok(relative) = path.strip_prefix(&layer.directory) else {
continue;
};
let relative = relative
.iter()
.map(|part| part.to_string_lossy())
.collect::<Vec<_>>()
.join("/");
for pattern in layer.patterns.iter().rev() {
if (!pattern.directories_only || directory) && pattern.regex.is_match(&relative) {
return pattern.ignored;
}
}
}
false
}
pub fn scan(
&mut self,
path: &Path,
project: Option<&Path>,
mut process: impl FnMut(&Path),
) -> Result<(), String> {
let entry = path
.symlink_metadata()
.map_err(|error| format!("{}: {error}", path.display()))?;
let directory = if entry.is_dir() {
path
} else {
path.parent().unwrap_or(path)
};
let mut boundary = project.unwrap_or(directory);
if boundary.starts_with(&self.working_directory)
&& directory.starts_with(&self.working_directory)
{
boundary = &self.working_directory;
}
if let Some(git_root) = directory
.ancestors()
.find(|candidate| candidate.join(".git").symlink_metadata().is_ok())
{
boundary = git_root;
}
let mut layers = Vec::new();
let mut ancestors: Vec<_> = path
.ancestors()
.skip(1)
.take_while(|ancestor| ancestor.starts_with(boundary))
.collect();
while let Some(ancestor) = ancestors.pop() {
if Self::ignored(ancestor, true, &layers) {
eprintln!("{}: skipped (ignored by project rules)", path.display());
return Ok(());
}
self.extend(ancestor, &mut layers)?;
}
self.walk(path, &mut layers, true, &mut process)
}
fn walk(
&mut self,
path: &Path,
layers: &mut Vec<Arc<IgnoreRules>>,
explicit: bool,
process: &mut impl FnMut(&Path),
) -> Result<(), String> {
let entry = path
.symlink_metadata()
.map_err(|error| format!("{}: {error}", path.display()))?;
if entry.file_type().is_symlink() || (entry.is_dir() && excluded(path)) {
return Ok(());
}
if Self::ignored(path, entry.is_dir(), layers) {
if explicit {
eprintln!("{}: skipped (ignored by project rules)", path.display());
}
return Ok(());
}
if entry.is_dir() {
if !self.visited.insert(path.to_owned()) {
return Ok(());
}
let mut children = fs::read_dir(path)
.and_then(|entries| entries.collect::<Result<Vec<_>, _>>())
.map_err(|error| format!("{}: {error}", path.display()))?;
children.sort_unstable_by_key(|child| child.file_name());
let inherited = layers.len();
self.extend(path, layers)?;
for child in children {
let child_path = child.path();
let kind = child
.file_type()
.map_err(|error| format!("{}: {error}", child_path.display()))?;
if (kind.is_dir() && !excluded(&child_path))
|| (kind.is_file() && language::detect(&child_path).is_some())
{
self.walk(&child_path, layers, false, process)?;
}
}
layers.truncate(inherited);
} else if !entry.is_file() || language::detect(path).is_none() || generated_name(path) {
if explicit {
eprintln!(
"{}: skipped (unsupported or generated file)",
path.display()
);
}
} else if self.visited.insert(path.to_owned()) {
process(path);
}
Ok(())
}
}