capy-cli 0.7.1

The command-line interface for the Capy web framework.
Documentation
use crate::FrontendDriver;
use anyhow::{bail, Context, Result};
use std::{
    fs,
    path::{Path, PathBuf},
};

const FILES: &[(&str, &str)] = &[
    (".capy-generator.lock", ""),
    (".gitattributes", "# Keep generated contracts byte-identical across Git checkouts.\n**/generated/** text eol=lf\n"),
    ("Cargo.toml", include_str!("../templates/Cargo.toml.txt")),
    ("src/main.rs", include_str!("../templates/main.rs.txt")),
    ("src/lib.rs", include_str!("../templates/lib.rs.txt")),
    ("app/mod.rs", "//! Application code.\npub mod controllers;\npub mod models;\npub mod requests;\n"),
    ("app/controllers/mod.rs", "//! API controllers.\n"),
    ("app/models/mod.rs", "//! SeaORM entities and convenient model aliases.\n"),
    ("app/requests/mod.rs", "//! Validated JSON requests.\n"),
    ("routes/mod.rs", "//! Application routes.\npub mod api;\n"),
    ("routes/api.rs", include_str!("../templates/routes.rs.txt")),
    ("database/mod.rs", "//! Database migrations.\npub mod migrations;\n"),
    ("database/migrations/mod.rs", include_str!("../templates/migrator.rs.txt")),
    ("config/app.toml", "name = \"{{name}}\"\nenvironment = \"development\"\nhost = \"127.0.0.1\"\nport = 8000\n"),
    ("config/server.toml", "# Optional host/port override legacy APP_HOST/APP_PORT.\n# host = \"0.0.0.0\"\n# port = 8000\nshutdown_timeout_seconds = 10\n"),
    ("config/api.toml", "# API contracts are opt-in on routes. Docs are development-only.\nopenapi = false\ndocs = false\n# title = \"My API\"\nversion = \"1.0.0\"\n"),
    ("config/http.toml", "# Zero request timeout intentionally disables the response-header deadline.\nrequest_timeout_seconds = 30\nreadiness_timeout_seconds = 2\nmax_body_bytes = 2097152\ncompression = true\n"),
    ("config/database.toml", "# SQLite makes the first run self-contained. Use DATABASE_URL for PostgreSQL.\nurl = \"sqlite://database/app.sqlite?mode=rwc\"\nmax_connections = 10\nmin_connections = 0\nconnect_timeout_seconds = 10\nacquire_timeout_seconds = 10\nidle_timeout_seconds = 600\n"),
    (".env.example", include_str!("../templates/env.example.txt")),
    (".gitignore", "/target\n.capy-generator.lock\n.env\n*.sqlite\n*.sqlite-shm\n*.sqlite-wal\n"),
    ("tests/health.rs", include_str!("../templates/health.rs.txt")),
    ("README.md", include_str!("../templates/README.md.txt")),
    ("capy.toml", "[frontend]\ndriver = \"{{frontend}}\"\n"),
];

/// Create a project without overwriting an existing directory.
pub fn new_project(path: &Path, name: &str) -> Result<()> {
    new_project_with_frontend(path, name, FrontendDriver::React)
}

/// Create a project with an explicit frontend selection.
pub fn new_project_with_frontend(path: &Path, name: &str, frontend: FrontendDriver) -> Result<()> {
    crate::names::project_name(name)?;
    let files = FILES
        .iter()
        .chain(frontend.files())
        .map(|(relative, contents)| {
            let contents = if *relative == "routes/mod.rs" && frontend == FrontendDriver::React {
                "//! Application routes.\npub mod api;\npub mod web;\n"
            } else { contents };
            let contents = contents
                .replace("{{name}}", name)
                .replace("{{frontend}}", frontend.as_str())
                .replace("{{frontend-setup}}", if frontend == FrontendDriver::React {
                    ".routes(application::routes::web::routes())\n        .frontend(\"frontend/dist\")"
                } else { "" })
                .replace("{{development}}", if frontend == FrontendDriver::React {
                    "Install Node.js 22.12+ (or 20.19+) and pnpm, then run `capy dev`.\nOpen http://127.0.0.1:5173. Capy installs missing dependencies and starts both servers.\nVite provides React HMR; Rust source changes automatically rebuild and restart the backend.\nCompilation errors retry after you save a fix. Press `1` then `r` for a manual restart.\nUse `CAPY_FRONTEND_PORT=5174 capy dev` if port 5173 is occupied.\nRequests to `/api/*` are proxied to the backend using the resolved app configuration."
                } else {
                    "Run `capy dev` and visit http://127.0.0.1:8000/api/health.\nNo Node.js or pnpm is required. Rust source changes automatically rebuild and restart the backend.\nCompilation errors retry after you save a fix. Press `1` then `r` for a manual restart."
                })
                .replace("{{deployment}}", if frontend == FrontendDriver::React {
                    "Deploy the release binary together with `frontend/dist`, `config/`, and `database/`.\nRun from the application root. Capy serves the SPA and static assets; no Node server\nis needed. Missing API routes remain JSON 404s. Missing assets in production\nstop startup with a message to run `capy build`."
                } else {
                    "Deploy the release binary together with `config/` and `database/`. Run from the application root."
                })
                .replace("{{framework-version}}", env!("CARGO_PKG_VERSION"))
                .replace("{{rust-version}}", env!("CARGO_PKG_RUST_VERSION"))
                .replace("{{crate}}", &name.replace('-', "_"));
            let contents = if relative.ends_with(".rs") {
                crate::generate::format_rust(&contents)?
            } else {
                contents
            };
            Ok((*relative, contents))
        })
        .collect::<Result<Vec<_>>>()?;
    fs::create_dir(path).with_context(|| {
        format!(
            "Cannot create {}. Choose a new directory name.",
            path.display()
        )
    })?;
    let result = (|| {
        for (relative, contents) in files {
            let target = path.join(relative);
            fs::create_dir_all(target.parent().expect("template has a parent"))?;
            fs::write(target, contents)?;
        }
        Ok(())
    })();
    if result.is_err() {
        // This directory was created exclusively by this call.
        let _ = fs::remove_dir_all(path);
    }
    result
}

/// Find a Capy application from its root or any nested directory.
pub fn find_project(start: impl AsRef<Path>) -> Result<PathBuf> {
    for path in start.as_ref().ancestors() {
        if path.join("Cargo.toml").is_file()
            && path.join("routes/api.rs").is_file()
            && path.join("app/mod.rs").is_file()
        {
            return Ok(path.to_owned());
        }
    }
    bail!("No Capy application found. Run this command inside a project created by `capy new`.")
}