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
716
717
use anyhow::Context;
use clap::{Parser, Subcommand};
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
mod add;
mod admin_client;
mod build;
mod config_template;
mod convert;
mod deploy;
mod dev;
mod dev_placeholder;
mod dev_registry;
mod generate;
mod kill;
mod list;
mod optimize;
mod process_scan;
mod release;
mod release_slots;
mod restart;
mod run;
mod scaffold;
mod service;
mod terminal_title;
mod upgrade;
mod wizard;
#[derive(Parser)]
#[command(
name = "xr",
version = upgrade::VERSION,
about = "The Larust command-line interface"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
// ---- Scaffold a project ----
/// Create a new Larust application
///
/// Omit `path` to walk through an interactive wizard (project
/// directory, authentication, optional features) instead of
/// specifying every choice up front.
New {
/// Directory to create the application in. If omitted, an
/// interactive wizard asks for this (and every other option
/// below) instead - see `xr new`'s own top-level help.
path: Option<String>,
/// Also scaffold session-based authentication (User model,
/// register/login/logout, auth/guest-protected routes). Ignored
/// when `path` is omitted - the wizard asks this itself.
#[arg(long)]
auth: bool,
/// Also scaffold Tauri desktop-app support (`src-tauri/`,
/// `DEPLOY_TYPE=app`) - opt-in, since it adds real dependency
/// weight most web-only apps don't want. Didn't scaffold it up
/// front? `xr add tauri` retrofits it onto an existing app anytime.
/// Ignored when `path` is omitted - the wizard asks this itself.
#[arg(long)]
tauri: bool,
/// Comma-separated optional `larust-support` features to enable
/// (db, permissions, reverb, sanctum, shield, sitemap, socialite -
/// see `larust-support`'s own `Cargo.toml` `[features]` table).
/// Ignored when `path` is omitted - the wizard asks this itself.
#[arg(long, value_delimiter = ',')]
features: Vec<String>,
/// Path to a Larust workspace checkout (a clone of the
/// `RustLaravel` repo) to resolve the framework's - still
/// unpublished - path dependencies from. Only needed when the new
/// app's directory isn't itself inside that checkout; by default
/// `xr new` looks for one by walking up from the target directory.
#[arg(long)]
workspace: Option<String>,
},
/// Retrofit an optional feature onto an already-scaffolded app
///
/// Run from inside the app's own directory. Currently supports:
/// `tauri` (scaffolds `src-tauri/` the same way `xr new --tauri` would,
/// without re-scaffolding anything else).
Add {
/// The feature to add (currently: `tauri`).
feature: String,
},
/// Convert an existing Laravel application into a new Larust
/// application
///
/// Phase 1: composer package report, routes, migrations, and config
/// only (fully mechanical; business logic is never auto-translated).
/// See `docs/ARCHITECTURE.md`'s "Laravel conversion" section.
///
/// Two mutually exclusive modes: `xr convert <path> --out <dir>`
/// converts a whole Laravel app into a fresh, empty `<dir>` (refuses
/// to run if `<dir>` already exists and isn't empty - there is no
/// incremental/merge support at all, so re-running this on a project
/// you've already converted and hand-edited needs a new empty
/// directory, not the same one). `xr convert --file <blade-path>
/// --destination <xr-path>` instead re-converts one `.blade.php`
/// template in isolation, overwriting `<xr-path>` if it already
/// exists - for pulling a single template through a converter fix (or
/// a template you edited on the Laravel side) without redoing the
/// whole project.
Convert {
/// Path to the existing Laravel application. Required for a
/// whole-project conversion; omit when using --file/--destination.
path: Option<String>,
/// Directory to create the converted Larust application in.
/// Required for a whole-project conversion; omit when using
/// --file/--destination.
#[arg(long)]
out: Option<String>,
/// Convert a single `.blade.php` template instead of a whole
/// project - pass together with --destination, and nothing else.
#[arg(long)]
file: Option<String>,
/// Where to write the converted `.blade.xr` file - pass together
/// with --file. Overwrites an existing file at this path.
#[arg(long)]
destination: Option<String>,
/// Path to a Larust workspace checkout to resolve the framework's
/// crates from as local path dependencies, instead of the default
/// `version = "..."` dependencies against the published crates -
/// for converting against local, possibly-unpublished framework
/// changes. Only meaningful for a whole-project conversion
/// (`<path> --out <dir>`); ignored with `--file`/`--destination`.
#[arg(long)]
workspace: Option<String>,
},
// ---- Generate code ----
/// Create a new empty migration file
#[command(name = "make:migration")]
MakeMigration {
/// Migration name, e.g. `create_posts_table`
name: String,
},
/// Create a new controller
#[command(name = "make:controller")]
MakeController {
/// Controller name, e.g. `PostController`
name: String,
/// Generate the 7 RESTful resource methods (index/create/store/show/edit/update/destroy)
#[arg(long)]
resource: bool,
},
/// Create a new model
#[command(name = "make:model")]
MakeModel {
/// Model name, e.g. `Post`
name: String,
/// Also generate a matching `CREATE TABLE` migration
#[arg(long)]
migration: bool,
},
/// Create a new form request
#[command(name = "make:request")]
MakeRequest {
/// Request name, e.g. `StorePostRequest`
name: String,
},
/// Create a new middleware
#[command(name = "make:middleware")]
MakeMiddleware {
/// Middleware name, e.g. `EnsureSubscribed`
name: String,
},
/// Create a new named CLI command (`xr <name>` runs it, once
/// registered in `routes/console.rs`)
#[command(name = "make:command")]
// The name genuinely belongs here - `make:command`, matching every
// sibling `Make*` variant's own `make:*` naming - it's only a clippy
// false positive because this enum's own name happens to be
// `Command`, an unrelated coincidence (it names *this* CLI's
// subcommand set, not `larust_support::console::Command`).
#[allow(clippy::enum_variant_names)]
MakeCommand {
/// Command struct name, e.g. `ReportPosts`
name: String,
},
/// Create a new model factory
#[command(name = "make:factory")]
MakeFactory {
/// Model name the factory builds, e.g. `Post`
name: String,
},
/// Create a new authorization policy for a model
#[command(name = "make:policy")]
MakePolicy {
/// Model name to write ability checks for, e.g. `Post`
name: String,
/// The `Authenticatable` type the checks take
#[arg(long, default_value = "User")]
user: String,
},
// ---- Database ----
/// Run pending database migrations
Migrate,
/// Drop every table and reapply every migration from scratch
#[command(name = "migrate:fresh")]
MigrateFresh {
/// Also run `database/seeders` afterward
#[arg(long)]
seed: bool,
},
/// Run `database/seeders` against the current database
#[command(name = "db:seed")]
DbSeed,
/// List every key in the app's embedded key-value store (requires the
/// `db` optional feature)
#[command(name = "db:list")]
DbList,
/// Print the value stored under `key` in the embedded key-value store
#[command(name = "db:get")]
DbGet {
/// The key to look up
key: String,
},
/// Set `key` to `value` in the embedded key-value store
///
/// `value` is parsed as JSON when possible (numbers, booleans, quoted
/// strings), otherwise stored as a plain string
#[command(name = "db:put")]
DbPut {
/// The key to set
key: String,
/// The value to store
value: String,
},
/// Remove `key` from the embedded key-value store
#[command(name = "db:forget")]
DbForget {
/// The key to remove
key: String,
},
// ---- Background workers ----
/// Start a worker that claims and processes queued jobs until stopped
#[command(name = "queue:work")]
QueueWork,
/// Start a worker that runs due scheduled tasks once a second until
/// stopped
///
/// Not safe to run as more than one process against the same app (see
/// `docs/ARCHITECTURE.md`'s "Scheduler" section)
#[command(name = "schedule:work")]
ScheduleWork,
// ---- Develop, build, run, and inspect the app ----
/// Watch the app, rebuild and restart it on change, and auto-refresh
/// any open browser tab once the new build is back up
Dev {
/// Port to serve on - overrides `.env`'s `APP_PORT` (and its own
/// `34187` fallback) for this run only, without editing `.env`.
#[arg(long)]
port: Option<u16>,
/// Maximum-verbosity mode for this session only: `APP_DEBUG=true`
/// (full error detail pages), `LOG_LEVEL=trace` (the most verbose
/// logging tier), and `RUST_BACKTRACE=full` (full panic
/// backtraces) - overrides `.env` without editing it, the same way
/// `--port` overrides `APP_PORT`. Never use this for a real
/// deploy - see `docs/the-basics/error-handling.md`'s own
/// `APP_DEBUG` warning.
#[arg(long)]
debug: bool,
},
/// Build (or rebuild) this app's frontend assets standalone
///
/// `npm run build`, the same step `xr deploy` runs before publishing a
/// release, without cutting a whole release. A silent no-op if the app
/// has no `node_modules/` (no frontend asset pipeline).
Build {
/// Also clear Vite's own dependency pre-bundling cache
/// (`node_modules/.vite/`) and the build output directory
/// (`public/build/`) before rebuilding - for when the build seems
/// stuck on something stale that an ordinary rebuild doesn't fix,
/// the equivalent of `php artisan cache:clear` for this one kind
/// of staleness.
#[arg(long)]
fresh: bool,
},
/// Prebuild this app for production without publishing a release
///
/// Builds frontend assets when present, then creates Cargo's optimized
/// release binary. Rust already compiles routes, templates, and framework
/// code ahead of time, so this is Larust's safe equivalent of Laravel's
/// optimize command rather than a mutable runtime code cache.
Optimize,
/// Build and publish a release, according to `DEPLOY_TYPE`
///
/// `.env`, `"web"` by default. `"web"`: `cargo build --release`, then
/// the same `storage/releases/` pointer-file convention `xr dev` uses
/// internally, then a live restart handoff against an already-running
/// process, same as `xr restart`. `"app"`: a native Tauri desktop
/// bundle (`cargo tauri build` from `src-tauri/` - scaffold that first
/// with `xr new --tauri`/`xr add tauri`).
Deploy {
/// If nothing is currently running to hand off to (the very first
/// deploy of an app), start the freshly published release in the
/// background instead of just publishing it and waiting for a
/// manual first start. No effect when the app is already running
/// (that case always hot-swaps, with or without this flag) or on
/// `DEPLOY_TYPE=app` builds (a desktop bundle isn't something `xr
/// deploy` starts for you). Ignored if `--service` is also given -
/// see that flag.
#[arg(long)]
run: bool,
/// Like `--run`, but starts it via `xr service:install` (a real
/// systemd unit, `Restart=on-failure`, enabled at boot) instead of
/// a bare detached process - crash- and reboot-safe from the very
/// first deploy, no separate `xr service:install` step needed
/// afterward. Linux only. Wins over `--run` if both are given -
/// starting the app both ways at once would just race for the
/// same port. Same "no effect once something is already running,
/// or on DEPLOY_TYPE=app" scope as `--run`.
#[arg(long)]
service: bool,
/// Remove Cargo release build artifacts after a successful web deploy.
/// Published releases and development caches are preserved; the next
/// deploy rebuilds dependencies. Not supported for DEPLOY_TYPE=app.
#[arg(long, conflicts_with = "clean_all")]
clean: bool,
/// Remove all Cargo build artifacts after a successful web deploy,
/// including debug dependencies. Published releases are preserved.
/// The next development build and deploy both rebuild dependencies.
#[arg(long, conflicts_with = "clean")]
clean_all: bool,
},
/// Start the currently-published release if nothing is already
/// listening on the app's own port
///
/// Resolves `storage/releases/current`, written by `xr deploy` - a
/// no-op, not an error, if something's already listening. For an `xr
/// deploy` run without `--run`/`--service` (publish and start as
/// separate, independently-auditable steps), or for starting a release
/// back up after it was stopped (`xr kill`, a crash with no `xr
/// service:install` in place) with no rebuild or republish involved.
Run,
/// Ask a running app to perform a zero-downtime restart handoff
///
/// See `GracefulShutdown { restart_channel: true, .. }` - a new
/// process takes over the listening socket before the old one begins
/// draining, so in-flight requests finish and no new connection is
/// ever refused
Restart,
/// Stop the `xr dev` session tied to the current directory
///
/// Stops whatever server it's currently watching over too - or, with
/// `--id`, a specific session from `xr list` regardless of which
/// directory this runs from - or, with `--all`, every other running
/// `xr` process on the machine, tracked by `xr list` or not (the
/// fallback for when something is holding the installed `xr` binary
/// itself open - e.g. blocking `xr upgrade` - and `xr list` shows
/// nothing)
Kill {
/// Stop the session with this id (its own PID, as shown by `xr
/// list`) instead of resolving the current directory's own
/// `APP_NAME`
#[arg(long)]
id: Option<u32>,
/// Stop every other running `xr` process on this machine, not
/// just the one tied to the current directory or `--id` -
/// including any `xr` invocation `xr list` never learned about
#[arg(long)]
all: bool,
},
/// List every `xr dev` session currently running on this machine
List,
/// List all registered routes
#[command(name = "route:list")]
RouteList,
// ---- Production service (systemd) ----
/// Register a deployed app with systemd so it survives a crash and
/// starts on boot
///
/// `Restart=on-failure`, Linux only. Run on the machine actually
/// serving the app, after at least one `xr deploy`. Ordinary `xr
/// deploy`/`xr restart` keep working exactly as before afterward - see
/// `service.rs`'s own doc comment for why this uses `on-failure`, not
/// `always`.
#[command(name = "service:install")]
ServiceInstall {
/// Register a minimal deployment directly, pointing systemd at
/// this binary path instead of requiring `storage/releases/current`
/// (which `xr deploy` would otherwise manage) - for when the only
/// things present are the compiled binary and a `.env` file. Sets
/// `LARUST_APP_ROOT` in the generated unit so the binary still
/// finds its own `.env`/`storage`/`database` relative to the
/// current directory even though it was likely built elsewhere.
#[arg(long, value_name = "PATH")]
simple: Option<PathBuf>,
},
/// Undo `xr service:install` - stops and disables the systemd unit and
/// removes its file
#[command(name = "service:uninstall")]
ServiceUninstall,
// ---- Maintenance ----
/// Prepare a release: bump this app's own Cargo.toml version, build
/// release notes from the commits since the last tag, and create a
/// local, annotated git tag - never pushes anything
///
/// A thin front-end over plain `git`, the same shape `audit`/`update`
/// already use over `cargo audit`/`cargo update`. Prints the exact
/// `git push` command to run yourself when ready, plus a reminder
/// that `xr deploy` on the server is a separate next step.
Release {
/// Bump the major version (X.0.0) before tagging
#[arg(long)]
major: bool,
/// Bump the minor version (x.Y.0) before tagging
#[arg(long)]
minor: bool,
/// Bump the patch version (x.y.Z) before tagging
#[arg(long)]
patch: bool,
},
/// Check dependencies for known security advisories (composer audit)
Audit,
/// Update the current app's dependencies within their declared
/// version constraints
///
/// `composer update` - not `xr` itself; see `upgrade` for that.
Update,
/// Upgrade the `xr` CLI itself (not the current app - see `update`)
///
/// Default: reinstalls `larust-cli` from crates.io (`cargo install
/// larust-cli`), matching an `xr` installed that way in the first
/// place. `--legacy` instead pulls and reinstalls from the checkout
/// `xr` was built from - checking for new commits on the current
/// branch's upstream first, fast-forwarding only, and doing nothing
/// if already up to date - for an `xr` installed via `install.sh`/
/// `install.ps1`/`cargo install --path` from a real checkout.
Upgrade {
/// Skip the "is there anything new" check and reinstall
/// regardless - the "repair/reinstall now" mode. Without
/// `--legacy`, forwards to `cargo install larust-cli --force`;
/// with it, reinstalls from the checkout's current state the way
/// re-running install.sh/install.ps1 would.
#[arg(long)]
force: bool,
/// Use the checkout-based upgrade path instead of the crates.io
/// default - for an `xr` built from a real Larust checkout
/// (`install.sh`/`install.ps1`/`cargo install --path`), not
/// installed via `cargo install larust-cli`.
#[arg(long)]
legacy: bool,
/// Stop every other running `xr` process first (same as `xr kill
/// --all`) if one is found holding the installed binary open -
/// otherwise `cargo install`'s own last step (replacing that
/// binary) fails outright with "Access is denied" on Windows,
/// with no way to tell from `xr list` alone what's holding it
#[arg(long)]
stop_running: bool,
},
/// Forward an app-defined command to the generated Larust application.
///
/// This is what makes `xr report:posts` and `xr command:list` work:
/// framework-owned commands above stay explicit, while commands the app
/// registers in `routes/console.rs` are resolved by the app itself.
#[command(external_subcommand)]
External(Vec<OsString>),
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
match cli.command {
Command::New {
path,
auth,
tauri,
features,
workspace,
} => {
let (path, auth, tauri, features, workspace) = match path {
Some(path) => {
wizard::validate_feature_names(&features)?;
(path, auth, tauri, features, workspace)
}
// No path given at all - the wizard collects every choice
// itself; `--auth`/`--tauri`/`--features` are ignored in
// this branch (see `Command::New`'s own doc comments on
// those fields). `workspace` isn't asked by the wizard at
// all - it's carried through unchanged from whatever
// `--workspace` was (or wasn't) given alongside the bare
// `xr new` invocation.
None => {
let answers = wizard::run()?;
(
answers.path,
answers.auth,
answers.tauri,
answers.features,
workspace,
)
}
};
let feature_refs: Vec<&str> = features.iter().map(String::as_str).collect();
match workspace {
Some(workspace) => scaffold::new_app_from_workspace(
&path,
auth,
Path::new(&workspace),
&feature_refs,
tauri,
)?,
None => scaffold::new_app_with_features(&path, auth, &feature_refs, tauri)?,
}
}
Command::Add { feature } => add::run(&feature)?,
Command::Convert {
path,
out,
file,
destination,
workspace,
} => match (path, out, file, destination) {
(Some(path), Some(out), None, None) => {
convert::run(&path, &out, workspace.as_deref().map(Path::new))?
}
(None, None, Some(file), Some(destination)) => {
convert::run_single_file(&file, &destination)?
}
// Every other combination is some kind of missing-or-mixed
// flag mistake - named specifically here (rather than one
// generic catch-all message) so the error actually matches
// what the user typed, instead of always suggesting "you
// mixed both modes" even when the real problem is just a
// forgotten `--out`.
(Some(_), None, None, None) => {
anyhow::bail!("a whole-project conversion also needs --out <dir>")
}
(Some(_), _, Some(_), _) | (Some(_), _, _, Some(_)) => anyhow::bail!(
"pass either `<path> --out <dir>` for a whole-project conversion, or \
`--file <blade-path> --destination <xr-path>` for a single template - not a \
mix of both"
),
(None, Some(_), _, _) => {
anyhow::bail!("--out was given but no <path> to convert - pass one, or drop --out")
}
(None, None, Some(_), None) => {
anyhow::bail!("--file was given but no --destination to write the result to")
}
(None, None, None, Some(_)) => {
anyhow::bail!("--destination was given but no --file to convert")
}
(None, None, None, None) => anyhow::bail!(
"pass either `<path> --out <dir>` for a whole-project conversion, or \
`--file <blade-path> --destination <xr-path>` for a single template"
),
},
Command::MakeMigration { name } => generate::make_migration(&name)?,
Command::MakeController { name, resource } => generate::make_controller(&name, resource)?,
Command::MakeModel { name, migration } => generate::make_model(&name, migration)?,
Command::MakeRequest { name } => generate::make_request(&name)?,
Command::MakeMiddleware { name } => generate::make_middleware(&name)?,
Command::MakeCommand { name } => generate::make_command(&name)?,
Command::MakeFactory { name } => generate::make_factory(&name)?,
Command::MakePolicy { name, user } => generate::make_policy(&name, &user)?,
Command::Migrate => run_app_subcommand("migrate", &[])?,
Command::MigrateFresh { seed } => {
run_app_subcommand("migrate:fresh", if seed { &["--seed"] } else { &[] })?
}
Command::DbSeed => run_app_subcommand("db:seed", &[])?,
Command::DbList => run_app_subcommand("db:list", &[])?,
Command::DbGet { key } => run_app_subcommand("db:get", &[&key])?,
Command::DbPut { key, value } => run_app_subcommand("db:put", &[&key, &value])?,
Command::DbForget { key } => run_app_subcommand("db:forget", &[&key])?,
Command::QueueWork => run_app_subcommand("queue:work", &[])?,
Command::ScheduleWork => run_app_subcommand("schedule:work", &[])?,
Command::Dev { port, debug } => dev::run(port, debug)?,
Command::Build { fresh } => build::run(fresh)?,
Command::Optimize => optimize::run()?,
Command::Deploy {
run,
service,
clean,
clean_all,
} => deploy::run(run, service, clean, clean_all)?,
Command::Run => run::run()?,
Command::Restart => restart::run()?,
Command::Kill { id, all } => kill::run(id, all)?,
Command::List => list::run(),
Command::RouteList => run_app_subcommand("route:list", &[])?,
Command::ServiceInstall { simple } => service::install(simple)?,
Command::ServiceUninstall => service::uninstall()?,
Command::Release {
major,
minor,
patch,
} => {
let bump = match (major, minor, patch) {
(true, false, false) => Some(release::Bump::Major),
(false, true, false) => Some(release::Bump::Minor),
(false, false, true) => Some(release::Bump::Patch),
(false, false, false) => None,
_ => anyhow::bail!("pass at most one of --major/--minor/--patch"),
};
release::run(bump)?;
}
Command::Audit => audit()?,
Command::Update => update()?,
Command::Upgrade {
force,
legacy,
stop_running,
} => upgrade::run(force, legacy, stop_running)?,
Command::External(parts) => {
let (name, args) = parts
.split_first()
.context("an app-defined command needs a command name")?;
let name = name.to_string_lossy();
let args: Vec<_> = args.iter().map(|arg| arg.to_string_lossy()).collect();
let args: Vec<_> = args.iter().map(|arg| arg.as_ref()).collect();
run_app_subcommand(&name, &args)?;
}
}
Ok(())
}
/// Runs from within a Larust app's own directory (matching Laravel's
/// `artisan` convention of operating on the current project) by shelling
/// into the app's own binary - routes and database connections are wired
/// up inside the app itself, so `xr` asks the app to perform the command
/// rather than reimplementing it externally. `args` is forwarded after
/// `subcommand` (empty for every subcommand except `db:get`/`db:put`/
/// `db:forget`, which need a key/value the generated `main.rs` reads via
/// `std::env::args().nth(2)`/`nth(3)`).
fn run_app_subcommand(subcommand: &str, args: &[&str]) -> anyhow::Result<()> {
let status = std::process::Command::new("cargo")
.args(["run", "--quiet", "--", subcommand])
.args(args)
.status()
.with_context(|| {
format!("failed to run `cargo run -- {subcommand}` in the current directory")
})?;
anyhow::ensure!(
status.success(),
"{subcommand} exited with a non-zero status"
);
Ok(())
}
/// Thin wrapper over `cargo audit` (RustSec advisory database) - Laravel
/// devs expect a security audit to be one command away (`composer audit`),
/// not a separate tool they have to discover. `cargo-audit` isn't part of
/// stock cargo, so this fails with an install hint rather than a bare
/// "no such command" if it's missing.
fn audit() -> anyhow::Result<()> {
let lockfile = find_cargo_lock()?;
let status = std::process::Command::new("cargo")
.args(["audit", "--file"])
.arg(&lockfile)
.status()
.context("failed to run `cargo audit`")?;
if !status.success() {
eprintln!("\nIf cargo-audit isn't installed yet: cargo install cargo-audit");
anyhow::bail!("cargo audit exited with a non-zero status");
}
Ok(())
}
/// Unlike `cargo build`/`cargo update`, `cargo audit` doesn't walk up to
/// find a workspace's `Cargo.lock` on its own - it only looks in the
/// current directory. Walk up ourselves and pass it `--file` explicitly,
/// so `xr audit` works the same whether run from a workspace member
/// directory (like `examples/blog` in this repo) or a standalone app root.
fn find_cargo_lock() -> anyhow::Result<PathBuf> {
let mut dir = std::env::current_dir().context("reading current directory")?;
loop {
let candidate = dir.join("Cargo.lock");
if candidate.exists() {
return Ok(candidate);
}
if !dir.pop() {
anyhow::bail!(
"no Cargo.lock found in this directory or any parent (run `cargo build` first)"
);
}
}
}
/// Thin wrapper over `cargo update` (Laravel's `composer update`) - updates
/// `Cargo.lock` within each dependency's declared version constraints.
/// Bumping a constraint itself (e.g. axum "0.7" -> "0.8") is a deliberate
/// edit to Cargo.toml, not something this command does automatically.
fn update() -> anyhow::Result<()> {
let status = std::process::Command::new("cargo")
.arg("update")
.status()
.context("failed to run `cargo update`")?;
anyhow::ensure!(
status.success(),
"cargo update exited with a non-zero status"
);
Ok(())
}