use std::path::{Path, PathBuf};
use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
use crate::support::AccessControl;
fn build_glob_set(patterns: &[String]) -> Result<GlobSet, String> {
let mut builder = GlobSetBuilder::new();
for pattern in patterns {
let glob = GlobBuilder::new(pattern)
.literal_separator(true)
.backslash_escape(false)
.build()
.map_err(|e| format!("Invalid pattern {pattern:?}: {e}"))?;
builder.add(glob);
}
builder
.build()
.map_err(|e| format!("Failed to build pattern set: {e}"))
}
pub async fn search_files(
root: &Path,
pattern: &str,
exclude_patterns: &[String],
access: &AccessControl,
) -> Result<Vec<PathBuf>, String> {
let matcher = build_glob_set(&[pattern.to_string()])?;
let excludes = if exclude_patterns.is_empty() {
None
} else {
Some(build_glob_set(exclude_patterns)?)
};
let mut results = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(current) = stack.pop() {
let mut entries = tokio::fs::read_dir(¤t)
.await
.map_err(|e| format!("Failed to read directory {}: {e}", current.display()))?;
while let Some(entry) = entries.next_entry().await.map_err(|e| e.to_string())? {
let path = entry.path();
let is_dir = entry.file_type().await.map_err(|e| e.to_string())?.is_dir();
if access.validate_path(&path.to_string_lossy()).await.is_err() {
continue;
}
let Ok(relative) = path.strip_prefix(root) else {
continue;
};
let relative = relative.to_string_lossy().replace('\\', "/");
if let Some(excludes) = &excludes
&& excludes.is_match(&relative)
{
continue;
}
if matcher.is_match(&relative) {
results.push(path.clone());
}
if is_dir {
stack.push(path);
}
}
}
Ok(results)
}
#[derive(Debug, serde::Serialize, schemars::JsonSchema)]
pub struct TreeEntry {
pub name: String,
#[serde(rename = "type")]
pub kind: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<TreeEntry>>,
}
pub async fn directory_tree(
root: &Path,
exclude_patterns: &[String],
access: &AccessControl,
) -> Result<Vec<TreeEntry>, String> {
build_tree(root, root, exclude_patterns, access).await
}
async fn build_tree(
root: &Path,
current: &Path,
exclude_patterns: &[String],
access: &AccessControl,
) -> Result<Vec<TreeEntry>, String> {
let mut entries = tokio::fs::read_dir(current)
.await
.map_err(|e| format!("Failed to read directory {}: {e}", current.display()))?;
let mut result = Vec::new();
while let Some(entry) = entries.next_entry().await.map_err(|e| e.to_string())? {
let path = entry.path();
if access.validate_path(&path.to_string_lossy()).await.is_err() {
continue;
}
let is_dir = entry.file_type().await.map_err(|e| e.to_string())?.is_dir();
let Ok(rel) = path.strip_prefix(root) else {
continue;
};
let rel_str = rel.to_string_lossy().replace('\\', "/");
if excluded(&rel_str, exclude_patterns) {
continue;
}
let mut node = TreeEntry {
name: entry.file_name().to_string_lossy().into_owned(),
kind: if is_dir { "directory" } else { "file" },
children: None,
};
if is_dir {
let children = Box::pin(build_tree(root, &path, exclude_patterns, access)).await?;
node.children = Some(children);
}
result.push(node);
}
Ok(result)
}
fn excluded(relative: &str, exclude_patterns: &[String]) -> bool {
exclude_patterns.iter().any(|pattern| {
if pattern.contains('*') {
matches_glob(relative, pattern)
} else {
matches_glob(relative, pattern)
|| matches_glob(relative, &format!("**/{pattern}"))
|| matches_glob(relative, &format!("**/{pattern}/**"))
}
})
}
fn matches_glob(relative: &str, pattern: &str) -> bool {
let Ok(set) = build_glob_set(&[pattern.to_string()]) else {
return false;
};
set.is_match(relative)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn glob_star_does_not_cross_separator() {
assert!(matches_glob("file.rs", "*.rs"));
assert!(matches_glob("a/b.rs", "**/*.rs"));
assert!(!matches_glob("a/b.rs", "*.rs"));
}
#[test]
fn glob_matches_dotfiles() {
assert!(matches_glob(".hidden", ".*"));
assert!(matches_glob("a/.hidden", "**/.*"));
}
#[test]
fn excluded_patterns_without_star() {
assert!(excluded("node_modules", &["node_modules".into()]));
assert!(excluded("a/node_modules", &["node_modules".into()]));
assert!(excluded("node_modules/pkg", &["node_modules".into()]));
assert!(excluded("a/node_modules/pkg", &["node_modules".into()]));
assert!(!excluded("a/nodemodules", &["node_modules".into()]));
}
#[test]
fn excluded_patterns_with_star() {
assert!(excluded("a/b.rs", &["a/*.rs".into()]));
assert!(!excluded("b/a.rs", &["a/*.rs".into()]));
}
}