use std::collections::HashSet;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Edge {
pub dir: String,
pub owns: String,
pub not_owns: String,
pub tokens: Option<u64>,
}
#[must_use]
pub fn edges(text: &str) -> Vec<Edge> {
let mut out = Vec::new();
let mut in_f = false;
for line in text.lines() {
if line.starts_with("## \u{a7}") {
in_f = line.starts_with("## \u{a7}F");
continue;
}
if !in_f {
continue;
}
let cells = split_row(line);
let [dir, owns, not_owns, tokens] = cells.as_slice() else {
continue;
};
if dir == "dir" {
continue;
}
out.push(Edge {
dir: dir.clone(),
owns: owns.clone(),
not_owns: not_owns.clone(),
tokens: tokens.parse().ok(),
});
}
out
}
fn split_row(line: &str) -> Vec<String> {
microlith::cells(line.trim())
.into_iter()
.map(|c| microlith::unescape(c.trim()))
.collect()
}
#[must_use]
pub fn chain(root: &Path, dir: &Path) -> Vec<PathBuf> {
let mut nodes = Vec::new();
let rel = dir.strip_prefix(root).unwrap_or(dir);
let mut cur = root.to_path_buf();
if is_node(&cur) {
nodes.push(cur.join("SPEC.md"));
}
for part in rel.components() {
cur = cur.join(part);
if is_node(&cur) {
nodes.push(cur.join("SPEC.md"));
}
}
nodes
}
#[must_use]
pub fn discover(root: &Path) -> Vec<PathBuf> {
let ignored = git_ignored(root);
let mut out = Vec::new();
walk(root, &ignored, &mut out);
out.sort();
out
}
fn git_ignored(dir: &Path) -> HashSet<PathBuf> {
let args = [
"ls-files",
"-z",
"--others",
"--ignored",
"--exclude-standard",
"--directory",
];
let Ok(out) = crate::git::at(dir, &args).output() else {
return HashSet::new();
};
if !out.status.success() {
return HashSet::new();
}
out.stdout
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.map(|p| {
let rel = String::from_utf8_lossy(p);
dir.join(rel.trim_end_matches('/'))
})
.collect()
}
#[must_use]
pub fn is_node(dir: &Path) -> bool {
dir.join("SPEC.md").is_file()
&& std::fs::read_dir(dir)
.is_ok_and(|rd| rd.flatten().any(|e| e.file_name() == "SPEC.md"))
}
fn walk(dir: &Path, ignored: &HashSet<PathBuf>, out: &mut Vec<PathBuf>) {
if is_node(dir) && !ignored.contains(&dir.join("SPEC.md")) {
out.push(dir.to_path_buf());
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for e in entries.flatten() {
let p = e.path();
if !p.is_dir() {
continue;
}
let name = p
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
if is_ignored_dir(&name) || ignored.contains(&p) {
continue;
}
walk(&p, ignored, out);
}
}
pub fn depth_violations(edges: &[Edge]) -> Vec<&Edge> {
edges
.iter()
.filter(|e| e.dir.split('/').count() != 1)
.collect()
}
pub fn missing_not_owns(edges: &[Edge]) -> Vec<&Edge> {
edges
.iter()
.filter(|e| e.not_owns.trim().is_empty())
.collect()
}
#[must_use]
pub fn mermaid(root: &Path) -> String {
let mut defs = String::new();
let mut links = String::new();
let mut seen: Vec<String> = Vec::new();
for node in discover(root) {
let rel = node.strip_prefix(root).unwrap_or(&node);
let from = label(rel);
if !seen.contains(&from) {
seen.push(from.clone());
defs.push_str(&format!(" {from}[{}]\n", ident(&disp(rel))));
}
let Ok(text) = std::fs::read_to_string(node.join("SPEC.md")) else {
continue;
};
for e in edges(&text) {
let id = label(&rel.join(&e.dir));
if !seen.contains(&id) {
seen.push(id.clone());
defs.push_str(&format!(" {id}[{}]\n", ident(&e.dir)));
}
links.push_str(&format!(" {from} --> {id}\n"));
}
}
format!("graph TD\n{defs}{links}")
}
#[must_use]
pub fn table(root: &Path) -> String {
let mut out =
String::from("| node | owns | does not own |\n|---|---|---|\n");
for node in discover(root) {
let rel = node.strip_prefix(root).unwrap_or(&node);
let Ok(text) = std::fs::read_to_string(node.join("SPEC.md")) else {
continue;
};
for e in edges(&text) {
out.push_str(&format!(
"| `{}` | {} | {} |\n",
rel.join(&e.dir).display(),
cell(&e.owns),
cell(&e.not_owns)
));
}
}
out
}
fn cell(s: &str) -> String {
s.replace('|', "\\|")
}
fn ident(s: &str) -> String {
let t: String = s
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
' '
}
})
.collect();
let t = t.split_whitespace().collect::<Vec<_>>().join(" ");
if t.is_empty() { "root".into() } else { t }
}
#[must_use]
pub fn tree(root: &Path) -> String {
let mut out = String::from(".\n");
fn walk_tree(root: &Path, rel: &Path, prefix: &str, out: &mut String) {
let Ok(text) = std::fs::read_to_string(root.join(rel).join("SPEC.md"))
else {
return;
};
let es = edges(&text);
for (i, e) in es.iter().enumerate() {
let last = i + 1 == es.len();
out.push_str(&format!(
"{prefix}{}{}\n",
if last { "`-- " } else { "|-- " },
e.dir
));
let deeper =
format!("{prefix}{}", if last { " " } else { "| " });
walk_tree(root, &rel.join(&e.dir), &deeper, out);
}
}
walk_tree(root, Path::new(""), "", &mut out);
out
}
#[must_use]
pub fn dot(root: &Path) -> String {
let mut out = String::from(
"digraph federation {\n rankdir=TB;\n node [shape=box];\n",
);
for node in discover(root) {
let rel = node.strip_prefix(root).unwrap_or(&node);
let Ok(text) = std::fs::read_to_string(node.join("SPEC.md")) else {
continue;
};
for e in edges(&text) {
out.push_str(&format!(
" \"{}\" -> \"{}\";\n",
disp(rel),
rel.join(&e.dir).display()
));
}
}
out.push_str("}\n");
out
}
fn label(p: &Path) -> String {
let s = p.to_string_lossy().replace(['/', '.', '-'], "_");
if s.is_empty() { "root".into() } else { s }
}
fn disp(p: &Path) -> String {
let s = p.to_string_lossy().to_string();
if s.is_empty() { ".".into() } else { s }
}
pub fn is_ignored_dir(name: &str) -> bool {
matches!(
name,
"target" | ".git" | "node_modules" | ".direnv"
| "result" | "pkl" | "vendor"
| ".claude" | ".github" | ".codex" | ".githooks"
) || name.starts_with("result-")
}
pub fn find_exhaustive_violations<'a>(
edges: &'a [Edge],
root: &Path,
) -> (Vec<&'a Edge>, Vec<PathBuf>) {
let mut counts = std::collections::HashMap::<&str, usize>::new();
for e in edges {
*counts.entry(e.dir.as_str()).or_insert(0) += 1;
}
let duplicates: Vec<&Edge> = edges
.iter()
.filter(|e| counts.get(e.dir.as_str()).copied().unwrap_or(0) > 1)
.collect();
let edge_dirs: std::collections::HashMap<&str, ()> =
edges.iter().map(|e| (e.dir.as_str(), ())).collect();
let ignored = git_ignored(root);
let mut missing = Vec::new();
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir()
&& let Some(name) = path.file_name().and_then(|s| s.to_str())
&& !edge_dirs.contains_key(name)
&& !is_ignored_dir(name)
&& !ignored.contains(&path)
{
missing.push(path);
}
}
}
(duplicates, missing)
}
#[must_use]
pub fn rust_files(dir: &Path) -> Vec<PathBuf> {
files_by_extension(dir, "rs", |name| name == "target")
}
#[must_use]
pub fn script_files(dir: &Path) -> Vec<PathBuf> {
files_by_extension(dir, "sh", is_ignored_dir)
}
fn files_by_extension(
dir: &Path,
ext: &str,
skip: fn(&str) -> bool,
) -> Vec<PathBuf> {
let ignored = git_ignored(dir);
let mut out = Vec::new();
collect(
dir,
&Walk {
ext,
skip,
ignored: &ignored,
},
&mut out,
);
out.sort();
out
}
struct Walk<'a> {
ext: &'a str,
skip: fn(&str) -> bool,
ignored: &'a HashSet<PathBuf>,
}
fn collect(dir: &Path, w: &Walk<'_>, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for e in entries.filter_map(Result::ok) {
let p = e.path();
let name = e.file_name().to_string_lossy().to_string();
if w.ignored.contains(&p) {
continue;
}
if p.is_dir() {
if !(w.skip)(&name) && !name.starts_with('.') {
collect(&p, w, out);
}
} else if p.extension().is_some_and(|x| x == w.ext) {
out.push(p);
}
}
}
#[must_use]
pub fn node_label(root: &Path, dir: &Path) -> String {
disp(dir.strip_prefix(root).unwrap_or(dir))
}
#[must_use]
pub fn spelled(root: &Path, rel: &Path) -> Vec<PathBuf> {
let want: Vec<_> = rel.components().collect();
if want.is_empty() {
return Vec::new();
}
discover(root)
.into_iter()
.filter(|node| {
let have: Vec<_> = node
.strip_prefix(root)
.unwrap_or(node)
.components()
.collect();
have.len() > want.len() && have.ends_with(&want)
})
.collect()
}
#[must_use]
pub fn owned_rust_files(node: &Path, nodes: &[PathBuf]) -> Vec<PathBuf> {
owned(rust_files(node), node, nodes)
}
#[must_use]
pub fn owned_script_files(node: &Path, nodes: &[PathBuf]) -> Vec<PathBuf> {
owned(script_files(node), node, nodes)
}
fn owned(files: Vec<PathBuf>, node: &Path, nodes: &[PathBuf]) -> Vec<PathBuf> {
files
.into_iter()
.filter(|f| {
!nodes
.iter()
.any(|n| n != node && n.starts_with(node) && f.starts_with(n))
})
.collect()
}
#[cfg(test)]
#[path = "tests/fed.rs"]
mod tests;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Nav {
pub rel: String,
pub path: String,
pub lens: String,
}
#[must_use]
fn nav_root() -> Vec<Nav> {
vec![
Nav {
rel: "up".into(),
path: "-".into(),
lens: "-".into(),
},
Nav {
rel: "self".into(),
path: ".".into(),
lens: "-".into(),
},
]
}
#[must_use]
pub fn nav(root: &Path, node: &Path) -> Vec<Nav> {
let rel = node.strip_prefix(root).unwrap_or(node);
if rel.as_os_str().is_empty() {
return nav_root();
}
let mut rows = Vec::new();
let mut cur = root.to_path_buf();
rows.push(Nav {
rel: "up".into(),
path: ".".into(),
lens: "-".into(),
});
for part in rel.components() {
let parent = cur.clone();
cur = cur.join(part);
let name = part.as_os_str().to_string_lossy().to_string();
let lens = lens_of(&parent, &name);
let path = cur
.strip_prefix(root)
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| name.clone());
if cur == node {
rows.push(Nav {
rel: "self".into(),
path,
lens,
});
rows.extend(siblings(&parent, root, &name));
} else {
rows.push(Nav {
rel: "up".into(),
path,
lens,
});
}
}
rows
}
fn lens_of(parent: &Path, child: &str) -> String {
let Ok(text) = std::fs::read_to_string(parent.join("SPEC.md")) else {
return "-".into();
};
edges(&text)
.into_iter()
.find(|e| e.dir == child)
.map_or_else(|| "-".into(), |e| e.owns)
}
fn siblings(parent: &Path, root: &Path, name: &str) -> Vec<Nav> {
let Ok(text) = std::fs::read_to_string(parent.join("SPEC.md")) else {
return Vec::new();
};
let base = parent.strip_prefix(root).unwrap_or(parent);
edges(&text)
.into_iter()
.filter(|e| e.dir != name)
.map(|e| Nav {
rel: "sib".into(),
path: base.join(&e.dir).to_string_lossy().to_string(),
lens: "-".into(),
})
.collect()
}
#[must_use]
pub fn nav_section(rows: &[Nav]) -> String {
let mut s = String::from("## \u{a7}N NAV\n\nrel|path|lens\n");
for r in rows {
s.push_str(&format!("{}|{}|{}\n", r.rel, r.path, escape_cell(&r.lens)));
}
s
}
fn escape_cell(cell: &str) -> String {
microlith::escape(cell)
}
#[cfg(test)]
#[path = "tests/nav.rs"]
mod nav_tests;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Home {
pub node: String,
pub owns: String,
pub not_owns: String,
}
#[must_use]
pub fn declared(root: &Path) -> Vec<Home> {
let mut out = vec![Home {
node: ".".to_string(),
owns: String::new(),
not_owns: String::new(),
}];
for node in discover(root) {
let Ok(text) = std::fs::read_to_string(node.join("SPEC.md")) else {
continue;
};
let rel = node.strip_prefix(root).unwrap_or(&node);
out.extend(edges(&text).into_iter().map(|e| Home {
node: join_rel(rel, &e.dir),
owns: e.owns,
not_owns: e.not_owns,
}));
}
out.sort_by(|a, b| a.node.cmp(&b.node));
out.dedup_by(|a, b| a.node == b.node);
out
}
fn join_rel(parent: &Path, child: &str) -> String {
let p = parent.to_string_lossy();
if p.is_empty() {
child.to_string()
} else {
format!("{p}/{child}")
}
}
#[cfg(test)]
#[path = "tests/declared.rs"]
mod declared_tests;
#[cfg(test)]
#[path = "tests/ignored.rs"]
mod ignored_tests;
#[cfg(test)]
#[path = "tests/case.rs"]
mod case_tests;