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.
//! A project's files as a tree: copying it (`generar campo`, `--simular`), its photo and what
//! changed between two photos (`--simular`, the history of `puerto deshacer`).
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

/// Never copied nor photographed: build output, dependencies, git, the devenv/direnv state, Task's
/// checksums and Puerto's own history (Fase 37.6).
pub const NOT_COPIED: &[&str] = &[
    "target",
    "node_modules",
    ".git",
    "dist",
    ".devenv",
    ".direnv",
    ".task",
    ".puerto",
];

/// Links are skipped: no entity file is one, and `.devenv` points into the nix store.
pub fn copy_project(from: &Path, to: &Path) -> std::io::Result<()> {
    for entry in fs::read_dir(from).map_err(copy_error(from))? {
        let entry = entry.map_err(copy_error(from))?;
        let path = entry.path();
        let name = entry.file_name();
        let target = to.join(&name);
        let file_type = entry.file_type().map_err(copy_error(&path))?;
        if file_type.is_symlink() {
            continue;
        }
        if file_type.is_dir() {
            if NOT_COPIED.iter().any(|d| name == *d) {
                continue;
            }
            fs::create_dir_all(&target).map_err(copy_error(&target))?;
            copy_project(&path, &target)?;
        } else {
            fs::copy(&path, &target).map_err(copy_error(&path))?;
        }
    }
    Ok(())
}

fn copy_error(path: &Path) -> impl FnOnce(std::io::Error) -> std::io::Error + '_ {
    move |e| {
        std::io::Error::new(
            e.kind(),
            format!("no se puede copiar {}: {e}", path.display()),
        )
    }
}

/// Every file under `root` that [`copy_project`] would copy, by its path relative to `root`.
pub type Snapshot = BTreeMap<PathBuf, Vec<u8>>;

pub fn snapshot(root: &Path) -> std::io::Result<Snapshot> {
    let mut files = Snapshot::new();
    photograph(root, Path::new(""), &mut files)?;
    Ok(files)
}

fn photograph(root: &Path, rel: &Path, files: &mut Snapshot) -> std::io::Result<()> {
    for entry in fs::read_dir(root.join(rel))? {
        let entry = entry?;
        let name = entry.file_name();
        let path = rel.join(&name);
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            continue;
        }
        if file_type.is_dir() {
            if !NOT_COPIED.iter().any(|d| name == *d) {
                photograph(root, &path, files)?;
            }
        } else {
            files.insert(path.clone(), fs::read(root.join(&path))?);
        }
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
    Created,
    /// Its lines added and removed.
    Modified {
        added: usize,
        removed: usize,
    },
    Deleted,
}

/// What changed from `before` to `after`, by path.
pub fn changes(before: &Snapshot, after: &Snapshot) -> Vec<(PathBuf, Change)> {
    let paths: std::collections::BTreeSet<&PathBuf> = before.keys().chain(after.keys()).collect();
    paths
        .into_iter()
        .filter_map(|path| {
            let change = match (before.get(path), after.get(path)) {
                (None, Some(_)) => Change::Created,
                (Some(_), None) => Change::Deleted,
                (Some(old), Some(new)) if old != new => lines_changed(old, new),
                _ => return None,
            };
            Some((path.clone(), change))
        })
        .collect()
}

fn lines_changed(old: &[u8], new: &[u8]) -> Change {
    let (old, new) = (String::from_utf8_lossy(old), String::from_utf8_lossy(new));
    let patch = diffy::create_patch(&old, &new);
    let (mut added, mut removed) = (0, 0);
    for line in patch.hunks().iter().flat_map(|h| h.lines()) {
        match line {
            diffy::Line::Insert(_) => added += 1,
            diffy::Line::Delete(_) => removed += 1,
            diffy::Line::Context(_) => {}
        }
    }
    Change::Modified { added, removed }
}