capy-cli 0.9.0

The command-line interface for the Capy web framework.
Documentation
use crate::Generator;
use anyhow::{bail, Context, Result};
use heck::{ToSnakeCase, ToUpperCamelCase};
use std::collections::BTreeMap;
use syn::{Item, UseTree};

const KEYWORDS: &[&str] = &[
    "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
    "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
    "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
    "unsafe", "use", "where", "while", "abstract", "become", "box", "do", "final", "gen", "macro",
    "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
];

fn windows_reserved(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "con"
            | "prn"
            | "aux"
            | "nul"
            | "com1"
            | "com2"
            | "com3"
            | "com4"
            | "com5"
            | "com6"
            | "com7"
            | "com8"
            | "com9"
            | "lpt1"
            | "lpt2"
            | "lpt3"
            | "lpt4"
            | "lpt5"
            | "lpt6"
            | "lpt7"
            | "lpt8"
            | "lpt9"
    )
}

pub(crate) fn validate_name(name: &str, hyphens: bool) -> Result<()> {
    if name.is_empty()
        || !name.as_bytes()[0].is_ascii_alphabetic()
        || !name
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'_' || (hyphens && c == b'-'))
        || KEYWORDS.contains(&name)
        || windows_reserved(name)
    {
        bail!("Invalid name `{name}`. Use a letter followed by letters, numbers, or underscores{}; Rust keywords and device names are reserved.", if hyphens { " or hyphens" } else { "" });
    }
    Ok(())
}

pub(crate) fn project_name(name: &str) -> Result<()> {
    validate_name(name, true)?;
    let normalized = name.replace('-', "_");
    validate_name(&normalized, false)?;
    if ["deps", "examples", "build", "incremental"].contains(&name) {
        bail!("`{name}` cannot be used as a Capy application name because it is reserved by Cargo");
    }
    if ["capy", "std", "core", "alloc", "test"].contains(&name) {
        bail!("`{name}` conflicts with an application dependency or Rust runtime crate; choose another project name");
    }
    if name.bytes().any(|c| c.is_ascii_uppercase()) {
        bail!("Use a lowercase project name, such as `blog` or `blog-api`.");
    }
    Ok(())
}

pub(crate) struct GeneratedNames {
    pub input: String,
    pub module: String,
    pub ty: String,
    pub model_alias: String,
}

impl GeneratedNames {
    pub fn new(input: &str) -> Result<Self> {
        validate_name(input, false)?;
        let module = input.to_snake_case();
        let ty = input.to_upper_camel_case();
        validate_name(&module, false)?;
        validate_name(&ty, false)?;
        Ok(Self {
            input: input.into(),
            module,
            model_alias: format!("{ty}Model"),
            ty,
        })
    }

    pub fn check_registry(&self, registry: &str, module: &str, kind: Generator) -> Result<()> {
        let symbols = registry_symbols(registry, matches!(kind, Generator::Migration))?;
        for symbol in std::iter::once(module).chain(
            matches!(kind, Generator::Model)
                .then_some([self.ty.as_str(), self.model_alias.as_str()])
                .into_iter()
                .flatten(),
        ) {
            if let Some(origin) = symbols.get(symbol) {
                bail!("`{}` would generate the name `{symbol}`, which already exists in the registry from `{origin}`", self.input);
            }
        }
        Ok(())
    }
}

// Parse Rust rather than matching lines: grouped, renamed and private imports
// occupy the same namespace. Glob/macro-generated bindings cannot be proved safe.
fn registry_symbols(registry: &str, migration: bool) -> Result<BTreeMap<String, String>> {
    fn imports(
        tree: &UseTree,
        prefix: &str,
        out: &mut BTreeMap<String, String>,
        migration: bool,
    ) -> Result<()> {
        match tree {
            UseTree::Path(p) => imports(&p.tree, &format!("{prefix}{}::", p.ident), out, migration)?,
            UseTree::Name(n) => {
                let name = if n.ident == "self" {
                    prefix.trim_end_matches("::").rsplit("::").next().unwrap_or("self").to_owned()
                } else { n.ident.to_string() };
                out.insert(name, format!("{prefix}{}", n.ident));
            }
            UseTree::Rename(n) => { out.insert(n.rename.to_string(), format!("{prefix}{}", n.ident)); }
            UseTree::Group(g) => for item in &g.items { imports(item, prefix, out, migration)?; },
            // The standard migration prelude cannot contain our timestamped module
            // names; migration generators add no other top-level bindings.
            UseTree::Glob(_) if migration && prefix == "capy::migration::prelude::" => {},
            UseTree::Glob(_) => bail!("Cannot check generated names against a glob import in the registry. Use explicit imports before generating."),
        }
        Ok(())
    }
    let mut out = BTreeMap::new();
    for item in syn::parse_file(registry)
        .context("Cannot parse module registry; fix its Rust syntax before generating")?
        .items
    {
        let ident = match item {
            Item::Mod(i) => Some(i.ident),
            Item::Struct(i) => Some(i.ident),
            Item::Enum(i) => Some(i.ident),
            Item::Type(i) => Some(i.ident),
            Item::Trait(i) => Some(i.ident),
            Item::Union(i) => Some(i.ident),
            Item::Fn(i) => Some(i.sig.ident),
            Item::Const(i) => Some(i.ident),
            Item::Static(i) => Some(i.ident),
            Item::ExternCrate(i) => Some(i.rename.map(|(_, ident)| ident).unwrap_or(i.ident)),
            Item::Use(i) => { imports(&i.tree, "", &mut out, migration)?; None }
            Item::Macro(_) => bail!("Cannot check generated names against a macro in the registry. Move it into a separate module before generating."),
            _ => None,
        };
        if let Some(ident) = ident {
            out.insert(ident.to_string(), ident.to_string());
        }
    }
    Ok(out
        .into_iter()
        .map(|(name, origin)| (name.strip_prefix("r#").unwrap_or(&name).to_owned(), origin))
        .collect())
}