use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
pub const NOT_COPIED: &[&str] = &[
"target",
"node_modules",
".git",
"dist",
".devenv",
".direnv",
".task",
".puerto",
];
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()),
)
}
}
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,
Modified {
added: usize,
removed: usize,
},
Deleted,
}
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 }
}