use std::{
env,
ffi::OsStr,
fs,
path::{Path, PathBuf},
};
use anyhow::{Context, Result};
use walkdir::WalkDir;
const DEFAULT_SEARCH_DIRS: &[&str] = &["crates"];
pub fn read_search_dirs(env_key: &str) -> Vec<PathBuf> {
match env::var(env_key) {
Ok(value) if !value.is_empty() => value.split(':').map(PathBuf::from).collect(),
_ => DEFAULT_SEARCH_DIRS.iter().map(PathBuf::from).collect(),
}
}
pub fn read_allowlist(env_key: &str) -> Vec<String> {
match env::var(env_key) {
Ok(value) if value.is_empty() => Vec::new(),
Ok(value) => value.split(';').map(str::to_string).collect(),
Err(_) => Vec::new(),
}
}
pub fn for_each_rs_file(
dir: &Path,
files_scanned: &mut usize,
skip: impl Fn(&Path) -> bool,
mut visit: impl FnMut(&Path, &str) -> Result<()>,
) -> Result<()> {
if !dir.exists() {
return Ok(());
}
for entry in WalkDir::new(dir).follow_links(false) {
let entry = entry.with_context(|| format!("walkdir under {}", dir.display()))?;
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
if path.extension().and_then(OsStr::to_str) != Some("rs") {
continue;
}
if skip(path) {
continue;
}
let source =
fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
*files_scanned += 1;
visit(path, &source)?;
}
Ok(())
}