puerto 0.22.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.
use crate::generators::layout::{self, Layer};
use std::{fs, path::Path};

use serde::Serialize;

use crate::generators::naming::{
    crud_use_case, is_crud_entity, pascal_to_snake, to_pascal_case, write_file,
};
use crate::generators::render::render;

#[derive(Serialize)]
struct BootstrapUseCase {
    action: String,
    uc_pascal: String,
    /// Unit-of-work entities only: which ports the use case is built with.
    repository: bool,
    uow: bool,
}

#[derive(Serialize)]
struct BootstrapEntity {
    pascal: String,
    snake: String,
    db: bool,
    /// Its writes go through a `Pg{Entity}UnitOfWorkFactory` (ADR-0018 § 2).
    uow: bool,
    /// Some use case is built with the repository / the unit of work factory.
    needs_repository: bool,
    needs_uow: bool,
    use_cases: Vec<BootstrapUseCase>,
}

/// Whether an entity's writes go through a unit of work: a CRUD entity of an `events` project.
pub fn uses_unit_of_work(entity: &crate::puerto_toml::Entity, events: bool) -> bool {
    events && entity.db && is_crud_entity(&pascal_to_snake(&entity.name), &entity.use_cases)
}

fn build_context(
    entities: &[crate::puerto_toml::Entity],
    project: &crate::puerto_toml::Project,
) -> tera::Context {
    let events = project.has_events();
    let ctx_entities: Vec<BootstrapEntity> = entities
        .iter()
        .map(|entity| {
            let snake = pascal_to_snake(&entity.name);
            let uow = uses_unit_of_work(entity, events);
            // With a unit of work, `create` only writes; `get` and `list` only read; the rest
            // (update, delete and every custom use case) read, then write. Without one, every use
            // case holds the repository.
            let create = crud_use_case("create", &snake);
            let reads = [crud_use_case("get", &snake), crud_use_case("list", &snake)];
            let use_cases: Vec<BootstrapUseCase> = entity
                .use_cases
                .iter()
                .map(|uc| BootstrapUseCase {
                    action: uc.clone(),
                    uc_pascal: to_pascal_case(uc),
                    repository: !uow || *uc != create,
                    uow: uow && !reads.contains(uc),
                })
                .collect();
            BootstrapEntity {
                pascal: entity.name.clone(),
                db: entity.db,
                uow,
                needs_repository: use_cases.iter().any(|uc| uc.repository),
                needs_uow: use_cases.iter().any(|uc| uc.uow),
                use_cases,
                snake,
            }
        })
        .collect();

    let mut ctx = tera::Context::new();
    ctx.insert("entities", &ctx_entities);
    let auth = project.has_auth();
    // An auth project's users live in Postgres whenever the project has a database.
    let user_db = auth && project.db;
    ctx.insert("has_db", &(entities.iter().any(|e| e.db) || user_db));
    ctx.insert("web", &project.web);
    ctx.insert("auth", &auth);
    ctx.insert("user_db", &user_db);
    let local = project.auth.as_deref() == Some("local");
    ctx.insert("local", &local);
    ctx.insert("apis", &api_expression(entities, auth, local));
    ctx.insert("any_db", &entities.iter().any(|e| e.db));
    // The spec export test wraps a mock per use case in an `Arc`.
    ctx.insert(
        "wraps_mocks",
        &(local || entities.iter().any(|e| !e.use_cases.is_empty())),
    );
    ctx
}

/// What `OpenApiService` serves: `()` with no API, the one `api_{snake}`, or a tuple of them —
/// `api_me` last in an auth project, then `api_auth` in a local one.
fn api_expression(entities: &[crate::puerto_toml::Entity], auth: bool, local: bool) -> String {
    let mut apis: Vec<String> = entities
        .iter()
        .map(|e| format!("api_{}", pascal_to_snake(&e.name)))
        .collect();
    if auth {
        apis.push("api_me".into());
    }
    if local {
        apis.push("api_auth".into());
    }
    match apis.as_slice() {
        [single] => single.clone(),
        _ => format!("({})", apis.join(", ")),
    }
}

/// `web`: the project has a frontend, so `bootstrap.rs` also carries the test that exports the
/// OpenAPI spec to `docs/api/openapi.json` (ADR-0013).
#[cfg(test)]
pub fn generate_bootstrap_content(
    entities: &[crate::puerto_toml::Entity],
    web: bool,
) -> Result<String, crate::generators::render::RenderError> {
    let project = crate::puerto_toml::Project {
        web,
        ..Default::default()
    };
    generate_bootstrap_for(entities, &project)
}

/// `project`: whether it has a frontend (the spec export test), domain events (its CRUD entities
/// are wired with a unit of work), auth (the authenticator, `GET /me`) and a database.
#[cfg(test)]
pub fn generate_bootstrap_for(
    entities: &[crate::puerto_toml::Entity],
    project: &crate::puerto_toml::Project,
) -> Result<String, crate::generators::render::RenderError> {
    let ctx = build_context(entities, project);
    render("bootstrap/bootstrap.tera", &ctx)
}

/// `puerto generar bootstrap` — refuses when the manifest describes code that is not on disk.
///
/// The write itself is unconditional in `regenerate_bootstrap()` (scaffold calls it right after
/// writing the very files in question). The refusal belongs to the standalone command, which is
/// the one a user runs against a manifest they hand-edited.
pub fn run_bootstrap_command(
    base: &Path,
    allow_missing: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if !allow_missing {
        let config = crate::puerto_toml::read(base)?;
        let mut lines = crate::generators::consistency::drift_lines(
            &crate::generators::consistency::missing_entity_files(base, &config),
        );
        lines.extend(crate::generators::consistency::missing_consumer_files(
            base, &config,
        ));
        lines.extend(crate::generators::consistency::missing_mail_files(
            base, &config,
        ));
        if !lines.is_empty() {
            return Err(format!(
                "refusing to write generated wiring that will not compile:\n  {}\n\nPass \
                 --permitir-faltantes to write it anyway.",
                lines.join("\n  ")
            )
            .into());
        }
    }
    regenerate_bootstrap(base)?;
    println!("✓ bootstrap.rs regenerated.");
    if crate::puerto_toml::read(base).is_ok_and(|c| c.project.web) {
        println!("✓ web/src/presentation/core/generated/ regenerated.");
    }
    Ok(())
}

/// Read puerto.toml and overwrite the generated wiring: `presentacion/cableado` (its `Cargo.toml`
/// too), `presentacion/api/src/generado/bootstrap.rs` and, in a web project,
/// `web/src/presentation/core/generated/*`. The `api` crate gains the REST crate of every context.
///
/// Warns — rather than refuses — on manifest/filesystem drift: this runs inside `scaffold`, where
/// the entity being generated is fine and it is some *other* declared entity that is missing.
pub fn regenerate_bootstrap(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;

    for line in crate::generators::consistency::drift_lines(
        &crate::generators::consistency::missing_entity_files(base, &config),
    )
    .into_iter()
    .chain(crate::generators::consistency::missing_consumer_files(
        base, &config,
    ))
    .chain(crate::generators::consistency::missing_mail_files(
        base, &config,
    )) {
        eprintln!("⚠ {line}");
    }

    let ctx = build_context(&config.entity, &config.project);
    write_file(
        &base.join(layout::CABLEADO_MANIFEST),
        &render("bootstrap/cableado_cargo.tera", &ctx)?,
    )?;
    write_file(
        &base.join(layout::CABLEADO_LIB),
        &render("bootstrap/cableado.tera", &ctx)?,
    )?;
    write_file(
        &base.join(layout::BOOTSTRAP_RS),
        &render("bootstrap/bootstrap.tera", &ctx)?,
    )?;
    for entity in &config.entity {
        let snake = pascal_to_snake(&entity.name);
        add_crate_dependency(
            base,
            layout::API_MANIFEST,
            "dependencies",
            &layout::crate_name(&snake, Layer::Rest),
            "{ workspace = true }",
        )?;
        if !entity.use_cases.is_empty() {
            // The spec export test builds every API from the use cases' doubles.
            add_crate_dependency(
                base,
                layout::API_MANIFEST,
                "dev-dependencies",
                &layout::crate_name(&snake, Layer::Application),
                "{ workspace = true, features = [\"pruebas\"] }",
            )?;
        }
    }

    crate::generators::crates::sync_workspace_dependencies(base)?;
    crate::generators::events::regenerate_events(base, &config)?;
    crate::generators::worker::regenerate_registry(base, &config)?;
    crate::generators::web::regenerate_web(base, &config)?;

    Ok(())
}

/// Adds `name = value` to the `[section]` of the crate manifest `manifest` (a path under `base`)
/// unless it is there: at the end of the section, which is created at the end of the file when
/// missing. How a binary gains a crate of the project (ADR-0023 § 7).
pub fn add_crate_dependency(
    base: &Path,
    manifest: &str,
    section: &str,
    name: &str,
    value: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(manifest);
    let src = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    let header = format!("[{section}]\n");
    let line = format!("{name} = {value}\n");
    let out = match src.find(&header) {
        Some(at) => {
            let body = at + header.len();
            let end = src[body..].find("\n[").map_or(src.len(), |i| body + i + 1);
            if src[body..end]
                .lines()
                .any(|l| l.starts_with(&format!("{name} = ")))
            {
                return Ok(());
            }
            let end = body + src[body..end].trim_end().len();
            let sep = if end > body { "\n" } else { "" };
            format!("{}{sep}{}{}", &src[..end], line.trim_end(), &src[end..])
        }
        None => {
            let sep = if src.ends_with('\n') { "\n" } else { "\n\n" };
            format!("{src}{sep}{header}{line}")
        }
    };
    fs::write(&path, out)?;
    Ok(())
}