puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
use std::path::Path;

pub fn require_puerto_project(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
    if !cwd.join("puerto.toml").exists() {
        return Err(
            "no se encuentra puerto.toml: ejecuta este comando desde la raíz de un proyecto Puerto"
                .into(),
        );
    }
    Ok(())
}

/// 37.3: the entity a command works on, which has to be in `puerto.toml` — if not, the similar one
/// or `puerto generar <create> <name>`, the command that starts one.
pub fn require_entity(
    cwd: &Path,
    name: &str,
    create: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    use crate::diagnostics::{Diagnostic, did_you_mean};
    let config = crate::puerto_toml::read(cwd)?;
    let names: Vec<&str> = config.entity.iter().map(|e| e.name.as_str()).collect();
    // The generators PascalCase what they are given: `producto` is `Producto`.
    if names.contains(&crate::generators::naming::to_pascal_case(name).as_str()) {
        return Ok(());
    }
    let help = did_you_mean(name, names.iter().copied()).unwrap_or_else(|| {
        format!("una entidad nueva se empieza con `puerto generar {create} {name}`")
    });
    let note = if names.is_empty() {
        "puerto.toml no declara ninguna entidad".to_string()
    } else {
        format!("las entidades: {}", names.join(", "))
    };
    Err(
        Diagnostic::new(format!("la entidad `{name}` no está en puerto.toml"))
            .help(help)
            .note(note)
            .to_string()
            .into(),
    )
}

pub fn run_list(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
    require_puerto_project(cwd)?;
    let config = crate::puerto_toml::read(cwd)?;
    print!("{}", list_report(&config));
    Ok(())
}

/// What the project has, a line each and only what it has: what `listar` prints under its name
/// and the TUI's «Proyecto» box (42.4).
pub fn project_lines(project: &crate::puerto_toml::Project) -> Vec<String> {
    let mut lines = vec![];
    if project.db {
        lines.push("Base de datos: sí".to_string());
    }
    if let Some(transport) = &project.events {
        lines.push(format!("Eventos: {transport}"));
    }
    if let Some(mode) = &project.auth {
        lines.push(format!("Auth: {mode}"));
    }
    if project.web {
        lines.push("Web: sí".to_string());
    }
    if project.portada {
        let app = project
            .app_path
            .as_deref()
            .unwrap_or(crate::puerto_toml::DEFAULT_APP_PATH);
        lines.push(format!("Portada: {app}"));
    }
    if project.notificaciones {
        lines.push("Notificaciones: sí".to_string());
    }
    lines
}

/// What `puerto listar` prints: the project, its entities with their use cases and custom events,
/// the shared value objects, the worker's consumers and the mails. A section with nothing in it is left out.
pub fn list_report(config: &crate::puerto_toml::PuertoConfig) -> String {
    let mut out = format!("Proyecto: {}\n", config.project.name);
    for line in project_lines(&config.project) {
        out.push_str(&format!("{line}\n"));
    }
    out.push('\n');
    if config.entity.is_empty() {
        out.push_str("No hay entidades.\n");
    }
    for entity in &config.entity {
        let repo_kind = if entity.db { "Postgres" } else { "en memoria" };
        out.push_str(&format!("  {} [{repo_kind}]\n", entity.name));
        for uc in &entity.use_cases {
            out.push_str(&format!("    · {uc}\n"));
        }
        if !entity.events.is_empty() {
            out.push_str(&format!("    eventos: {}\n", entity.events.join(", ")));
        }
        let files: Vec<&str> = entity
            .fields
            .iter()
            .filter(|f| f.field_type.contains("Fichero"))
            .map(|f| f.name.as_str())
            .collect();
        if !files.is_empty() {
            out.push_str(&format!("    ficheros: {}\n", files.join(", ")));
        }
    }
    if !config.value_object.is_empty() {
        out.push_str("\nObjetos valor compartidos:\n");
        for vo in &config.value_object {
            out.push_str(&format!("  {} ({})\n", vo.name, vo.inner_type));
        }
    }
    if !config.consumer.is_empty() {
        out.push_str("\nConsumidores:\n");
        for consumer in &config.consumer {
            out.push_str(&format!(
                "  {} ← {}\n",
                consumer.name,
                consumer.events.join(", ")
            ));
        }
    }
    if !config.scheduled.is_empty() {
        out.push_str("\nTareas programadas:\n");
        for task in &config.scheduled {
            out.push_str(&format!(
                "  {}  {} ({})\n",
                task.name,
                task.cron,
                task.zone.as_deref().unwrap_or("UTC")
            ));
        }
    }
    if !config.mail.is_empty() {
        out.push_str("\nCorreos:\n");
        for mail in &config.mail {
            if mail.on.is_empty() {
                out.push_str(&format!("  {}\n", mail.name));
            } else {
                out.push_str(&format!("  {} ← {}\n", mail.name, mail.on.join(", ")));
            }
        }
    }
    out
}