use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use zoning::Result;
use zoning::ordinance::{self, Ordinance};
use zoning::report;
use zoning::spinner::Spinner;
use zoning::survey::{Ask, Survey};
use super::Tracked;
use super::args::Options;
pub(super) fn explain(
options: &Options,
root: &Path,
tracked: &mut Tracked<'_>,
spinner: &Spinner,
) -> Result<ExitCode> {
let here =
std::env::current_dir().map_err(|e| format!("cannot read the current directory: {e}"))?;
let wanted: Vec<PathBuf> = options
.args
.iter()
.map(|arg| {
here.join(arg).canonicalize().map_err(|_| format!("no such file: `{arg}`").into())
})
.collect::<Result<_>>()?;
let mut best: Option<Ordinance> = None;
for path in ordinance::discover(root, &options.under) {
let contract = Ordinance::read(&path, options.language)?;
let holds = wanted.iter().all(|w| w.starts_with(&contract.module_root));
let deeper =
best.as_ref().is_none_or(|prior| contract.module_root.starts_with(&prior.module_root));
if holds && deeper {
best = Some(contract);
}
}
let Some(contract) = best else {
return Err(format!(
"no governed package holds {} — `zone list` shows what is governed, and \
`zone draft <dir>` starts a contract for what is not",
options.args.iter().map(|a| format!("`{a}`")).collect::<Vec<_>>().join(" and ")
)
.into());
};
let found = Survey::of(&Ask {
repo_root: root,
module_root: &contract.module_root,
exclude: &contract.exclude,
dialect: contract.dialect,
package: &contract.package,
tracked: tracked.of(contract.dialect),
});
let named: Vec<String> = wanted
.iter()
.map(|path| judged(path, &contract, &found, tracked))
.collect::<Result<_>>()?;
let answer = match (named.as_slice(), options.json) {
([one], false) => report::file(one, &contract, &found, &options.ink),
([one], true) => report::machine::node(one, &contract, &found),
([from, to], false) => report::edge(from, to, &contract, &found, &options.ink),
([from, to], true) => report::machine::edge(from, to, &contract, &found),
_ => return Err("`explain` takes one file, or two".into()),
};
spinner.stop();
print!("{}", answer.text);
let _ = std::io::stdout().flush();
Ok(if answer.clean { ExitCode::SUCCESS } else { ExitCode::FAILURE })
}
fn judged(
path: &Path,
contract: &Ordinance,
found: &Survey,
tracked: &mut Tracked<'_>,
) -> Result<String> {
let rel = path
.strip_prefix(&contract.module_root)
.map_err(|_| format!("{} is outside {}", path.display(), contract.module_root.display()))?
.to_string_lossy()
.replace('\\', "/");
if found.files.contains(&rel) {
return Ok(rel);
}
let dialect = contract.dialect;
let why = if !dialect.extensions().iter().any(|e| rel.ends_with(&format!(".{e}"))) {
format!("{} reads {}", dialect.name(), dialect.extensions().join(", "))
} else if let Some(pattern) = contract.exclude.iter().find(|p| p.matches(&rel)) {
format!("the contract excludes `{pattern}`")
} else if tracked.of(dialect).is_some_and(|known| !known.contains(path)) {
"version control does not know it yet — commit it, or pass `--untracked`".to_owned()
} else {
"it is not in the judged set".to_owned()
};
Err(format!("{} holds `{rel}` but does not judge it: {why}", contract.package).into())
}