use std::path::{Path, PathBuf};
pub const CORPUS_ENV: &str = "PROLINK_CAPTURES";
const DEFAULT_RELATIVE: &str = "captures";
#[derive(Clone, Debug)]
pub struct Corpus {
root: PathBuf,
}
impl Corpus {
pub fn locate() -> Option<Self> {
if let Some(path) = std::env::var_os(CORPUS_ENV) {
let root = PathBuf::from(path);
return root.is_dir().then_some(Self { root });
}
let root = workspace_root()?.join(DEFAULT_RELATIVE);
root.is_dir().then_some(Self { root })
}
pub fn at(root: impl Into<PathBuf>) -> Option<Self> {
let root = root.into();
root.is_dir().then_some(Self { root })
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn captures(&self) -> Vec<PathBuf> {
let mut found = Vec::new();
collect(&self.root, &mut found);
found.sort();
found
}
}
fn collect(directory: &Path, into: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(directory) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(&path, into);
} else if matches!(
path.extension().and_then(|extension| extension.to_str()),
Some("pcap" | "pcapng")
) {
into.push(path);
}
}
}
fn workspace_root() -> Option<PathBuf> {
Path::new(env!("CARGO_MANIFEST_DIR"))
.ancestors()
.nth(2)
.map(Path::to_path_buf)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_directory_that_is_not_there_is_not_a_corpus() {
assert!(Corpus::at("/nonexistent/prolink/captures").is_none());
}
#[test]
fn the_workspace_root_is_two_levels_above_this_crate() {
let root = workspace_root().expect("a workspace root");
assert!(
root.join("Cargo.toml").is_file(),
"expected the workspace manifest at {root:?}"
);
assert!(root.join("crates/prolink-capture").is_dir());
}
}