use super::*;
pub(super) fn child_dirs(dir: &Path) -> Result<Vec<String>, String> {
let entries = std::fs::read_dir(dir)
.map_err(|e| format!("sherd: {}: {e}", dir.display()))?;
let mut children: Vec<String> = entries
.filter_map(Result::ok)
.filter(|e| e.path().is_dir())
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| !n.starts_with('.') && n != "target")
.collect();
children.sort();
Ok(children)
}
pub(super) fn sync_cmd(
root: &Path,
dir: Option<&PathBuf>,
check: bool,
) -> ExitCode {
let targets = dir.map_or_else(
|| fed::discover(root),
|d| {
let found = fed::discover(d);
if found.is_empty() {
vec![d.clone()]
} else {
found
}
},
);
let Ok(wrote) = sync_all(root, &targets, check) else {
return ExitCode::from(2);
};
println!(
"\n {} nodes examined · {wrote} {}",
targets.len(),
if check { "stale" } else { "rewritten" }
);
if wrote == 0 {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
pub(super) fn sync_all(
root: &Path,
targets: &[PathBuf],
check: bool,
) -> Result<usize, ()> {
let mut wrote = 0usize;
for node in targets {
match sync_node(root, node, check) {
Ok(true) => {
sync_report(node, check);
wrote = wrote.saturating_add(1);
}
Ok(false) => {}
Err(e) => {
eprintln!("sherd: {e}");
return Err(());
}
}
}
Ok(wrote)
}
pub(super) fn sync_report(node: &Path, check: bool) {
let verb = if check { "STALE" } else { "rewritten" };
println!("{}: §N {verb}", node.display());
}
pub(super) fn nav_anchor(text: &str) -> &'static str {
if text.contains("## \u{a7}F") {
"F FEDERATION"
} else {
"G GOAL"
}
}
pub(super) fn sync_node(
root: &Path,
node: &Path,
check: bool,
) -> Result<bool, String> {
let path = node.join("SPEC.md");
let text = std::fs::read_to_string(&path)
.map_err(|e| format!("{}: {e}", path.display()))?;
let body = fed::nav_section(&fed::nav(root, node));
let next = spec::upsert_section(&text, "N NAV", &body, nav_anchor(&text));
if next == text {
return Ok(false);
}
if check {
return Ok(true);
}
std::fs::write(&path, next)
.map_err(|e| format!("{}: {e}", path.display()))?;
Ok(true)
}
pub(super) fn init_refusal(target: &Path) -> Option<ExitCode> {
target.exists().then(|| {
eprintln!(
"sherd: {} exists -- refusing to overwrite a spec. There is no --force: \
delete it yourself if that is what you mean.",
target.display()
);
ExitCode::from(1)
})
}
pub(super) fn init_cmd(
root: &Path,
dir: Option<&str>,
stdout: bool,
) -> ExitCode {
let dir = arg_dir(dir, root);
if !dir.is_dir() {
eprintln!("sherd: {} is not a directory", dir.display());
return ExitCode::from(2);
}
let target = dir.join("SPEC.md");
if let Some(refusal) = (!stdout).then(|| init_refusal(&target)).flatten() {
return refusal;
}
match init_body(root, &dir) {
Err(e) => init_failed(&e),
Ok((body, n)) => init_emit(&target, &body, n, stdout),
}
}
pub(super) fn init_failed(msg: &str) -> ExitCode {
eprintln!("{msg}");
ExitCode::from(1)
}
pub(super) fn init_emit(
target: &Path,
body: &str,
children: usize,
stdout: bool,
) -> ExitCode {
if stdout {
print!("{body}");
return ExitCode::SUCCESS;
}
init_write(target, body, children)
}
pub(super) fn init_body(
root: &Path,
dir: &Path,
) -> Result<(String, usize), String> {
let children = child_dirs(dir)?;
let name = dir
.strip_prefix(root)
.ok()
.and_then(|p| p.to_str())
.filter(|s| !s.is_empty())
.unwrap_or(".");
Ok((crate::spec::scaffold(name, &children), children.len()))
}
pub(super) fn init_write(
target: &Path,
body: &str,
children: usize,
) -> ExitCode {
match std::fs::write(target, body) {
Ok(()) => {
println!(
"{}: scaffolded, {children} child row(s). Fill the prompts, then `sherd check`.",
target.display()
);
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("sherd: {}: {e}", target.display());
ExitCode::from(1)
}
}
}
pub(super) fn slice_cmd(root: &Path, mode: &str) -> ExitCode {
let registry = root.join(".sherd-slices");
if !registry.is_file() {
println!("slice: no registry (none required)");
return ExitCode::SUCCESS;
}
let decls = match std::fs::read_to_string(®istry)
.map_err(|e| format!("{}: {e}", registry.display()))
.and_then(|t| slice::parse_decls(&t))
{
Ok(d) => d,
Err(e) => {
eprintln!("sherd: {e}");
return ExitCode::from(2);
}
};
let mut drift = 0;
for d in &decls {
let rendered = match slice::render(root, d) {
Ok(r) => r,
Err(e) => {
eprintln!("sherd: {e}");
return ExitCode::from(1);
}
};
let out = root.join(&d.output);
let current = std::fs::read_to_string(&out).unwrap_or_default();
let full: u64 = slice::sources(root, &d.source)
.iter()
.filter_map(|f| std::fs::read_to_string(f).ok())
.map(|s| tokens::count(&s).tokens)
.sum();
let sliced = tokens::count(&rendered).tokens;
match mode {
"--list" => println!(
" {:<28} {:>7} -> {:>5} tok ({:.0}%) {:?}",
d.output.display(),
full,
sliced,
100.0 * sliced as f64 / full.max(1) as f64,
d.rule
),
"--check" => {
if current != rendered {
println!(
"{}: DRIFT -- differs from what its source produces",
d.output.display()
);
drift += 1;
}
}
_ => {
if let Err(e) = std::fs::write(&out, &rendered) {
eprintln!("sherd: {}: {e}", out.display());
return ExitCode::from(2);
}
println!(
" {:<28} {:>7} -> {:>5} tok",
d.output.display(),
full,
sliced
);
}
}
}
if mode == "--check" {
println!("\n {} slice(s) checked · {drift} drifted", decls.len());
if drift > 0 {
println!(" regenerate with `sherd slice`, or fix the source");
return ExitCode::from(1);
}
}
ExitCode::SUCCESS
}
#[cfg(test)]
#[path = "tests/author.rs"]
mod tests;