-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy pathcli.rs
715 lines (665 loc) · 22.1 KB
/
cli.rs
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! command-line interface for running various tasks and commands
//! related to the application. It allows developers to interact with the
//! application via the command line.
//!
//! # Example
//!
//! ```rust,ignore
//! use myapp::app::App;
//! use loco_rs::cli;
//! use migration::Migrator;
//!
//! #[tokio::main]
//! async fn main() {
//! cli::main::<App, Migrator>().await
//! }
//! ```
cfg_if::cfg_if! {
if #[cfg(feature = "with-db")] {
use sea_orm_migration::MigratorTrait;
use crate::doctor;
use crate::boot::{run_db};
use crate::db;
use std::process::exit;
} else {}
}
use std::path::PathBuf;
use clap::{ArgAction, Parser, Subcommand};
use duct::cmd;
use loco_gen::{Component, ScaffoldKind};
use crate::{
app::{AppContext, Hooks},
boot::{
create_app, create_context, list_endpoints, list_middlewares, run_scheduler, run_task,
start, RunDbCommand, ServeParams, StartMode,
},
config::Config,
environment::{resolve_from_env, Environment, DEFAULT_ENVIRONMENT},
logger, task, Error,
};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Playground {
/// Specify the environment
#[arg(short, long, global = true, help = &format!("Specify the environment [default: {}]", DEFAULT_ENVIRONMENT))]
environment: Option<String>,
}
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
#[command(subcommand)]
command: Commands,
/// Specify the environment
#[arg(short, long, global = true, help = &format!("Specify the environment [default: {}]", DEFAULT_ENVIRONMENT))]
environment: Option<String>,
}
#[derive(Subcommand)]
enum Commands {
/// Start an app
#[clap(alias("s"))]
Start {
/// start worker
#[arg(short, long, action)]
worker: bool,
/// start same-process server and worker
#[arg(short, long, action)]
server_and_worker: bool,
/// server bind address
#[arg(short, long, action)]
binding: Option<String>,
/// server port address
#[arg(short, long, action)]
port: Option<i32>,
/// disable the banner display
#[arg(short, long, action = ArgAction::SetTrue)]
no_banner: bool,
},
#[cfg(feature = "with-db")]
/// Perform DB operations
Db {
#[command(subcommand)]
command: DbCommands,
},
/// Describe all application endpoints
Routes {},
/// Describe all application middlewares
Middleware {
// print out the middleware configurations.
#[arg(short, long, action)]
config: bool,
},
/// Run a custom task
#[clap(alias("t"))]
Task {
/// Task name (identifier)
name: Option<String>,
/// Task params (e.g. <`my_task`> foo:bar baz:qux)
#[clap(value_parser = parse_key_val::<String,String>)]
params: Vec<(String, String)>,
},
/// Run the scheduler
Scheduler {
/// Run a specific job by its name.
#[arg(short, long, action)]
name: Option<String>,
/// Run jobs that are associated with a specific tag.
#[arg(short, long, action)]
tag: Option<String>,
/// Specify a path to a dedicated scheduler configuration file. by
/// default load schedulers job setting from environment config.
#[clap(value_parser)]
#[arg(short, long, action)]
config: Option<PathBuf>,
/// Show all configured jobs
#[arg(short, long, action)]
list: bool,
},
/// code generation creates a set of files and code templates based on a
/// predefined set of rules.
#[clap(alias("g"))]
Generate {
/// What to generate
#[command(subcommand)]
component: ComponentArg,
},
#[cfg(feature = "with-db")]
/// Validate and diagnose configurations.
Doctor {
/// print out the current configurations.
#[arg(short, long, action)]
config: bool,
},
/// Display the app version
Version {},
/// Watch and restart the app
#[clap(alias("w"))]
Watch {
/// start worker
#[arg(short, long, action)]
worker: bool,
/// start same-process server and worker
#[arg(short, long, action)]
server_and_worker: bool,
},
}
#[derive(Subcommand)]
enum ComponentArg {
#[cfg(feature = "with-db")]
/// Generates a new model file for defining the data structure of your
/// application, and test file logic.
Model {
/// Name of the thing to generate
name: String,
/// Is it a link table? Use this in many-to-many relations
#[arg(short, long, action)]
link: bool,
/// Generate migration code only. Don't run the migration automatically.
#[arg(short, long, action)]
migration_only: bool,
/// Model fields, eg. title:string hits:int
#[clap(value_parser = parse_key_val::<String,String>)]
fields: Vec<(String, String)>,
},
#[cfg(feature = "with-db")]
/// Generates a new migration file
Migration {
/// Name of the migration to generate
name: String,
},
#[cfg(feature = "with-db")]
/// Generates a CRUD scaffold, model and controller
Scaffold {
/// Name of the thing to generate
name: String,
/// Model fields, eg. title:string hits:int
#[clap(value_parser = parse_key_val::<String,String>)]
fields: Vec<(String, String)>,
/// The kind of scaffold to generate
#[clap(short, long, value_enum, group = "scaffold_kind_group")]
kind: Option<ScaffoldKind>,
/// Use HTMX scaffold
#[clap(long, group = "scaffold_kind_group")]
htmx: bool,
/// Use HTML scaffold
#[clap(long, group = "scaffold_kind_group")]
html: bool,
/// Use API scaffold
#[clap(long, group = "scaffold_kind_group")]
api: bool,
},
/// Generate a new controller with the given controller name, and test file.
Controller {
/// Name of the thing to generate
name: String,
/// Actions
actions: Vec<String>,
/// The kind of controller actions to generate
#[clap(short, long, value_enum, group = "scaffold_kind_group")]
kind: Option<ScaffoldKind>,
/// Use HTMX controller actions
#[clap(long, group = "scaffold_kind_group")]
htmx: bool,
/// Use HTML controller actions
#[clap(long, group = "scaffold_kind_group")]
html: bool,
/// Use API controller actions
#[clap(long, group = "scaffold_kind_group")]
api: bool,
},
/// Generate a Task based on the given name
Task {
/// Name of the thing to generate
name: String,
},
/// Generate a scheduler jobs configuration template
Scheduler {},
/// Generate worker
Worker {
/// Name of the thing to generate
name: String,
},
/// Generate mailer
Mailer {
/// Name of the thing to generate
name: String,
},
/// Generate a deployment infrastructure
Deployment {},
}
impl ComponentArg {
fn into_gen_component(self, config: &Config) -> crate::Result<Component> {
match self {
#[cfg(feature = "with-db")]
Self::Model {
name,
link,
migration_only,
fields,
} => Ok(Component::Model {
name,
link,
migration_only,
fields,
}),
#[cfg(feature = "with-db")]
Self::Migration { name } => Ok(Component::Migration { name }),
#[cfg(feature = "with-db")]
Self::Scaffold {
name,
fields,
kind,
htmx,
html,
api,
} => {
let kind = if let Some(kind) = kind {
kind
} else if htmx {
ScaffoldKind::Htmx
} else if html {
ScaffoldKind::Html
} else if api {
ScaffoldKind::Api
} else {
return Err(crate::Error::string(
"Error: One of `kind`, `htmx`, `html`, or `api` must be specified.",
));
};
Ok(Component::Scaffold { name, fields, kind })
}
Self::Controller {
name,
actions,
kind,
htmx,
html,
api,
} => {
let kind = if let Some(kind) = kind {
kind
} else if htmx {
ScaffoldKind::Htmx
} else if html {
ScaffoldKind::Html
} else if api {
ScaffoldKind::Api
} else {
return Err(crate::Error::string(
"Error: One of `kind`, `htmx`, `html`, or `api` must be specified.",
));
};
Ok(Component::Controller {
name,
actions,
kind,
})
}
Self::Task { name } => Ok(Component::Task { name }),
Self::Scheduler {} => Ok(Component::Scheduler {}),
Self::Worker { name } => Ok(Component::Worker { name }),
Self::Mailer { name } => Ok(Component::Mailer { name }),
Self::Deployment {} => {
let copy_asset_folder = &config
.server
.middlewares
.static_assets
.clone()
.map(|a| a.folder.path);
let fallback_file = &config
.server
.middlewares
.static_assets
.clone()
.map(|a| a.fallback);
Ok(Component::Deployment {
asset_folder: copy_asset_folder.clone(),
fallback_file: fallback_file.clone(),
host: config.server.host.clone(),
port: config.server.port,
})
}
}
}
}
#[derive(Subcommand)]
enum DbCommands {
/// Create schema
Create,
/// Migrate schema (up)
Migrate,
/// Run one down migration, or add a number to run multiple down migrations
/// (i.e. `down 2`)
Down {
/// The number of migrations to rollback
#[arg(default_value_t = 1)]
steps: u32,
},
/// Drop all tables, then reapply all migrations
Reset,
/// Migration status
Status,
/// Generate entity .rs files from database schema
Entities,
/// Truncate data in tables (without dropping)
Truncate,
}
impl From<DbCommands> for RunDbCommand {
fn from(value: DbCommands) -> Self {
match value {
DbCommands::Migrate => Self::Migrate,
DbCommands::Down { steps } => Self::Down(steps),
DbCommands::Reset => Self::Reset,
DbCommands::Status => Self::Status,
DbCommands::Entities => Self::Entities,
DbCommands::Truncate => Self::Truncate,
DbCommands::Create => {
unreachable!("Create db should't handled in the global db commands")
}
}
}
}
/// Parse a single key-value pair
fn parse_key_val<T, U>(
s: &str,
) -> std::result::Result<(T, U), Box<dyn std::error::Error + Send + Sync>>
where
T: std::str::FromStr,
T::Err: std::error::Error + Send + Sync + 'static,
U: std::str::FromStr,
U::Err: std::error::Error + Send + Sync + 'static,
{
let pos = s
.find(':')
.ok_or_else(|| format!("invalid KEY=value: no `:` found in `{s}`"))?;
Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}
#[cfg(feature = "with-db")]
/// run playgroup code
///
/// # Errors
///
/// When could not create app context
pub async fn playground<H: Hooks>() -> crate::Result<AppContext> {
let cli = Playground::parse();
let environment: Environment = cli.environment.unwrap_or_else(resolve_from_env).into();
let app_context = create_context::<H>(&environment).await?;
Ok(app_context)
}
/// # Main CLI Function
///
/// The `main` function is the entry point for the command-line interface (CLI)
/// of the application. It parses command-line arguments, interprets the
/// specified commands, and performs corresponding actions. This function is
/// generic over `H` and `M`, where `H` represents the application hooks and `M`
/// represents the migrator trait for handling database migrations.
///
/// # Errors
///
/// Returns an any error indicating success or failure during the CLI execution.
///
/// # Example
///
/// ```rust,ignore
/// use myapp::app::App;
/// use loco_rs::cli;
/// use migration::Migrator;
///
/// #[tokio::main]
/// async fn main() {
/// cli::main::<App, Migrator>().await
/// }
/// ```
#[cfg(feature = "with-db")]
#[allow(clippy::too_many_lines)]
#[allow(clippy::cognitive_complexity)]
pub async fn main<H: Hooks, M: MigratorTrait>() -> crate::Result<()> {
use colored::Colorize;
use loco_gen::AppInfo;
let cli: Cli = Cli::parse();
let environment: Environment = cli.environment.unwrap_or_else(resolve_from_env).into();
let config = environment.load()?;
if !H::init_logger(&config, &environment)? {
logger::init::<H>(&config.logger);
}
let task_span = create_root_span(&environment);
let _guard = task_span.enter();
match cli.command {
Commands::Start {
worker,
server_and_worker,
binding,
port,
no_banner,
} => {
let start_mode = if worker {
StartMode::WorkerOnly
} else if server_and_worker {
StartMode::ServerAndWorker
} else {
StartMode::ServerOnly
};
let boot_result = create_app::<H, M>(start_mode, &environment).await?;
let serve_params = ServeParams {
port: port.map_or(boot_result.app_context.config.server.port, |p| p),
binding: binding
.unwrap_or_else(|| boot_result.app_context.config.server.binding.to_string()),
};
start::<H>(boot_result, serve_params, no_banner).await?;
}
#[cfg(feature = "with-db")]
Commands::Db { command } => {
if matches!(command, DbCommands::Create) {
db::create(&environment.load()?.database.uri).await?;
} else {
let app_context = create_context::<H>(&environment).await?;
run_db::<H, M>(&app_context, command.into()).await?;
}
}
Commands::Routes {} => {
let app_context = create_context::<H>(&environment).await?;
show_list_endpoints::<H>(&app_context);
}
Commands::Middleware { config } => {
let app_context = create_context::<H>(&environment).await?;
let middlewares = list_middlewares::<H>(&app_context);
for middleware in middlewares.iter().filter(|m| m.enabled) {
println!(
"{:<22} {}",
middleware.id.bold(),
if config {
middleware.detail.as_str()
} else {
""
}
);
}
println!("\n");
for middleware in middlewares.iter().filter(|m| !m.enabled) {
println!("{:<22} (disabled)", middleware.id.bold().dimmed(),);
}
}
Commands::Task { name, params } => {
let vars = task::Vars::from_cli_args(params);
let app_context = create_context::<H>(&environment).await?;
run_task::<H>(&app_context, name.as_ref(), &vars).await?;
}
Commands::Scheduler {
name,
config,
tag,
list,
} => {
let app_context = create_context::<H>(&environment).await?;
run_scheduler::<H>(&app_context, config.as_ref(), name, tag, list).await?;
}
Commands::Generate { component } => {
loco_gen::generate(
component.into_gen_component(&config)?,
&AppInfo {
app_name: H::app_name().to_string(),
},
)?;
}
Commands::Doctor { config: config_arg } => {
if config_arg {
println!("{}", &config);
println!("Environment: {}", &environment);
} else {
let mut should_exit = false;
for (_, check) in doctor::run_all(&config).await {
if !should_exit && !check.valid() {
should_exit = true;
}
println!("{check}");
}
if should_exit {
exit(1);
}
}
}
Commands::Version {} => {
println!("{}", H::app_version(),);
}
Commands::Watch {
worker,
server_and_worker,
} => {
// cargo-watch -s 'cargo loco start'
let mut subcmd = vec!["cargo", "loco", "start"];
if worker {
subcmd.push("--worker");
} else if server_and_worker {
subcmd.push("--server-and-worker");
}
cmd("cargo-watch", &["-s", &subcmd.join(" ")])
.run()
.map_err(|err| {
Error::Message(format!(
"failed to start with `cargo-watch`. Did you `cargo install \
cargo-watch`?. error details: `{err}`",
))
})?;
}
}
Ok(())
}
#[cfg(not(feature = "with-db"))]
pub async fn main<H: Hooks>() -> crate::Result<()> {
use colored::Colorize;
use loco_gen::AppInfo;
let cli = Cli::parse();
let environment: Environment = cli.environment.unwrap_or_else(resolve_from_env).into();
let config = environment.load()?;
if !H::init_logger(&config, &environment)? {
logger::init::<H>(&config.logger);
}
let task_span = create_root_span(&environment);
let _guard = task_span.enter();
match cli.command {
Commands::Start {
worker,
server_and_worker,
binding,
port,
no_banner,
} => {
let start_mode = if worker {
StartMode::WorkerOnly
} else if server_and_worker {
StartMode::ServerAndWorker
} else {
StartMode::ServerOnly
};
let boot_result = create_app::<H>(start_mode, &environment).await?;
let serve_params = ServeParams {
port: port.map_or(boot_result.app_context.config.server.port, |p| p),
binding: binding.map_or(
boot_result.app_context.config.server.binding.to_string(),
|b| b,
),
};
start::<H>(boot_result, serve_params, no_banner).await?;
}
Commands::Routes {} => {
let app_context = create_context::<H>(&environment).await?;
show_list_endpoints::<H>(&app_context)
}
Commands::Middleware { config } => {
let app_context = create_context::<H>(&environment).await?;
let middlewares = list_middlewares::<H>(&app_context);
for middleware in middlewares.iter().filter(|m| m.enabled) {
println!(
"{:<22} {}",
middleware.id.bold(),
if config {
middleware.detail.as_str()
} else {
""
}
);
}
println!("\n");
for middleware in middlewares.iter().filter(|m| !m.enabled) {
println!("{:<22} (disabled)", middleware.id.bold().dimmed(),);
}
}
Commands::Task { name, params } => {
let vars = task::Vars::from_cli_args(params);
let app_context = create_context::<H>(&environment).await?;
run_task::<H>(&app_context, name.as_ref(), &vars).await?;
}
Commands::Scheduler {
name,
config,
tag,
list,
} => {
let app_context = create_context::<H>(&environment).await?;
run_scheduler::<H>(&app_context, config.as_ref(), name, tag, list).await?;
}
Commands::Generate { component } => {
gen::generate(
component.into_gen_component(&config)?,
&AppInfo {
app_name: H::app_name().to_string(),
},
)?;
}
Commands::Version {} => {
println!("{}", H::app_version(),);
}
Commands::Watch {
worker,
server_and_worker,
} => {
// cargo-watch -s 'cargo loco start'
let mut subcmd = vec!["cargo", "loco", "start"];
if worker {
subcmd.push("--worker");
} else if server_and_worker {
subcmd.push("--server-and-worker");
}
cmd("cargo-watch", &["-s", &subcmd.join(" ")])
.run()
.map_err(|err| {
Error::Message(format!(
"failed to start with `cargo-watch`. Did you `cargo install \
cargo-watch`?. error details: `{err}`",
))
})?;
}
}
Ok(())
}
fn show_list_endpoints<H: Hooks>(ctx: &AppContext) {
let mut routes = list_endpoints::<H>(ctx);
routes.sort_by(|a, b| a.uri.cmp(&b.uri));
for router in routes {
println!("{router}");
}
}
fn create_root_span(environment: &Environment) -> tracing::Span {
tracing::span!(tracing::Level::DEBUG, "app", environment = %environment)
}