1use crate::*;
23use std::collections::HashMap;
24use std::fmt;
25use std::path::{Path, PathBuf};
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum DiffError {
30 Syntax(Error),
32 WrongShape(String),
34 DuplicatePath(String),
36 BeforeAnyFile,
38 EmptyPath,
40 Refused(String),
42 FileNotFound(String),
44 PathEscapes(String),
46 EmptySearch(String),
48 PatternNotFound { path: String, pattern: String },
50 PatternAmbiguous { path: String, pattern: String },
52 Io(String),
54}
55
56impl fmt::Display for DiffError {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self {
59 DiffError::Syntax(e) => write!(f, "{e}"),
60 DiffError::WrongShape(s) => write!(f, "heading declares shape '{s}', not diff"),
61 DiffError::DuplicatePath(p) => write!(f, "the same path twice: {p}"),
62 DiffError::BeforeAnyFile => write!(f, "a record before the first FS"),
63 DiffError::EmptyPath => write!(f, "empty path"),
64 DiffError::Refused(why) => write!(f, "{why}"),
65 DiffError::FileNotFound(p) => write!(f, "no such file: {p}"),
66 DiffError::PathEscapes(p) => write!(f, "path escapes the target directory: {p}"),
67 DiffError::EmptySearch(p) => write!(f, "empty search text in {p}"),
68 DiffError::PatternNotFound { path, pattern } => {
69 write!(f, "pattern not found in {path}: {pattern:?}")
70 }
71 DiffError::PatternAmbiguous { path, pattern } => {
72 write!(f, "pattern matched more than once in {path}: {pattern:?}")
73 }
74 DiffError::Io(e) => write!(f, "{e}"),
75 }
76 }
77}
78
79impl std::error::Error for DiffError {}
80
81impl From<Error> for DiffError {
82 fn from(e: Error) -> Self {
83 DiffError::Syntax(e)
84 }
85}
86
87impl From<std::io::Error> for DiffError {
88 fn from(e: std::io::Error) -> Self {
89 DiffError::Io(e.to_string())
90 }
91}
92
93type DiffResult<T> = std::result::Result<T, DiffError>;
94
95fn refused(why: &str) -> DiffError {
96 DiffError::Refused(why.to_string())
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Unit {
102 pub old: Vec<u8>,
103 pub new: Option<Vec<u8>>,
104}
105
106impl Unit {
107 pub fn is_anchor(&self) -> bool {
108 self.new.is_none()
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Eq, Default)]
114pub struct Pattern {
115 pub units: Vec<Unit>,
116}
117
118impl Pattern {
119 pub fn search(&self) -> Vec<u8> {
121 self.units
122 .iter()
123 .flat_map(|u| u.old.iter().copied())
124 .collect()
125 }
126
127 pub fn replacement(&self) -> Vec<u8> {
129 self.units
130 .iter()
131 .flat_map(|u| u.new.as_ref().unwrap_or(&u.old).iter().copied())
132 .collect()
133 }
134
135 pub fn is_assertion(&self) -> bool {
137 self.units.iter().all(Unit::is_anchor)
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct FileEdit {
144 pub path: String,
145 pub records: Vec<Pattern>,
146}
147
148pub fn parse(buf: &[u8]) -> DiffResult<Vec<FileEdit>> {
151 let mut parser = Parser::new(buf, false);
152 let container = Container::parse(buf, buf.len(), &mut parser)?;
153 if container.documents().len() != 1 {
154 return Err(refused("a diff is one document"));
155 }
156 let doc = &container.documents()[0];
157 if let Some(shape) = doc.heading().shape() {
158 if shape != "diff" {
159 return Err(DiffError::WrongShape(shape.to_string()));
160 }
161 }
162 if parser.dead_elements() > 0 {
163 return Err(refused(
164 "a dead element in a diff: a hunk is kept without applying by writing it in a note",
165 ));
166 }
167 let mut files: Vec<FileEdit> = Vec::new();
168 for f in doc.body().files() {
169 if f.is_leading() {
170 if f.groups().is_empty() {
171 continue;
172 }
173 return Err(DiffError::BeforeAnyFile);
174 }
175 let path = String::from_utf8_lossy(f.name()).into_owned();
176 if path.is_empty() {
177 return Err(DiffError::EmptyPath);
178 }
179 if files.iter().any(|e| e.path == path) {
180 return Err(DiffError::DuplicatePath(path));
181 }
182 let mut records = Vec::new();
183 for g in f.groups() {
184 if g.depth() > 0 {
185 return Err(refused("GS in a diff"));
186 }
187 if g.has_header() {
188 return Err(refused("a header row in a diff"));
189 }
190 for r in g.records() {
191 records.push(pattern_of(r)?);
192 }
193 }
194 files.push(FileEdit { path, records });
195 }
196 Ok(files)
197}
198
199fn pattern_of(rec: &Record<'_>) -> DiffResult<Pattern> {
200 if rec.keyed() {
201 return Err(refused("a keyed unit in a diff record"));
202 }
203 let mut units = Vec::new();
204 for u in rec.units() {
205 let old = diff_value(u.raw())?;
206 match u.subs() {
207 [] => units.push(Unit { old, new: None }),
208 [sub] => {
209 if !sub.subs().is_empty() {
210 return Err(refused("a sub-unit of a sub-unit in a diff record"));
211 }
212 let new = diff_value(sub.raw())?;
213 if old.is_empty() && new.is_empty() {
214 return Err(refused("a substitution of nothing by nothing"));
215 }
216 units.push(Unit {
217 old,
218 new: Some(new),
219 });
220 }
221 _ => return Err(refused("two sub-units on one unit: one old has one new")),
222 }
223 }
224 Ok(Pattern { units })
225}
226
227fn diff_value(raw: &[u8]) -> DiffResult<Vec<u8>> {
229 if is_level(raw) {
230 return Err(refused("a nested level in a diff record"));
231 }
232 if is_reference(raw) {
233 return Err(refused("a reference in a diff record"));
234 }
235 Ok(value(raw)?.into_owned())
236}
237
238pub fn apply(
242 diff_buf: &[u8],
243 files: &HashMap<String, String>,
244) -> DiffResult<HashMap<String, String>> {
245 let edits = parse(diff_buf)?;
246 let mut results = Vec::new();
247 for e in &edits {
248 let content = files
249 .get(&e.path)
250 .ok_or_else(|| DiffError::FileNotFound(e.path.clone()))?;
251 results.push((e.path.clone(), apply_file(content.as_bytes(), e)?));
252 }
253 let mut out = files.clone();
254 for (k, v) in results {
255 out.insert(k, String::from_utf8_lossy(&v).into_owned());
256 }
257 Ok(out)
258}
259
260pub fn apply_bytes(
262 diff_buf: &[u8],
263 files: &HashMap<String, Vec<u8>>,
264) -> DiffResult<HashMap<String, Vec<u8>>> {
265 let edits = parse(diff_buf)?;
266 let mut results = Vec::new();
267 for e in &edits {
268 let content = files
269 .get(&e.path)
270 .ok_or_else(|| DiffError::FileNotFound(e.path.clone()))?;
271 results.push((e.path.clone(), apply_file(content, e)?));
272 }
273 let mut out = files.clone();
274 for (k, v) in results {
275 out.insert(k, v);
276 }
277 Ok(out)
278}
279
280pub fn apply_files(diff_buf: &[u8], base_dir: impl AsRef<Path>) -> DiffResult<()> {
284 let edits = parse(diff_buf)?;
285 let base = std::fs::canonicalize(base_dir.as_ref())?;
286 let mut planned: Vec<(PathBuf, Vec<u8>)> = Vec::new();
287 for e in &edits {
288 let target = base.join(&e.path);
289 let resolved =
290 std::fs::canonicalize(&target).map_err(|_| DiffError::FileNotFound(e.path.clone()))?;
291 if !resolved.starts_with(&base) {
292 return Err(DiffError::PathEscapes(e.path.clone()));
293 }
294 let data = std::fs::read(&resolved)?;
295 planned.push((resolved, apply_file(&data, e)?));
296 }
297 for (target, bytes) in planned {
298 let mut tmp = target.clone().into_os_string();
299 tmp.push(".c0diff.tmp");
300 std::fs::write(&tmp, &bytes)?;
301 std::fs::rename(&tmp, &target)?;
302 }
303 Ok(())
304}
305
306pub fn apply_file(data: &[u8], edit: &FileEdit) -> DiffResult<Vec<u8>> {
309 let mut cursor = 0;
310 let mut matches: Vec<(usize, usize, Vec<u8>)> = Vec::new();
311 for pat in &edit.records {
312 let search = pat.search();
313 if search.is_empty() {
314 return Err(DiffError::EmptySearch(edit.path.clone()));
315 }
316 let Some(first) = find(data, &search, cursor) else {
317 return Err(DiffError::PatternNotFound {
318 path: edit.path.clone(),
319 pattern: String::from_utf8_lossy(&search).into_owned(),
320 });
321 };
322 if find(data, &search, first + 1).is_some() {
323 return Err(DiffError::PatternAmbiguous {
324 path: edit.path.clone(),
325 pattern: String::from_utf8_lossy(&search).into_owned(),
326 });
327 }
328 matches.push((first, first + search.len(), pat.replacement()));
329 cursor = first + search.len();
330 }
331 let mut out = Vec::with_capacity(data.len());
332 let mut pos = 0;
333 for (s, e, repl) in matches {
334 out.extend_from_slice(&data[pos..s]);
335 out.extend_from_slice(&repl);
336 pos = e;
337 }
338 out.extend_from_slice(&data[pos..]);
339 Ok(out)
340}
341
342fn find(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
343 if needle.is_empty() || from > hay.len() {
344 return None;
345 }
346 hay[from..]
347 .windows(needle.len())
348 .position(|w| w == needle)
349 .map(|i| i + from)
350}
351
352pub fn build<F: FnOnce(&mut DiffBuilder)>(f: F) -> Vec<u8> {
354 let mut b = DiffBuilder::new();
355 f(&mut b);
356 b.into_bytes()
357}
358
359pub struct DiffBuilder {
361 buf: Vec<u8>,
362}
363
364impl Default for DiffBuilder {
365 fn default() -> Self {
366 Self::new()
367 }
368}
369
370impl DiffBuilder {
371 pub fn new() -> Self {
373 let mut b = DiffBuilder { buf: Vec::new() };
374 b.buf.push(SYN);
375 b.buf.push(SOH);
376 b.buf.extend_from_slice(b"shape");
377 b.buf.push(US);
378 b.buf.extend_from_slice(b"diff");
379 b
380 }
381
382 pub fn bare() -> Self {
384 DiffBuilder { buf: Vec::new() }
385 }
386
387 pub fn file<F: FnOnce(&mut DiffBuilder)>(&mut self, path: &str, f: F) -> &mut Self {
389 self.buf.push(FS);
390 if let Err(e) = write_name(&mut self.buf, path.as_bytes()) {
391 panic!("{e}");
392 }
393 f(self);
394 self
395 }
396
397 pub fn record<F: FnOnce(&mut PatternBuilder)>(&mut self, f: F) -> &mut Self {
399 self.buf.push(RS);
400 let mut pb = PatternBuilder {
401 buf: &mut self.buf,
402 first: true,
403 };
404 f(&mut pb);
405 self
406 }
407
408 pub fn replace(
410 &mut self,
411 context_before: &str,
412 old_text: &str,
413 new_text: &str,
414 context_after: &str,
415 ) -> &mut Self {
416 self.record(|r| {
417 if !context_before.is_empty() {
418 r.anchor(context_before);
419 }
420 r.sub(old_text, new_text);
421 if !context_after.is_empty() {
422 r.anchor(context_after);
423 }
424 })
425 }
426
427 pub fn insert_after(&mut self, anchor: &str, text: &str) -> &mut Self {
429 self.record(|r| {
430 r.anchor(anchor).sub("", text);
431 })
432 }
433
434 pub fn delete(
436 &mut self,
437 old_text: &str,
438 context_before: &str,
439 context_after: &str,
440 ) -> &mut Self {
441 self.replace(context_before, old_text, "", context_after)
442 }
443
444 pub fn assert(&mut self, text: &str) -> &mut Self {
446 self.record(|r| {
447 r.anchor(text);
448 })
449 }
450
451 pub fn note(&mut self, text: &str) -> &mut Self {
453 self.buf.push(BEL);
454 write_value(&mut self.buf, text.as_bytes());
455 self
456 }
457
458 pub fn eot(&mut self) -> &mut Self {
459 self.buf.push(EOT);
460 self
461 }
462
463 pub fn as_bytes(&self) -> &[u8] {
464 &self.buf
465 }
466
467 pub fn into_bytes(self) -> Vec<u8> {
468 self.buf
469 }
470}
471
472pub struct PatternBuilder<'a> {
474 buf: &'a mut Vec<u8>,
475 first: bool,
476}
477
478impl PatternBuilder<'_> {
479 pub fn anchor(&mut self, text: &str) -> &mut Self {
481 self.sep();
482 write_value(self.buf, text.as_bytes());
483 self
484 }
485
486 pub fn sub(&mut self, old_text: &str, new_text: &str) -> &mut Self {
488 self.sep();
489 write_value(self.buf, old_text.as_bytes());
490 self.buf.push(SUB);
491 self.buf.push(US);
492 write_value(self.buf, new_text.as_bytes());
493 self
494 }
495
496 fn sep(&mut self) {
497 if !self.first {
498 self.buf.push(US);
499 }
500 self.first = false;
501 }
502}