puerto 0.33.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/historial/` and `puerto deshacer` (Fase 37.6, ADR-0032).
//!
//! Puerto never commits: the user reviews what it wrote with `git diff`, and a commit would run
//! their hooks. Each `puerto generar …` that changes a file leaves a record instead —
//! `operacion.toml` and the before and after of each file it touched — and `deshacer` reverts the
//! last one with the three-way merge of `generar campo` (diffy), so an edit made after it stays.
use crate::diagnostics::Diagnostic;
use crate::tree::{self, Snapshot};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

const HISTORY: &str = ".puerto/historial";

#[derive(Serialize, Deserialize)]
struct Operation {
    #[serde(rename = "comando")]
    command: String,
    version: String,
}

/// `run` in the project at `cwd`, and its record if it changed any file — also when it fails half
/// way, which is when undoing it matters most. Its result is `run`'s.
pub fn record(
    cwd: &Path,
    command: &str,
    run: impl FnOnce() -> Result<(), Box<dyn std::error::Error>>,
) -> Result<(), Box<dyn std::error::Error>> {
    let before = tree::snapshot(cwd)?;
    let result = run();
    let after = tree::snapshot(cwd)?;
    if before != after
        && let Err(e) = write_record(cwd, command, &before, &after)
    {
        eprintln!("aviso: no se ha podido guardar en {HISTORY} (puerto deshacer no lo verá): {e}");
    }
    result
}

fn write_record(
    cwd: &Path,
    command: &str,
    before: &Snapshot,
    after: &Snapshot,
) -> std::io::Result<()> {
    let history = cwd.join(HISTORY);
    fs::create_dir_all(&history)?;
    let ignore = cwd.join(".puerto/.gitignore");
    if !ignore.exists() {
        // Local, like `target/`; and it works in a project from before this phase.
        fs::write(ignore, "*\n")?;
    }
    let next = records(cwd)?.last().map_or(0, |(n, _)| *n) + 1;
    let dir = history.join(format!("{next:04}"));
    fs::create_dir(&dir)?;
    for (path, _) in tree::changes(before, after) {
        for (side, snapshot) in [("antes", before), ("despues", after)] {
            if let Some(bytes) = snapshot.get(&path) {
                let target = dir.join(side).join(&path);
                fs::create_dir_all(target.parent().unwrap_or(&dir))?;
                fs::write(target, bytes)?;
            }
        }
    }
    let operation = Operation {
        command: command.to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
    };
    fs::write(
        dir.join("operacion.toml"),
        toml::to_string(&operation).unwrap_or_default(),
    )
}

/// The records, oldest first, by number.
fn records(cwd: &Path) -> std::io::Result<Vec<(u32, PathBuf)>> {
    let Ok(entries) = fs::read_dir(cwd.join(HISTORY)) else {
        return Ok(vec![]);
    };
    let mut records: Vec<(u32, PathBuf)> = entries
        .flatten()
        .filter_map(|e| Some((e.file_name().to_str()?.parse().ok()?, e.path())))
        .collect();
    records.sort();
    Ok(records)
}

/// What undoing does to one file.
enum Step {
    Write(Vec<u8>),
    Remove,
    /// Written with conflict markers (only with `--forzar`).
    Conflict(String),
    /// Left as it is, and why.
    Keep(&'static str),
}

/// `puerto deshacer [--forzar]`: reverts the last record and deletes it. What it did, to print.
pub fn undo(cwd: &Path, force: bool) -> Result<String, Box<dyn std::error::Error>> {
    let Some((_, dir)) = records(cwd)?.pop() else {
        return Err(Diagnostic::new("no hay nada que deshacer")
            .note(format!(
                "cada `puerto generar …` que cambia algo deja su ficha en {HISTORY}/, y está vacío"
            ))
            .to_string()
            .into());
    };
    let operation: Operation = toml::from_str(&fs::read_to_string(dir.join("operacion.toml"))?)?;
    let before = snapshot_or_empty(&dir.join("antes"))?;
    let after = snapshot_or_empty(&dir.join("despues"))?;

    let mut plan: Vec<(PathBuf, Step)> = vec![];
    for path in before
        .keys()
        .chain(after.keys())
        .collect::<std::collections::BTreeSet<_>>()
    {
        let current = fs::read(cwd.join(path)).ok();
        let (was, left) = (before.get(path), after.get(path));
        let step = if current.as_ref() == left {
            match was {
                Some(bytes) => Step::Write(bytes.clone()),
                None => Step::Remove,
            }
        } else if current.as_ref() == was {
            continue;
        } else {
            match (was, left, &current) {
                (Some(was), Some(left), Some(current)) => merge(was, left, current),
                (None, Some(_), Some(_)) => Step::Keep("lo creó y lo cambiaste después"),
                (Some(_), None, Some(_)) => Step::Keep("lo borró y lo volviste a crear"),
                _ => Step::Keep("lo borraste después"),
            }
        };
        plan.push((path.clone(), step));
    }

    let blocked: Vec<String> = plan
        .iter()
        .filter_map(|(path, step)| match step {
            Step::Keep(why) => Some(format!("{}: {why}", path.display())),
            Step::Conflict(_) => Some(format!(
                "{}: lo cambiaste después, en las mismas líneas",
                path.display()
            )),
            _ => None,
        })
        .collect();
    if !blocked.is_empty() && !force {
        return Err(Diagnostic::new(format!(
            "no se puede deshacer `{}` sin pisar lo que cambiaste después; no se ha tocado nada",
            operation.command
        ))
        .help(
            "con --forzar deshace el resto: deja marcas de conflicto (<<<<<<<) en los que chocan y \
             no borra los que creó y cambiaste",
        )
        .note(blocked.join("\n"))
        .to_string()
        .into());
    }

    let current: Snapshot = plan
        .iter()
        .filter_map(|(path, _)| Some((path.clone(), fs::read(cwd.join(path)).ok()?)))
        .collect();
    let mut target = current.clone();
    let mut conflicts = vec![];
    for (path, step) in &plan {
        let file = cwd.join(path);
        match step {
            Step::Write(bytes) => {
                if let Some(parent) = file.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&file, bytes)?;
                target.insert(path.clone(), bytes.clone());
            }
            Step::Remove => {
                fs::remove_file(&file)?;
                remove_empty_parents(cwd, &file);
                target.remove(path);
            }
            Step::Conflict(merged) => {
                fs::write(&file, merged)?;
                target.insert(path.clone(), merged.clone().into_bytes());
                conflicts.push(path.display().to_string());
            }
            Step::Keep(_) => {}
        }
    }
    fs::remove_dir_all(&dir)?;

    let mut report = format!("Deshecho: {}\n\n", operation.command);
    report.push_str(&crate::commands::simulate::report(&tree::changes(
        &current, &target,
    )));
    for (path, step) in &plan {
        if let Step::Keep(why) = step {
            report.push_str(&format!("= {} (se queda: {why})\n", path.display()));
        }
    }
    let migrations: Vec<String> = plan
        .iter()
        .filter(|(path, step)| path.starts_with("migraciones") && matches!(step, Step::Remove))
        .map(|(path, _)| path.display().to_string())
        .collect();
    if !migrations.is_empty() {
        report.push_str(&format!(
            "\naviso: deshecha {}, pero la base de datos no se toca: si ya la aplicaste, sigue ahí \
             (task db:reiniciar la empieza de cero)\n",
            migrations.join(", ")
        ));
    }
    if !conflicts.is_empty() {
        eprint!("{report}");
        return Err(format!(
            "quedan marcas de conflicto (<<<<<<<) en {}: resuélvelas a mano",
            conflicts.join(", ")
        )
        .into());
    }
    Ok(report)
}

fn snapshot_or_empty(dir: &Path) -> std::io::Result<Snapshot> {
    if dir.is_dir() {
        tree::snapshot(dir)
    } else {
        Ok(Snapshot::new())
    }
}

/// The file as it was before the command, keeping what changed after it: a three-way merge whose
/// base is the file as the command left it.
fn merge(was: &[u8], left: &[u8], current: &[u8]) -> Step {
    let (Ok(was), Ok(left), Ok(current)) = (
        std::str::from_utf8(was),
        std::str::from_utf8(left),
        std::str::from_utf8(current),
    ) else {
        return Step::Keep("no es texto y lo cambiaste después");
    };
    match diffy::merge(left, current, was) {
        Ok(merged) => Step::Write(merged.into_bytes()),
        Err(conflicted) => Step::Conflict(conflicted),
    }
}

/// The directories `file` leaves empty, up to the project.
fn remove_empty_parents(cwd: &Path, file: &Path) {
    let mut dir = file.parent();
    while let Some(current) = dir {
        if current == cwd || fs::remove_dir(current).is_err() {
            break;
        }
        dir = current.parent();
    }
}