use std::io::Write as _;
use std::path::Path;
use std::process::ExitCode;
use zoning::Result;
use zoning::ordinance;
use zoning::report::Ink;
use zoning::spinner::Spinner;
use super::Tracked;
use super::args::Options;
use super::scope::{barren, declared, module, pathdiff, probe, spoken, tail};
pub(super) fn draft(
options: &Options,
tracked: &mut Tracked<'_>,
spinner: &Spinner,
) -> Result<ExitCode> {
let here =
std::env::current_dir().map_err(|e| format!("cannot read the current directory: {e}"))?;
let target = options.args.first().map_or(".", String::as_str);
let dir = here.join(target).canonicalize().map_err(|e| format!("`{target}`: {e}"))?;
let language = spoken(&dir).unwrap_or(options.language);
let declares = |at: &Path| language.manifests().iter().any(|m| at.join(m).exists());
if let Some(parent) = dir.parent().filter(|p| !declares(&dir) && declares(p)) {
let up = pathdiff(&here, parent);
return Err(format!(
"`{target}` is where the code lives, not where the package is declared — `{}` is, \
and `root {target}` inside its contract is how that gets said. Draft the package: \
`zone draft {up}`",
tail(parent)
)
.into());
}
let name = declared(&dir, language)
.or_else(|| dir.file_name().map(|n| n.to_string_lossy().into_owned()))
.ok_or_else(|| format!("`{target}` has no directory name to take the package name from"))?;
let (source, nested) = module(&dir);
let held: Vec<_> = ordinance::parcels(&dir, &[])
.into_iter()
.filter(|p| !p.dir.is_empty() && p.dir != ".")
.collect();
if !declares(&dir) && !held.is_empty() {
let names: Vec<&str> = held.iter().map(|p| p.dir.as_str()).collect();
return Err(format!(
"{name} is not a package — it holds {}: {}. Draft each of them: a contract \
governs one module's imports, and these do not share a module",
names.len(),
names.join(", ")
)
.into());
}
let found = probe(&dir, source, language, tracked, &nested, &name);
if found.files.is_empty() {
return Err(barren(&dir, source, language, &nested).into());
}
let text = zoning::draft::contract(&found, &name, source, &nested);
if !options.write {
spinner.stop();
print!("{text}");
let _ = std::io::stdout().flush();
return Ok(ExitCode::SUCCESS);
}
if let Some(existing) = ordinance::governing(&dir) {
return Err(format!(
"{} already governs {name} — a draft never overwrites a contract somebody \
wrote; drop `--write` to read the draft instead",
tail(&existing)
)
.into());
}
let file = dir.join(format!("{name}.zone"));
std::fs::write(&file, &text).map_err(|e| format!("{}: {e}", file.display()))?;
spinner.stop();
let Ink { green, reset, dim, .. } = options.ink;
println!(
"{green}✓{reset} wrote {} {dim}— now run `zone verify --package {name}`{reset}",
file.display()
);
Ok(ExitCode::SUCCESS)
}