use crate::*;
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffError {
Syntax(Error),
WrongShape(String),
DuplicatePath(String),
BeforeAnyFile,
EmptyPath,
Refused(String),
FileNotFound(String),
PathEscapes(String),
EmptySearch(String),
PatternNotFound { path: String, pattern: String },
PatternAmbiguous { path: String, pattern: String },
Io(String),
}
impl fmt::Display for DiffError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DiffError::Syntax(e) => write!(f, "{e}"),
DiffError::WrongShape(s) => write!(f, "heading declares shape '{s}', not diff"),
DiffError::DuplicatePath(p) => write!(f, "the same path twice: {p}"),
DiffError::BeforeAnyFile => write!(f, "a record before the first FS"),
DiffError::EmptyPath => write!(f, "empty path"),
DiffError::Refused(why) => write!(f, "{why}"),
DiffError::FileNotFound(p) => write!(f, "no such file: {p}"),
DiffError::PathEscapes(p) => write!(f, "path escapes the target directory: {p}"),
DiffError::EmptySearch(p) => write!(f, "empty search text in {p}"),
DiffError::PatternNotFound { path, pattern } => {
write!(f, "pattern not found in {path}: {pattern:?}")
}
DiffError::PatternAmbiguous { path, pattern } => {
write!(f, "pattern matched more than once in {path}: {pattern:?}")
}
DiffError::Io(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for DiffError {}
impl From<Error> for DiffError {
fn from(e: Error) -> Self {
DiffError::Syntax(e)
}
}
impl From<std::io::Error> for DiffError {
fn from(e: std::io::Error) -> Self {
DiffError::Io(e.to_string())
}
}
type DiffResult<T> = std::result::Result<T, DiffError>;
fn refused(why: &str) -> DiffError {
DiffError::Refused(why.to_string())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unit {
pub old: Vec<u8>,
pub new: Option<Vec<u8>>,
}
impl Unit {
pub fn is_anchor(&self) -> bool {
self.new.is_none()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pattern {
pub units: Vec<Unit>,
}
impl Pattern {
pub fn search(&self) -> Vec<u8> {
self.units
.iter()
.flat_map(|u| u.old.iter().copied())
.collect()
}
pub fn replacement(&self) -> Vec<u8> {
self.units
.iter()
.flat_map(|u| u.new.as_ref().unwrap_or(&u.old).iter().copied())
.collect()
}
pub fn is_assertion(&self) -> bool {
self.units.iter().all(Unit::is_anchor)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEdit {
pub path: String,
pub records: Vec<Pattern>,
}
pub fn parse(buf: &[u8]) -> DiffResult<Vec<FileEdit>> {
let mut parser = Parser::new(buf, false);
let container = Container::parse(buf, buf.len(), &mut parser)?;
if container.documents().len() != 1 {
return Err(refused("a diff is one document"));
}
let doc = &container.documents()[0];
if let Some(shape) = doc.heading().shape() {
if shape != "diff" {
return Err(DiffError::WrongShape(shape.to_string()));
}
}
if parser.dead_elements() > 0 {
return Err(refused(
"a dead element in a diff: a hunk is kept without applying by writing it in a note",
));
}
let mut files: Vec<FileEdit> = Vec::new();
for f in doc.body().files() {
if f.is_leading() {
if f.groups().is_empty() {
continue;
}
return Err(DiffError::BeforeAnyFile);
}
let path = String::from_utf8_lossy(f.name()).into_owned();
if path.is_empty() {
return Err(DiffError::EmptyPath);
}
if files.iter().any(|e| e.path == path) {
return Err(DiffError::DuplicatePath(path));
}
let mut records = Vec::new();
for g in f.groups() {
if g.depth() > 0 {
return Err(refused("GS in a diff"));
}
if g.has_header() {
return Err(refused("a header row in a diff"));
}
for r in g.records() {
records.push(pattern_of(r)?);
}
}
files.push(FileEdit { path, records });
}
Ok(files)
}
fn pattern_of(rec: &Record<'_>) -> DiffResult<Pattern> {
if rec.keyed() {
return Err(refused("a keyed unit in a diff record"));
}
let mut units = Vec::new();
for u in rec.units() {
let old = diff_value(u.raw())?;
match u.subs() {
[] => units.push(Unit { old, new: None }),
[sub] => {
if !sub.subs().is_empty() {
return Err(refused("a sub-unit of a sub-unit in a diff record"));
}
let new = diff_value(sub.raw())?;
if old.is_empty() && new.is_empty() {
return Err(refused("a substitution of nothing by nothing"));
}
units.push(Unit {
old,
new: Some(new),
});
}
_ => return Err(refused("two sub-units on one unit: one old has one new")),
}
}
Ok(Pattern { units })
}
fn diff_value(raw: &[u8]) -> DiffResult<Vec<u8>> {
if is_level(raw) {
return Err(refused("a nested level in a diff record"));
}
if is_reference(raw) {
return Err(refused("a reference in a diff record"));
}
Ok(value(raw)?.into_owned())
}
pub fn apply(
diff_buf: &[u8],
files: &HashMap<String, String>,
) -> DiffResult<HashMap<String, String>> {
let edits = parse(diff_buf)?;
let mut results = Vec::new();
for e in &edits {
let content = files
.get(&e.path)
.ok_or_else(|| DiffError::FileNotFound(e.path.clone()))?;
results.push((e.path.clone(), apply_file(content.as_bytes(), e)?));
}
let mut out = files.clone();
for (k, v) in results {
out.insert(k, String::from_utf8_lossy(&v).into_owned());
}
Ok(out)
}
pub fn apply_bytes(
diff_buf: &[u8],
files: &HashMap<String, Vec<u8>>,
) -> DiffResult<HashMap<String, Vec<u8>>> {
let edits = parse(diff_buf)?;
let mut results = Vec::new();
for e in &edits {
let content = files
.get(&e.path)
.ok_or_else(|| DiffError::FileNotFound(e.path.clone()))?;
results.push((e.path.clone(), apply_file(content, e)?));
}
let mut out = files.clone();
for (k, v) in results {
out.insert(k, v);
}
Ok(out)
}
pub fn apply_files(diff_buf: &[u8], base_dir: impl AsRef<Path>) -> DiffResult<()> {
let edits = parse(diff_buf)?;
let base = std::fs::canonicalize(base_dir.as_ref())?;
let mut planned: Vec<(PathBuf, Vec<u8>)> = Vec::new();
for e in &edits {
let target = base.join(&e.path);
let resolved =
std::fs::canonicalize(&target).map_err(|_| DiffError::FileNotFound(e.path.clone()))?;
if !resolved.starts_with(&base) {
return Err(DiffError::PathEscapes(e.path.clone()));
}
let data = std::fs::read(&resolved)?;
planned.push((resolved, apply_file(&data, e)?));
}
for (target, bytes) in planned {
let mut tmp = target.clone().into_os_string();
tmp.push(".c0diff.tmp");
std::fs::write(&tmp, &bytes)?;
std::fs::rename(&tmp, &target)?;
}
Ok(())
}
pub fn apply_file(data: &[u8], edit: &FileEdit) -> DiffResult<Vec<u8>> {
let mut cursor = 0;
let mut matches: Vec<(usize, usize, Vec<u8>)> = Vec::new();
for pat in &edit.records {
let search = pat.search();
if search.is_empty() {
return Err(DiffError::EmptySearch(edit.path.clone()));
}
let Some(first) = find(data, &search, cursor) else {
return Err(DiffError::PatternNotFound {
path: edit.path.clone(),
pattern: String::from_utf8_lossy(&search).into_owned(),
});
};
if find(data, &search, first + 1).is_some() {
return Err(DiffError::PatternAmbiguous {
path: edit.path.clone(),
pattern: String::from_utf8_lossy(&search).into_owned(),
});
}
matches.push((first, first + search.len(), pat.replacement()));
cursor = first + search.len();
}
let mut out = Vec::with_capacity(data.len());
let mut pos = 0;
for (s, e, repl) in matches {
out.extend_from_slice(&data[pos..s]);
out.extend_from_slice(&repl);
pos = e;
}
out.extend_from_slice(&data[pos..]);
Ok(out)
}
fn find(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
if needle.is_empty() || from > hay.len() {
return None;
}
hay[from..]
.windows(needle.len())
.position(|w| w == needle)
.map(|i| i + from)
}
pub fn build<F: FnOnce(&mut DiffBuilder)>(f: F) -> Vec<u8> {
let mut b = DiffBuilder::new();
f(&mut b);
b.into_bytes()
}
pub struct DiffBuilder {
buf: Vec<u8>,
}
impl Default for DiffBuilder {
fn default() -> Self {
Self::new()
}
}
impl DiffBuilder {
pub fn new() -> Self {
let mut b = DiffBuilder { buf: Vec::new() };
b.buf.push(SYN);
b.buf.push(SOH);
b.buf.extend_from_slice(b"shape");
b.buf.push(US);
b.buf.extend_from_slice(b"diff");
b
}
pub fn bare() -> Self {
DiffBuilder { buf: Vec::new() }
}
pub fn file<F: FnOnce(&mut DiffBuilder)>(&mut self, path: &str, f: F) -> &mut Self {
self.buf.push(FS);
if let Err(e) = write_name(&mut self.buf, path.as_bytes()) {
panic!("{e}");
}
f(self);
self
}
pub fn record<F: FnOnce(&mut PatternBuilder)>(&mut self, f: F) -> &mut Self {
self.buf.push(RS);
let mut pb = PatternBuilder {
buf: &mut self.buf,
first: true,
};
f(&mut pb);
self
}
pub fn replace(
&mut self,
context_before: &str,
old_text: &str,
new_text: &str,
context_after: &str,
) -> &mut Self {
self.record(|r| {
if !context_before.is_empty() {
r.anchor(context_before);
}
r.sub(old_text, new_text);
if !context_after.is_empty() {
r.anchor(context_after);
}
})
}
pub fn insert_after(&mut self, anchor: &str, text: &str) -> &mut Self {
self.record(|r| {
r.anchor(anchor).sub("", text);
})
}
pub fn delete(
&mut self,
old_text: &str,
context_before: &str,
context_after: &str,
) -> &mut Self {
self.replace(context_before, old_text, "", context_after)
}
pub fn assert(&mut self, text: &str) -> &mut Self {
self.record(|r| {
r.anchor(text);
})
}
pub fn note(&mut self, text: &str) -> &mut Self {
self.buf.push(BEL);
write_value(&mut self.buf, text.as_bytes());
self
}
pub fn eot(&mut self) -> &mut Self {
self.buf.push(EOT);
self
}
pub fn as_bytes(&self) -> &[u8] {
&self.buf
}
pub fn into_bytes(self) -> Vec<u8> {
self.buf
}
}
pub struct PatternBuilder<'a> {
buf: &'a mut Vec<u8>,
first: bool,
}
impl PatternBuilder<'_> {
pub fn anchor(&mut self, text: &str) -> &mut Self {
self.sep();
write_value(self.buf, text.as_bytes());
self
}
pub fn sub(&mut self, old_text: &str, new_text: &str) -> &mut Self {
self.sep();
write_value(self.buf, old_text.as_bytes());
self.buf.push(SUB);
self.buf.push(US);
write_value(self.buf, new_text.as_bytes());
self
}
fn sep(&mut self) {
if !self.first {
self.buf.push(US);
}
self.first = false;
}
}