armature-cli 0.5.0

CLI tool for Armature framework - scaffolding and development
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
//! Integration tests for the `armature` CLI binary.
//!
//! These exercise project scaffolding, code generation, route listing, OpenAPI
//! client generation, and exit-code behavior end-to-end in throwaway tempdirs.

use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
use std::path::Path;

/// Build a `Command` for the `armature` binary rooted in `dir`, with color off.
fn armature_in(dir: &Path) -> Command {
    let mut cmd = Command::cargo_bin("armature").unwrap();
    cmd.current_dir(dir);
    cmd.arg("--no-color");
    cmd
}

/// Create a minimal Armature-looking project (Cargo.toml + src) inside `dir`.
fn scaffold_project(dir: &Path) {
    fs::write(
        dir.join("Cargo.toml"),
        "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\narmature = \"0.1\"\n",
    )
    .unwrap();
    fs::create_dir_all(dir.join("src/controllers")).unwrap();
    fs::write(dir.join("src/main.rs"), "fn main() {}\n").unwrap();
    fs::write(dir.join("src/controllers/mod.rs"), "pub mod health;\n").unwrap();
}

fn assert_exists(base: &Path, rel: &str) {
    assert!(
        base.join(rel).exists(),
        "expected generated file/dir to exist: {}",
        rel
    );
}

// =============================================================================
// Command tree validity (guards against duplicate clap aliases, which make
// clap's debug asserts panic on EVERY invocation)
// =============================================================================

#[test]
fn command_tree_is_valid() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path()).arg("--version").assert().success();
    // Exercise nested subcommand help to force the whole tree to build.
    armature_in(tmp.path())
        .args(["openapi", "--help"])
        .assert()
        .success();
    armature_in(tmp.path())
        .args(["generate", "--help"])
        .assert()
        .success();
}

// =============================================================================
// Project templates
// =============================================================================

#[test]
fn new_minimal_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "minimal", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    for f in [
        "Cargo.toml",
        "src/main.rs",
        "src/controllers/mod.rs",
        "src/controllers/health.rs",
        ".env.example",
        "README.md",
        ".gitignore",
    ] {
        assert_exists(&root, f);
    }
}

#[test]
fn new_full_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "full", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    for f in [
        "src/services/mod.rs",
        "src/middleware/mod.rs",
        "src/guards/mod.rs",
        "src/models/mod.rs",
        "Dockerfile",
        "docker-compose.yml",
    ] {
        assert_exists(&root, f);
    }
}

#[test]
fn new_microservice_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "microservice", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    assert_exists(&root, "src/handlers/mod.rs");
    assert_exists(&root, "src/jobs/mod.rs");
    assert_exists(&root, "Dockerfile");
}

#[test]
fn new_graphql_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "graphql", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    assert_exists(&root, "src/graphql/mod.rs");
    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("async-graphql"),
        "graphql template Cargo.toml must depend on async-graphql, got:\n{cargo}"
    );
}

#[test]
fn new_grpc_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "grpc", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    assert_exists(&root, "src/grpc/mod.rs");
    assert_exists(&root, "proto/service.proto");
    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("tonic"),
        "grpc template Cargo.toml must depend on tonic, got:\n{cargo}"
    );
}

#[test]
fn new_lambda_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "lambda", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("lambda_http") || cargo.contains("lambda_runtime"),
        "lambda template Cargo.toml must depend on a lambda crate, got:\n{cargo}"
    );
    let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
    assert!(
        main.contains("lambda"),
        "lambda main.rs should reference lambda runtime"
    );
}

#[test]
fn new_cloudrun_produces_tree() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "cloudrun", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    assert_exists(&root, "Dockerfile");
    // Cloud Run deployment descriptor.
    assert!(
        root.join("service.yaml").exists() || root.join("cloudbuild.yaml").exists(),
        "cloudrun template must emit a Cloud Run deploy descriptor"
    );

    // The embedded Dockerfile's `ARG BIN_NAME=app` placeholder must actually
    // be substituted with the project's kebab-case binary name end-to-end —
    // not just that the file exists (see commands/new.rs's `ARG BIN_NAME`
    // patch in `create_project_structure`).
    let dockerfile_contents = fs::read_to_string(root.join("Dockerfile")).unwrap();
    assert!(
        dockerfile_contents.contains("ARG BIN_NAME=acme"),
        "Dockerfile must have 'ARG BIN_NAME=app' substituted with the \
         project's kebab-case name, got:\n{dockerfile_contents}"
    );
    assert!(
        !dockerfile_contents.contains("ARG BIN_NAME=app"),
        "Dockerfile must not still contain the unsubstituted 'ARG BIN_NAME=app' \
         placeholder, got:\n{dockerfile_contents}"
    );
}

// Note: there is no `new_azure_container_produces_tree` test alongside the
// two above. `templates/azure-container/Dockerfile` is a standalone
// reference example, not an `armature new --template ...` target — there's
// no "azure-container" entry in `KNOWN_TEMPLATES` (see `commands/new.rs`),
// so there's no CLI-generated Dockerfile for a test like this to exercise.
// See the matching note in `armature-cli/src/templates.rs` next to
// `CLOUDRUN_DOCKERFILE_TEMPLATE`.

#[test]
fn clap_rejects_unknown_template_before_new_runs() {
    // `--template` is a clap `ValueEnum` (`ProjectTemplate`), so an unknown
    // value like "bogus" is rejected by clap's own arg parsing before
    // `armature new` ever dispatches into `new::run`/`validate_template`.
    // This test only proves that the CLI-level parse failure has no
    // filesystem side effects; it does NOT exercise `validate_template`'s
    // before-write guarantee (see
    // `commands::new::tests::run_rejects_unknown_template_before_creating_directory`
    // in `src/commands/new.rs` for that).
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "bogus", "--skip-git"])
        .assert()
        .failure();

    assert!(
        !tmp.path().join("acme").exists(),
        "no project directory must be created for an invalid template"
    );
}

#[test]
fn new_database_docker_ci_emits_config() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args([
            "new",
            "acme",
            "--template",
            "minimal",
            "--database",
            "postgres",
            "--docker",
            "--ci",
            "--skip-git",
        ])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("sqlx") || cargo.contains("postgres"),
        "postgres database should add a db dependency, got:\n{cargo}"
    );
    assert_exists(&root, "Dockerfile");
    assert_exists(&root, ".github/workflows/ci.yml");
}

// =============================================================================
// generate --fields
// =============================================================================

#[test]
fn generate_dto_injects_fields() {
    let tmp = tempfile::tempdir().unwrap();
    scaffold_project(tmp.path());

    armature_in(tmp.path())
        .args(["g", "dto", "user", "--fields", "name:string,email:string"])
        .assert()
        .success();

    let dto = fs::read_to_string(tmp.path().join("src/dto/user.rs")).unwrap();
    assert!(
        dto.contains("pub name: String"),
        "DTO must contain the requested name field, got:\n{dto}"
    );
    assert!(
        dto.contains("pub email: String"),
        "DTO must contain the requested email field, got:\n{dto}"
    );
}

#[test]
fn generate_model_writes_struct_with_fields() {
    let tmp = tempfile::tempdir().unwrap();
    scaffold_project(tmp.path());

    armature_in(tmp.path())
        .args([
            "generate",
            "model",
            "user",
            "--fields",
            "email:string,age:i32,active:bool",
        ])
        .assert()
        .success();

    let model_file = tmp.path().join("src/models/user.rs");
    assert!(
        model_file.exists(),
        "expected src/models/user.rs to be written"
    );

    let model = fs::read_to_string(&model_file).unwrap();
    assert!(
        model.contains("pub struct User"),
        "model must define a User struct, got:\n{model}"
    );
    assert!(
        model.contains("pub email: String"),
        "model must contain the requested email field, got:\n{model}"
    );
    assert!(
        model.contains("pub age: i32"),
        "model must contain the requested age field, got:\n{model}"
    );
    assert!(
        model.contains("pub active: bool"),
        "model must contain the requested active field, got:\n{model}"
    );

    // src/models/mod.rs must be created/updated to declare the new module.
    let mod_file = fs::read_to_string(tmp.path().join("src/models/mod.rs")).unwrap();
    assert!(
        mod_file.contains("pub mod user;"),
        "models/mod.rs must declare the new module, got:\n{mod_file}"
    );

    // No migration was requested, so no migrations directory should exist.
    assert!(
        !tmp.path().join("migrations").exists(),
        "migrations directory should not be created without --migration"
    );
}

#[test]
fn generate_model_with_migration_writes_up_and_down_sql() {
    let tmp = tempfile::tempdir().unwrap();
    scaffold_project(tmp.path());

    armature_in(tmp.path())
        .args([
            "generate",
            "model",
            "post",
            "--fields",
            "title:string,published:bool",
            "--migration",
        ])
        .assert()
        .success();

    assert_exists(tmp.path(), "src/models/post.rs");

    let migrations_dir = tmp.path().join("migrations");
    assert!(
        migrations_dir.exists(),
        "expected a migrations directory to be created"
    );

    let entries: Vec<_> = fs::read_dir(&migrations_dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    assert_eq!(
        entries.len(),
        1,
        "expected exactly one migration directory, got: {:?}",
        entries
    );

    let migration_dir = &entries[0];
    let dir_name = migration_dir.file_name().unwrap().to_string_lossy();
    assert!(
        dir_name.ends_with("_create_posts"),
        "migration directory should be named '<timestamp>_create_posts', got: {dir_name}"
    );

    let up_sql = fs::read_to_string(migration_dir.join("up.sql")).unwrap();
    assert!(
        up_sql.contains("CREATE TABLE posts"),
        "up.sql must create the posts table, got:\n{up_sql}"
    );
    assert!(
        up_sql.contains("title VARCHAR NOT NULL"),
        "up.sql must contain the title column, got:\n{up_sql}"
    );
    assert!(
        up_sql.contains("published BOOLEAN NOT NULL"),
        "up.sql must contain the published column, got:\n{up_sql}"
    );

    let down_sql = fs::read_to_string(migration_dir.join("down.sql")).unwrap();
    assert!(
        down_sql.contains("DROP TABLE IF EXISTS posts"),
        "down.sql must drop the posts table, got:\n{down_sql}"
    );
}

// =============================================================================
// routes
// =============================================================================

fn scaffold_routes_project(dir: &Path) {
    scaffold_project(dir);
    fs::write(
        dir.join("src/controllers/users.rs"),
        r#"
#[middleware(LoggerMiddleware)]
#[guard(AuthGuard)]
#[get("/api/users")]
pub async fn list() {}

#[post("/api/users")]
pub async fn create() {}
"#,
    )
    .unwrap();
}

#[test]
fn routes_formats_differ() {
    let tmp = tempfile::tempdir().unwrap();
    scaffold_routes_project(tmp.path());

    let json = armature_in(tmp.path())
        .args(["routes", "--format", "json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json = String::from_utf8(json).unwrap();
    assert!(json.contains('['), "json format should emit a JSON array");

    let markdown = armature_in(tmp.path())
        .args(["routes", "--format", "markdown"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let markdown = String::from_utf8(markdown).unwrap();
    assert!(
        markdown.contains('|'),
        "markdown format should emit a table with pipes"
    );

    let yaml = armature_in(tmp.path())
        .args(["routes", "--format", "yaml"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let yaml = String::from_utf8(yaml).unwrap();
    assert!(
        yaml.contains("method:") || yaml.contains("- method"),
        "yaml format should emit yaml keys"
    );

    assert_ne!(json, markdown, "json and markdown output must differ");
    assert_ne!(json, yaml, "json and yaml output must differ");
}

#[test]
fn routes_reports_middleware_stats() {
    let tmp = tempfile::tempdir().unwrap();
    scaffold_routes_project(tmp.path());

    armature_in(tmp.path())
        .args(["routes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Routes with middleware: 1"));
}

#[test]
fn routes_path_filter() {
    let tmp = tempfile::tempdir().unwrap();
    scaffold_project(tmp.path());
    fs::write(
        tmp.path().join("src/controllers/mixed.rs"),
        "#[get(\"/api/users\")]\npub async fn a() {}\n#[get(\"/health\")]\npub async fn b() {}\n",
    )
    .unwrap();

    armature_in(tmp.path())
        .args(["routes", "--path", "users"])
        .assert()
        .success()
        .stdout(predicate::str::contains("/api/users"))
        .stdout(predicate::str::contains("/health").not());
}

// =============================================================================
// validate exit code
// =============================================================================

#[test]
fn validate_fails_on_missing_src() {
    let tmp = tempfile::tempdir().unwrap();
    fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();

    // --config-only avoids invoking cargo; the missing src still fails validation.
    armature_in(tmp.path())
        .args(["validate", "--config-only"])
        .assert()
        .failure()
        // stdout carries the specific check that failed, proving this is a real
        // validation finding and not e.g. a clap arg-parse failure.
        .stdout(predicate::str::contains("Missing src directory"))
        // stderr carries the top-level error surfaced by `main`, which
        // distinguishes an exit-from-validation (`CliError::Validation`) from
        // an exit caused by argument parsing (clap prints its own
        // "error: unexpected argument"/usage text instead of this message).
        .stderr(predicate::str::contains("Validation error"));
}

// =============================================================================
// openapi client generation
// =============================================================================

fn write_petstore_spec(dir: &Path) -> std::path::PathBuf {
    let spec = r#"openapi: 3.0.0
info:
  title: Pet Store
  version: 1.0.0
paths:
  /pets:
    get:
      operationId: listPets
      responses:
        '200':
          description: ok
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Pet'
components:
  schemas:
    Pet:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
"#;
    let path = dir.join("openapi.yaml");
    fs::write(&path, spec).unwrap();
    path
}

#[test]
fn openapi_rust_client_honors_logging_and_retry() {
    let tmp = tempfile::tempdir().unwrap();
    write_petstore_spec(tmp.path());

    armature_in(tmp.path())
        .args([
            "openapi",
            "client",
            "openapi.yaml",
            "--language",
            "rust",
            "--output",
            "out",
            "--with-logging",
            "--with-retry",
        ])
        .assert()
        .success();

    let client = fs::read_to_string(tmp.path().join("out/client.rs")).unwrap();
    assert!(
        client.contains("retry") || client.contains("Retry"),
        "with-retry must emit retry code, got:\n{client}"
    );
    assert!(
        client.to_lowercase().contains("log")
            || client.contains("eprintln")
            || client.contains("tracing"),
        "with-logging must emit logging code"
    );
}

#[test]
fn openapi_ts_client_honors_logging_and_retry_and_base_url() {
    let tmp = tempfile::tempdir().unwrap();
    write_petstore_spec(tmp.path());

    armature_in(tmp.path())
        .args([
            "openapi",
            "client",
            "openapi.yaml",
            "--language",
            "typescript",
            "--output",
            "out",
            "--with-logging",
            "--with-retry",
            "--base-url",
            "https://api.example.com",
        ])
        .assert()
        .success();

    let client = fs::read_to_string(tmp.path().join("out/client.ts")).unwrap();
    assert!(
        client.contains("retry") || client.contains("Retry"),
        "with-retry must emit retry code in TS"
    );
    assert!(
        client.contains("console."),
        "with-logging must emit console logging in TS"
    );
    assert!(
        client.contains("https://api.example.com"),
        "base-url must be baked into the generated TS client"
    );
}

// =============================================================================
// Removed `db` subcommand
// =============================================================================

#[test]
fn db_subcommand_removed() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["db", "migrate"])
        .assert()
        .failure();
}

// =============================================================================
// Ignored smoke test: cargo-check a generated project
// =============================================================================

#[test]
#[ignore = "compiles a generated project; slow and needs network for crates.io"]
fn generated_minimal_project_cargo_checks() {
    let tmp = tempfile::tempdir().unwrap();
    armature_in(tmp.path())
        .args(["new", "acme", "--template", "minimal", "--skip-git"])
        .assert()
        .success();

    let root = tmp.path().join("acme");
    let status = std::process::Command::new("cargo")
        .arg("check")
        .current_dir(&root)
        .status()
        .unwrap();
    assert!(
        status.success(),
        "generated minimal project should cargo-check"
    );
}

// =============================================================================
// Unimplemented subcommands must fail, not silently succeed
// =============================================================================

/// Subcommands that are declared but do nothing must exit non-zero.
///
/// They used to print "coming soon!" and return `Ok(())`, so `armature deploy
/// --env prod` in CI reported a successful deploy having deployed nothing, and
/// `armature serve` as a container start-command exited 0 with no server
/// running. They are also `hide = true` now, so they no longer appear in
/// `--help` — but remain invocable (and failing) for anyone who scripted them.
#[test]
fn unimplemented_subcommands_exit_non_zero() {
    let tmp = tempfile::tempdir().unwrap();
    for args in [
        vec!["serve"],
        vec!["deploy", "--env", "prod"],
        vec!["upgrade"],
        vec!["upgrade", "--check"],
        vec!["bench"],
        vec!["lint"],
        vec!["config", "show"],
        vec!["config", "set", "k", "v"],
        vec!["config", "init"],
        vec!["plugin", "install", "foo"],
        vec!["plugin", "uninstall", "foo"],
        vec!["plugin", "new", "foo"],
        vec!["openapi", "validate", "openapi.yaml"],
        vec!["openapi", "generate"],
    ] {
        armature_in(tmp.path())
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains("not implemented yet"));
    }
}

/// Hidden-but-real commands stay out of the top-level help listing.
#[test]
fn unimplemented_subcommands_are_hidden_from_help() {
    let tmp = tempfile::tempdir().unwrap();
    let out = armature_in(tmp.path())
        .arg("--help")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let help = String::from_utf8(out).unwrap();
    for hidden in ["deploy", "bench"] {
        assert!(
            !help.contains(&format!("  {}", hidden)),
            "`{hidden}` is not implemented and must not be advertised in --help:\n{help}"
        );
    }
}