use std::collections::HashMap;
use std::fs;
use std::io::Read as _;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
pub struct Parcel {
pub dir: String,
pub language: &'static str,
pub contracts: Vec<PathBuf>,
pub vendored_by: Option<String>,
}
#[must_use]
pub fn anchor(zone: &Path) -> PathBuf {
let dir = held(zone.parent());
if dir.file_name().is_some_and(|name| name == "contract") {
return held(dir.parent()).to_path_buf();
}
dir.to_path_buf()
}
fn held(dir: Option<&Path>) -> &Path {
match dir {
Some(dir) if !dir.as_os_str().is_empty() => dir,
_ => Path::new("."),
}
}
pub(super) fn charters(dir: &Path) -> Vec<PathBuf> {
let mut found: Vec<PathBuf> = [dir.to_path_buf(), dir.join("contract")]
.iter()
.filter_map(|home| fs::read_dir(home).ok())
.flat_map(|entries| entries.flatten().map(|entry| entry.path()))
.filter(|path| {
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zone")) && path.is_file()
})
.collect();
found.sort();
found
}
#[must_use]
pub fn governing(dir: &Path) -> Option<PathBuf> {
charters(dir).into_iter().find(|path| governs(path))
}
#[must_use]
pub fn discover(repo_root: &Path, under: &[String]) -> Vec<PathBuf> {
sweep(repo_root, under).0
}
#[must_use]
pub fn parcels(repo_root: &Path, under: &[String]) -> Vec<Parcel> {
let (contracts, mut found) = sweep(repo_root, under);
let vendored = borrowed(repo_root, &found);
for parcel in &mut found {
let home = repo_root.join(&parcel.dir);
parcel.contracts = contracts.iter().filter(|c| anchor(c) == home).cloned().collect();
parcel.vendored_by = vendored.get(&parcel.dir).cloned();
}
found
}
fn borrowed(repo_root: &Path, found: &[Parcel]) -> HashMap<String, String> {
let mut owned = HashMap::new();
for parcel in found {
let Some(dialect) = crate::survey::dialect(parcel.language) else { continue };
let base = repo_root.join(&parcel.dir);
for manifest in dialect.manifests() {
let Ok(text) = fs::read_to_string(base.join(manifest)) else { continue };
for dir in dialect.vendored(&text) {
let rel = posix(&Path::new(&parcel.dir).join(&dir));
owned.insert(rel.trim_start_matches("./").to_owned(), parcel.dir.clone());
}
}
}
owned
}
fn sweep(repo_root: &Path, under: &[String]) -> (Vec<PathBuf>, Vec<Parcel>) {
let (mut contracts, mut parcels) = match indexed(repo_root) {
Some(paths) => sift(repo_root, paths.iter().map(String::as_str)),
None => walked(repo_root),
};
if !under.is_empty() {
let scoped: Vec<String> = under.iter().filter_map(|u| narrowed(repo_root, u)).collect();
let within = |rel: &str| {
scoped.iter().any(|u| u == "." || rel == u || rel.starts_with(&format!("{u}/")))
};
contracts.retain(|c| c.strip_prefix(repo_root).is_ok_and(|r| within(&posix(r))));
parcels.retain(|p| within(&p.dir));
}
contracts.sort();
parcels.sort_by(|a, b| a.dir.cmp(&b.dir));
parcels.dedup_by(|a, b| a.dir == b.dir);
(contracts, parcels)
}
fn narrowed(repo_root: &Path, under: &str) -> Option<String> {
let named = Path::new(under);
let full = if named.is_absolute() { named.to_path_buf() } else { repo_root.join(named) };
let rel = posix(settled(&full).strip_prefix(settled(repo_root)).ok()?);
Some(if rel.is_empty() { ".".to_owned() } else { rel })
}
fn settled(path: &Path) -> PathBuf {
let mut lexical = PathBuf::new();
for part in path.components() {
match part {
Component::CurDir => {}
Component::ParentDir => {
if !lexical.pop() {
lexical.push(part);
}
}
named => lexical.push(named),
}
}
let mut tail = Vec::new();
let mut walk = lexical.as_path();
loop {
if let Ok(real) = walk.canonicalize() {
return tail.iter().rev().fold(real, |deep, name| deep.join(name));
}
match (walk.parent(), walk.file_name()) {
(Some(up), Some(name)) => {
tail.push(name);
walk = up;
}
_ => return lexical,
}
}
}
fn indexed(repo_root: &Path) -> Option<Vec<String>> {
let mut command = Command::new("git");
command
.args(["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--"])
.arg("*.zone")
.current_dir(repo_root);
for dialect in crate::survey::dialects() {
for manifest in dialect.manifests() {
command.arg(manifest).arg(format!("*/{manifest}"));
}
}
let out = command.output().ok()?;
out.status.success().then(|| {
String::from_utf8_lossy(&out.stdout)
.split('\0')
.filter(|p| !p.is_empty())
.map(str::to_owned)
.collect()
})
}
fn sift<'a>(repo_root: &Path, paths: impl Iterator<Item = &'a str>) -> (Vec<PathBuf>, Vec<Parcel>) {
let (mut contracts, mut parcels) = (Vec::new(), Vec::new());
for rel in paths {
let (dir, name) = rel.rsplit_once('/').unwrap_or((".", rel));
if Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("zone")) {
let path = repo_root.join(rel);
if governs(&path) {
contracts.push(path);
}
} else if let Some(dialect) =
crate::survey::dialects().iter().find(|d| d.manifests().contains(&name))
{
parcels.push(Parcel {
dir: dir.to_owned(),
language: dialect.name(),
contracts: Vec::new(),
vendored_by: None,
});
}
}
(contracts, parcels)
}
fn walked(repo_root: &Path) -> (Vec<PathBuf>, Vec<Parcel>) {
let mut stack = vec![repo_root.to_path_buf()];
let mut found: Vec<String> = Vec::new();
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
let Ok(kind) = entry.file_type() else { continue };
if kind.is_dir() {
if !crate::survey::SKIP.contains(&name.as_ref()) {
stack.push(entry.path());
}
} else if let Ok(rel) = entry.path().strip_prefix(repo_root) {
found.push(posix(rel));
}
}
}
sift(repo_root, found.iter().map(String::as_str))
}
fn governs(path: &Path) -> bool {
match lead(&head(path)) {
Some("package") | None => true,
Some("workspace") => match fs::read_to_string(path) {
Ok(text) => match super::parse::parse(&text, path) {
Ok(tree) => tree.package.is_some(),
Err(_) => true,
},
Err(_) => false,
},
Some(_) => false,
}
}
fn head(path: &Path) -> String {
let mut bytes = Vec::new();
if let Ok(file) = fs::File::open(path) {
let _ = file.take(8192).read_to_end(&mut bytes);
}
String::from_utf8_lossy(&bytes).into_owned()
}
fn lead(text: &str) -> Option<&str> {
text.lines()
.map(|line| line.split("//").next().unwrap_or_default().trim())
.find(|line| !line.is_empty())
.and_then(|line| line.split_whitespace().next())
}
pub(super) fn posix(rel: &Path) -> String {
rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/")
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, reason = "a test that cannot build its fixture has failed")]
use super::*;
#[test]
fn a_contract_governs_the_directory_it_sits_in() {
assert_eq!(anchor(Path::new("libs/acme/acme.zone")), Path::new("libs/acme"));
assert_eq!(anchor(Path::new("acme.zone")), Path::new("."));
}
#[test]
fn the_older_drawer_still_governs_its_parent() {
assert_eq!(anchor(Path::new("libs/acme/contract/acme.zone")), Path::new("libs/acme"));
assert_eq!(anchor(Path::new("contract/acme.zone")), Path::new("."));
}
#[test]
fn identity_is_the_leading_declaration() {
assert_eq!(lead("// a comment\n\npackage x {\n"), Some("package"));
assert_eq!(lead("workspace {\n"), Some("workspace"));
assert_eq!(lead("$TTL 3600\n@ IN SOA ns1.example.com.\n"), Some("$TTL"));
assert_eq!(lead("; bind comment\n$ORIGIN example.com.\n"), Some(";"));
assert_eq!(lead("\n\n// nothing but comments\n"), None);
}
#[test]
fn a_narrowing_is_a_place_and_not_a_spelling() {
let root = std::env::temp_dir().join("zoning-narrowed-test/libs/kernels");
fs::create_dir_all(&root).expect("temp tree");
let tree = root.parent().and_then(Path::parent).expect("two levels up");
for spelling in ["libs/kernels", "./libs/kernels", "libs/./kernels"] {
assert_eq!(narrowed(tree, spelling).as_deref(), Some("libs/kernels"), "{spelling}");
}
assert_eq!(narrowed(tree, &root.display().to_string()).as_deref(), Some("libs/kernels"));
assert_eq!(narrowed(tree, ".").as_deref(), Some("."));
assert_eq!(narrowed(tree, "../elsewhere"), None);
let plain = fs::canonicalize(std::env::temp_dir())
.expect("a temp dir to resolve")
.join("zoning-narrowed-plain/libs/kernels");
fs::create_dir_all(&plain).expect("temp tree");
let bare = plain.parent().and_then(Path::parent).expect("two levels up");
assert_eq!(narrowed(bare, "libs/kernels").as_deref(), Some("libs/kernels"));
assert_eq!(narrowed(bare, ".").as_deref(), Some("."));
assert_eq!(narrowed(bare, "../elsewhere"), None);
assert_eq!(narrowed(bare, "libs/kernels/../../../elsewhere"), None);
}
}