puerto 0.10.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
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
use std::path::Path;

use serde_json::json;

use crate::generators::effective_fields;
use crate::generators::naming::{pascal_to_snake, to_pascal_case, write_file};
use crate::generators::render::render;
use crate::generators::types::{
    field_vo_constructor, is_enum_vo, is_option_vo, is_value_object, is_vec_vo, literal_import,
    literal_names_vo, resolve_type, vo_import_path,
};
use crate::patchers::lib_rs::patch_business_lib_application_crud;
use crate::puerto_toml::{Field, ValueObjectDefinition};

// ── Helpers ──────────────────────────────────────────────────────────────────

fn enum_or_string(f: &Field, fallback: &str) -> String {
    if is_enum_vo(f) {
        let first = f.enum_variants.as_deref().unwrap().first().unwrap();
        format!("\"{first}\".to_string()")
    } else {
        format!("\"{fallback}\".to_string()")
    }
}

fn build_test_props(eff: &[Field], string_override: &str) -> String {
    eff.iter()
        .map(|f| {
            if is_option_vo(f) {
                format!("            {}: None,", f.name)
            } else if is_vec_vo(f) {
                format!("            {}: vec![],", f.name)
            } else if is_enum_vo(f) {
                let vo = f.value_object.as_deref().unwrap();
                let first_variant = f.enum_variants.as_deref().unwrap().first().unwrap();
                format!("            {}: {}::{},", f.name, vo, first_variant)
            } else if is_value_object(f) {
                let mapping = resolve_type(&f.field_type).unwrap();
                let vo = f.value_object.as_deref().unwrap();
                let value = if f.field_type == "String" {
                    format!("\"{}\".to_string()", string_override)
                } else {
                    mapping.default_expr.to_string()
                };
                format!(
                    "            {}: {}::new({}).expect(\"valid {}\"),",
                    f.name, vo, value, vo
                )
            } else {
                let mapping = resolve_type(&f.field_type).unwrap();
                let value = if f.field_type == "String" {
                    format!("\"{}\".to_string()", string_override)
                } else {
                    mapping.default_expr.to_string()
                };
                format!("            {}: {},", f.name, value)
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn build_create_params_vo(eff: &[Field]) -> String {
    eff.iter()
        .map(|f| {
            let mapping = resolve_type(&f.field_type).unwrap();
            let value = if f.field_type == "String" {
                enum_or_string(f, "example")
            } else {
                mapping.default_expr.to_string()
            };
            format!("            {}: {},", f.name, value)
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn build_empty_create_params(eff: &[Field], empty_field: &str) -> String {
    eff.iter()
        .map(|f| {
            if f.name == empty_field {
                format!("            {}: \"\".to_string(),", f.name)
            } else {
                let mapping = resolve_type(&f.field_type).unwrap();
                let value = if f.field_type == "String" {
                    enum_or_string(f, "example")
                } else {
                    mapping.default_expr.to_string()
                };
                format!("            {}: {},", f.name, value)
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn build_update_params(eff: &[Field]) -> String {
    let mut lines = vec!["            id: entity_id,".to_string()];
    for f in eff.iter() {
        let value = if f.field_type == "String" {
            enum_or_string(f, "updated")
        } else {
            resolve_type(&f.field_type)
                .unwrap()
                .default_expr
                .to_string()
        };
        lines.push(format!("            {}: {},", f.name, value));
    }
    lines.join("\n")
}

fn build_empty_update_params(eff: &[Field], empty_field: &str) -> String {
    let mut lines = vec!["            id: entity_id,".to_string()];
    for f in eff.iter() {
        if f.name == empty_field {
            lines.push(format!("            {}: \"\".to_string(),", f.name));
        } else {
            let value = if f.field_type == "String" {
                enum_or_string(f, "updated")
            } else {
                resolve_type(&f.field_type)
                    .unwrap()
                    .default_expr
                    .to_string()
            };
            lines.push(format!("            {}: {},", f.name, value));
        }
    }
    lines.join("\n")
}

fn build_not_found_params(eff: &[Field]) -> String {
    let mut lines = vec!["            id: Uuid::new_v4(),".to_string()];
    for f in eff.iter() {
        let mapping = resolve_type(&f.field_type).unwrap();
        let value = if f.field_type == "String" {
            enum_or_string(f, "new")
        } else {
            mapping.default_expr.to_string()
        };
        lines.push(format!("            {}: {},", f.name, value));
    }
    lines.join("\n")
}

/// Test-module imports for the use cases whose tests build an `EntityProps` literal
/// (get / list / update / delete).
///
/// The impls themselves name no primitive type, so those imports must **not** sit at file level —
/// there they are dead in a non-test build (`unused_imports`, and `-D warnings` in the generated
/// project's `make lint`). The test module is where a `Uuid`, `DateTime<Utc>` or
/// `HashMap<String, String>` field literal needs its type in scope (E0433 otherwise), alongside the
/// VO types the Props literal constructs.
///
/// `always_uuid` covers the templates whose tests name `Uuid` no matter the entity's fields (the
/// `id: Uuid::new_v4()` of the not-found cases). It must not be emitted twice for an entity that
/// also *has* a `Uuid` field — that is a duplicate import (E0252).
fn build_test_imports_block(
    eff: &[Field],
    snake: &str,
    shared_vos: &[ValueObjectDefinition],
    always_uuid: bool,
) -> String {
    let mut imports: Vec<String> = vec![];
    let mut push = |stmt: String| {
        if !imports.contains(&stmt) {
            imports.push(stmt);
        }
    };
    if always_uuid {
        push("    use uuid::Uuid;".to_string());
    }
    for f in eff {
        if let Some(imp) = literal_import(f) {
            push(format!("    use {imp};"));
        }
    }
    for f in eff.iter().filter(|f| literal_names_vo(f)) {
        push(format!("    use {};", vo_import_path(f, snake, shared_vos)));
    }
    if imports.is_empty() {
        String::new()
    } else {
        imports.join("\n") + "\n"
    }
}

/// Test-module imports for the create use case.
///
/// Its tests build `CreateEntityParams` literals only — always primitives — so unlike the Props
/// builders above it needs no VO import, and adding one would be an unused import.
fn build_create_test_imports_block(eff: &[Field]) -> String {
    let mut imports: Vec<String> = vec![];
    for imp in eff.iter().filter_map(literal_import) {
        let stmt = format!("    use {imp};");
        if !imports.contains(&stmt) {
            imports.push(stmt);
        }
    }
    if imports.is_empty() {
        String::new()
    } else {
        imports.join("\n") + "\n"
    }
}

/// File-level imports for the create/update impls: VO types only.
///
/// The impl bodies construct VOs (`Name::new(params.name)?`) but never name a primitive type — the
/// params carry those. A primitive import here is dead code in a non-test build.
fn build_vo_imports(
    eff: &[Field],
    snake: &str,
    shared_vos: &[ValueObjectDefinition],
) -> Vec<String> {
    let mut imports: Vec<String> = vec![];
    for f in eff.iter().filter(|f| is_value_object(f)) {
        let stmt = format!("use {};", vo_import_path(f, snake, shared_vos));
        if !imports.contains(&stmt) {
            imports.push(stmt);
        }
    }
    imports
}

// ── Context builders ──────────────────────────────────────────────────────────

fn build_create_context(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    let eff = effective_fields(fields);
    let extra_imports = build_vo_imports(&eff, snake, shared_vos);
    let test_imports = build_create_test_imports_block(&eff);
    let model_import = format!("{{{pascal}, {pascal}Props}}");

    let props_fields = eff
        .iter()
        .map(|f| {
            if is_value_object(f) {
                // Bound by `vo_constructions` under the field's own name: shorthand init.
                format!("            {},", f.name)
            } else {
                format!("            {}: params.{},", f.name, f.name)
            }
        })
        .collect::<Vec<_>>()
        .join("\n");

    let vo_constr: Vec<String> = eff
        .iter()
        .filter(|f| is_value_object(f))
        .map(|f| field_vo_constructor(f, "params.", pascal, shared_vos))
        .collect();
    let vo_constructions = if vo_constr.is_empty() {
        String::new()
    } else {
        vo_constr.join("\n") + "\n"
    };

    let valid_test_name = if eff.len() == 1
        && eff[0].name == "name"
        && eff[0].field_type == "String"
        && !is_value_object(&eff[0])
    {
        format!("should_create_{snake}_when_name_is_valid")
    } else {
        format!("should_create_{snake}_when_fields_are_valid")
    };

    let valid_params = build_create_params_vo(&eff);

    let valid_assertion = if let Some(f) = eff
        .iter()
        .find(|f| f.field_type == "String" && !is_value_object(f))
    {
        format!(
            "\n        assert_eq!(result.unwrap().{}, \"example\");",
            f.name
        )
    } else if let Some(f) = eff
        .iter()
        .find(|f| is_value_object(f) && !is_enum_vo(f) && f.field_type == "String")
    {
        format!(
            "\n        assert_eq!(result.unwrap().{}.value(), \"example\");",
            f.name
        )
    } else if let Some(f) = eff.iter().find(|f| is_enum_vo(f)) {
        // Enum VOs expose `as_str()`, not `value()`; the params use the first variant.
        let first = f.enum_variants.as_deref().unwrap().first().unwrap();
        format!(
            "\n        assert_eq!(result.unwrap().{}.as_str(), \"{first}\");",
            f.name
        )
    } else {
        String::new()
    };

    let mut validation_test_cases: Vec<serde_json::Value> = vec![];
    for sf in eff
        .iter()
        .filter(|f| f.field_type == "String" && !is_value_object(f))
    {
        let empty_params = build_empty_create_params(&eff, &sf.name);
        validation_test_cases.push(json!({
            "test_name": format!("should_return_error_when_{}_is_empty", sf.name),
            "empty_params": empty_params,
            "error_str": format!("{snake}.validation_error.{}_empty", sf.name),
        }));
    }
    for vf in eff
        .iter()
        .filter(|f| is_value_object(f) && f.field_type == "String")
    {
        let vo = vf.value_object.as_deref().unwrap();
        let vo_snake = pascal_to_snake(vo);
        let empty_params = build_empty_create_params(&eff, &vf.name);
        validation_test_cases.push(json!({
            "test_name": format!("should_return_error_when_{}_is_empty", vf.name),
            "empty_params": empty_params,
            "error_str": format!("{snake}.invalid_{vo_snake}"),
        }));
    }

    let mut ctx = tera::Context::new();
    ctx.insert("pascal", pascal);
    ctx.insert("snake", snake);
    ctx.insert("extra_imports", &extra_imports);
    ctx.insert("test_imports", &test_imports);
    ctx.insert("model_import", &model_import);
    ctx.insert("vo_constructions", &vo_constructions);
    ctx.insert("props_fields", &props_fields);
    ctx.insert("valid_test_name", &valid_test_name);
    ctx.insert("valid_params", &valid_params);
    ctx.insert("valid_assertion", &valid_assertion);
    ctx.insert("validation_test_cases", &validation_test_cases);
    ctx
}

fn build_get_context(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    let eff = effective_fields(fields);
    let props_fields = build_test_props(&eff, "example");
    let test_imports = build_test_imports_block(&eff, snake, shared_vos, true);

    let found_assertion = if let Some(f) = eff
        .iter()
        .find(|f| f.field_type == "String" && !is_value_object(f))
    {
        format!(
            "\n        assert_eq!(result.unwrap().{}, \"example\");",
            f.name
        )
    } else if let Some(f) = eff
        .iter()
        .find(|f| is_value_object(f) && f.field_type == "String" && !is_enum_vo(f))
    {
        format!(
            "\n        assert_eq!(result.unwrap().{}.value(), \"example\");",
            f.name
        )
    } else {
        String::new()
    };

    let mut ctx = tera::Context::new();
    ctx.insert("pascal", pascal);
    ctx.insert("snake", snake);
    ctx.insert("props_fields", &props_fields);
    ctx.insert("found_assertion", &found_assertion);
    ctx.insert("test_imports", &test_imports);
    ctx
}

fn build_list_context(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    let eff = effective_fields(fields);
    let first_props = build_test_props(&eff, "first");
    let second_props = build_test_props(&eff, "second");
    let test_imports = build_test_imports_block(&eff, snake, shared_vos, false);

    let mut ctx = tera::Context::new();
    ctx.insert("pascal", pascal);
    ctx.insert("snake", snake);
    ctx.insert("first_props", &first_props);
    ctx.insert("second_props", &second_props);
    ctx.insert("test_imports", &test_imports);
    ctx
}

fn build_update_context(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    let eff = effective_fields(fields);

    let extra_imports = build_vo_imports(&eff, snake, shared_vos);

    let validations: Vec<String> = eff
        .iter()
        .filter(|f| f.field_type == "String" && !is_value_object(f))
        .map(|f| {
            format!(
                "        if params.{}.trim().is_empty() {{\n            let err = {}Error::ValidationError(\"{}_empty\".into());\n            tracing::warn!(error = %err, \"update_{}: rejected\");\n            return Err(err);\n        }}",
                f.name, pascal, f.name, snake
            )
        })
        .collect();
    let validations_str = if validations.is_empty() {
        String::new()
    } else {
        validations.join("\n") + "\n"
    };

    let vo_constr: Vec<String> = eff
        .iter()
        .filter(|f| is_value_object(f))
        .map(|f| field_vo_constructor(f, "params.", pascal, shared_vos))
        .collect();
    let vo_constructions = if vo_constr.is_empty() {
        String::new()
    } else {
        vo_constr.join("\n") + "\n"
    };

    let assignments: Vec<String> = eff
        .iter()
        .map(|f| {
            if is_value_object(f) {
                format!("        entity.{} = {};", f.name, f.name)
            } else {
                format!("        entity.{} = params.{};", f.name, f.name)
            }
        })
        .collect();
    let assignments_str = assignments.join("\n");

    let original_props = build_test_props(&eff, "original");
    let update_params = build_update_params(&eff);
    let not_found_params = build_not_found_params(&eff);
    let test_imports = build_test_imports_block(&eff, snake, shared_vos, true);

    let primitive_string_fields: Vec<&Field> = eff
        .iter()
        .filter(|f| f.field_type == "String" && !is_value_object(f))
        .collect();
    let valid_assertion = if let Some(f) = primitive_string_fields.first().copied() {
        format!("assert_eq!(result.unwrap().{}, \"updated\");", f.name)
    } else if let Some(f) = eff
        .iter()
        .find(|f| is_value_object(f) && f.field_type == "String" && !is_enum_vo(f))
    {
        format!(
            "assert_eq!(result.unwrap().{}.value(), \"updated\");",
            f.name
        )
    } else {
        "assert!(result.is_ok());".to_string()
    };

    let mut validation_test_cases: Vec<serde_json::Value> = vec![];
    for sf in &primitive_string_fields {
        let empty_params = build_empty_update_params(&eff, &sf.name);
        validation_test_cases.push(json!({
            "test_name": format!("should_return_error_when_{}_is_empty", sf.name),
            "empty_params": empty_params,
            "error_str": format!("{snake}.validation_error.{}_empty", sf.name),
        }));
    }
    for vf in eff
        .iter()
        .filter(|f| f.field_type == "String" && is_value_object(f) && !is_enum_vo(f))
    {
        let vo = vf.value_object.as_deref().unwrap();
        let vo_snake = pascal_to_snake(vo);
        let empty_params = build_empty_update_params(&eff, &vf.name);
        validation_test_cases.push(json!({
            "test_name": format!("should_return_error_when_{}_is_empty", vf.name),
            "empty_params": empty_params,
            "error_str": format!("{snake}.invalid_{vo_snake}"),
        }));
    }

    let mut ctx = tera::Context::new();
    ctx.insert("pascal", pascal);
    ctx.insert("snake", snake);
    ctx.insert("extra_imports", &extra_imports);
    ctx.insert("validations", &validations_str);
    ctx.insert("vo_constructions", &vo_constructions);
    ctx.insert("assignments", &assignments_str);
    ctx.insert("original_props", &original_props);
    ctx.insert("update_params", &update_params);
    ctx.insert("not_found_params", &not_found_params);
    ctx.insert("valid_assertion", &valid_assertion);
    ctx.insert("test_imports", &test_imports);
    ctx.insert("validation_test_cases", &validation_test_cases);
    ctx
}

fn build_delete_context(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    let eff = effective_fields(fields);
    let props_fields = build_test_props(&eff, "example");
    let test_imports = build_test_imports_block(&eff, snake, shared_vos, true);

    let mut ctx = tera::Context::new();
    ctx.insert("pascal", pascal);
    ctx.insert("snake", snake);
    ctx.insert("props_fields", &props_fields);
    ctx.insert("test_imports", &test_imports);
    ctx
}

// ── Public generators (context builder + render) ──────────────────────────────

pub fn generate_create_use_case_impl(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> String {
    let ctx = build_create_context(pascal, snake, fields, shared_vos);
    render("application/create.tera", &ctx).expect("application/create.tera render failed")
}

pub fn generate_get_use_case_impl(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> String {
    let ctx = build_get_context(pascal, snake, fields, shared_vos);
    render("application/get.tera", &ctx).expect("application/get.tera render failed")
}

pub fn generate_list_use_case_impl(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> String {
    let ctx = build_list_context(pascal, snake, fields, shared_vos);
    render("application/list.tera", &ctx).expect("application/list.tera render failed")
}

pub fn generate_update_use_case_impl(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> String {
    let ctx = build_update_context(pascal, snake, fields, shared_vos);
    render("application/update.tera", &ctx).expect("application/update.tera render failed")
}

pub fn generate_delete_use_case_impl(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> String {
    let ctx = build_delete_context(pascal, snake, fields, shared_vos);
    render("application/delete.tera", &ctx).expect("application/delete.tera render failed")
}

// ── File writers ──────────────────────────────────────────────────────────────

pub fn write_application_files(
    pascal: &str,
    snake: &str,
    base: &Path,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
    write_file(
        &base.join(format!(
            "business/src/application/{snake}/create_{snake}.rs"
        )),
        &generate_create_use_case_impl(pascal, snake, fields, shared_vos),
    )?;
    write_file(
        &base.join(format!("business/src/application/{snake}/get_{snake}.rs")),
        &generate_get_use_case_impl(pascal, snake, fields, shared_vos),
    )?;
    write_file(
        &base.join(format!("business/src/application/{snake}/list_{snake}.rs")),
        &generate_list_use_case_impl(pascal, snake, fields, shared_vos),
    )?;
    write_file(
        &base.join(format!(
            "business/src/application/{snake}/update_{snake}.rs"
        )),
        &generate_update_use_case_impl(pascal, snake, fields, shared_vos),
    )?;
    write_file(
        &base.join(format!(
            "business/src/application/{snake}/delete_{snake}.rs"
        )),
        &generate_delete_use_case_impl(pascal, snake, fields, shared_vos),
    )?;
    Ok(())
}

pub fn run_generate_application(name: &str, base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let pascal = to_pascal_case(name);
    let snake = pascal_to_snake(&pascal);

    if !config.entity.iter().any(|e| e.name == pascal) {
        return Err(format!(
            "{pascal} not found in puerto.toml. Run `puerto generate domain {pascal}` first."
        )
        .into());
    }

    let fields: Vec<Field> = config
        .entity
        .iter()
        .find(|e| e.name == pascal)
        .map(|e| e.fields.clone())
        .unwrap_or_default();
    let shared_vos = config.value_object.clone();

    write_application_files(&pascal, &snake, base, &fields, &shared_vos)?;
    patch_business_lib_application_crud(base, &snake)?;

    println!("✓ business/application/ — 5 use case impls (create, get, list, update, delete)");
    println!();
    println!("  Next: puerto generate repository {pascal}");
    Ok(())
}