use super::*;
pub(super) fn split_cmd(root: &Path, dir: &Path, apply: bool) -> ExitCode {
if apply {
eprintln!(
"sherd: --apply is not built. `split` proposes; moving rows between \
specs is a judgement a reader makes."
);
return ExitCode::from(2);
}
if !crate::fed::is_node(dir) {
eprintln!("sherd: {} carries no SPEC.md", dir.display());
return ExitCode::from(2);
}
let (cost, ceiling) = split_budget(root, dir);
println!(
"{}: chain {cost} tok of {ceiling}",
fed::node_label(root, dir)
);
let proposed = split::structure(dir);
if proposed.is_empty() {
println!(" no module declarations found -- nothing to propose");
return ExitCode::SUCCESS;
}
let spec = std::fs::read_to_string(dir.join("SPEC.md")).unwrap_or_default();
print_structure(&proposed, &spec, dir);
ExitCode::SUCCESS
}
pub(super) fn seam_cmd(root: &Path, dir: &Path) -> ExitCode {
println!("seam -- the public types a node declares\n");
let nodes = fed::discover(root);
let mut examined = 0usize;
let mut declared = 0usize;
for node in nodes.iter().filter(|n| n.starts_with(dir)) {
let types = node_types(node, &nodes);
examined = examined.saturating_add(1);
declared = declared.saturating_add(types.len());
print_seam(&fed::node_label(root, node), &types);
}
seam_summary(examined, declared);
if examined == 0 {
eprintln!("{}", no_node(root, dir));
return ExitCode::from(2);
}
ExitCode::SUCCESS
}
pub(super) fn seam_summary(examined: usize, declared: usize) {
println!("\n {examined} node(s) examined · {declared} public type(s)");
println!(
" A parallel build needs these names BEFORE any node is written. \
WHICH of them are shared is a judgement this does not make."
);
}
pub(super) fn print_seam(label: &str, types: &[code::PubType]) {
if types.is_empty() {
println!(" {label:<24} no public types");
return;
}
println!(" {label:<24} {} type(s)", types.len());
for t in types {
println!(" {} {}", t.kind, t.name);
}
}
pub(super) fn wave_cmd(root: &Path, dir: &Path) -> ExitCode {
println!("wave -- the schedule a parallel build would follow\n");
let s = wave::wave(root, dir);
for (i, round) in s.rounds.iter().enumerate() {
print_round(i.saturating_add(1), round);
}
print_blocked(&s.blocked);
print_unresolved(&wave::unresolved_calls(root, dir));
let examined = s
.rounds
.iter()
.map(Vec::len)
.sum::<usize>()
.saturating_add(s.blocked.len());
wave_summary(&s, examined);
if examined == 0 {
eprintln!("{}", no_node(root, dir));
return ExitCode::from(2);
}
ExitCode::SUCCESS
}
pub(super) fn wave_json_cmd(root: &Path, dir: &Path) -> ExitCode {
let (s, cycles) = wave::wave_with_cycles(root, dir);
let examined = s
.rounds
.iter()
.map(Vec::len)
.sum::<usize>()
.saturating_add(s.blocked.len());
if examined == 0 {
eprintln!("{}", no_node(root, dir));
return ExitCode::from(2);
}
let edges = wave::edges(root, dir);
let unresolved = wave::unresolved_calls(root, dir);
println!("{}", wave_json(&s, &cycles, &edges, &unresolved));
ExitCode::SUCCESS
}
pub(super) fn wave_json(
s: &wave::Schedule,
cycles: &[Vec<String>],
edges: &[wave::Edge],
unresolved: &[wave::Unresolved],
) -> String {
use crate::plan::json_str;
let list = |v: &[String]| {
format!(
"[{}]",
v.iter().map(|x| json_str(x)).collect::<Vec<_>>().join(",")
)
};
let nested = |v: &[Vec<String>]| {
format!(
"[{}]",
v.iter().map(|r| list(r)).collect::<Vec<_>>().join(",")
)
};
let edge = |e: &wave::Edge| {
format!(
"{{\"from\":{},\"to\":{},\"kind\":{},\"sibling\":{},\"inferred\":{}}}",
json_str(&e.from),
json_str(&e.to),
json_str(e.kind.as_str()),
e.sibling,
e.inferred
)
};
let call = |u: &wave::Unresolved| {
format!(
"{{\"node\":{},\"file\":{},\"call\":{}}}",
json_str(&u.node),
json_str(&u.script),
json_str(&u.call)
)
};
format!(
"{{\"rounds\":{},\"blocked\":{},\"cycles\":{},\"edges\":[{}],\"unresolved\":[{}],\"depth\":{},\"width\":{}}}",
nested(&s.rounds),
list(&s.blocked),
nested(cycles),
edges.iter().map(edge).collect::<Vec<_>>().join(","),
unresolved.iter().map(call).collect::<Vec<_>>().join(","),
s.depth(),
s.width()
)
}
pub(super) fn print_round(n: usize, nodes: &[String]) {
println!(" round {n:<3} {:>2} node(s)", nodes.len());
for node in nodes {
println!(" {node}");
}
}
pub(super) fn print_blocked(blocked: &[String]) {
if blocked.is_empty() {
return;
}
println!("\n BLOCKED -- a cycle in the code DAG, so no round reaches:");
for node in blocked {
println!(" {node}");
}
println!(
" these import each other, so they are ONE unit of work -- a \
wave cannot split them across workers."
);
}
pub(super) fn print_unresolved(calls: &[wave::Unresolved]) {
if calls.is_empty() {
return;
}
println!(
"\n UNRESOLVED -- {} script call(s) name no tracked script, so they are \
not edges. Check each:",
calls.len()
);
for c in calls {
println!(" {}: {}", c.script, c.call);
}
}
pub(super) fn wave_summary(s: &wave::Schedule, examined: usize) {
println!(
"\n {examined} node(s) examined · depth {} · width {}",
s.depth(),
s.width()
);
println!(
" DEPTH is the critical path -- rounds a wave cannot avoid. WIDTH \
is the most workers it can ever keep busy at once."
);
wave_edges(s);
wave_notes();
}
pub(super) fn wave_edges(s: &wave::Schedule) {
let seam = s.edges.saturating_sub(s.blocking);
println!(
" {} sibling edge(s) · {} blocking · {seam} type-only",
s.edges, s.blocking
);
if seam > 0 {
println!(
" the type-only ones name a sibling's public TYPES and \
nothing else, so a `sherd seam` commit satisfies them before \
any node is written -- they are not waits."
);
}
}
pub(super) fn wave_notes() {
println!(
" Edges are `use crate::` imports between sibling nodes: the CODE \
dag, NOT the §F federation dag (`src/wave:V1`)."
);
println!(
" Nothing was written: no worktree, no worker, no executor, no \
model. WHO writes the code is named and swappable (`.:V123`)."
);
}
pub(super) fn node_types(node: &Path, nodes: &[PathBuf]) -> Vec<code::PubType> {
let sources: Vec<String> = fed::owned_rust_files(node, nodes)
.iter()
.filter_map(|f| std::fs::read_to_string(f).ok())
.collect();
code::types_in(&sources)
}
pub(super) fn print_structure(
proposed: &[split::Proposed],
spec: &str,
dir: &Path,
) {
let scripts = fed::script_files(dir);
println!("\n node evidence rows tok members");
for r in split::rank_in(dir, proposed, spec) {
print_candidate(&r, &split::scripts_of(dir, r.node, &scripts), dir);
}
let named: usize = proposed.iter().map(|p| p.members.len()).sum();
let tally = |e: split::Evidence| {
proposed.iter().filter(|p| p.evidence == e).count()
};
println!(
"\n {} node(s) over {named} module(s): {} directory · {} pub mod · \
{} family · {} declared.",
proposed.len(),
tally(split::Evidence::Drawn),
tally(split::Evidence::Published),
tally(split::Evidence::Cohesion),
tally(split::Evidence::Declared),
);
println!(
" Evidence is how explicitly the author drew the boundary. A \
`declared` node is a module and nothing more -- real, and the \
weakest reason to promote one. Grouping those is a judgement this \
does not make."
);
let ambiguous = split::ambiguous_scripts(spec, &scripts);
if !ambiguous.is_empty() {
println!(
" {} cited script name(s) match more than one file and count for \
no node: {}",
ambiguous.len(),
ambiguous.join(" ")
);
}
if split::uniform_evidence(proposed) {
println!(
" Every module carries the SAME grade, so it ranks nothing here \
-- the order above is by spec rows, which is the only signal \
this tree offers."
);
}
}
pub(super) fn split_budget(root: &Path, dir: &Path) -> (u64, u64) {
let cost = lens::pack(root, dir, lens::Depth::Rule)
.map(|p| p.cost.tokens)
.unwrap_or_default();
let ceiling = lens::ceiling_for(root, dir).unwrap_or_default();
(cost, ceiling)
}
#[cfg(test)]
#[path = "tests/propose.rs"]
mod tests;
pub(super) fn print_candidate(
r: &split::Ranked<'_>,
scripts: &[std::path::PathBuf],
dir: &Path,
) {
let p = r.node;
let members = if p.members.len() > 1 {
format!("{} ({})", p.members.len(), p.members.join(" "))
} else {
String::new()
};
let note = if p.split_layout {
" MERGE the .rs into mod.rs first"
} else {
""
};
println!(
" {:<14} {:<10} {:>4} {:>4} {members}{note}",
p.name,
p.evidence.label(),
r.rows,
r.tokens,
);
if !p.shared.is_empty() {
println!(" {:<14} shares: {}", "", p.shared.join(", "));
}
if !scripts.is_empty() {
println!(
" {:<14} {} script(s){}",
"",
scripts.len(),
script_dirs(scripts, &dir.join(&p.name))
);
}
}
pub(super) fn script_dirs(
scripts: &[std::path::PathBuf],
node: &Path,
) -> String {
let mut counts: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
for s in scripts {
let rel = s.strip_prefix(node).unwrap_or(s);
if let Some(parent) = rel.parent().filter(|p| !p.as_os_str().is_empty())
{
let n = counts.entry(parent.display().to_string()).or_insert(0);
*n = n.saturating_add(1);
}
}
let mut busiest: Vec<(String, usize)> = counts.into_iter().collect();
busiest.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
let shown: Vec<String> = busiest
.iter()
.take(5)
.map(|(d, n)| format!("{d} {n}"))
.collect();
if shown.is_empty() {
String::new()
} else {
format!(" · in {}", shown.join(", "))
}
}