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.
//! `puerto actualizar` (Fase 37.7, ADR-0033): an upgrade is done by the agent, with what this
//! prepares for it. It touches no code: it says which version the project's runtime is on and
//! which the CLI is, the steps, and — in order — the `Breaking` and `Migration Guide` of every
//! version since the project's, from the CHANGELOG this CLI was released with.
use std::path::Path;

/// The repository's CHANGELOG (`crates/cli/CHANGELOG.md` links to it, so the crate carries it).
pub const CHANGELOG: &str = include_str!("../../CHANGELOG.md");

pub fn run_update(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
    crate::commands::list::require_puerto_project(cwd)?;
    let manifest = std::fs::read_to_string(cwd.join("Cargo.toml"))?;
    print!(
        "{}",
        report(&manifest, env!("CARGO_PKG_VERSION"), CHANGELOG)?
    );
    Ok(())
}

/// What `puerto actualizar` prints for a project whose root `Cargo.toml` is `manifest`.
pub fn report(manifest: &str, cli: &str, changelog: &str) -> Result<String, String> {
    let project = runtime_requirement(manifest).ok_or(
        "el Cargo.toml raíz no pide ningún crate del runtime (puerto-nucleo, puerto-web…): no es \
         un proyecto Puerto, o no se sabe de qué versión es",
    )?;
    let (from, to) = (numbers(&project), numbers(cli));
    let target = crate::runtime::requirement(cli);
    if from[..2] == to[..2] {
        return Ok(format!(
            "✓ El proyecto ya usa la {project}, la de esta CLI: no hay nada que actualizar.\n"
        ));
    }
    if from[..2] > to[..2] {
        return Err(format!(
            "el proyecto es de la {project} y esta CLI, la {cli}: actualiza antes la CLI (cargo \
             install puerto --locked)"
        ));
    }

    let mut out = format!(
        "El proyecto usa el runtime de Puerto {project}; esta CLI es la {cli}.\n\n\
         Lo hace el agente (paso a paso, en .claude/skills/actualizar-puerto/SKILL.md, si el proyecto la\n\
         tiene; la trae desde la 0.33):\n\
         \x20 1. Aplica, en orden, la guía de cada versión de abajo.\n\
         \x20 2. Sube los crates puerto-* del [workspace.dependencies] del Cargo.toml raíz a \"{target}\".\n\
         \x20 3. puerto generar bootstrap\n\
         \x20 4. puerto validar, task test y task lint\n\
         \x20 5. Que el usuario lo revise con git diff.\n"
    );
    for (version, body) in sections(changelog) {
        let n = numbers(&version);
        if n[..2] > from[..2] && n[..] <= to[..] {
            out.push_str(&format!("\n## [{version}]\n\n{}\n", breaking(&body)));
        }
    }
    Ok(out)
}

/// The `major.minor` the project asks of the runtime, from its first runtime crate.
fn runtime_requirement(manifest: &str) -> Option<String> {
    let manifest: toml::Table = manifest.parse().ok()?;
    let deps = manifest
        .get("workspace")
        .and_then(|w| w.get("dependencies"))
        .or_else(|| manifest.get("dependencies"))?;
    crate::runtime::RUNTIME_CRATES.iter().find_map(|name| {
        let version = match deps.get(*name)? {
            toml::Value::String(v) => v.as_str(),
            toml::Value::Table(t) => t.get("version")?.as_str()?,
            _ => return None,
        };
        Some(version.trim_start_matches(['^', '=', '~']).to_string())
    })
}

/// `0.31.1` → `[0, 31, 1]`; a missing part is a 0, so `0.31` compares as `0.31.0`.
fn numbers(version: &str) -> Vec<u64> {
    let mut n: Vec<u64> = version.split('.').map(|p| p.parse().unwrap_or(0)).collect();
    n.resize(3.max(n.len()), 0);
    n
}

/// Each `## [version] - date` of the CHANGELOG, oldest first, with its text.
fn sections(changelog: &str) -> Vec<(String, String)> {
    let mut sections: Vec<(String, String)> = changelog
        .split("\n## [")
        .filter_map(|chunk| {
            let chunk = chunk.strip_prefix("## [").unwrap_or(chunk);
            let (version, rest) = chunk.split_once(']')?;
            let body = rest.split_once('\n').map_or("", |(_, b)| b);
            Some((version.to_string(), body.to_string()))
        })
        .filter(|(version, _)| version.starts_with(|c: char| c.is_ascii_digit()))
        .collect();
    sections.reverse();
    sections
}

/// A version's `### Breaking` and `### Migration Guide`, or that it has none.
fn breaking(body: &str) -> String {
    let parts: Vec<String> = body
        .split("\n### ")
        .filter_map(|part| {
            let part = part.strip_prefix("### ").unwrap_or(part);
            ["Breaking", "Migration Guide"]
                .iter()
                .any(|h| part.starts_with(&format!("{h}\n")))
                .then(|| format!("### {}", part.trim_end()))
        })
        .collect();
    if parts.is_empty() {
        "(sin cambios incompatibles)".into()
    } else {
        parts.join("\n\n")
    }
}