capy-cli 0.1.0

Project scaffolding, generators, and development commands for the Capy web framework.
Documentation
use anyhow::{bail, Context, Result};
use std::{
    fs,
    path::{Path, PathBuf},
};

const FILES: &[(&str, &str)] = &[
    (".capy-generator.lock", ""),
    ("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/database.toml", "# SQLite makes the first run self-contained. Use DATABASE_URL for PostgreSQL.\nurl = \"sqlite://database/app.sqlite?mode=rwc\"\nmax_connections = 10\nconnect_timeout_seconds = 10\n"),
    (".env.example", "APP_ENVIRONMENT=development\nAPP_HOST=127.0.0.1\nAPP_PORT=8000\nDATABASE_URL=sqlite://database/app.sqlite?mode=rwc\n# PostgreSQL (create the database first):\n# DATABASE_URL=postgres://postgres:postgres@localhost/{{crate}}\n"),
    (".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", "# {{name}}\n\nBuilt with Capy.\n\nFor local development, run `capy serve` and visit http://127.0.0.1:8000/health.\nSQLite works out of the box. Copy `.env.example` to `.env` to customize settings.\nFor PostgreSQL, create a database and set `DATABASE_URL`.\n\nUse `capy routes`, `capy test`, and `capy --help`.\nMigrations are explicit: run `capy migrate` before using new tables.\n\nFor deployment, run `cargo build --release`, then `APP_ENVIRONMENT=production ./target/release/{{name}}`.\nProduction JSON logs include request IDs, method, route, status and latency. Use `RUST_LOG` to customize filtering.\nResponses include `x-request-id`.\n"),
];

/// Create a project without overwriting an existing directory.
pub fn new_project(path: &Path, name: &str) -> Result<()> {
    crate::names::project_name(name)?;
    let files = FILES
        .iter()
        .map(|(relative, contents)| {
            let contents = contents
                .replace("{{name}}", name)
                .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`.")
}