capy-cli 0.10.0

The command-line interface for the Capy web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Capy command line interface.

mod contracts;
mod dev;
mod doctor;
mod process;

use anyhow::{Context, Result};
use capy_cli::{
    find_project, generate, new_project_with_frontend, AccessProfile, FrontendDriver, Generator,
};
use clap::{Parser, Subcommand, ValueEnum};
use std::{
    path::PathBuf,
    process::{Command, ExitCode},
};

#[derive(Parser)]
#[command(
    name = "capy",
    version,
    about = "Capy — A calmer way to build web apps in Rust."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a ready-to-run Capy application.
    New {
        name: String,
        /// Create a backend-only application.
        #[arg(long, conflicts_with = "frontend")]
        api: bool,
        /// Frontend stack (defaults to react).
        #[arg(long, value_enum)]
        frontend: Option<FrontendDriver>,
    },
    /// Watch Rust sources and run the development dashboard (plain output in CI/non-TTY terminals).
    Dev(dev::Options),
    /// Build frontend assets and the Rust release application.
    Build,
    /// Run the Rust application only (does not start Vite).
    Serve,
    /// Diagnose tools, project configuration and database connectivity without installing anything.
    Doctor,
    /// Validate production configuration, assets and migration registration offline; do not start HTTP.
    Check,
    /// List registered API routes without opening a database connection.
    Routes {
        /// Include stable operation identifiers and response contract types.
        #[arg(long)]
        api: bool,
    },
    /// Generate generated/openapi.json without opening a database connection.
    Openapi {
        /// Fail on drift without changing generated files.
        #[arg(long)]
        check: bool,
        /// Reject undocumented public API routes unless explicitly exempted.
        #[arg(long)]
        strict: bool,
    },
    /// Generate OpenAPI and frontend/src/generated/api-types.ts from Rust DTOs.
    Types {
        /// Fail on drift without changing generated files (for CI).
        #[arg(long)]
        check: bool,
        /// Reject undocumented public API routes unless explicitly exempted.
        #[arg(long)]
        strict: bool,
    },
    /// Create and register a controller.
    #[command(name = "make:controller")]
    MakeController { name: String },
    /// Create and register a SeaORM entity.
    #[command(name = "make:model")]
    MakeModel { name: String },
    /// Create and register a validated JSON request.
    #[command(name = "make:request")]
    MakeRequest { name: String },
    /// Create and register a SeaORM migration.
    #[command(name = "make:migration")]
    MakeMigration { name: String },
    /// Generate a complete resource with typed fields, CRUD contracts and tests.
    #[command(name = "make:resource")]
    MakeResource {
        name: String,
        /// Fields such as title:string, slug:string:unique, published:boolean=false.
        fields: Vec<String>,
        /// Include a React feature module using generated API contracts.
        #[arg(long)]
        frontend: bool,
        /// private (default with auth) or public-read; requires make:auth.
        #[arg(long, value_enum)]
        access: Option<ResourceAccess>,
        /// Add nested list, create and show routes under this referenced parent.
        #[arg(long)]
        nested: Option<String>,
    },
    /// Add an additive resource column and emit manual application-code instructions.
    #[command(name = "resource:add-field")]
    ResourceAddField {
        resource: String,
        field: String,
        /// Acknowledge that a unique index can fail on duplicate existing data.
        #[arg(long)]
        acknowledge_unique: bool,
    },
    /// Add a nullable reference to an existing resource without rewriting feature code.
    #[command(name = "resource:add-reference")]
    ResourceAddReference { resource: String, field: String },
    /// Add a composite index or scoped unique constraint to a resource table.
    #[command(name = "resource:add-index")]
    ResourceAddIndex {
        resource: String,
        /// Two to four comma-separated model fields, such as owner_id,slug.
        columns: String,
        /// Create a unique constraint instead of a nonunique index.
        #[arg(long)]
        unique: bool,
        /// Acknowledge that existing duplicate values may reject a unique index.
        #[arg(long)]
        acknowledge_unique: bool,
    },
    /// Install conventional browser authentication.
    #[command(name = "make:auth")]
    MakeAuth {
        /// Generate login, registration, recovery, verification and account pages.
        #[arg(long)]
        frontend: bool,
    },
    /// Delete expired sessions and password-reset records.
    #[command(name = "auth:prune")]
    AuthPrune,
    /// Generate a typed mailable and compiled text/HTML templates.
    #[command(name = "make:mail")]
    MakeMail { name: String },
    /// Generate a mail notification and compiled templates.
    #[command(name = "make:notification")]
    MakeNotification { name: String },
    /// Inspect the private local development inbox (requires the mail feature).
    Mail {
        #[command(subcommand)]
        command: Option<MailCommand>,
    },
    /// Create and register a durable job; installs jobs on first use.
    #[command(name = "make:job")]
    MakeJob { name: String },
    /// Run the application worker with bounded concurrency.
    #[command(name = "queue:work")]
    QueueWork {
        #[arg(long = "queue")]
        queues: Vec<String>,
        #[arg(long)]
        concurrency: Option<usize>,
    },
    /// Inspect failed jobs without dumping payloads.
    #[command(name = "queue:failed")]
    QueueFailed,
    /// Return a failed job to its original queue.
    #[command(name = "queue:retry")]
    QueueRetry { id: String },
    /// Permanently delete one failed job.
    #[command(name = "queue:forget")]
    QueueForget { id: String },
    /// List named application tasks without connecting to a database.
    #[command(name = "task:list")]
    TaskList,
    /// Run one registered operational task with application services.
    #[command(name = "task:run")]
    TaskRun { name: String },
    /// Run the dedicated UTC scheduler process; requires scheduler feature and migrations.
    #[command(name = "scheduler:run")]
    SchedulerRun,
    /// Apply pending migrations.
    #[command(alias = "db:migrate")]
    Migrate,
    /// Run explicit application-owned development/test seeds in one transaction.
    #[command(name = "db:seed")]
    Seed,
    /// Revert the most recently applied migration.
    #[command(name = "migrate:rollback", alias = "db:rollback")]
    MigrateRollback,
    /// Show pending and applied migrations.
    #[command(name = "migrate:status", alias = "db:status")]
    MigrateStatus,
    /// Run application tests; pass Cargo test arguments after --.
    Test {
        #[arg(last = true)]
        args: Vec<String>,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum ResourceAccess {
    Private,
    PublicRead,
}

impl From<ResourceAccess> for AccessProfile {
    fn from(value: ResourceAccess) -> Self {
        match value {
            ResourceAccess::Private => Self::Private,
            ResourceAccess::PublicRead => Self::PublicRead,
        }
    }
}

#[derive(Subcommand)]
enum MailCommand {
    /// List captured message IDs, timestamps, recipients and subjects.
    List,
    /// Inspect text, HTML source, sender and custom headers in your terminal.
    Show { id: String },
    /// Remove all messages from the configured development inbox.
    Clear,
}

fn main() -> ExitCode {
    match execute(Cli::parse()) {
        Ok(code) => code,
        Err(error) => {
            eprintln!("Capy could not complete the command.\n\n{error:#}");
            ExitCode::FAILURE
        }
    }
}

fn execute(cli: Cli) -> Result<ExitCode> {
    let command = match cli.command {
        Commands::New {
            name,
            api,
            frontend,
        } => {
            let frontend = if api {
                FrontendDriver::None
            } else {
                frontend.unwrap_or(FrontendDriver::React)
            };
            new_project_with_frontend(&PathBuf::from(&name), &name, frontend)?;
            println!("Created {name}.\n\n  cd {name}\n  capy dev\n\nSQLite is ready for local development. Set DATABASE_URL to use PostgreSQL.");
            return Ok(ExitCode::SUCCESS);
        }
        Commands::MakeMail { ref name } | Commands::MakeNotification { ref name } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = if matches!(cli.command, Commands::MakeMail { .. }) {
                capy_cli::make_mail(&root, name)?
            } else {
                capy_cli::make_notification(&root, name)?
            };
            println!("Created outbound communication and updated {} files. Development logs metadata only; configure SMTP to deliver.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::Mail { command } => {
            let args = match command.unwrap_or(MailCommand::List) {
                MailCommand::List => vec!["mail:list".into()],
                MailCommand::Show { id } => vec!["mail:show".into(), id],
                MailCommand::Clear => vec!["mail:clear".into()],
            };
            return process::application_command(&find_project(std::env::current_dir()?)?, &args);
        }
        Commands::MakeJob { name } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::make_job(&root, &name)?;
            println!(
                "Created job and updated {} files. Run capy migrate, then capy queue:work.",
                paths.len()
            );
            return Ok(ExitCode::SUCCESS);
        }
        Commands::QueueWork {
            queues,
            concurrency,
        } => {
            let mut args = vec!["queue:work".to_owned()];
            for queue in queues {
                args.extend(["--queue".into(), queue]);
            }
            if let Some(concurrency) = concurrency {
                args.extend(["--concurrency".into(), concurrency.to_string()]);
            }
            return process::application_command(&find_project(std::env::current_dir()?)?, &args);
        }
        Commands::QueueFailed => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["queue:failed".into()],
            )
        }
        Commands::QueueRetry { id } => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["queue:retry".into(), id],
            )
        }
        Commands::QueueForget { id } => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["queue:forget".into(), id],
            )
        }
        Commands::TaskList => "task:list",
        Commands::TaskRun { name } => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["task:run".into(), name],
            );
        }
        Commands::SchedulerRun => {
            return process::application_command(
                &find_project(std::env::current_dir()?)?,
                &["scheduler:run".into()],
            );
        }
        Commands::MakeResource {
            name,
            fields,
            frontend,
            access,
            nested,
        } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::make_resource_with_options(
                &root,
                &name,
                &fields,
                frontend,
                access.map(Into::into),
                nested.as_deref(),
            )?;
            println!("Created resource and updated {} files. Run capy db:migrate, capy types, and capy test.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::ResourceAddField {
            resource,
            field,
            acknowledge_unique,
        } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::resource_add_field(&root, &resource, &field, acknowledge_unique)?;
            println!("Generated and registered an additive migration ({} files). Review database/evolution/ before applying it. Application feature code requires the exact manual changes in that note; customized code was not rewritten.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::ResourceAddReference { resource, field } => {
            if !field.contains(":references?:") {
                anyhow::bail!("resource:add-reference requires a nullable field such as post_id:references?:Post. Add a required constraint only after backfilling existing rows.");
            }
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::resource_add_field(&root, &resource, &field, false)?;
            println!("Generated and registered a nullable foreign-key migration ({} files). Review database/evolution/ before applying it. Application feature code requires the exact manual changes in that note; customized code was not rewritten.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::ResourceAddIndex {
            resource,
            columns,
            unique,
            acknowledge_unique,
        } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::resource_add_index(
                &root,
                &resource,
                &columns,
                unique,
                acknowledge_unique,
            )?;
            println!("Generated and registered a composite {} migration ({} files). Review database/evolution/ and existing data before capy db:migrate.", if unique { "unique" } else { "index" }, paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::MakeAuth { frontend } => {
            let root = find_project(std::env::current_dir()?)?;
            let paths = capy_cli::make_auth_with_frontend(&root, frontend)?;
            println!("Installed conventional auth ({} files).\nRun capy migrate, then capy types (React) or capy openapi (--api).\nReplace app/auth.rs reset delivery before production.", paths.len());
            return Ok(ExitCode::SUCCESS);
        }
        Commands::AuthPrune => "auth:prune",
        Commands::MakeController { name } => return make(Generator::Controller, &name),
        Commands::MakeModel { name } => return make(Generator::Model, &name),
        Commands::MakeRequest { name } => return make(Generator::Request, &name),
        Commands::MakeMigration { name } => return make(Generator::Migration, &name),
        Commands::Test { args } => return cargo(&[vec!["test".into()], args].concat()),
        Commands::Dev(options) => {
            return dev::run(&find_project(std::env::current_dir()?)?, options)
        }
        Commands::Build => return process::build(&find_project(std::env::current_dir()?)?),
        Commands::Serve => return process::serve(&find_project(std::env::current_dir()?)?),
        Commands::Doctor => return doctor::run(&find_project(std::env::current_dir()?)?),
        Commands::Check => {
            let root = find_project(std::env::current_dir()?)?;
            doctor::check(&root)?;
            let status = cargo(&[
                "run".into(),
                "--offline".into(),
                "--quiet".into(),
                "--".into(),
                "check".into(),
            ])?;
            if status != ExitCode::SUCCESS {
                return Ok(status);
            }
            let types =
                capy_cli::ProjectConfig::load(&root)?.frontend.driver == FrontendDriver::React;
            return contracts::run(&root, types, true, true);
        }
        Commands::Routes { api } => {
            if api {
                "routes:api"
            } else {
                "routes"
            }
        }
        Commands::Openapi { check, strict } => {
            return contracts::run_with_strict(
                &find_project(std::env::current_dir()?)?,
                false,
                check,
                false,
                strict,
            )
        }
        Commands::Types { check, strict } => {
            return contracts::run_with_strict(
                &find_project(std::env::current_dir()?)?,
                true,
                check,
                false,
                strict,
            )
        }
        Commands::Migrate => "migrate",
        Commands::Seed => "db:seed",
        Commands::MigrateRollback => "migrate:rollback",
        Commands::MigrateStatus => "migrate:status",
    };
    cargo(&["run".into(), "--quiet".into(), "--".into(), command.into()])
}

fn make(kind: Generator, name: &str) -> Result<ExitCode> {
    let root = find_project(std::env::current_dir()?)?;
    let path = generate(&root, kind, name)?;
    println!(
        "Created {}",
        path.strip_prefix(&root).unwrap_or(&path).display()
    );
    if matches!(kind, Generator::Controller) {
        println!("Routing is explicit. Add this declaration to the Routes chain in routes/api.rs (mounted under /api), choosing an unused path:\n    {}", capy_cli::controller_route(name)?);
    }
    Ok(ExitCode::SUCCESS)
}

fn cargo(args: &[String]) -> Result<ExitCode> {
    let root = find_project(std::env::current_dir()?)?;
    let status = Command::new("cargo")
        .args(args)
        .current_dir(root)
        .status()
        .context("Could not start Cargo. Install the stable Rust toolchain.")?;
    Ok(process::exit_code(status))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn dev_cli_flags_validate_conflicts() {
        for args in [
            vec!["capy", "dev"],
            vec!["capy", "dev", "--inline"],
            vec!["capy", "dev", "--tui"],
            vec!["capy", "dev", "--stream"],
            vec!["capy", "dev", "--tui", "--stream"],
        ] {
            assert!(Cli::try_parse_from(args).is_ok());
        }
        for flag in ["--tui", "--stream"] {
            assert!(Cli::try_parse_from(["capy", "dev", "--inline", flag]).is_err());
        }
    }
}