zoning 1.4.0

An import-topology gate: declare the zones a package's imports may cross, and judge the real import graph against them.
Documentation
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};

/// A contract describing what a directory's graph already does.
///
/// The directory is taken as typed, from the shell's own working directory — `draft .`
/// means here, whatever subtree a verify would have chosen to read.
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}"))?;
    // The manifest on disk outranks the default, in that order: a directory that declares
    // itself has already said what language it is, and `--language` is for the ones that
    // have not. Without this, `draft` on a Python package under the default dialect finds
    // no `build.zig`, decides the package is not a package, and refuses the exact command
    // `list` just printed.
    let language = spoken(&dir).unwrap_or(options.language);
    let declares = |at: &Path| language.manifests().iter().any(|m| at.join(m).exists());
    // `draft src` is the natural mistake, because `src` is where the code is. It is also
    // the one mistake that succeeds quietly: a package named after the source directory,
    // its contract filed one level too deep, and every later `--package` invocation
    // spelled wrong. The package is the directory somebody declared, so say so.
    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);
    // The target itself is a parcel of this sweep whenever it holds a manifest, and it is
    // not one of the packages it "holds" — naming it would render as an empty path and read
    // as a message with a word missing.
    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);
    }
    // At the package root, beside the manifest it belongs to. A tool that made a
    // directory before it had anything to put in it was asking for a filing cabinet to
    // hold one page; the older `contract/` spelling is still read, just no longer minted.
    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)
}