use super::*;
pub(super) const WINDOW: u64 = 131_072;
pub(super) fn record_debt(root: &Path, now: crate::debt::Measured) -> ExitCode {
match crate::debt::record(root, now) {
Ok(msg) => {
println!("{msg}");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("sherd: {e}");
ExitCode::from(1)
}
}
}
pub(super) fn coverage_cmd(
root: &Path,
mode: Option<&str>,
cargo: &str,
) -> ExitCode {
use crate::debt::Build;
let mut code = 0u8;
for build in Build::BOTH {
let row = build.row();
let Some(was) = crate::debt::recorded_floor_of(root, build) else {
if build == Build::All {
let path = root.join(".coverage");
eprintln!("sherd: {}: no `lines` row to read", path.display());
return ExitCode::from(2);
}
println!(" {row}: no floor recorded (none required)");
continue;
};
let Some(now) = crate::debt::coverage_of(root, cargo, build) else {
eprintln!(
"sherd: could not read a coverage total for `{row}` -- that \
is an ERROR, not a floor breach (sherd/tdd:V26)"
);
return ExitCode::from(2);
};
let one = if mode == Some("--record") {
record_coverage(root, build, now)
} else {
check_coverage(row, now, was)
};
code = code.max(one);
}
ExitCode::from(code)
}
pub(super) fn record_coverage(
root: &Path,
build: crate::debt::Build,
now: usize,
) -> u8 {
match crate::debt::record_coverage_of(root, build, now) {
Ok(msg) => {
println!("{msg}");
0
}
Err(e) => {
eprintln!("sherd: {e}");
1
}
}
}
pub(super) fn check_coverage(row: &str, now: usize, was: usize) -> u8 {
let (ok, report) = crate::debt::coverage_verdict(now, was);
if ok {
println!(" {row}: {}", report.trim_start());
return 0;
}
eprintln!("{row}: {report}");
1
}
pub(super) fn debt_cmd(
root: &Path,
mode: Option<&str>,
cargo: &str,
) -> ExitCode {
let Some(now) = crate::debt::measure(root, cargo) else {
eprintln!(
"sherd: clippy did not COMPILE, so its count is not a \
measurement -- a target that fails to build emits no warnings \
at all (sherd/debt:V3)."
);
return ExitCode::from(2);
};
let Some(was) = crate::debt::recorded_ceilings(root) else {
let registry = root.join(".lint-debt");
if registry.is_file() {
eprintln!(
"sherd: {}: no `density` and `shape` rows to read",
registry.display()
);
} else {
eprintln!(
"sherd: {}: no ratchet here. `sherd debt` needs a `.lint-debt` \
carrying `density` and `shape`.",
registry.display()
);
}
return ExitCode::from(2);
};
if mode == Some("--record") {
return record_debt(root, now);
}
let (ok, report) = crate::debt::verdict(now, was);
if ok {
println!("{report}");
} else {
eprintln!("{report}");
}
if ok {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
pub(super) struct BudgetRow {
pub node: PathBuf,
pub chain_tokens: u64,
pub own_tokens: u64,
pub chain_nodes: usize,
pub ceiling: u64,
pub over_by: Option<u64>,
}
#[derive(Default)]
pub(super) struct Budget {
pub rows: Vec<BudgetRow>,
pub total: u64,
pub over: usize,
pub method: Option<&'static str>,
pub unmeasured: Vec<(PathBuf, String)>,
pub stderr: Option<String>,
pub cold: bool,
}
impl Budget {
pub(super) fn code(&self) -> u8 {
if self.stderr.is_some() {
1
} else if self.rows.is_empty() {
2
} else if self.over > 0 && !self.cold {
1
} else {
0
}
}
}
pub(super) fn measure_budget(root: &Path, dir: &Path) -> Budget {
let mut b = Budget {
cold: tokens::Ceilings::load(root).is_ok_and(|c| c.is_cold()),
..Budget::default()
};
for node in fed::discover(root) {
if !node.starts_with(dir) {
continue;
}
let packed = lens::pack(root, &node, lens::Depth::Rule)
.and_then(|p| Ok((lens::own_cost(&node, lens::Depth::Rule)?, p)));
let (own, p) = match packed {
Ok(both) => both,
Err(e) => {
b.stderr = Some(format!("sherd: {}: {e}", node.display()));
b.unmeasured.push((node, e.to_string()));
return b;
}
};
let ceiling = match lens::ceiling_for(root, &node) {
Ok(c) => c,
Err(e) => {
b.stderr = Some(format!("sherd: {e}"));
b.unmeasured.push((node, e));
return b;
}
};
b.total += p.cost.tokens;
b.method = Some(p.cost.method);
let over_by = match lens::verdict(p.cost.tokens, ceiling) {
lens::Verdict::Fits { .. } => None,
lens::Verdict::Over { by } => {
b.over += 1;
Some(by)
}
};
b.rows.push(BudgetRow {
node,
chain_tokens: p.cost.tokens,
own_tokens: own.tokens,
chain_nodes: p.chain.len(),
ceiling,
over_by,
});
}
b
}
pub(super) fn budget_text(root: &Path, b: &Budget) -> String {
let mut out = format!(
"window {WINDOW} · entry {} · working {}\n\n",
tokens::ENTRY_COST,
tokens::working(WINDOW)
);
for r in &b.rows {
let rel = r.node.strip_prefix(root).unwrap_or(&r.node);
let name = if rel.as_os_str().is_empty() {
Path::new(".")
} else {
rel
};
let mark = r
.over_by
.map_or(String::new(), |by| format!(" OVER by {by}"));
out.push_str(&format!(
" {:<24} chain {:>6} tok ({} nodes) ceiling {:>6}{mark}\n",
name.display(),
r.chain_tokens,
r.chain_nodes,
r.ceiling
));
}
if b.stderr.is_some() {
return out;
}
out.push_str(&format!(
"\n {} nodes examined · {} tok if all chains loaded · {} over ceiling\n",
b.rows.len(),
b.total,
b.over
));
if b.cold && !b.rows.is_empty() {
out.push_str(&format!(
" no .context-limits: ceilings are the {} tok default, and \
over is advisory until you set them\n",
tokens::DEFAULT_NODE
));
}
out
}
#[cfg(test)]
pub(super) fn budget(root: &Path, dir: PathBuf) -> ExitCode {
budget_as(root, &dir, false)
}
pub(super) fn budget_as(root: &Path, dir: &Path, json: bool) -> ExitCode {
let b = measure_budget(root, dir);
if json {
println!("{}", budget_json(root, &b));
} else {
print!("{}", budget_text(root, &b));
}
if let Some(e) = &b.stderr {
eprintln!("{e}");
} else if b.rows.is_empty() {
eprintln!("{}", no_node(root, dir));
}
ExitCode::from(b.code())
}
pub(super) fn lens_cmd(
root: &Path,
dir: &Path,
depth: lens::Depth,
) -> ExitCode {
match lens::pack(root, dir, depth) {
Ok(p) => {
eprintln!("# chain: {} nodes · {}", p.chain.len(), p.cost);
for c in &p.children {
eprintln!(
"# -> {:<16} {} [not: {}]",
c.dir, c.owns, c.not_owns
);
}
print!("{}", p.text);
ExitCode::SUCCESS
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
eprintln!("{}", no_node(root, dir));
ExitCode::from(2)
}
Err(e) => {
eprintln!("sherd: {}: {e}", dir.display());
ExitCode::from(2)
}
}
}
pub(super) fn fed_cmd(dir: &Path) -> ExitCode {
let path = dir.join("SPEC.md");
let Ok(text) = std::fs::read_to_string(&path) else {
eprintln!("sherd: no SPEC.md at {}", dir.display());
return ExitCode::from(2);
};
let edges = fed::edges(&text);
for e in &edges {
println!("{:<16} {:<40} not: {}", e.dir, e.owns, e.not_owns);
}
if edges.is_empty() {
println!(
"{}: no §F table -- this node federates nothing. \
`sherd split` proposes where the boundaries are.",
dir.display()
);
}
ExitCode::SUCCESS
}
pub(super) fn route_cmd(root: &Path, query: &str) -> ExitCode {
match plan::route(root, query) {
plan::Route::Hit(node, why) => {
println!(
"{}\n matched: {}",
node.strip_prefix(root).unwrap_or(&node).display(),
why.join(", ")
);
ExitCode::SUCCESS
}
plan::Route::Miss => route_miss(root),
plan::Route::Ambiguous(nodes) => route_ambiguous(root, &nodes),
}
}
pub(super) fn route_miss(root: &Path) -> ExitCode {
if fed::discover(root).len() <= 1 {
println!(
"this repository has one node, so there is nothing to route to. \
`sherd init <dir>` starts a federation."
);
} else {
println!(
"no node matched. `sherd graph --table` lists what each one owns."
);
}
ExitCode::from(2)
}
pub(super) fn route_ambiguous(root: &Path, nodes: &[PathBuf]) -> ExitCode {
println!("ambiguous -- the query spans {} nodes:", nodes.len());
for n in nodes {
println!(" {}", n.strip_prefix(root).unwrap_or(n).display());
}
ExitCode::from(3)
}
#[cfg(test)]
#[path = "tests/measure.rs"]
mod tests;