puerto 0.11.0

Puerto — Rust full-stack DDD framework CLI. Scaffolds Clean Architecture projects with auto-wired DI, SQLx support, and zero manual wiring. Formerly puerto-framework.
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
use super::*;

// ── T-07: compile matrix ──────────────────────────────────────────────────
//
// The structural tests above assert on substrings of the generated *text*. Nothing there proves
// the text is valid Rust — which is how `Option<VO>`/`Vec<VO>` (T-01), `--no-demo` (T-02) and
// use-case-less entities (T-03) shipped broken. These scenarios generate a real project, scaffold
// into it, and run `cargo test --workspace` inside it: the only assertion that cannot be fooled.
//
// They are `#[ignore]`d (slow) and run via `make test/full`.

/// One end-to-end generation scenario.
pub(super) struct Scenario<'a> {
    /// Temp-dir suffix and snapshot name; must be unique per scenario.
    pub(super) name: &'a str,
    /// A `--db` project (`puerto new --db`): Pg repositories, migrations.
    db: bool,
    /// Strip the Greeting demo before scaffolding (`puerto new --no-demo`).
    no_demo: bool,
    /// Shared VOs declared in puerto.toml before any scaffold (`(name, inner_type)`).
    shared_vos: &'a [(&'a str, &'a str)],
    /// Entities to scaffold: `(PascalName, CLI field args)`.
    entities: &'a [(&'a str, &'a [&'a str])],
    /// Custom use cases added after scaffolding: `(PascalEntity, snake_action)`.
    use_cases: &'a [(&'a str, &'a str)],
}

// The scenarios, shared with the snapshot tests (`generated_output.rs`): one proves the output
// compiles, the other that it did not change.

pub(super) const NO_DEMO: Scenario = Scenario {
    name: "no_demo",
    db: false,
    no_demo: true,
    shared_vos: &[],
    use_cases: &[],
    entities: &[("Persona", &["name:String"])],
};

pub(super) const PRIMITIVES: Scenario = Scenario {
    name: "primitives",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[(
        "Product",
        &[
            "title:String",
            "price:i64",
            "in_stock:bool",
            "rate:f64",
            "released_at:DateTime",
            "meta:map",
            // A `Uuid` field (the usual foreign key) was missing from this matrix, which is how
            // the generators shipped dropping it from every params struct and DTO.
            "category_id:Uuid",
        ],
    )],
};

pub(super) const UUID_VO: Scenario = Scenario {
    name: "uuid_vo",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[("Booking", &["reference:String", "tenant_id:TenantId:Uuid"])],
};

pub(super) const OPT_VEC_PRIM: Scenario = Scenario {
    name: "opt_vec_prim",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[(
        "Article",
        &[
            "title:String",
            "summary:opt:String",
            "views:opt:i64",
            "tags:vec:String",
            "scores:vec:i64",
        ],
    )],
};

pub(super) const PLAIN_VO: Scenario = Scenario {
    name: "plain_vo",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[(
        "Item",
        &["name:Name:String", "sku:Sku:String!", "weight:Weight:i64"],
    )],
};

pub(super) const OPT_VEC_VO: Scenario = Scenario {
    name: "opt_vec_vo",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[(
        "Persona",
        &[
            "name:String",
            "middle_name:MiddleName:opt:String",
            "tags:Tag:vec:String",
        ],
    )],
};

pub(super) const ENUM_VO: Scenario = Scenario {
    name: "enum_vo",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[(
        "Order",
        &[
            "reference:String",
            "status:Status:enum:Pending/Confirmed/Cancelled",
        ],
    )],
};

pub(super) const SHARED_VO: Scenario = Scenario {
    name: "shared_vo",
    db: false,
    no_demo: false,
    shared_vos: &[("Email", "String"), ("Money", "i64")],
    use_cases: &[],
    entities: &[("Customer", &["name:String", "email:Email", "credit:Money"])],
};

pub(super) const MULTI_ENTITY: Scenario = Scenario {
    name: "multi_entity",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[
        ("Product", &["title:String", "price:i64"]),
        ("Category", &["name:Name:String"]),
    ],
};

pub(super) const VO_KITCHEN_SINK: Scenario = Scenario {
    name: "vo_kitchen_sink",
    db: false,
    no_demo: false,
    shared_vos: &[("Email", "String")],
    use_cases: &[],
    entities: &[(
        "Account",
        &[
            "title:String",
            "price:i64",
            "name:Name:String",
            "sku:Sku:String!",
            "note:opt:String",
            "middle_name:MiddleName:opt:String",
            "tags:Tag:vec:String",
            "status:Status:enum:Active/Archived",
            "email:Email",
        ],
    )],
};

pub(super) const ENUM_ONLY: Scenario = Scenario {
    name: "enum_only",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[],
    entities: &[("Ticket", &["state:State:enum:Open/Closed"])],
};

pub(super) const CUSTOM_USE_CASE: Scenario = Scenario {
    name: "custom_use_case",
    db: false,
    no_demo: false,
    shared_vos: &[],
    use_cases: &[("Product", "archive_product")],
    entities: &[("Product", &["title:String", "price:i64"])],
};

pub(super) const POSTGRES_EVERY_TYPE: Scenario = Scenario {
    name: "postgres_every_type",
    db: true,
    no_demo: false,
    shared_vos: &[("Email", "String")],
    use_cases: &[("Product", "archive_product")],
    entities: &[
        (
            "Product",
            &[
                "title:String",
                "sku:String!",
                "price:i64!",
                "rating:f64",
                "active:bool",
                "ref_id:Uuid",
                "published_at:DateTime",
                "summary:opt:String",
                "views:opt:i64",
                "expires_at:opt:DateTime",
                "tags:vec:String",
                "scores:vec:i64",
                "meta:map",
            ],
        ),
        (
            "Customer",
            &[
                "email:Email",
                "name:Name:String",
                "code:Code:String!",
                "age:Age:i64",
                "joined:Joined:DateTime",
                "middle:MiddleName:opt:String",
                "labels:Label:vec:String",
                "status:Status:enum:Active/Inactive",
            ],
        ),
        ("Ticket", &["state:State:enum:Open/Closed"]),
    ],
};

/// Generates the project, applies the scenario, and asserts the result compiles, **passes its own
/// `make lint`** and **its tests pass**. `cargo check` is not enough: T-01 only broke test targets,
/// and every generated project ships a `make lint` with `-D warnings` that a fresh `puerto new`
/// used to fail.
fn assert_scenario_compiles(scenario: &Scenario) {
    let dir = scenario_workspace(scenario.name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project(&format!("compile-{}", scenario.name), &dir).unwrap();
    apply_scenario(scenario, &output);
    assert_generated_project_is_clean(&output, &dir, scenario.name, &[]);
    cleanup(&dir);
}

/// Applies the scenario's shared VOs, entities and custom use cases to a generated project.
pub(super) fn apply_scenario(scenario: &Scenario, output: &Path) {
    if scenario.db {
        crate::generators::project::apply_db_to_new_project(output).unwrap();
    }
    if scenario.no_demo {
        scaffold::apply_no_demo(output).unwrap();
    }

    for (vo_name, inner) in scenario.shared_vos {
        puerto_toml::add_value_object(output, vo_name, inner).unwrap();
    }

    let shared_vos = puerto_toml::read(output).unwrap().value_object;

    for (entity, field_args) in scenario.entities {
        let parsed: Vec<puerto_toml::Field> = field_args
            .iter()
            .map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
            .collect();
        let fields = puerto_toml::apply_shared_vo_inference(parsed, &shared_vos);
        crate::generators::types::validate_fields(&fields).unwrap();
        scaffold::run_scaffold(entity, output, &fields, OverwritePolicy::Ask).unwrap();
    }

    for (entity, action) in scenario.use_cases {
        scaffold::run_use_case(entity, action, output).unwrap();
    }
}

/// Runs `cargo clippy --all-targets -D warnings` and `cargo test` inside a generated project.
///
/// A target dir **per scenario**: every generated project names its crates
/// `business`/`infrastructure`/`presentation`, so a shared target dir has them overwrite each
/// other's artifacts and fail for reasons unrelated to the code under test.
pub(super) fn assert_generated_project_is_clean(
    output: &Path,
    dir: &Path,
    name: &str,
    envs: &[(&str, &str)],
) {
    for args in [
        &[
            "clippy",
            "--workspace",
            "--all-targets",
            "--",
            "-D",
            "warnings",
        ][..],
        &["test", "--workspace"][..],
    ] {
        let result = std::process::Command::new("cargo")
            .args(args)
            .env("CARGO_TARGET_DIR", dir.join("target"))
            .envs(envs.iter().copied())
            .current_dir(output)
            .output()
            .expect("failed to run cargo");

        if !result.status.success() {
            eprintln!("stdout:\n{}", String::from_utf8_lossy(&result.stdout));
            eprintln!("stderr:\n{}", String::from_utf8_lossy(&result.stderr));
            panic!(
                "scenario '{name}': generated project failed `cargo {}`",
                args.join(" ")
            );
        }
    }
}

/// Workspace for one scenario: the generated project plus its cargo target dir.
///
/// Lives under Puerto's own `target/`, not `/tmp`: a full build tree per scenario is gigabytes,
/// and on a tmpfs `/tmp` the matrix hits "Disk quota exceeded" instead of reporting on the code.
/// `cleanup()` on success keeps the total bounded by how many scenarios run concurrently; a
/// failing scenario keeps its tree for inspection.
pub(super) fn scenario_workspace(scenario: &str) -> PathBuf {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../target/compile-matrix")
        .join(scenario);
    let _ = fs::create_dir_all(&root);
    root
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_no_demo_then_scaffold() {
    assert_scenario_compiles(&NO_DEMO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_all_primitive_field_types() {
    assert_scenario_compiles(&PRIMITIVES);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_uuid_value_object() {
    assert_scenario_compiles(&UUID_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_option_and_vec_primitives() {
    assert_scenario_compiles(&OPT_VEC_PRIM);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_plain_and_unique_value_objects() {
    assert_scenario_compiles(&PLAIN_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_option_and_vec_value_objects() {
    assert_scenario_compiles(&OPT_VEC_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_enum_value_object() {
    assert_scenario_compiles(&ENUM_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_shared_value_objects() {
    assert_scenario_compiles(&SHARED_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_multiple_entities() {
    assert_scenario_compiles(&MULTI_ENTITY);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_every_value_object_kind_at_once() {
    assert_scenario_compiles(&VO_KITCHEN_SINK);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_domain_first_layered_flow_and_fields() {
    // T-06: `generate domain -- fields` persists the fields, so the three later layered commands
    // read them back from puerto.toml. Before, every one of them was field-blind and this flow
    // could only ever produce the default `name: String`.
    let dir = scenario_workspace("layered_fields");
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project("compile-layered-fields", &dir).unwrap();

    let fields: Vec<puerto_toml::Field> = [
        "amount:i64",
        "reference:Reference:String",
        "note:opt:String",
    ]
    .iter()
    .map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
    .collect();

    scaffold::run_generate_domain("Invoice", &output, &fields).unwrap();
    scaffold::run_generate_application("Invoice", &output).unwrap();
    scaffold::run_generate_repository("Invoice", &output).unwrap();
    scaffold::run_generate_presentation("Invoice", &output).unwrap();

    assert_generated_project_is_clean(&output, &dir, "layered_fields", &[]);

    cleanup(&dir);
}

// ── T-13: review fixes — matrix gaps ──────────────────────────────────────

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_enum_vo_as_only_string_field() {
    // The create test asserted `.value()` on the first String-typed field — an enum VO has
    // `as_str()`, so an entity whose only String was an enum never compiled its tests.
    assert_scenario_compiles(&ENUM_ONLY);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_custom_use_case_after_scaffold() {
    // `generate use-case` on a scaffolded entity wired the use case into `ProductApi` in
    // bootstrap.rs while routes.rs had no such field (E0560).
    assert_scenario_compiles(&CUSTOM_USE_CASE);
}

/// `PUERTO_TEST_DATABASE_URL` — a Postgres server URL **without** a database name, e.g.
/// `postgres://postgres:pg@localhost:55432`. `make test/db` starts one in Docker and sets it.
pub(super) fn test_database_server() -> Option<String> {
    std::env::var("PUERTO_TEST_DATABASE_URL")
        .ok()
        .map(|u| u.trim_end_matches('/').to_string())
        .filter(|u| !u.is_empty())
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_project_with_every_type_compiles_lints_and_passes_integration_tests() {
    // Nothing in the matrix generated a `--db` project, which is how `HashMap` columns, the Pg
    // repository test imports, timestamp round-trips and `unique` seeds all shipped broken.
    let Some(server) = test_database_server() else {
        eprintln!("PUERTO_TEST_DATABASE_URL not set — skipping (run `make test/db`)");
        return;
    };
    let dir = scenario_workspace("postgres_every_type");
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project("compile-postgres", &dir).unwrap();
    apply_scenario(&POSTGRES_EVERY_TYPE, &output);

    let database_url = format!("{server}/puerto_matrix");
    for args in [
        &["database", "drop", "-y"][..],
        &["database", "create"][..],
        &["migrate", "run", "--source", "infrastructure/migrations"][..],
    ] {
        let status = std::process::Command::new("sqlx")
            .args(args)
            .env("DATABASE_URL", &database_url)
            .current_dir(&output)
            .status()
            .expect("sqlx CLI not found — cargo install sqlx-cli");
        assert!(status.success(), "`sqlx {}` failed", args.join(" "));
    }

    assert_generated_project_is_clean(
        &output,
        &dir,
        "postgres_every_type",
        &[("DATABASE_URL", &database_url), ("SQLX_OFFLINE", "false")],
    );

    cleanup(&dir);
}