chyabrung-cli 0.2.3

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy` — the Chyabrung command line tool.

#![forbid(unsafe_code)]

mod add;
mod build;
mod db;
mod deploy;
mod dev;
mod docker;
mod doctor;
mod maintenance;
mod make;
mod new;
mod resource;
mod upgrade;
mod routes;
mod util;

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "chy", version, about = "🥁 Chyabrung — build with rhythm", propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Create a new app from a template (api, blog, saas)
    New {
        /// App name (directory)
        name: String,
        /// Template: api, blog or saas
        #[arg(short, long, default_value = "api")]
        template: String,
        /// Path to a local Chyabrung checkout to depend on
        #[arg(long)]
        chyabrung_path: Option<String>,
    },
    /// Turn on framework features in Cargo.toml (e.g. `chy add ui auth sqlite`)
    Add {
        /// Features to enable; run `chy add --list` to see them
        features: Vec<String>,
        /// List the available features
        #[arg(long)]
        list: bool,
    },
    /// Run the dev server with hot reload
    Dev {
        /// Extra cargo features
        #[arg(long)]
        features: Option<String>,
        /// Live-reload port
        #[arg(long, default_value_t = 35729)]
        reload_port: u16,
    },
    /// Optimized release build (binary, CSS, WASM islands, optional static export)
    Build {
        /// Also pre-render pages to dist/site
        #[arg(long = "static")]
        static_site: bool,
        /// Skip the WASM build even if the crate supports hydration
        #[arg(long)]
        no_wasm: bool,
    },
    /// Generate a model (use --migration to add a migration)
    #[command(name = "make:model")]
    MakeModel {
        name: String,
        #[arg(short, long)]
        migration: bool,
    },
    /// Generate a controller (`#[controller]` with CRUD handlers)
    #[command(name = "make:controller")]
    MakeController { name: String },
    /// Generate a full resource: model, migration, request, controller, route and test
    #[command(name = "make:resource")]
    MakeResource {
        /// e.g. `Comment`
        name: String,
        /// Columns, e.g. "body:text,post_id:int,approved:bool,note:string?"
        /// (types: string, text, int, float, bool; `?` = optional). Default: "name:string"
        #[arg(short, long)]
        fields: Option<String>,
    },
    /// Generate a migration with `up` / `down` (`create_posts_table` and `add_bio_to_users_table` are pre-filled)
    #[command(name = "make:migration")]
    MakeMigration { name: String },
    /// Generate a migration that adds a full-text search index (for `Model::search`)
    #[command(name = "make:search")]
    MakeSearch {
        /// Table, e.g. `posts`
        table: String,
        /// Columns to search, e.g. "title,body"
        #[arg(short, long)]
        columns: String,
    },
    /// Generate a middleware
    #[command(name = "make:middleware")]
    MakeMiddleware { name: String },
    /// Generate a background job
    #[command(name = "make:job")]
    MakeJob { name: String },
    /// Generate a page under app/ (e.g. `blog/[slug]`)
    #[command(name = "make:page")]
    MakePage { path: String },
    /// Generate a seeder SQL file
    #[command(name = "make:seeder")]
    MakeSeeder { name: String },
    /// Put the app into maintenance mode: a 503 "back soon" page (admins and the bypass URL get through)
    Down {
        /// Message shown to visitors
        #[arg(short, long)]
        message: Option<String>,
        /// Seconds clients should wait before retrying (Retry-After header)
        #[arg(long)]
        retry: Option<u64>,
        /// Bypass path: opening /<secret> lets you use the site (default: random)
        #[arg(long)]
        secret: Option<String>,
        /// Don't create a bypass URL
        #[arg(long, conflicts_with = "secret")]
        no_secret: bool,
        /// Let an IP address through (repeatable)
        #[arg(long)]
        allow: Vec<String>,
    },
    /// End maintenance mode
    Up,
    /// Move this app to the chyabrung version matching this `chy` (edits Cargo.toml, updates Cargo.lock)
    Upgrade,
    /// Install the latest `chy` (works even while another `chy dev` is running)
    #[command(name = "self-update")]
    SelfUpdate,
    /// Run pending migrations
    Migrate,
    /// Roll back the last batch of migrations
    #[command(name = "migrate:rollback")]
    MigrateRollback {
        #[arg(long, default_value_t = 1)]
        step: u32,
    },
    /// Show migration status
    #[command(name = "migrate:status")]
    MigrateStatus,
    /// Roll back everything and migrate again
    #[command(name = "migrate:fresh")]
    MigrateFresh,
    /// Run seeders (database/seeds/*.sql, then src/bin/seed.rs if present)
    #[command(name = "db:seed")]
    DbSeed,
    /// Generate APP_KEY in .env
    #[command(name = "key:generate")]
    KeyGenerate {
        /// Print instead of writing .env
        #[arg(long)]
        show: bool,
    },
    /// Print every route: method, path, name and middleware
    Routes {
        /// Extra cargo features
        #[arg(long)]
        features: Option<String>,
        /// Print JSON instead of a table
        #[arg(long)]
        json: bool,
    },
    /// Check the setup: APP_KEY, database, migrations, port and tools
    Doctor,
    /// Generate a Dockerfile, .dockerignore and docker-compose.yml (app + PostgreSQL + Redis)
    Docker {
        /// Overwrite existing files
        #[arg(long)]
        force: bool,
    },
    /// Deploy to a VPS: build, upload, systemd, Nginx and Let's Encrypt
    Deploy {
        /// Print the plan and generated files without running anything
        #[arg(long)]
        dry_run: bool,
    },
}

fn main() {
    upgrade::cleanup_old_exe();
    let cli = Cli::parse();
    let result = match cli.cmd {
        Cmd::New { name, template, chyabrung_path } => new::run(&name, &template, chyabrung_path.as_deref()),
        Cmd::Add { features, list } => if list { add::list() } else { add::run_add(&features) },
        Cmd::Dev { features, reload_port } => dev::run(features.as_deref(), reload_port),
        Cmd::Build { static_site, no_wasm } => build::run(static_site, !no_wasm),
        Cmd::MakeModel { name, migration } => make::model(&name, migration),
        Cmd::MakeController { name } => make::controller(&name),
        Cmd::MakeResource { name, fields } => resource::run(&name, fields.as_deref()),
        Cmd::MakeMigration { name } => make::migration(&name).map(|_| ()),
        Cmd::MakeSearch { table, columns } => make::search(&table, &columns),
        Cmd::MakeMiddleware { name } => make::middleware(&name),
        Cmd::MakeJob { name } => make::job(&name),
        Cmd::MakePage { path } => make::page(&path),
        Cmd::MakeSeeder { name } => make::seeder(&name),
        Cmd::Down { message, retry, secret, no_secret, allow } => {
            maintenance::down(maintenance::DownOptions { message, retry, secret, no_secret, allow })
        }
        Cmd::Up => maintenance::up(),
        Cmd::Upgrade => upgrade::upgrade(),
        Cmd::SelfUpdate => upgrade::self_update(),
        Cmd::Migrate => db::migrate(),
        Cmd::MigrateRollback { step } => db::rollback(step),
        Cmd::MigrateStatus => db::status(),
        Cmd::MigrateFresh => db::fresh(),
        Cmd::DbSeed => db::seed(),
        Cmd::KeyGenerate { show } => util::key_generate(show),
        Cmd::Routes { features, json } => routes::run(features.as_deref(), json),
        Cmd::Doctor => doctor::run(),
        Cmd::Docker { force } => docker::run(force),
        Cmd::Deploy { dry_run } => deploy::run(dry_run),
    };
    if let Err(e) = result {
        eprintln!("\x1b[31merror:\x1b[0m {e}");
        std::process::exit(1);
    }
}