nest-rs-cli 1.1.0

Scaffolding CLI for NestRS — new projects, feature generators, and project health checks.
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

fn write_fake_workspace(root: &Path) {
    fs::create_dir_all(root.join("crates/features/src")).unwrap();
    fs::create_dir_all(root.join("apps")).unwrap();
    fs::write(
        root.join("Cargo.toml"),
        r#"
[workspace]
members = ["crates/*", "apps/*"]

[workspace.package]
version = "0.1.0"
"#,
    )
    .unwrap();
    fs::write(
        root.join("crates/features/src/lib.rs"),
        "pub mod users;\n\npub use users::UsersModule;\n",
    )
    .unwrap();
    fs::write(
        root.join("crates/features/Cargo.toml"),
        "[package]\nname = \"features\"\n\n[dependencies]\nnest-rs-core.workspace = true\n",
    )
    .unwrap();
    fs::write(root.join(".env"), "NESTRS_DATABASE__URL=postgres://x\n").unwrap();
}

/// An app crate inside the fake workspace, carrying the
/// `#[module(imports = [ … ])]` shape the auto-wiring anchors on.
fn write_fake_app(root: &Path, name: &str) -> PathBuf {
    let app = root.join("apps").join(name);
    fs::create_dir_all(app.join("src")).unwrap();
    fs::write(
        app.join("Cargo.toml"),
        format!("[package]\nname = \"{name}\"\n\n[dependencies]\nnest-rs-core.workspace = true\n"),
    )
    .unwrap();
    fs::write(
        app.join("src/module.rs"),
        "use nest_rs_core::module;\nuse nest_rs_http::{HttpConfig, HttpModule};\n\n\
         #[module(\n    imports = [\n        \
         HttpModule::for_root(HttpConfig { port: 3000, ..Default::default() }),\n    ],\n)]\n\
         pub struct AppModule;\n",
    )
    .unwrap();
    app
}

/// Run `nestrs <args...>` with cwd at `dir`, asserting success.
fn run_ok(dir: &Path, args: &[&str]) -> String {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(args)
        .current_dir(dir)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "args {args:?} stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).into_owned()
}

#[test]
fn new_standalone_hello_template() {
    let dir = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "demo-api", "--standalone"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let app = dir.path().join("demo-api");
    assert!(app.join("src/main.rs").is_file());
    assert!(app.join("src/lib.rs").is_file());
    assert!(app.join("src/controller.rs").is_file());
    // The scaffolded smoke test needs no live infra ⇒ `integration` suite.
    assert!(app.join("tests/integration/main.rs").is_file());
    // …and an empty `e2e` suite beside it: the test recipes filter on
    // `binary(e2e)`, which nextest refuses to parse when nothing matches.
    assert!(app.join("tests/e2e/main.rs").is_file());
    assert!(app.join("Cargo.toml").is_file());
    assert!(app.join("Dockerfile").is_file());
    assert!(app.join(".dockerignore").is_file());
    assert!(app.join("rust-toolchain.toml").is_file());
    assert!(app.join(".env").is_file());
    assert!(app.join(".env.development").is_file());
    let dev_env = fs::read_to_string(app.join(".env.development")).unwrap();
    assert!(dev_env.contains("NESTRS_LOG=debug"));
    assert!(app.join(".env.example").is_file());

    let main_rs = fs::read_to_string(app.join("src/main.rs")).unwrap();
    // Baseline logging is nest-rs-core's job now — a scaffold must not pull
    // the observability stack; it stays a documented opt-in.
    assert!(!main_rs.contains("OpenTelemetry"));
    assert!(main_rs.contains("Environment::init"));

    let module_rs = fs::read_to_string(app.join("src/module.rs")).unwrap();
    assert!(!module_rs.contains("OpenTelemetryModule"));

    let cargo = fs::read_to_string(app.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("[workspace]"));
    assert!(cargo.contains("nest-rs-guards"));
    assert!(cargo.contains("nest-rs-interceptors"));
    assert!(!cargo.contains("nest-rs-opentelemetry"));
    assert!(app.join(".gitignore").is_file());
    assert!(app.join("Justfile").is_file());
    let justfile = fs::read_to_string(app.join("Justfile")).unwrap();
    assert!(justfile.contains("build:"));
    assert!(justfile.contains("cargo build --release"));
    assert!(justfile.contains("mod test"));
    // The db verbs drive the workspace's `migrations`/`seed` crates, which a
    // single crate has nowhere to put — so neither the module nor the file.
    assert!(!justfile.contains("mod db"));
    assert!(!app.join("db.just").exists());
    assert!(app.join("test.just").is_file());
    let test_just = fs::read_to_string(app.join("test.just")).unwrap();
    assert!(test_just.contains("unit:"));
    assert!(test_just.contains("e2e:"));
    assert!(test_just.contains("doc:"));
    assert!(test_just.contains("cargo test --doc"));
}

#[test]
fn new_workspace_greenfield() {
    let dir = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "acme"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let root = dir.path().join("acme");
    assert!(root.join("Cargo.toml").is_file());
    assert!(
        root.join("crates/features/src/hello/http/controller.rs")
            .is_file()
    );
    // The default app and demo feature are both named `hello`.
    assert!(root.join("apps/hello/src/module.rs").is_file());
    assert!(!root.join("apps/hello/src/controller.rs").exists());
    // The scaffolded smoke test needs no live infra ⇒ `integration` suite,
    // with an empty `e2e` suite beside it so the nextest filtersets resolve.
    assert!(root.join("apps/hello/tests/integration/main.rs").is_file());
    assert!(root.join("apps/hello/tests/e2e/main.rs").is_file());
    let smoke = fs::read_to_string(root.join("apps/hello/tests/integration/main.rs")).unwrap();
    assert!(
        !smoke.contains("with_test_telemetry"),
        "that builder method is behind an optional feature the scaffold does not enable"
    );
    // The db verbs name these two crates in every recipe.
    assert!(root.join("crates/migrations/src/bin/migrate.rs").is_file());
    assert!(root.join("crates/migrations/src/migrator.rs").is_file());
    assert!(root.join("crates/seed/src/main.rs").is_file());
    // No Dockerfile ships in workspace mode, so nothing to ignore for.
    assert!(!root.join(".dockerignore").exists());
    assert!(root.join("Justfile").is_file());
    let justfile = fs::read_to_string(root.join("Justfile")).unwrap();
    assert!(justfile.contains("dev app=\"hello\""));
    // `build --all` is a conditional on the single `build` recipe, not a separate recipe.
    assert!(!justfile.contains("build-all"));
    assert!(justfile.contains(r#"if app == "--all""#));
    assert!(justfile.contains("mod test"));
    assert!(justfile.contains("mod db"));

    let test_just = fs::read_to_string(root.join("test.just")).unwrap();
    assert!(test_just.contains("unit:"));
    assert!(test_just.contains("e2e:"));
    assert!(test_just.contains("cargo test --workspace --doc"));
    let db_just = fs::read_to_string(root.join("db.just")).unwrap();
    assert!(db_just.contains("up:"));
    assert!(db_just.contains("reset: fresh seed"));

    let module = fs::read_to_string(root.join("apps/hello/src/module.rs")).unwrap();
    assert!(module.contains("HelloHttpModule"));
    assert!(module.contains("features::hello"));
    assert!(module.contains("port: 3000"));

    let env = fs::read_to_string(root.join(".env")).unwrap();
    assert!(!env.contains("NESTRS_HTTP__PORT"));

    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("members = [\"crates/*\", \"apps/*\"]"));
}

#[test]
fn new_app_inside_nestrs_workspace() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "demo-api"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let app = dir.path().join("apps/demo-api");
    assert!(app.join("src/module.rs").is_file());
    assert!(app.join("src/main.rs").is_file());
    // Logic never lands in an app crate — the greeting is a feature.
    assert!(!app.join("src/controller.rs").exists());

    let module = fs::read_to_string(app.join("src/module.rs")).unwrap();
    assert!(module.contains("HttpConfig { port: 3000"));
    assert!(!module.contains("for_root(None)"));

    // The norm: an app added to a workspace gets its own `hello` feature, so it
    // answers on `/` the first time it runs rather than 404ing.
    let feature = dir.path().join("crates/features/src/demo_api");
    assert!(feature.join("service.rs").is_file());
    let controller = fs::read_to_string(feature.join("http/controller.rs")).unwrap();
    assert!(
        controller.contains(r#"#[controller(path = "/")]"#) && controller.contains("#[public]"),
        "the scaffolded app must mount a public GET /: {controller}"
    );
    assert!(
        module.contains("DemoApiHttpModule") && module.contains("features::demo_api"),
        "and the app must import it: {module}"
    );

    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(lib.contains("pub mod demo_api;"), "features lib.rs: {lib}");
    // The pre-existing feature declaration survives the edit.
    assert!(lib.contains("pub mod users;"), "features lib.rs: {lib}");

    // A smoke test ships with the greeting it asserts.
    assert!(app.join("tests/integration/main.rs").is_file());
}

/// `nestrs new posts` where a `posts` feature already exists would clobber
/// product code. Refuse instead — the app name is free to change.
#[test]
fn new_app_refuses_to_reuse_an_existing_feature_name() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    fs::create_dir_all(dir.path().join("crates/features/src/users")).unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "users"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(!output.status.success());
    assert!(!dir.path().join("apps/users").exists());
}

#[test]
fn new_app_picks_next_http_port() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    fs::create_dir_all(dir.path().join("apps/auth/src")).unwrap();
    fs::write(
        dir.path().join("apps/auth/src/module.rs"),
        "HttpModule::for_root(HttpConfig { port: 3001, ..Default::default() })",
    )
    .unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "blog"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let module = fs::read_to_string(dir.path().join("apps/blog/src/module.rs")).unwrap();
    assert!(module.contains("HttpConfig { port: 3002"));
}

#[test]
fn new_app_inside_workspace_already_exists() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    fs::create_dir_all(dir.path().join("apps/blog")).unwrap();

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "blog"])
        .current_dir(dir.path())
        .output()
        .unwrap();

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("already exists"));
    assert!(stderr.contains("blog"));
}

#[test]
fn new_workspace_app_scaffold() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["new", "blog", "-o"])
        .arg(dir.path())
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let app = dir.path().join("apps/blog");
    assert!(app.join("src/module.rs").is_file());
    assert!(app.join("src/lib.rs").is_file());
    assert!(!app.join("src/controller.rs").exists());
    assert!(dir.path().join(".env").is_file());
    assert!(dir.path().join(".env.development").is_file());
    assert!(dir.path().join("Justfile").is_file());
    assert!(dir.path().join(".gitignore").is_file());
    assert!(dir.path().join("compose.yml").is_file());

    // The committed `.env` points at the compose services (T26): the DB URL is
    // active so `nestrs run db up` works out of the box; the port stays code.
    let env = fs::read_to_string(dir.path().join(".env")).unwrap();
    assert!(!env.contains("NESTRS_HTTP__PORT"));
    assert!(env.contains("NESTRS_DATABASE__URL=postgres://"));

    let module = fs::read_to_string(app.join("src/module.rs")).unwrap();
    assert!(module.contains("HttpConfig { port: 3000"));
    assert!(!module.contains("OpenTelemetryModule"));
}

#[test]
fn generate_feature_creates_port_and_wires_lib() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "feature", "posts", "-p", dir.path().to_str().unwrap()],
    );

    let feature = dir.path().join("crates/features/src/posts");
    assert!(feature.join("mod.rs").is_file());
    assert!(feature.join("module.rs").is_file());
    assert!(feature.join("service.rs").is_file());
    // no transport yet
    assert!(!feature.join("http").exists());

    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(lib.contains("pub mod posts;"));
}

#[test]
fn generate_resource_creates_crud_slice_and_deps() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "resource", "posts", "-p", dir.path().to_str().unwrap()],
    );

    let feature = dir.path().join("crates/features/src/posts");
    assert!(feature.join("entity.rs").is_file());
    assert!(feature.join("service.rs").is_file());
    assert!(feature.join("http/controller.rs").is_file());

    let entity = fs::read_to_string(feature.join("entity.rs")).unwrap();
    assert!(entity.contains("#[expose(name = \"Post\""));
    assert!(entity.contains("table_name = \"post\""));

    // Dependencies spliced into both manifests. `schemars` and `nest-rs-authz`
    // are what `#[expose]`/`#[crud]` expand to, so their absence would only
    // surface as macro-expansion errors on the first `cargo check`.
    let root_cargo = fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
    assert!(root_cargo.contains("nest-rs-seaorm"));
    assert!(root_cargo.contains("schemars"));
    assert!(root_cargo.contains("nest-rs-authz"));
    assert!(
        root_cargo.contains("sea-orm = { version = \"2.0\""),
        "the generated pin tracks the released sea-orm, not a release candidate: {root_cargo}"
    );
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    assert!(features_cargo.contains("nest-rs-seaorm"));
    assert!(features_cargo.contains("schemars"));
    assert!(features_cargo.contains("nest-rs-authz"));

    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(lib.contains("pub mod posts;"));
}

#[test]
fn generate_resource_emits_the_guarded_form_and_bootstraps_auth() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "resource", "posts", "-p", dir.path().to_str().unwrap()],
    );

    let feature = dir.path().join("crates/features/src/posts");
    let controller = fs::read_to_string(feature.join("http/controller.rs")).unwrap();
    assert!(
        controller.contains("#[use_guards(AuthnGuard, AuthzGuard)]"),
        "a DB-backed controller serves nothing without an ability guard: {controller}"
    );
    assert!(
        controller.contains("#[crud(") && controller.contains("entity = PostEntity"),
        "the resource controller uses the #[crud] form: {controller}"
    );

    let module = fs::read_to_string(feature.join("http/module.rs")).unwrap();
    assert!(
        module.contains("AuthzHttpModule"),
        "the http module imports AuthzHttpModule: {module}"
    );

    // The guards it names have to exist — so the adapter came with it.
    let src = dir.path().join("crates/features/src");
    assert!(src.join("authn/strategy.rs").is_file());
    assert!(src.join("authz/ability.rs").is_file());
    assert!(src.join("authz/http/guard.rs").is_file());
    assert!(src.join("identity/claims.rs").is_file());

    let env = fs::read_to_string(dir.path().join(".env")).unwrap();
    assert!(env.contains("NESTRS_AUTHN__SECRET"));
}

#[test]
fn generate_auth_scaffolds_the_adapter_once() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &["g", "auth", "-p", dir.path().to_str().unwrap()],
    );

    let src = dir.path().join("crates/features/src");
    let ability = fs::read_to_string(src.join("authz/ability.rs")).unwrap();
    assert!(ability.contains("impl AbilityFactory for AppAbility"));
    // Both branches are scaffolded empty: the authenticated policy and the
    // visitor one a `#[public]` route reads. Leaving `define_visitor` out would
    // hide the only place an anonymous read can be granted.
    assert!(
        ability.contains("fn define(") && ability.contains("fn define_visitor("),
        "the scaffolded policy carries both branches: {ability}"
    );
    let guard = fs::read_to_string(src.join("authz/http/guard.rs")).unwrap();
    assert!(guard.contains("AbilityGuard<AppAbility>"));

    let lib = fs::read_to_string(src.join("lib.rs")).unwrap();
    assert!(lib.contains("pub mod authn;"));
    assert!(lib.contains("pub mod authz;"));
    assert!(lib.contains("pub use identity::{Claims, Role};"));

    // A workspace has exactly one auth adapter; a second run must not clobber
    // the policy the developer has been editing.
    let second = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["g", "auth", "-p", dir.path().to_str().unwrap()])
        .current_dir(dir.path())
        .output()
        .unwrap();
    assert!(!second.status.success());
}

// Both auth roots have to reach the composition site from one run. They are two
// imports into the same `module.rs`, and a scaffold transaction resolves every
// edit against the file *on disk* — so queuing them as two edits would silently
// drop the first, leaving an app that lists only half of what it serves.
#[test]
fn generate_auth_wires_both_roots_into_the_app() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let app = write_fake_app(dir.path(), "api");

    run_ok(&app, &["g", "auth"]);

    let module = fs::read_to_string(app.join("src/module.rs")).unwrap();
    for (use_path, ident) in [
        ("features::authn::AuthnModule", "AuthnModule"),
        ("features::authz::AuthzHttpModule", "AuthzHttpModule"),
    ] {
        assert!(module.contains(&format!("use {use_path};")), "{module}");
        assert!(
            module.contains(&format!("{ident},")),
            "the imports array must list {ident}: {module}"
        );
    }
    // The pre-existing import is untouched.
    assert!(module.contains("HttpModule::for_root"), "{module}");
}

// Same obligation on the bootstrap path: `g resource` scaffolds the adapter when
// the workspace has none, so it owes the same composition site the same entries
// — in the one edit it already spends on `module.rs` for its own module.
#[test]
fn generate_resource_wires_the_auth_roots_it_bootstrapped() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let app = write_fake_app(dir.path(), "api");
    // `g resource` wires only into an app that already has a database.
    let module_rs = app.join("src/module.rs");
    let with_db = fs::read_to_string(&module_rs)
        .unwrap()
        .replace("    ],", "        DatabaseModule::for_root(None),\n    ],");
    fs::write(&module_rs, with_db).unwrap();

    run_ok(&app, &["g", "resource", "posts"]);

    let module = fs::read_to_string(&module_rs).unwrap();
    for ident in ["PostsHttpModule", "AuthnModule", "AuthzHttpModule"] {
        assert!(module.contains(&format!("{ident},")), "{ident}: {module}");
    }
}

fn write_fake_migrations_crate(root: &Path) {
    let dir = root.join("crates/migrations/src");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        dir.join("lib.rs"),
        "mod m20260101_000000_init;\nmod migrator;\n\npub use migrator::Migrator;\n",
    )
    .unwrap();
    fs::write(
        dir.join("migrator.rs"),
        "use sea_orm_migration::prelude::*;\n\nuse super::{\n    m20260101_000000_init,\n};\n\npub struct Migrator;\n",
    )
    .unwrap();
    fs::write(dir.join("m20260101_000000_init.rs"), "// init\n").unwrap();
}

#[test]
fn generate_migration_registers_in_both_lib_and_migrator() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    write_fake_migrations_crate(dir.path());

    run_ok(
        dir.path(),
        &[
            "g",
            "migration",
            "create_widget",
            "-p",
            dir.path().to_str().unwrap(),
        ],
    );

    let mig = dir.path().join("crates/migrations/src");
    // The generated file: m<date>_<seq>_create_widget.rs (date is today).
    let generated: Vec<_> = fs::read_dir(&mig)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| n.ends_with("_create_widget.rs"))
        .collect();
    assert_eq!(
        generated.len(),
        1,
        "one migration file created: {generated:?}"
    );
    let stem = generated[0].trim_end_matches(".rs").to_string();

    // Registered in BOTH lib.rs and migrator.rs — the whole point.
    let lib = fs::read_to_string(mig.join("lib.rs")).unwrap();
    assert!(lib.contains(&format!("mod {stem};")), "lib.rs: {lib}");

    let migrator = fs::read_to_string(mig.join("migrator.rs")).unwrap();
    // The new stem appears twice (the `use super::` import and the `Box::new`
    // vec entry) regardless of how rustfmt wrapped the file.
    assert!(
        migrator.matches(&stem).count() >= 2,
        "migrator must import and box the new migration: {migrator}"
    );
    assert!(
        migrator.contains(&format!("Box::new({stem}::Migration)")),
        "migrator vec: {migrator}"
    );
    // The pre-existing migration survives the regeneration.
    assert!(
        migrator.contains("Box::new(m20260101_000000_init::Migration)"),
        "migrator kept init: {migrator}"
    );
    assert!(
        migrator.contains("pub async fn migrate"),
        "migrator has migrate fn"
    );
}

#[test]
fn generate_migration_bootstraps_the_crate_when_absent() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    // No `crates/migrations` — a workspace scaffolded before it shipped.
    run_ok(
        dir.path(),
        &[
            "g",
            "migration",
            "create_widget",
            "-p",
            dir.path().to_str().unwrap(),
        ],
    );

    let mig = dir.path().join("crates/migrations/src");
    assert!(mig.join("lib.rs").is_file());
    assert!(mig.join("bin/migrate.rs").is_file());
    assert!(dir.path().join("crates/seed/src/main.rs").is_file());

    let lib = fs::read_to_string(mig.join("lib.rs")).unwrap();
    assert!(
        lib.contains("_create_widget;"),
        "lib.rs registers it: {lib}"
    );
    let migrator = fs::read_to_string(mig.join("migrator.rs")).unwrap();
    assert!(
        migrator.contains("_create_widget::Migration)"),
        "migrator boxes it: {migrator}"
    );
}

#[test]
fn generate_http_adapter_wires_feature_mod() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "http", "posts", "-p", path]);

    let feature = dir.path().join("crates/features/src/posts");
    assert!(feature.join("http/controller.rs").is_file());
    assert!(feature.join("http/module.rs").is_file());

    let mod_rs = fs::read_to_string(feature.join("mod.rs")).unwrap();
    assert!(mod_rs.contains("pub mod http;"));
    assert!(mod_rs.contains("PostsController"));
    assert!(mod_rs.contains("PostsHttpModule"));
}

#[test]
fn generate_ws_adapter_ensures_dep_and_wires() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "ws", "posts", "-p", path]);

    assert!(
        dir.path()
            .join("crates/features/src/posts/ws/gateway.rs")
            .is_file()
    );
    let features_cargo = fs::read_to_string(dir.path().join("crates/features/Cargo.toml")).unwrap();
    assert!(features_cargo.contains("nest-rs-ws"));
}

#[test]
fn generate_queue_adapter_puts_command_at_the_port() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "queue", "posts", "-p", path]);

    let feature = dir.path().join("crates/features/src/posts");

    // The imperative queue payload is a `Command` at the port, not inside the
    // `queue/` adapter — a producer↔worker contract the processor imports.
    let command_rs = fs::read_to_string(feature.join("command.rs")).unwrap();
    assert!(command_rs.contains("pub struct ProcessPostCommand"));

    let processor_rs = fs::read_to_string(feature.join("queue/processor.rs")).unwrap();
    assert!(processor_rs.contains("use crate::posts::ProcessPostCommand;"));
    assert!(processor_rs.contains("job: ProcessPostCommand"));
    // The payload is imported, never redefined in the adapter.
    assert!(!processor_rs.contains("pub struct ProcessPostCommand"));

    // The port `mod.rs` exposes both the command and the adapter module.
    let mod_rs = fs::read_to_string(feature.join("mod.rs")).unwrap();
    assert!(mod_rs.contains("mod command;"));
    assert!(mod_rs.contains("pub use command::ProcessPostCommand;"));
    assert!(mod_rs.contains("pub mod queue;"));
    assert!(mod_rs.contains("PostsQueueModule"));
}

#[test]
fn generate_adapter_is_rejected_on_rerun() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());
    let path = dir.path().to_str().unwrap();

    run_ok(dir.path(), &["g", "feature", "posts", "-p", path]);
    run_ok(dir.path(), &["g", "http", "posts", "-p", path]);

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["g", "http", "posts", "-p", path])
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("already exists"));
}

#[test]
fn generate_adapter_requires_existing_feature() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["g", "ws", "ghost", "-p", dir.path().to_str().unwrap()])
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert!(String::from_utf8_lossy(&output.stderr).contains("not found"));
}

#[test]
fn generate_dry_run_writes_nothing() {
    let dir = tempfile::tempdir().unwrap();
    write_fake_workspace(dir.path());

    run_ok(
        dir.path(),
        &[
            "g",
            "feature",
            "posts",
            "--dry-run",
            "-p",
            dir.path().to_str().unwrap(),
        ],
    );

    assert!(!dir.path().join("crates/features/src/posts").exists());
    let lib = fs::read_to_string(dir.path().join("crates/features/src/lib.rs")).unwrap();
    assert!(!lib.contains("pub mod posts;"));
}

#[test]
fn version_prints_single_line() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("version")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let line = stdout.trim();
    assert!(line.starts_with("NestRS "));
    assert!(!line.contains('\n'));
}

#[test]
fn about_prints_metadata_block() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("about")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Version:"));
    assert!(stdout.contains("Tagline:"));
    assert!(stdout.contains("Yoann Vanitou"));
}

#[test]
fn run_subcommand_is_listed_in_help() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("--help")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("run"));
}

#[test]
fn run_without_toolchain_and_no_bootstrap_errors_clearly() {
    // Hide just/bacon/cargo from the child so the toolchain probe finds nothing,
    // then assert the bootstrap-disabled path reports a manual-install hint
    // instead of silently installing or panicking.
    let empty = tempfile::tempdir().unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .args(["run", "--no-bootstrap", "dev"])
        .env("PATH", empty.path())
        .output()
        .unwrap();

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("just"), "stderr: {stderr}");
    assert!(stderr.contains("cargo install"), "stderr: {stderr}");
}

#[test]
fn doctor_passes_with_rust_toolchain() {
    let output = Command::new(env!("CARGO_BIN_EXE_nestrs"))
        .arg("doctor")
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}