1use crate::document::parse_heading;
20use crate::*;
21use std::collections::HashMap;
22use std::fmt;
23use std::path::{Path, PathBuf};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum DiffError {
28 Syntax(Error),
30 WrongShape(String),
32 DuplicatePath(String),
34 BeforeAnyFile,
36 TextPath,
38 EmptyOld,
40 MissingSub,
42 FileNotFound(String),
44 PathEscapes(String),
46 EmptySearch(String),
48 PatternNotFound { path: String, pattern: String },
50 PatternAmbiguous { path: String, pattern: String },
52 ReplaceAllNothing { path: String, old: String },
54 Io(String),
56}
57
58impl fmt::Display for DiffError {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 match self {
61 DiffError::Syntax(e) => write!(f, "{e}"),
62 DiffError::WrongShape(s) => write!(f, "heading declares shape '{s}', not diff"),
63 DiffError::DuplicatePath(p) => write!(f, "the same path twice: {p}"),
64 DiffError::BeforeAnyFile => write!(f, "section or replace-all before any file"),
65 DiffError::TextPath => write!(f, "a path cannot be text"),
66 DiffError::EmptyOld => write!(f, "replace-all with an empty old part"),
67 DiffError::MissingSub => write!(f, "replace-all without SUB"),
68 DiffError::FileNotFound(p) => write!(f, "no such file: {p}"),
69 DiffError::PathEscapes(p) => write!(f, "path escapes the target directory: {p}"),
70 DiffError::EmptySearch(p) => write!(f, "empty search text in {p}"),
71 DiffError::PatternNotFound { path, pattern } => {
72 write!(f, "pattern not found in {path}: {pattern:?}")
73 }
74 DiffError::PatternAmbiguous { path, pattern } => {
75 write!(f, "pattern matched more than once in {path}: {pattern:?}")
76 }
77 DiffError::ReplaceAllNothing { path, old } => {
78 write!(f, "replace-all found nothing in {path}: {old:?}")
79 }
80 DiffError::Io(e) => write!(f, "{e}"),
81 }
82 }
83}
84
85impl std::error::Error for DiffError {}
86
87impl From<Error> for DiffError {
88 fn from(e: Error) -> Self {
89 DiffError::Syntax(e)
90 }
91}
92
93impl From<std::io::Error> for DiffError {
94 fn from(e: std::io::Error) -> Self {
95 DiffError::Io(e.to_string())
96 }
97}
98
99type DiffResult<T> = std::result::Result<T, DiffError>;
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct Unit {
104 pub old: Vec<u8>,
105 pub new: Option<Vec<u8>>,
106}
107
108impl Unit {
109 pub fn is_anchor(&self) -> bool {
110 self.new.is_none()
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Default)]
116pub struct Section {
117 pub units: Vec<Unit>,
118 pub replaces: Vec<(Vec<u8>, Vec<u8>)>,
119}
120
121impl Section {
122 pub fn search(&self) -> Vec<u8> {
124 self.units
125 .iter()
126 .flat_map(|u| u.old.iter().copied())
127 .collect()
128 }
129
130 pub fn replacement(&self) -> Vec<u8> {
132 self.units
133 .iter()
134 .flat_map(|u| u.new.as_ref().unwrap_or(&u.old).iter().copied())
135 .collect()
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct FileEdit {
143 pub path: String,
144 pub leading_replaces: Vec<(Vec<u8>, Vec<u8>)>,
145 pub sections: Vec<Section>,
146}
147
148pub fn parse(buf: &[u8]) -> DiffResult<Vec<FileEdit>> {
150 let len = buf.len();
151 let mut pos = scan::layout(buf, 0, len);
152 if pos < len && buf[pos] == SYN {
153 let (heading, p) = parse_heading(buf, pos + 1, len)?;
154 pos = p;
155 if let Some(shape) = heading.shape() {
156 if shape != "diff" {
157 return Err(DiffError::WrongShape(shape.to_string()));
158 }
159 }
160 }
161 let mut files: Vec<FileEdit> = Vec::new();
162 let mut path: Option<String> = None;
163 let mut leading = Vec::new();
164 let mut sections: Vec<Section> = Vec::new();
165 let flush = |path: &mut Option<String>,
166 leading: &mut Vec<(Vec<u8>, Vec<u8>)>,
167 sections: &mut Vec<Section>,
168 files: &mut Vec<FileEdit>| {
169 if let Some(p) = path.take() {
170 files.push(FileEdit {
171 path: p,
172 leading_replaces: std::mem::take(leading),
173 sections: std::mem::take(sections),
174 });
175 }
176 leading.clear();
177 sections.clear();
178 };
179 while pos < len {
180 pos = scan::layout(buf, pos, len);
181 if pos >= len {
182 break;
183 }
184 let mut b = buf[pos];
185 let mut dead = false;
186 if b == BEL {
187 let p2 = scan::layout(buf, pos + 1, len);
188 if p2 < len && (buf[p2] == FS || buf[p2] == GS || buf[p2] == RS) {
189 dead = true;
190 pos = p2;
191 b = buf[pos];
192 } else {
193 pos = scan::comment(buf, pos, len)?; continue;
195 }
196 }
197 match b {
198 FS => {
199 let (name, p) = read_name(buf, pos + 1, len)?;
200 pos = p;
201 if !dead {
202 flush(&mut path, &mut leading, &mut sections, &mut files);
203 if files.iter().any(|f| f.path == name) {
204 return Err(DiffError::DuplicatePath(name));
205 }
206 path = Some(name);
207 }
208 }
209 GS => {
210 if path.is_none() {
211 return Err(DiffError::BeforeAnyFile);
212 }
213 let (units, p) = parse_pattern(buf, pos + 1, len)?;
214 pos = p;
215 if !dead {
216 sections.push(Section {
217 units,
218 replaces: Vec::new(),
219 });
220 }
221 }
222 RS => {
223 if path.is_none() {
224 return Err(DiffError::BeforeAnyFile);
225 }
226 let (old, p) = read_dvalue(buf, pos + 1, len)?;
227 pos = p;
228 if old.is_empty() {
229 return Err(DiffError::EmptyOld);
230 }
231 if !(pos < len && buf[pos] == SUB) {
232 return Err(DiffError::MissingSub);
233 }
234 let (new, p) = read_dvalue(buf, pos + 1, len)?;
235 pos = p;
236 if !dead {
237 match sections.last_mut() {
238 Some(s) => s.replaces.push((old, new)),
239 None => leading.push((old, new)),
240 }
241 }
242 }
243 ETB => {
244 pos = scan::plain(buf, scan::layout(buf, pos + 1, len), len);
245 }
246 EOT => {
247 pos = scan::layout(buf, pos + 1, len);
248 if pos < len && buf[pos] != SYN && buf[pos] != EM {
249 return Err(Error::syntax("unexpected byte after EOT", pos).into());
250 }
251 break;
252 }
253 _ => return Err(Error::syntax("unexpected byte in a diff body", pos).into()),
254 }
255 }
256 flush(&mut path, &mut leading, &mut sections, &mut files);
257 Ok(files)
258}
259
260pub fn apply(
264 diff_buf: &[u8],
265 files: &HashMap<String, String>,
266) -> DiffResult<HashMap<String, String>> {
267 let edits = parse(diff_buf)?;
268 let mut results = Vec::new();
269 for e in &edits {
270 let content = files
271 .get(&e.path)
272 .ok_or_else(|| DiffError::FileNotFound(e.path.clone()))?;
273 results.push((e.path.clone(), apply_file(content.as_bytes(), e)?));
274 }
275 let mut out = files.clone();
276 for (k, v) in results {
277 out.insert(k, String::from_utf8_lossy(&v).into_owned());
278 }
279 Ok(out)
280}
281
282pub fn apply_bytes(
284 diff_buf: &[u8],
285 files: &HashMap<String, Vec<u8>>,
286) -> DiffResult<HashMap<String, Vec<u8>>> {
287 let edits = parse(diff_buf)?;
288 let mut results = Vec::new();
289 for e in &edits {
290 let content = files
291 .get(&e.path)
292 .ok_or_else(|| DiffError::FileNotFound(e.path.clone()))?;
293 results.push((e.path.clone(), apply_file(content, e)?));
294 }
295 let mut out = files.clone();
296 for (k, v) in results {
297 out.insert(k, v);
298 }
299 Ok(out)
300}
301
302pub fn apply_files(diff_buf: &[u8], base_dir: impl AsRef<Path>) -> DiffResult<()> {
306 let edits = parse(diff_buf)?;
307 let base = std::fs::canonicalize(base_dir.as_ref())?;
308 let mut planned: Vec<(PathBuf, Vec<u8>)> = Vec::new();
309 for e in &edits {
310 let target = base.join(&e.path);
311 let resolved =
312 std::fs::canonicalize(&target).map_err(|_| DiffError::FileNotFound(e.path.clone()))?;
313 if !resolved.starts_with(&base) {
314 return Err(DiffError::PathEscapes(e.path.clone()));
315 }
316 let data = std::fs::read(&resolved)?;
317 planned.push((resolved, apply_file(&data, e)?));
318 }
319 for (target, bytes) in planned {
320 let mut tmp = target.clone().into_os_string();
321 tmp.push(".c0diff.tmp");
322 std::fs::write(&tmp, &bytes)?;
323 std::fs::rename(&tmp, &target)?;
324 }
325 Ok(())
326}
327
328pub fn apply_file(data: &[u8], edit: &FileEdit) -> DiffResult<Vec<u8>> {
330 let mut cursor = 0;
331 let mut matches: Vec<(usize, usize, Vec<u8>)> = Vec::new();
332 for sec in &edit.sections {
333 let search = sec.search();
334 if search.is_empty() {
335 return Err(DiffError::EmptySearch(edit.path.clone()));
336 }
337 let Some(first) = find(data, &search, cursor) else {
338 return Err(DiffError::PatternNotFound {
339 path: edit.path.clone(),
340 pattern: String::from_utf8_lossy(&search).into_owned(),
341 });
342 };
343 if find(data, &search, first + 1).is_some() {
344 return Err(DiffError::PatternAmbiguous {
345 path: edit.path.clone(),
346 pattern: String::from_utf8_lossy(&search).into_owned(),
347 });
348 }
349 matches.push((first, first + search.len(), sec.replacement()));
350 cursor = first + search.len();
351 }
352 let mut out = Vec::with_capacity(data.len());
354 let first_start = matches.first().map_or(data.len(), |m| m.0);
355 out.extend(replace_all(
356 &data[..first_start],
357 &edit.leading_replaces,
358 &edit.path,
359 )?);
360 for (i, (_, e, repl)) in matches.iter().enumerate() {
361 out.extend_from_slice(repl);
362 let next = matches.get(i + 1).map_or(data.len(), |m| m.0);
363 out.extend(replace_all(
364 &data[*e..next],
365 &edit.sections[i].replaces,
366 &edit.path,
367 )?);
368 }
369 Ok(out)
370}
371
372fn replace_all(segment: &[u8], replaces: &[(Vec<u8>, Vec<u8>)], path: &str) -> DiffResult<Vec<u8>> {
373 let mut segment = segment.to_vec();
374 for (old, new) in replaces {
375 let mut count = 0;
376 let mut out = Vec::with_capacity(segment.len());
377 let mut pos = 0;
378 while let Some(i) = find(&segment, old, pos) {
379 out.extend_from_slice(&segment[pos..i]);
380 out.extend_from_slice(new);
381 pos = i + old.len();
382 count += 1;
383 }
384 if count == 0 {
385 return Err(DiffError::ReplaceAllNothing {
386 path: path.to_string(),
387 old: String::from_utf8_lossy(old).into_owned(),
388 });
389 }
390 out.extend_from_slice(&segment[pos..]);
391 segment = out;
392 }
393 Ok(segment)
394}
395
396fn find(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
397 if needle.is_empty() || from > hay.len() {
398 return None;
399 }
400 hay[from..]
401 .windows(needle.len())
402 .position(|w| w == needle)
403 .map(|i| i + from)
404}
405
406fn read_name(buf: &[u8], pos: usize, len: usize) -> DiffResult<(String, usize)> {
407 let pos = scan::layout(buf, pos, len);
408 if pos < len && buf[pos] == STX {
409 return Err(DiffError::TextPath);
410 }
411 let stop = scan::plain(buf, pos, len);
412 Ok((
413 String::from_utf8_lossy(trim(&buf[pos..stop])).into_owned(),
414 stop,
415 ))
416}
417
418fn read_dvalue(buf: &[u8], pos: usize, len: usize) -> DiffResult<(Vec<u8>, usize)> {
419 let pos = scan::layout(buf, pos, len);
420 if pos >= len {
421 return Ok((Vec::new(), pos));
422 }
423 if buf[pos] == STX {
424 let stop = scan::text(buf, pos, len)?;
425 let val = decode_text(&buf[pos + 1..stop - 1]).into_owned();
426 Ok((val, scan::layout(buf, stop, len)))
427 } else if buf[pos] >= 0x20 {
428 let stop = scan::plain(buf, pos, len);
429 Ok((trim(&buf[pos..stop]).to_vec(), stop))
430 } else {
431 Ok((Vec::new(), pos))
432 }
433}
434
435fn parse_pattern(buf: &[u8], mut pos: usize, len: usize) -> DiffResult<(Vec<Unit>, usize)> {
436 let mut units = Vec::new();
437 loop {
438 let (old, p) = read_dvalue(buf, pos, len)?;
439 pos = p;
440 if pos < len && buf[pos] == SUB {
441 let (new, p) = read_dvalue(buf, pos + 1, len)?;
442 pos = p;
443 units.push(Unit {
444 old,
445 new: Some(new),
446 });
447 } else {
448 units.push(Unit { old, new: None });
449 }
450 while pos < len && buf[pos] == BEL {
452 let p2 = scan::layout(buf, pos + 1, len);
453 if !(p2 < len && (buf[p2] >= 0x20 || buf[p2] == STX)) {
454 break;
455 }
456 pos = scan::layout(buf, scan::comment(buf, pos, len)?, len);
457 }
458 if !(pos < len && buf[pos] == US) {
459 break;
460 }
461 pos += 1;
462 }
463 Ok((units, pos))
464}
465
466pub fn build<F: FnOnce(&mut DiffBuilder)>(f: F) -> Vec<u8> {
468 let mut b = DiffBuilder::new();
469 f(&mut b);
470 b.into_bytes()
471}
472
473pub struct DiffBuilder {
475 buf: Vec<u8>,
476}
477
478impl Default for DiffBuilder {
479 fn default() -> Self {
480 Self::new()
481 }
482}
483
484impl DiffBuilder {
485 pub fn new() -> Self {
487 let mut b = DiffBuilder { buf: Vec::new() };
488 b.buf.push(SYN);
489 b.buf.push(SOH);
490 b.buf.extend_from_slice(b"shape");
491 b.buf.push(US);
492 b.buf.extend_from_slice(b"diff");
493 b
494 }
495
496 pub fn bare() -> Self {
498 DiffBuilder { buf: Vec::new() }
499 }
500
501 pub fn file<F: FnOnce(&mut DiffBuilder)>(&mut self, path: &str, f: F) -> &mut Self {
503 self.buf.push(FS);
504 if let Err(e) = write_name(&mut self.buf, path.as_bytes()) {
505 panic!("{e}");
506 }
507 f(self);
508 self
509 }
510
511 pub fn section<F: FnOnce(&mut SectionBuilder)>(&mut self, f: F) -> &mut Self {
513 self.buf.push(GS);
514 let mut sb = SectionBuilder {
515 buf: &mut self.buf,
516 first: true,
517 };
518 f(&mut sb);
519 self
520 }
521
522 pub fn replace(
524 &mut self,
525 context_before: &str,
526 old_text: &str,
527 new_text: &str,
528 context_after: &str,
529 ) -> &mut Self {
530 self.section(|s| {
531 if !context_before.is_empty() {
532 s.anchor(context_before);
533 }
534 s.sub(old_text, new_text);
535 if !context_after.is_empty() {
536 s.anchor(context_after);
537 }
538 })
539 }
540
541 pub fn replace_all(&mut self, old_text: &str, new_text: &str) -> &mut Self {
544 assert!(
545 !old_text.is_empty(),
546 "replace-all needs a non-empty old part"
547 );
548 self.buf.push(RS);
549 write_value(&mut self.buf, old_text.as_bytes());
550 self.buf.push(SUB);
551 write_value(&mut self.buf, new_text.as_bytes());
552 self
553 }
554
555 pub fn note(&mut self, text: &str) -> &mut Self {
557 self.buf.push(BEL);
558 write_value(&mut self.buf, text.as_bytes());
559 self
560 }
561
562 pub fn eot(&mut self) -> &mut Self {
563 self.buf.push(EOT);
564 self
565 }
566
567 pub fn as_bytes(&self) -> &[u8] {
568 &self.buf
569 }
570
571 pub fn into_bytes(self) -> Vec<u8> {
572 self.buf
573 }
574}
575
576pub struct SectionBuilder<'a> {
578 buf: &'a mut Vec<u8>,
579 first: bool,
580}
581
582impl SectionBuilder<'_> {
583 pub fn anchor(&mut self, text: &str) -> &mut Self {
585 self.sep();
586 write_value(self.buf, text.as_bytes());
587 self
588 }
589
590 pub fn sub(&mut self, old_text: &str, new_text: &str) -> &mut Self {
592 self.sep();
593 write_value(self.buf, old_text.as_bytes());
594 self.buf.push(SUB);
595 write_value(self.buf, new_text.as_bytes());
596 self
597 }
598
599 fn sep(&mut self) {
600 if !self.first {
601 self.buf.push(US);
602 }
603 self.first = false;
604 }
605}