use crate::{fed, tokens};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Depth {
Rule,
Why,
All,
}
#[derive(Debug)]
pub struct Pack {
pub chain: Vec<PathBuf>,
pub text: String,
pub children: Vec<fed::Edge>,
pub cost: tokens::Count,
}
pub fn pack(root: &Path, dir: &Path, depth: Depth) -> std::io::Result<Pack> {
if !fed::is_node(dir) {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{}: no SPEC.md -- not a node", dir.display()),
));
}
let chain = fed::chain(root, dir);
let mut text = String::new();
for (i, spec) in chain.iter().enumerate() {
let raw = std::fs::read_to_string(spec)?;
let mut part = render(raw, depth);
if depth != Depth::All && i + 1 < chain.len() {
part = crate::spec::without_tasks(&part);
}
text.push_str(&part);
text.push('\n');
}
if depth == Depth::Why {
let why = dir.join("SPEC.why.md");
if why.is_file() {
text.push_str(&std::fs::read_to_string(why)?);
}
}
let own = chain.last().map_or(String::new(), |p| {
std::fs::read_to_string(p).unwrap_or_default()
});
Ok(Pack {
chain,
children: fed::edges(&own),
cost: tokens::count(&text),
text,
})
}
fn render(raw: String, depth: Depth) -> String {
match depth {
Depth::All => raw,
Depth::Rule | Depth::Why => crate::spec::rule_depth(&raw),
}
}
pub fn own_cost(dir: &Path, depth: Depth) -> std::io::Result<tokens::Count> {
let raw = std::fs::read_to_string(dir.join("SPEC.md"))?;
Ok(tokens::count(&render(raw, depth)))
}
pub fn ceiling_for(root: &Path, node: &Path) -> Result<u64, String> {
let rel = node.strip_prefix(root).unwrap_or(node);
let key = if rel.as_os_str().is_empty() {
"SPEC.md".into()
} else {
rel.to_string_lossy().to_string()
};
Ok(tokens::Ceilings::load(root)?.for_path(&key))
}
#[derive(Debug, PartialEq, Eq)]
pub enum Verdict {
Fits { slack: u64 },
Over { by: u64 },
}
#[must_use]
pub fn verdict(cost: u64, budget: u64) -> Verdict {
if cost <= budget {
Verdict::Fits {
slack: budget - cost,
}
} else {
Verdict::Over { by: cost - budget }
}
}
#[cfg(test)]
#[path = "tests/lens.rs"]
mod tests;