slave 0.4.0

Laravel-inspired CLI for Rust MCP servers: scaffold apps whose business operations are MCP tools over Streamable HTTP, with built-in auth, users, roles and Turso migrations
//! `slave new <name>`: scaffold a new domain-based application.

use std::fs;
use std::path::Path;

use anyhow::{Context, Result, bail};

use crate::cli::NewArgs;
use crate::{generator, naming, templates, timestamp};

pub fn run(args: &NewArgs) -> Result<()> {
    let name = args.name.as_str();
    naming::validate_project_name(name)?;
    let framework_dependency = framework_dependency(args.framework_path.as_deref())?;
    let gateway_dependency = gateway_dependency(args.framework_path.as_deref())?;

    let target = std::env::current_dir()
        .context("failed to read the current directory")?
        .join(name);
    if target.exists() {
        bail!("destination `{}` already exists", target.display());
    }

    fs::create_dir(&target)
        .with_context(|| format!("failed to create directory {}", target.display()))?;

    let dependencies = [framework_dependency, gateway_dependency];
    if let Err(err) = scaffold(&target, name, &dependencies) {
        // Only remove what we just created; the directory did not exist before.
        let _ = fs::remove_dir_all(&target);
        return Err(err);
    }

    println!("\nApplication `{name}` created successfully.\n");
    println!("Next steps:");
    println!("  cd {name}");
    println!("  slave migrate      # create the users, roles and auth_tokens tables");
    println!("  slave make:app dashboard --domain admin.localhost   # optional: add a web app");
    println!("  slave serve        # MCP backend + gateway: http://mcp.localhost:8000/mcp");
    println!("                     # call the auth_register tool; the first account is admin");
    Ok(())
}

fn scaffold(target: &Path, name: &str, [framework, gateway]: &[String; 2]) -> Result<()> {
    // One timestamp per initial migration, strictly increasing so they run in order.
    let [ts_users, ts_roles, ts_tokens]: [String; 3] =
        timestamp::utc_now_sequence(3)?
            .try_into()
            .map_err(|_| anyhow::anyhow!("failed to generate migration timestamps"))?;
    let vars = [
        ("name", name),
        ("slave_version", env!("CARGO_PKG_VERSION")),
        ("framework_dependency", framework.as_str()),
        ("gateway_dependency", gateway.as_str()),
        ("ts_users", ts_users.as_str()),
        ("ts_roles", ts_roles.as_str()),
        ("ts_tokens", ts_tokens.as_str()),
    ];
    for file in templates::PROJECT {
        let path = templates::render(file.path, &vars);
        let contents = templates::render(file.contents, &vars);
        generator::write_file(&target.join(&path), &contents, false)?;
        println!("  created {name}/{path}");
    }

    // Like Laravel, start with a working .env copied from the example.
    let env_example = templates::PROJECT
        .iter()
        .find(|file| file.path == ".env.example")
        .map(|file| templates::render(file.contents, &vars))
        .unwrap_or_default();
    generator::write_file(&target.join(".env"), &env_example, false)?;
    println!("  created {name}/.env");
    Ok(())
}

/// Returns the `slave-framework` line for the generated workspace dependencies.
///
/// Default features are off at the workspace level so web apps stay light;
/// the backend package turns `auth` and `database` back on.
fn framework_dependency(local_path: Option<&Path>) -> Result<String> {
    match local_path {
        None => Ok(format!(
            "slave-framework = {{ version = \"{}\", default-features = false }}",
            templates::FRAMEWORK_VERSION
        )),
        Some(path) => {
            let path = local_crate(path, "slave-framework")?;
            Ok(format!(
                "slave-framework = {{ path = \"{path}\", default-features = false }}"
            ))
        }
    }
}

/// Returns the `slave-gateway` line. With a local framework checkout, the
/// gateway is taken from the same workspace (`<framework>/../gateway`).
fn gateway_dependency(framework_path: Option<&Path>) -> Result<String> {
    let local = framework_path
        .and_then(|path| path.canonicalize().ok())
        .and_then(|path| path.parent().map(|parent| parent.join("gateway")))
        .filter(|path| path.join("Cargo.toml").is_file());
    match local {
        None => Ok(format!(
            "slave-gateway = \"{}\"",
            templates::GATEWAY_VERSION
        )),
        Some(path) => {
            let path = local_crate(&path, "slave-gateway")?;
            Ok(format!("slave-gateway = {{ path = \"{path}\" }}"))
        }
    }
}

/// Canonicalizes `path`, checks it holds crate `name`, and escapes it for TOML.
fn local_crate(path: &Path, name: &str) -> Result<String> {
    let path = path
        .canonicalize()
        .with_context(|| format!("path {} does not exist", path.display()))?;
    let manifest = fs::read_to_string(path.join("Cargo.toml")).unwrap_or_default();
    if !manifest.contains(&format!("name = \"{name}\"")) {
        bail!("{} does not contain the {name} crate", path.display());
    }
    Ok(path
        .to_string_lossy()
        .replace('\\', "\\\\")
        .replace('"', "\\\""))
}