Skip to main content

grit_lib/apply/
mod.rs

1//! Unified/`git`-diff patch parsing and blob-level hunk application.
2//!
3//! Parses patch text into structured [`FilePatch`]/[`Hunk`] data with no I/O or
4//! environment access. [`apply_hunks_to_blob`] applies hunks to a single blob
5//! in memory (worktree/index application is built on this in later layers).
6//!
7//! Library guide: [apply](https://grit-scm.com/docs/library/embedding)
8//!
9//! ```rust
10//! use grit_lib::repo::{InitOptions, Repository};
11//! # fn main() -> grit_lib::error::Result<()> {
12//! let dir = tempfile::tempdir()?;
13//! let (_repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
14//! # Ok(())
15//! # }
16//! ```
17
18mod apply_blob;
19
20pub use apply_blob::{apply_hunks_to_blob, ApplyOptions};
21
22use crate::error::{ApplyError, BinaryPatchError, Error, PatchSide, Result};
23use crate::quote_path_root::unquote_c_style_prefix;
24use regex::Regex;
25use std::sync::OnceLock;
26
27/// A single hunk in a unified diff.
28#[derive(Debug, Clone)]
29pub struct Hunk {
30    /// 1-based line number in the old file.
31    pub old_start: usize,
32    /// Number of lines in the old side.
33    pub old_count: usize,
34    /// 1-based line number in the new file.
35    pub new_start: usize,
36    /// Number of lines on the new side.
37    pub new_count: usize,
38    /// 1-based line number in the patch file of the first hunk body line (line after `@@`).
39    pub first_body_line: usize,
40    /// Lines of the hunk body (' ', '+', '-' prefixed, or bare '\' no newline).
41    pub lines: Vec<HunkLine>,
42}
43
44/// One line in a unified-diff hunk body.
45#[derive(Debug, Clone)]
46pub enum HunkLine {
47    /// Unchanged context line (leading space in the patch).
48    Context(String),
49    /// Added line (leading `+`).
50    Add(String),
51    /// Removed line (leading `-`).
52    Remove(String),
53    /// "\ No newline at end of file"
54    NoNewline,
55}
56
57/// Represents one file in a unified diff.
58#[derive(Debug, Clone)]
59pub struct FilePatch {
60    /// Path from `diff --git` old side (`a/...`) when present.
61    pub diff_old_path: Option<String>,
62    /// Path from `diff --git` new side (`b/...`) when present.
63    pub diff_new_path: Option<String>,
64    /// Path on the old side (None for new files).
65    pub old_path: Option<String>,
66    /// Path on the new side (None for deleted files).
67    pub new_path: Option<String>,
68    /// Whether an explicit `---` header line was present.
69    pub saw_old_header: bool,
70    /// Whether an explicit `+++` header line was present.
71    pub saw_new_header: bool,
72    /// Old mode from extended header.
73    pub old_mode: Option<String>,
74    /// New mode from extended header.
75    pub new_mode: Option<String>,
76    /// Source line (1-based) of `old mode` / `deleted file mode` for diagnostics.
77    pub old_mode_line: Option<usize>,
78    /// Source line (1-based) of `new mode` / `new file mode` for diagnostics.
79    pub new_mode_line: Option<usize>,
80    /// Whether this file is being newly created.
81    pub is_new: bool,
82    /// Whether this file is being deleted.
83    pub is_deleted: bool,
84    /// Whether this is a rename.
85    pub is_rename: bool,
86    /// Whether this is a copy.
87    pub is_copy: bool,
88    /// Similarity index (e.g., 90 for 90%).
89    pub similarity_index: Option<u32>,
90    /// Dissimilarity index for rewrites.
91    pub dissimilarity_index: Option<u32>,
92    /// Old blob OID from the index header (abbreviated).
93    pub old_oid: Option<String>,
94    /// New blob OID from the index header (abbreviated).
95    pub new_oid: Option<String>,
96    /// Parsed binary patch payload (`GIT binary patch`) if present.
97    pub binary_patch: Option<BinaryPatchPayload>,
98    /// Whether this is a binary change (`GIT binary patch` payload or a
99    /// `Binary files ... differ` marker); stat/numstat show `Bin` / `-`.
100    pub is_binary: bool,
101    /// Hunks to apply.
102    pub hunks: Vec<Hunk>,
103    /// Merged `core.whitespace` + `whitespace` attribute (Git `ws_rule`); `0` before assignment.
104    pub ws_rule: u32,
105    /// Git `patch->is_toplevel_relative`: set for `diff --git` patches only. When false, paths are
106    /// prefixed with the setup directory (work-tree-relative CWD) like `prefix_patch` in Git.
107    pub is_toplevel_relative: bool,
108}
109
110/// Whether a `GIT binary patch` section holds a full literal or a delta against the other side.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum BinaryPatchSectionKind {
113    /// Zlib-compressed full file contents (`literal N`).
114    Literal,
115    /// Zlib-compressed Git binary delta (`delta N`) applied to the preimage blob.
116    Delta,
117}
118
119/// One forward or reverse chunk in a `GIT binary patch`.
120#[derive(Debug, Clone)]
121pub struct BinaryPatchSection {
122    /// Whether this chunk is a full literal or a delta.
123    pub kind: BinaryPatchSectionKind,
124    /// Zlib-compressed payload from the `GIT binary patch` section.
125    pub compressed: Vec<u8>,
126    /// Declared uncompressed size from the section header (`literal N` / `delta N`).
127    pub declared_size: usize,
128}
129
130/// Binary patch payload as compressed base85 chunks for forward/reverse apply.
131#[derive(Debug, Clone)]
132pub struct BinaryPatchPayload {
133    /// Forward-direction patch chunk applied when checking out the new blob.
134    pub forward: BinaryPatchSection,
135    /// Reverse section when present (second `literal`/`delta` block).
136    pub reverse: Option<BinaryPatchSection>,
137}
138
139impl FilePatch {
140    fn empty() -> Self {
141        Self {
142            diff_old_path: None,
143            diff_new_path: None,
144            old_path: None,
145            new_path: None,
146            saw_old_header: false,
147            saw_new_header: false,
148            old_mode: None,
149            new_mode: None,
150            old_mode_line: None,
151            new_mode_line: None,
152            is_new: false,
153            is_deleted: false,
154            is_rename: false,
155            is_copy: false,
156            similarity_index: None,
157            dissimilarity_index: None,
158            old_oid: None,
159            new_oid: None,
160            binary_patch: None,
161            is_binary: false,
162            hunks: Vec::new(),
163            ws_rule: 0,
164            is_toplevel_relative: false,
165        }
166    }
167
168    /// Effective path for the file.
169    /// For deletions, use old_path (new is /dev/null).
170    /// For additions, use new_path (old is /dev/null).
171    /// Otherwise prefer new_path.
172    pub fn effective_path(&self) -> Option<&str> {
173        if self.is_deleted {
174            return self
175                .old_path
176                .as_deref()
177                .filter(|p| *p != "/dev/null")
178                .or(self.new_path.as_deref().filter(|p| *p != "/dev/null"));
179        }
180        if self.is_new {
181            return self
182                .new_path
183                .as_deref()
184                .filter(|p| *p != "/dev/null")
185                .or(self.old_path.as_deref().filter(|p| *p != "/dev/null"));
186        }
187        self.new_path
188            .as_deref()
189            .filter(|p| *p != "/dev/null")
190            .or(self.old_path.as_deref().filter(|p| *p != "/dev/null"))
191    }
192
193    /// Source path to read preimage content from.
194    ///
195    /// For rename/copy patches this is the old path, otherwise this is the
196    /// effective path.
197    pub(crate) fn source_path(&self) -> Option<&str> {
198        if self.is_rename || self.is_copy {
199            self.old_path
200                .as_deref()
201                .filter(|p| *p != "/dev/null")
202                .or(self.effective_path())
203        } else if let (Some(old), Some(new)) = (self.old_path.as_deref(), self.new_path.as_deref())
204        {
205            if old != "/dev/null" && new != "/dev/null" && old != new {
206                Some(old)
207            } else {
208                self.effective_path()
209            }
210        } else {
211            self.effective_path()
212        }
213    }
214
215    /// Destination path to write postimage content to.
216    ///
217    /// For additions/renames/copies this is the new path, otherwise this is
218    /// the effective path.
219    pub(crate) fn target_path(&self) -> Option<&str> {
220        if self.is_new || self.is_rename || self.is_copy {
221            self.new_path
222                .as_deref()
223                .filter(|p| *p != "/dev/null")
224                .or(self.effective_path())
225        } else {
226            self.effective_path()
227        }
228    }
229
230    /// True when this patch touches a gitlink/submodule (mode `160000`).
231    pub(crate) fn involves_gitlink(&self) -> bool {
232        self.old_mode.as_deref() == Some("160000") || self.new_mode.as_deref() == Some("160000")
233    }
234}
235
236/// Strip trailing `\r` and surrounding whitespace from parsed header tokens.
237///
238/// `git diff` may emit CRLF line endings; without this, `new mode 160000\r` fails to match
239/// submodule handling (`t4137-apply-submodule`).
240fn sanitize_patch_header_value(s: &mut String) {
241    *s = s.trim().trim_end_matches('\r').to_string();
242}
243
244/// Strip Git's `diff --git a/... b/...` path prefix when it leaked into stored paths.
245///
246/// Binary patches often omit `---`/`+++` lines that would normally resynchronize names; without
247/// this, paths like `a/bin.png` are misinterpreted as real file paths (`t4108-apply-threeway`).
248fn strip_git_diff_path_prefix(path: &str) -> String {
249    if path == "/dev/null" {
250        return path.to_string();
251    }
252    let p = path.trim_start_matches("./");
253    if let Some(rest) = p.strip_prefix("a/") {
254        return rest.to_string();
255    }
256    if let Some(rest) = p.strip_prefix("b/") {
257        return rest.to_string();
258    }
259    path.to_string()
260}
261
262fn sanitize_file_patch_headers(fp: &mut FilePatch) {
263    if let Some(ref mut s) = fp.old_mode {
264        sanitize_patch_header_value(s);
265        if s.is_empty() {
266            fp.old_mode = None;
267        }
268    }
269    if let Some(ref mut s) = fp.new_mode {
270        sanitize_patch_header_value(s);
271        if s.is_empty() {
272            fp.new_mode = None;
273        }
274    }
275    if let Some(ref mut s) = fp.old_oid {
276        sanitize_patch_header_value(s);
277    }
278    if let Some(ref mut s) = fp.new_oid {
279        sanitize_patch_header_value(s);
280    }
281    for ref mut s in [
282        &mut fp.diff_old_path,
283        &mut fp.diff_new_path,
284        &mut fp.old_path,
285        &mut fp.new_path,
286    ]
287    .into_iter()
288    .flatten()
289    {
290        sanitize_patch_header_value(s);
291        **s = strip_git_diff_path_prefix(s);
292    }
293}
294
295/// Collapse runs of `/` to a single slash (Git `squash_slash`).
296fn squash_slash_path(s: &str) -> String {
297    let mut out = String::with_capacity(s.len());
298    let mut prev_slash = false;
299    for ch in s.chars() {
300        if ch == '/' {
301            if !prev_slash {
302                out.push('/');
303            }
304            prev_slash = true;
305        } else {
306            prev_slash = false;
307            out.push(ch);
308        }
309    }
310    out
311}
312
313fn bytes_to_path_string(bytes: &[u8]) -> Result<String> {
314    let s = String::from_utf8(bytes.to_vec()).map_err(|_| ApplyError::PathNotUtf8)?;
315    Ok(squash_slash_path(&s))
316}
317
318/// Skip `p_value` leading path components (Git `skip_tree_prefix`); `p_value == 0` allows absolute paths.
319fn skip_tree_prefix_bytes(line: &[u8], p_value: usize) -> Option<&[u8]> {
320    if p_value == 0 {
321        return Some(line);
322    }
323    let mut nslash = p_value;
324    let mut i = 0usize;
325    while i < line.len() {
326        if line[i] == b'/' {
327            nslash = nslash.saturating_sub(1);
328            if nslash == 0 {
329                return if i == 0 { None } else { Some(&line[i + 1..]) };
330            }
331        }
332        i += 1;
333    }
334    None
335}
336
337/// Strip `p_value` leading `/`-separated components from a UTF-8 path (for `rename from` etc.).
338fn skip_tree_prefix_str(path: &str, p_value: usize) -> Option<String> {
339    let stripped = skip_tree_prefix_bytes(path.as_bytes(), p_value)?;
340    Some(String::from_utf8_lossy(stripped).into_owned())
341}
342
343fn sane_tz_len(line: &[u8]) -> usize {
344    const SUFFIX: &[u8] = b" +0500";
345    if line.len() < SUFFIX.len() || line[line.len() - SUFFIX.len()] != b' ' {
346        return 0;
347    }
348    let tz = &line[line.len() - SUFFIX.len()..];
349    if tz[1] != b'+' && tz[1] != b'-' {
350        return 0;
351    }
352    for p in &tz[2..] {
353        if !p.is_ascii_digit() {
354            return 0;
355        }
356    }
357    SUFFIX.len()
358}
359
360fn tz_with_colon_len(line: &[u8]) -> usize {
361    // Git: suffix is ` ±HH:MM` (space, sign, two hour digits, colon, two minute digits) = 7 bytes.
362    const SUFFIX_LEN: usize = 7;
363    if line.len() < SUFFIX_LEN || line[line.len() - 3] != b':' {
364        return 0;
365    }
366    let tz = &line[line.len() - SUFFIX_LEN..];
367    if tz[0] != b' ' || (tz[1] != b'+' && tz[1] != b'-') {
368        return 0;
369    }
370    let p = &tz[2..];
371    if p.len() != 5
372        || !p[0].is_ascii_digit()
373        || !p[1].is_ascii_digit()
374        || p[2] != b':'
375        || !p[3].is_ascii_digit()
376        || !p[4].is_ascii_digit()
377    {
378        return 0;
379    }
380    SUFFIX_LEN
381}
382
383fn date_len(line: &[u8]) -> usize {
384    const SHORT: &[u8] = b"72-02-05";
385    if line.len() < SHORT.len() || line[line.len() - 3] != b'-' {
386        return 0;
387    }
388    let mut p = line.len() - SHORT.len();
389    let date = &line[p..];
390    if !date[0].is_ascii_digit()
391        || !date[1].is_ascii_digit()
392        || date[2] != b'-'
393        || !date[3].is_ascii_digit()
394        || !date[4].is_ascii_digit()
395        || date[5] != b'-'
396        || !date[6].is_ascii_digit()
397        || !date[7].is_ascii_digit()
398    {
399        return 0;
400    }
401    if p >= 2 {
402        let y1 = line[p - 1];
403        let y2 = line[p - 2];
404        if y1.is_ascii_digit() && y2.is_ascii_digit() {
405            p -= 2;
406        }
407    }
408    line.len() - p
409}
410
411fn short_time_len(line: &[u8]) -> usize {
412    const PAT: &[u8] = b" 07:01:32";
413    if line.len() < PAT.len() || line[line.len() - 3] != b':' {
414        return 0;
415    }
416    let p = line.len() - PAT.len();
417    let time = &line[p..];
418    if time[0] != b' '
419        || !time[1].is_ascii_digit()
420        || !time[2].is_ascii_digit()
421        || time[3] != b':'
422        || !time[4].is_ascii_digit()
423        || !time[5].is_ascii_digit()
424        || time[6] != b':'
425        || !time[7].is_ascii_digit()
426        || !time[8].is_ascii_digit()
427    {
428        return 0;
429    }
430    PAT.len()
431}
432
433fn fractional_time_len(line: &[u8]) -> usize {
434    if line.is_empty() || !line[line.len() - 1].is_ascii_digit() {
435        return 0;
436    }
437    let mut p = line.len() - 1;
438    while p > 0 && line[p].is_ascii_digit() {
439        p -= 1;
440    }
441    if p == 0 || line[p] != b'.' {
442        return 0;
443    }
444    let n = short_time_len(&line[..p]);
445    if n == 0 {
446        return 0;
447    }
448    line.len() - p + n
449}
450
451fn trailing_spaces_len(line: &[u8]) -> usize {
452    if line.is_empty() || line[line.len() - 1] != b' ' {
453        return 0;
454    }
455    let mut p = line.len();
456    while p > 0 {
457        p -= 1;
458        if line[p] != b' ' {
459            return line.len() - (p + 1);
460        }
461    }
462    line.len()
463}
464
465fn diff_timestamp_len(line: &[u8]) -> usize {
466    if line.is_empty() || !line[line.len() - 1].is_ascii_digit() {
467        return 0;
468    }
469    let mut end = line.len();
470    let mut n = sane_tz_len(&line[..end]);
471    if n == 0 {
472        n = tz_with_colon_len(&line[..end]);
473    }
474    if n == 0 {
475        return 0;
476    }
477    end -= n;
478
479    n = short_time_len(&line[..end]);
480    if n == 0 {
481        n = fractional_time_len(&line[..end]);
482    }
483    if n == 0 {
484        return 0;
485    }
486    end -= n;
487
488    n = date_len(&line[..end]);
489    if n == 0 {
490        return 0;
491    }
492    end -= n;
493
494    if end == 0 {
495        return 0;
496    }
497    match line[end - 1] {
498        b'\t' => {
499            end -= 1;
500            line.len() - end
501        }
502        b' ' => {
503            end -= trailing_spaces_len(&line[..end]);
504            line.len() - end
505        }
506        _ => 0,
507    }
508}
509
510/// Git `find_name_common` with optional `end` bound (exclusive).
511fn find_name_common_bounded(
512    line: &[u8],
513    def: Option<&[u8]>,
514    p_value: usize,
515    end: usize,
516) -> Option<Vec<u8>> {
517    let end = end.min(line.len());
518    let mut start: Option<usize> = if p_value == 0 { Some(0) } else { None };
519    let mut p = p_value;
520    let mut i = 0usize;
521    while i < end {
522        let c = line[i];
523        i += 1;
524        if c == b'/' && p > 0 {
525            p -= 1;
526            if p == 0 {
527                start = Some(i);
528            }
529        }
530    }
531    let start = start?;
532    let len = i - start;
533    if len == 0 {
534        return def.map(|d| d.to_vec());
535    }
536    let slice = &line[start..i];
537    if let Some(d) = def {
538        if d.len() < len && slice.starts_with(d) {
539            return Some(d.to_vec());
540        }
541    }
542    Some(slice.to_vec())
543}
544
545/// Git `find_name_traditional` on the line after `--- ` / `+++ ` (no prefix).
546fn find_name_traditional(line: &[u8], def: Option<&[u8]>, p_value: usize) -> Option<Vec<u8>> {
547    if line.first() == Some(&b'"') {
548        let (decoded, _) = unquote_c_style_prefix(std::str::from_utf8(line).ok()?)?;
549        let skip = skip_tree_prefix_bytes(&decoded, p_value)?;
550        return Some(skip.to_vec());
551    }
552    let ts = diff_timestamp_len(line);
553    let name_end = line.len().saturating_sub(ts);
554    find_name_common_bounded(line, def, p_value, name_end)
555}
556
557fn find_name_tab_terminated(line: &[u8], p_value: usize) -> Option<Vec<u8>> {
558    if line.first() == Some(&b'"') {
559        let (decoded, _) = unquote_c_style_prefix(std::str::from_utf8(line).ok()?)?;
560        let skip = skip_tree_prefix_bytes(&decoded, p_value)?;
561        return Some(skip.to_vec());
562    }
563    let end = line
564        .iter()
565        .position(|&b| b == b'\t' || b == b'\n' || b == b'\r')
566        .unwrap_or(line.len());
567    find_name_common_bounded(line, None, p_value, end)
568}
569
570fn is_dev_null_nameline(line: &[u8]) -> bool {
571    line.strip_prefix(b"/dev/null")
572        .map(|rest| rest.is_empty() || rest.first().is_some_and(|b| b.is_ascii_whitespace()))
573        .unwrap_or(false)
574}
575
576fn count_slashes_in_prefix(prefix: &str) -> usize {
577    prefix.bytes().filter(|&b| b == b'/').count()
578}
579
580/// Git `guess_p_value` for traditional patches (`apply.c`). Uses `setup_git_directory` prefix.
581fn guess_p_value_from_nameline(line: &[u8], setup_prefix: Option<&str>) -> Option<usize> {
582    if is_dev_null_nameline(line) {
583        return None;
584    }
585    let name = find_name_traditional(line, None, 0)?;
586    let name_str = String::from_utf8_lossy(&name);
587    if !name_str.contains('/') {
588        return Some(0);
589    }
590    let pfx = setup_prefix.filter(|p| !p.is_empty())?;
591    if name_str.starts_with(pfx) {
592        return Some(count_slashes_in_prefix(pfx));
593    }
594    let slash = name_str.find('/')?;
595    let rest = name_str.get(slash + 1..)?;
596    if rest.starts_with(pfx) {
597        return Some(count_slashes_in_prefix(pfx) + 1);
598    }
599    None
600}
601
602fn epoch_stamp_regex() -> &'static Regex {
603    // hygiene: immutable compiled regex for patch epoch stamps
604    static RE: OnceLock<Regex> = OnceLock::new();
605    RE.get_or_init(|| {
606        // Provably infallible: the pattern is a fixed string literal that is a valid regex.
607        #[allow(clippy::expect_used)]
608        Regex::new(r"^([0-2][0-9]):([0-5][0-9]):00(?:\.0+)? ([-+][0-2][0-9]:?[0-5][0-9])")
609            .expect("epoch stamp regex is a valid constant pattern")
610    })
611}
612
613/// True when the `---`/`+++` line has a tab-separated epoch timestamp (Git `has_epoch_timestamp`).
614fn has_epoch_timestamp(nameline: &[u8]) -> bool {
615    let Some(tab) = nameline.iter().position(|&b| b == b'\t') else {
616        return false;
617    };
618    let mut ts = &nameline[tab + 1..];
619    let epoch_hour = if let Some(r) = ts.strip_prefix(b"1969-12-31 ") {
620        ts = r;
621        24i32
622    } else if let Some(r) = ts.strip_prefix(b"1970-01-01 ") {
623        ts = r;
624        0i32
625    } else {
626        return false;
627    };
628    let end = ts.iter().position(|&b| b == b'\n').unwrap_or(ts.len());
629    let stamp = &ts[..end];
630    let stamp_str = match std::str::from_utf8(stamp) {
631        Ok(s) => s,
632        Err(_) => return false,
633    };
634    let caps = match epoch_stamp_regex().captures(stamp_str) {
635        Some(c) => c,
636        None => return false,
637    };
638    let hour: i32 = caps
639        .get(1)
640        .and_then(|m| m.as_str().parse().ok())
641        .unwrap_or(-1);
642    let minute: i32 = caps
643        .get(2)
644        .and_then(|m| m.as_str().parse().ok())
645        .unwrap_or(-1);
646    let tz_s = match caps.get(3).map(|m| m.as_str()) {
647        Some(s) if !s.is_empty() => s,
648        _ => return false,
649    };
650    if hour < 0 || minute < 0 {
651        return false;
652    }
653    let tz_byte = tz_s.as_bytes()[0];
654    let tz_rest = &tz_s[1..];
655    let zoneoffset: i32 = if let Some(colon_pos) = tz_rest.find(':') {
656        let h: i32 = tz_rest[..colon_pos].parse().unwrap_or(0);
657        let mm: i32 = tz_rest[colon_pos + 1..].parse().unwrap_or(0);
658        h * 60 + mm
659    } else if tz_rest.len() >= 4 {
660        let n: i32 = tz_rest[..4].parse().unwrap_or(0);
661        (n / 100) * 60 + (n % 100)
662    } else {
663        return false;
664    };
665    let zoneoffset = if tz_byte == b'-' {
666        -zoneoffset
667    } else {
668        zoneoffset
669    };
670    hour * 60 + minute - zoneoffset == epoch_hour * 60
671}
672
673/// Parse `---` / `+++` pair for a traditional unified diff (Git `parse_traditional_patch`).
674fn parse_traditional_patch_pair(
675    old_line: &[u8],
676    new_line: &[u8],
677    strip: usize,
678    p_guess: &mut Option<usize>,
679    setup_prefix: Option<&str>,
680) -> Result<FilePatch> {
681    let old_p = old_line.strip_prefix(b"--- ").unwrap_or(old_line);
682    let new_p = new_line.strip_prefix(b"+++ ").unwrap_or(new_line);
683
684    if p_guess.is_none() {
685        let p = guess_p_value_from_nameline(old_p, setup_prefix);
686        let q = guess_p_value_from_nameline(new_p, setup_prefix);
687        let chosen = match (p, q) {
688            (None, None) => None,
689            (Some(a), None) => Some(a),
690            (None, Some(b)) => Some(b),
691            (Some(a), Some(b)) if a == b => Some(a),
692            _ => None,
693        };
694        *p_guess = chosen;
695    }
696    let p_val = p_guess.unwrap_or(strip);
697
698    let mut fp = FilePatch {
699        saw_old_header: true,
700        saw_new_header: true,
701        ..FilePatch::empty()
702    };
703
704    if is_dev_null_nameline(old_p) {
705        fp.is_new = true;
706        let name = find_name_traditional(new_p, None, p_val)
707            .ok_or_else(|| Error::from(ApplyError::MissingFilename))?;
708        fp.new_path = Some(bytes_to_path_string(&name)?);
709    } else if is_dev_null_nameline(new_p) {
710        fp.is_deleted = true;
711        let name = find_name_traditional(old_p, None, p_val)
712            .ok_or_else(|| Error::from(ApplyError::MissingFilename))?;
713        fp.old_path = Some(bytes_to_path_string(&name)?);
714    } else {
715        let first_name = find_name_traditional(old_p, None, p_val)
716            .ok_or_else(|| Error::from(ApplyError::MissingFilename))?;
717        let name = find_name_traditional(new_p, Some(&first_name), p_val)
718            .ok_or_else(|| Error::from(ApplyError::MissingFilename))?;
719        let name_str = bytes_to_path_string(&name)?;
720        if has_epoch_timestamp(old_p) {
721            fp.is_new = true;
722            fp.new_path = Some(name_str);
723        } else if has_epoch_timestamp(new_p) {
724            fp.is_deleted = true;
725            fp.old_path = Some(name_str);
726        } else {
727            // Git uses the `+++` filename for both sides when neither line carries an epoch
728            // marker; the `---` line only participates via `def` when shortening `.orig` etc.
729            fp.old_path = Some(name_str.clone());
730            fp.new_path = Some(name_str);
731        }
732    }
733
734    Ok(fp)
735}
736
737/// Default filename from `diff --git` when both sides agree (Git `git_header_name`).
738fn git_header_def_name(line: &str, p_value: usize) -> Option<String> {
739    let rest = line.strip_prefix("diff --git ").unwrap_or(line);
740    let rest_b = rest.as_bytes();
741
742    if rest_b.first() == Some(&b'"') {
743        let (first_decoded, second_raw) = unquote_c_style_prefix(rest)?;
744        let rel_first = skip_tree_prefix_bytes(&first_decoded, p_value)?;
745        let second = second_raw.trim_start_matches(|c: char| c.is_ascii_whitespace());
746        if second.is_empty() {
747            return None;
748        }
749        if second.as_bytes().first() == Some(&b'"') {
750            let (second_decoded, _) = unquote_c_style_prefix(second)?;
751            let rel2 = skip_tree_prefix_bytes(&second_decoded, p_value)?;
752            if rel2 != rel_first {
753                return None;
754            }
755        } else {
756            let rel2 = skip_tree_prefix_bytes(second.as_bytes(), p_value)?;
757            if rel2.len() != rel_first.len() || rel2 != rel_first {
758                return None;
759            }
760        }
761        return bytes_to_path_string(rel_first).ok();
762    }
763
764    let name = skip_tree_prefix_bytes(rest_b, p_value)?;
765    let name_start = name.as_ptr() as usize - rest_b.as_ptr() as usize;
766
767    for offset in 0..name.len() {
768        if name[offset] != b'"' {
769            continue;
770        }
771        let second_slice = &rest_b[name_start + offset..];
772        let (decoded, _) = unquote_c_style_prefix(std::str::from_utf8(second_slice).ok()?)?;
773        let np = skip_tree_prefix_bytes(&decoded, p_value)?;
774        let plen = np.len();
775        if plen < offset
776            && name.len() > plen
777            && &name[..plen] == np
778            && name[plen].is_ascii_whitespace()
779        {
780            return bytes_to_path_string(np).ok();
781        }
782        return None;
783    }
784
785    let line_len = rest.len().saturating_sub(name_start);
786    let mut len = 0usize;
787    while len < line_len {
788        match rest_b[name_start + len] {
789            b'\n' => return None,
790            b'\t' | b' ' => {
791                let after = name_start + len + 1;
792                if after > name_start + line_len {
793                    return None;
794                }
795                let second =
796                    skip_tree_prefix_bytes(&rest_b[after..name_start + line_len], p_value)?;
797                let names_match =
798                    name.len() >= len && second.len() >= len && name[..len] == second[..len];
799                let boundary_ok = second.get(len) == Some(&b'\n') || second.len() == len;
800                if names_match && boundary_ok {
801                    return bytes_to_path_string(&name[..len]).ok();
802                }
803            }
804            _ => {}
805        }
806        len += 1;
807    }
808    None
809}
810
811/// Path from `rename from` / `copy from` lines (Git `find_name` with `terminate == 0`).
812fn find_name_extended_header(rest: &str, p_extended: usize) -> Option<String> {
813    let rest = rest.trim_end_matches(['\r', '\n']);
814    let b = rest.as_bytes();
815    if b.first() == Some(&b'"') {
816        let (decoded, tail) = unquote_c_style_prefix(rest)?;
817        if !tail.trim().is_empty() {
818            return None;
819        }
820        let skip = skip_tree_prefix_bytes(&decoded, p_extended)?;
821        return bytes_to_path_string(skip).ok();
822    }
823    let end = b
824        .iter()
825        .position(|&c| c == b'\t' || c == b'\n' || c == b'\r' || c == b' ')
826        .unwrap_or(b.len());
827    let name = find_name_common_bounded(b, None, p_extended, end)?;
828    bytes_to_path_string(&name).ok()
829}
830
831/// Parse a unified diff into a list of `FilePatch` entries.
832///
833/// `strip` is Git's `p_value` (`-p` count, default 1). `setup_prefix` is Git's
834/// `setup_git_directory` prefix (work-tree-relative path from CWD to the repo
835/// root, with trailing `/`); pass `None` when running from the work-tree root.
836/// The caller computes it because it is a CLI/environment concern.
837pub fn parse_patch(
838    input: &str,
839    strip: usize,
840    input_name: &str,
841    recount: bool,
842    setup_prefix: Option<&str>,
843) -> Result<Vec<FilePatch>> {
844    let lines: Vec<&str> = input.lines().collect();
845    let mut patches = Vec::new();
846    let mut i = 0;
847    let mut p_guess_for_traditional = None;
848    let setup_prefix_for_guess = setup_prefix.filter(|p| !p.is_empty());
849
850    while i < lines.len() {
851        let mut fp = if lines[i].starts_with("diff --git ") {
852            let (fp, next_i) = parse_git_patch_header(&lines, i, strip)?;
853            i = next_i;
854            fp
855        } else if lines[i].starts_with("--- ")
856            && i + 1 < lines.len()
857            && lines[i + 1].starts_with("+++ ")
858        {
859            let fp = parse_traditional_patch_pair(
860                lines[i].as_bytes(),
861                lines[i + 1].as_bytes(),
862                strip,
863                &mut p_guess_for_traditional,
864                setup_prefix_for_guess,
865            )?;
866            i += 2;
867            while i < lines.len() && lines[i].starts_with("index ") {
868                i += 1;
869            }
870            fp
871        } else {
872            i += 1;
873            continue;
874        };
875
876        if i < lines.len() && lines[i] == "GIT binary patch" {
877            let (binary_patch, next_i) = parse_binary_patch(&lines, i + 1)?;
878            fp.binary_patch = Some(binary_patch);
879            fp.is_binary = true;
880            i = next_i;
881        } else {
882            while i < lines.len() && lines[i].starts_with("@@ ") {
883                let (hunk, next_i) = parse_hunk(&lines, i, input_name, recount)?;
884                fp.hunks.push(hunk);
885                i = next_i;
886            }
887        }
888
889        sanitize_file_patch_headers(&mut fp);
890        patches.push(fp);
891    }
892
893    Ok(patches)
894}
895
896// Binary sections among extended headers are consumed here; those following
897// explicit file headers are consumed by the common patch-body loop.
898fn parse_git_patch_header(
899    lines: &[&str],
900    mut i: usize,
901    strip: usize,
902) -> Result<(FilePatch, usize)> {
903    let p_strip = strip;
904    let p_extended = strip.saturating_sub(1);
905    let mut fp = FilePatch {
906        is_toplevel_relative: true,
907        ..FilePatch::empty()
908    };
909
910    let header_line = lines[i];
911    let def_name = git_header_def_name(header_line, p_strip);
912
913    // Parse "diff --git a/foo b/foo"
914    let rest = &header_line["diff --git ".len()..];
915    if let Some((a, b)) = split_diff_git_paths(rest) {
916        fp.diff_old_path = Some(a.clone());
917        fp.diff_new_path = Some(b.clone());
918        fp.old_path = Some(skip_tree_prefix_str(&a, p_strip).ok_or_else(|| {
919            Error::from(ApplyError::MalformedHeaderPath {
920                side: PatchSide::Old,
921                path: a.clone(),
922            })
923        })?);
924        fp.new_path = Some(skip_tree_prefix_str(&b, p_strip).ok_or_else(|| {
925            Error::from(ApplyError::MalformedHeaderPath {
926                side: PatchSide::New,
927                path: b.clone(),
928            })
929        })?);
930    }
931    i += 1;
932
933    // Parse extended headers
934    while i < lines.len()
935        && !lines[i].starts_with("--- ")
936        && !lines[i].starts_with("diff --git ")
937        && !lines[i].starts_with("@@ ")
938    {
939        let line = lines[i];
940        let line_no = i + 1;
941        if let Some(val) = line.strip_prefix("old mode ") {
942            let v = val.trim_end_matches('\r').trim_end();
943            if v.is_empty() {
944                return Err(ApplyError::InvalidMode {
945                    line: line_no,
946                    text: line.to_owned(),
947                }
948                .into());
949            }
950            fp.old_mode = Some(v.to_string());
951            fp.old_mode_line = Some(line_no);
952        } else if let Some(val) = line.strip_prefix("new mode ") {
953            let v = val.trim_end_matches('\r').trim_end();
954            if v.is_empty() {
955                return Err(ApplyError::InvalidMode {
956                    line: line_no,
957                    text: line.to_owned(),
958                }
959                .into());
960            }
961            fp.new_mode = Some(v.to_string());
962            fp.new_mode_line = Some(line_no);
963        } else if let Some(val) = line.strip_prefix("new file mode ") {
964            let v = val.trim_end_matches('\r').trim_end();
965            if v.is_empty() {
966                return Err(ApplyError::InvalidMode {
967                    line: line_no,
968                    text: line.to_owned(),
969                }
970                .into());
971            }
972            fp.is_new = true;
973            fp.new_mode = Some(v.to_string());
974            fp.new_mode_line = Some(line_no);
975        } else if let Some(val) = line.strip_prefix("deleted file mode ") {
976            let v = val.trim_end_matches('\r').trim_end();
977            if v.is_empty() {
978                return Err(ApplyError::InvalidMode {
979                    line: line_no,
980                    text: line.to_owned(),
981                }
982                .into());
983            }
984            fp.is_deleted = true;
985            fp.old_mode = Some(v.to_string());
986            fp.old_mode_line = Some(line_no);
987        } else if let Some(val) = line.strip_prefix("rename from ") {
988            fp.is_rename = true;
989            if let Some(p) = find_name_extended_header(val, p_extended) {
990                fp.old_path = Some(p);
991            }
992        } else if let Some(val) = line.strip_prefix("rename to ") {
993            fp.is_rename = true;
994            if let Some(p) = find_name_extended_header(val, p_extended) {
995                fp.new_path = Some(p);
996            }
997        } else if let Some(val) = line.strip_prefix("copy from ") {
998            fp.is_copy = true;
999            if let Some(p) = find_name_extended_header(val, p_extended) {
1000                fp.old_path = Some(p);
1001            }
1002        } else if let Some(val) = line.strip_prefix("copy to ") {
1003            fp.is_copy = true;
1004            if let Some(p) = find_name_extended_header(val, p_extended) {
1005                fp.new_path = Some(p);
1006            }
1007        } else if let Some(val) = line.strip_prefix("similarity index ") {
1008            fp.similarity_index = val.trim_end_matches('%').parse().ok();
1009        } else if let Some(val) = line.strip_prefix("dissimilarity index ") {
1010            fp.dissimilarity_index = val.trim_end_matches('%').parse().ok();
1011        } else if let Some(val) = line.strip_prefix("index ") {
1012            // Parse "index abc123..def456 100644" or "index abc123..def456"
1013            let mut parts = val.split_whitespace();
1014            let hash_part = parts.next().unwrap_or("");
1015            if let Some((old, new)) = hash_part.split_once("..") {
1016                fp.old_oid = Some(old.to_string());
1017                fp.new_oid = Some(new.to_string());
1018            }
1019            if let Some(mode_tok) = parts.next() {
1020                let v = mode_tok.trim_end_matches('\r').trim_end();
1021                if !v.is_empty() {
1022                    fp.old_mode = Some(v.to_string());
1023                    fp.old_mode_line = Some(line_no);
1024                }
1025            }
1026        } else if line == "GIT binary patch" {
1027            let (binary_patch, next_i) = parse_binary_patch(lines, i + 1)?;
1028            fp.binary_patch = Some(binary_patch);
1029            fp.is_binary = true;
1030            i = next_i;
1031            break;
1032        } else if line.starts_with("Binary files ") && line.ends_with(" differ") {
1033            // Plain (non --binary) diff of a binary change; no payload to
1034            // apply but stat/numstat must report it as binary.
1035            fp.is_binary = true;
1036        }
1037        // skip other extended headers
1038        i += 1;
1039    }
1040
1041    if let Some(dn) = def_name {
1042        if fp.old_path.is_none() {
1043            fp.old_path = Some(dn.clone());
1044        }
1045        if fp.new_path.is_none() {
1046            fp.new_path = Some(dn);
1047        }
1048    }
1049
1050    // Parse ---/+++ headers if present
1051    if i < lines.len() && lines[i].starts_with("--- ") {
1052        let old_p = lines[i]["--- ".len()..].trim_end_matches(['\r', '\n']);
1053        let old_b = old_p.as_bytes();
1054        if is_dev_null_nameline(old_b) {
1055            fp.old_path = Some("/dev/null".to_string());
1056        } else if let Some(p) = find_name_tab_terminated(old_b, p_strip) {
1057            fp.old_path = Some(bytes_to_path_string(&p)?);
1058        }
1059        fp.saw_old_header = true;
1060        i += 1;
1061        if i < lines.len() && lines[i].starts_with("+++ ") {
1062            let new_p = lines[i]["+++ ".len()..].trim_end_matches(['\r', '\n']);
1063            let new_b = new_p.as_bytes();
1064            if is_dev_null_nameline(new_b) {
1065                fp.new_path = Some("/dev/null".to_string());
1066            } else if let Some(p) = find_name_tab_terminated(new_b, p_strip) {
1067                fp.new_path = Some(bytes_to_path_string(&p)?);
1068            }
1069            fp.saw_new_header = true;
1070            i += 1;
1071        }
1072    }
1073
1074    while i < lines.len() && lines[i].starts_with("index ") {
1075        let line = lines[i];
1076        let val = line["index ".len()..].trim_end();
1077        if let Some((old, new)) = val
1078            .split_whitespace()
1079            .next()
1080            .and_then(|h| h.split_once(".."))
1081        {
1082            fp.old_oid = Some(old.to_string());
1083            fp.new_oid = Some(new.to_string());
1084        }
1085        i += 1;
1086    }
1087
1088    Ok((fp, i))
1089}
1090
1091/// Parse a `GIT binary patch` payload.
1092fn parse_binary_patch(lines: &[&str], mut i: usize) -> Result<(BinaryPatchPayload, usize)> {
1093    let forward = parse_binary_section(lines, &mut i)?;
1094    let reverse = if i < lines.len()
1095        && (lines[i].starts_with("literal ") || lines[i].starts_with("delta "))
1096    {
1097        Some(parse_binary_section(lines, &mut i)?)
1098    } else {
1099        None
1100    };
1101
1102    Ok((BinaryPatchPayload { forward, reverse }, i))
1103}
1104
1105/// Parse one `literal <size>` or `delta <size>` block from a binary patch.
1106fn parse_binary_section(lines: &[&str], i: &mut usize) -> Result<BinaryPatchSection> {
1107    let header = lines.get(*i).copied().unwrap_or_default();
1108    let (kind, size_str) = if let Some(s) = header.strip_prefix("literal ") {
1109        (BinaryPatchSectionKind::Literal, s)
1110    } else if let Some(s) = header.strip_prefix("delta ") {
1111        (BinaryPatchSectionKind::Delta, s)
1112    } else {
1113        return Err(ApplyError::from(BinaryPatchError::UnsupportedSection {
1114            header: header.to_owned(),
1115        })
1116        .into());
1117    };
1118    let declared_size: usize = size_str.trim().parse().map_err(|_| {
1119        ApplyError::from(BinaryPatchError::InvalidSectionSize {
1120            size: size_str.trim().to_owned(),
1121        })
1122    })?;
1123    *i += 1;
1124
1125    let mut compressed = Vec::new();
1126    while *i < lines.len() {
1127        let line = lines[*i];
1128        if line.is_empty() {
1129            *i += 1;
1130            break;
1131        }
1132        decode_binary_patch_line(line, &mut compressed)?;
1133        *i += 1;
1134    }
1135
1136    Ok(BinaryPatchSection {
1137        kind,
1138        compressed,
1139        declared_size,
1140    })
1141}
1142
1143/// Decode one binary patch payload line into compressed bytes.
1144fn decode_binary_patch_line(line: &str, out: &mut Vec<u8>) -> Result<()> {
1145    let mut chars = line.chars();
1146    let Some(len_ch) = chars.next() else {
1147        return Err(ApplyError::from(BinaryPatchError::EmptyLine).into());
1148    };
1149    let expected_len = decode_binary_line_len(len_ch)?;
1150    let body = chars.as_str().as_bytes();
1151    let decoded = crate::git_binary_base85::decode_body(body, expected_len)
1152        .map_err(|_| ApplyError::from(BinaryPatchError::InvalidBase85))?;
1153    out.extend_from_slice(&decoded);
1154    Ok(())
1155}
1156
1157fn decode_binary_line_len(ch: char) -> Result<usize> {
1158    if ch.is_ascii_uppercase() {
1159        return Ok((ch as u8 - b'A' + 1) as usize);
1160    }
1161    if ch.is_ascii_lowercase() {
1162        return Ok((ch as u8 - b'a' + 27) as usize);
1163    }
1164    Err(ApplyError::from(BinaryPatchError::InvalidLineLength { marker: ch }).into())
1165}
1166
1167/// Length marker for a payload line of `raw_len` bytes; callers pass chunks of 1..=52 bytes.
1168fn encode_binary_line_len(raw_len: usize) -> char {
1169    let raw_len = raw_len.clamp(1, 52) as u8;
1170    if raw_len <= 26 {
1171        char::from(b'A' + raw_len - 1)
1172    } else {
1173        char::from(b'a' + raw_len - 27)
1174    }
1175}
1176
1177fn zlib_compress_binary_payload(data: &[u8]) -> Result<Vec<u8>> {
1178    use flate2::write::ZlibEncoder;
1179    use flate2::Compression;
1180    use std::io::Write;
1181
1182    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1183    encoder.write_all(data)?;
1184    encoder.finish().map_err(Error::from)
1185}
1186
1187fn append_binary_literal_section(out: &mut String, uncompressed: &[u8]) -> Result<()> {
1188    let compressed = zlib_compress_binary_payload(uncompressed)?;
1189    out.push_str(&format!("literal {}\n", uncompressed.len()));
1190    for chunk in compressed.chunks(52) {
1191        let len_ch = encode_binary_line_len(chunk.len());
1192        let body = crate::git_binary_base85::encode(chunk);
1193        out.push_str(&format!("{len_ch}{body}\n"));
1194    }
1195    out.push('\n');
1196    Ok(())
1197}
1198
1199/// Write the `GIT binary patch` body (literal forward then reverse) to `out`.
1200///
1201/// Forward literal is `new`; reverse literal is `old`, matching Git's `git diff --binary`.
1202/// The `index` line and `diff --git` header are the caller's responsibility.
1203pub(crate) fn write_git_binary_patch_sections<W: std::io::Write>(
1204    out: &mut W,
1205    old: &[u8],
1206    new: &[u8],
1207) -> Result<()> {
1208    out.write_all(b"GIT binary patch\n")?;
1209    let mut buf = String::new();
1210    append_binary_literal_section(&mut buf, new)?;
1211    out.write_all(buf.as_bytes())?;
1212    buf.clear();
1213    append_binary_literal_section(&mut buf, old)?;
1214    out.write_all(buf.as_bytes())?;
1215    Ok(())
1216}
1217
1218/// Emit a unified diff whose body is a `GIT binary patch` with zlib+base85 literals.
1219///
1220/// Forward literal is `new`; reverse literal is `old`, matching Git's `git diff --binary`.
1221pub fn write_git_binary_patch(
1222    old: &[u8],
1223    new: &[u8],
1224    _old_path: &str,
1225    _new_path: &str,
1226) -> Result<String> {
1227    use crate::objects::{HashAlgo, ObjectKind};
1228
1229    let old_oid = HashAlgo::Sha1.hash_object(ObjectKind::Blob, old)?;
1230    let new_oid = HashAlgo::Sha1.hash_object(ObjectKind::Blob, new)?;
1231    let mut out = String::with_capacity(old.len() + new.len() + 128);
1232    out.push_str(&format!(
1233        "index {}..{} 100644\n",
1234        old_oid.to_hex(),
1235        new_oid.to_hex()
1236    ));
1237    out.push_str("GIT binary patch\n");
1238    append_binary_literal_section(&mut out, new)?;
1239    append_binary_literal_section(&mut out, old)?;
1240    Ok(out)
1241}
1242
1243/// Inflate zlib-compressed binary payload.
1244pub fn inflate_binary_payload(compressed: &[u8]) -> Result<Vec<u8>> {
1245    use flate2::read::ZlibDecoder;
1246    use std::io::Read;
1247
1248    let mut decoder = ZlibDecoder::new(compressed);
1249    let mut out = Vec::new();
1250    decoder.read_to_end(&mut out).map_err(|e| {
1251        ApplyError::from(BinaryPatchError::Inflate {
1252            detail: e.to_string(),
1253        })
1254    })?;
1255    Ok(out)
1256}
1257
1258/// Expand one binary patch section to uncompressed bytes.
1259///
1260/// Delta sections require `base` (the preimage blob Git applies the delta against).
1261pub(crate) fn materialize_binary_patch_section(
1262    section: &BinaryPatchSection,
1263    base: Option<&[u8]>,
1264) -> Result<Vec<u8>> {
1265    let inflated = inflate_binary_payload(&section.compressed)?;
1266    match section.kind {
1267        BinaryPatchSectionKind::Literal => {
1268            if inflated.len() != section.declared_size {
1269                return Err(ApplyError::from(BinaryPatchError::SizeMismatch {
1270                    actual: inflated.len(),
1271                    declared: section.declared_size,
1272                })
1273                .into());
1274            }
1275            Ok(inflated)
1276        }
1277        BinaryPatchSectionKind::Delta => {
1278            let base = base
1279                .ok_or_else(|| Error::from(ApplyError::from(BinaryPatchError::DeltaWithoutBase)))?;
1280            crate::unpack_objects::apply_delta(base, &inflated)
1281        }
1282    }
1283}
1284
1285/// Reconstruct the post-image blob from the forward section and the old file contents.
1286pub fn materialize_binary_patch_forward(
1287    payload: &BinaryPatchPayload,
1288    old: &[u8],
1289) -> Result<Vec<u8>> {
1290    materialize_binary_patch_section(&payload.forward, Some(old))
1291}
1292
1293/// Reconstruct the pre-image blob from the reverse section and the new file contents.
1294pub fn materialize_binary_patch_reverse(
1295    payload: &BinaryPatchPayload,
1296    new: &[u8],
1297) -> Result<Vec<u8>> {
1298    let reverse = payload
1299        .reverse
1300        .as_ref()
1301        .ok_or_else(|| ApplyError::from(BinaryPatchError::NoReverseSection))?;
1302    materialize_binary_patch_section(reverse, Some(new))
1303}
1304
1305/// Split the two path tokens from the remainder of a `diff --git` line (after `diff --git `).
1306fn split_diff_git_paths(s: &str) -> Option<(String, String)> {
1307    let s = s.trim_end_matches(['\r', '\n']);
1308
1309    if s.as_bytes().first() == Some(&b'"') {
1310        let (first, rest_raw) = unquote_c_style_prefix(s)?;
1311        let rest = rest_raw.trim_start_matches(|c: char| c.is_ascii_whitespace());
1312        if rest.is_empty() {
1313            return None;
1314        }
1315        if rest.as_bytes().first() == Some(&b'"') {
1316            let (second, _) = unquote_c_style_prefix(rest)?;
1317            return Some((
1318                String::from_utf8_lossy(&first).into_owned(),
1319                String::from_utf8_lossy(&second).into_owned(),
1320            ));
1321        }
1322        let second = rest;
1323        if second.len() != first.len() || second.as_bytes() != first.as_slice() {
1324            return None;
1325        }
1326        return Some((
1327            String::from_utf8_lossy(&first).into_owned(),
1328            second.to_string(),
1329        ));
1330    }
1331
1332    if let Some(pos) = s.find(" b/") {
1333        let a = &s[..pos];
1334        let b = &s[pos + 1..];
1335        return Some((a.to_string(), b.to_string()));
1336    }
1337    if s.starts_with("a/") {
1338        if let Some(pos) = s.find(" /dev/null") {
1339            let a = &s[..pos];
1340            return Some((a.to_string(), "/dev/null".to_string()));
1341        }
1342    }
1343    if let Some(b) = s.strip_prefix("/dev/null ") {
1344        return Some(("/dev/null".to_string(), b.to_string()));
1345    }
1346
1347    let name = s.as_bytes();
1348    let line_len = name.len();
1349    let mut len = 0usize;
1350    while len < line_len {
1351        match name[len] {
1352            b'\n' => return None,
1353            b'\t' | b' ' => {
1354                if len + 1 > line_len {
1355                    return None;
1356                }
1357                let second = &name[len + 1..line_len];
1358                let names_match =
1359                    name.len() >= len && second.len() >= len && name[..len] == second[..len];
1360                let boundary_ok = second.get(len) == Some(&b'\n') || second.len() == len;
1361                if names_match && boundary_ok {
1362                    return Some((
1363                        String::from_utf8_lossy(&name[..len]).into_owned(),
1364                        String::from_utf8_lossy(second).into_owned(),
1365                    ));
1366                }
1367            }
1368            _ => {}
1369        }
1370        len += 1;
1371    }
1372    None
1373}
1374
1375/// Parse a single hunk starting at line `i` (which should be an `@@` line).
1376fn parse_hunk(
1377    lines: &[&str],
1378    start: usize,
1379    input_name: &str,
1380    recount: bool,
1381) -> Result<(Hunk, usize)> {
1382    let header = lines[start];
1383    let (old_start, old_count, new_start, new_count) =
1384        parse_hunk_header(header).ok_or_else(|| ApplyError::InvalidHunkHeader {
1385            header: header.to_owned(),
1386        })?;
1387
1388    let mut hunk = Hunk {
1389        old_start,
1390        old_count,
1391        new_start,
1392        new_count,
1393        first_body_line: start + 2,
1394        lines: Vec::new(),
1395    };
1396
1397    // Track how many old/new lines the body actually provides so a hunk that
1398    // ends prematurely is diagnosed like Git: "corrupt patch at <file>:<line>"
1399    // (t4012; Git parse_fragment returns -1 when oldlines/newlines remain).
1400    let mut old_seen = 0usize;
1401    let mut new_seen = 0usize;
1402    let mut i = start + 1;
1403    while i < lines.len() {
1404        let line = lines[i];
1405        if line.starts_with("@@ ") || line.starts_with("diff --git ") {
1406            break;
1407        }
1408        // `---` / `+++` with a space begin a new file header; do not treat `---` as a `-` hunk line
1409        // (would misparse `--- /dev/null` as a remove of `-- /dev/null` and merge the next file).
1410        if line.starts_with("--- ") || line.starts_with("+++ ") {
1411            break;
1412        }
1413        if line == "-- " {
1414            // format-patch signature separator; not part of hunk body
1415            break;
1416        }
1417        if let Some(rest) = line.strip_prefix('+') {
1418            hunk.lines.push(HunkLine::Add(rest.to_string()));
1419            new_seen += 1;
1420        } else if let Some(rest) = line.strip_prefix('-') {
1421            hunk.lines.push(HunkLine::Remove(rest.to_string()));
1422            old_seen += 1;
1423        } else if line.is_empty() {
1424            hunk.lines.push(HunkLine::Context(String::new()));
1425            old_seen += 1;
1426            new_seen += 1;
1427        } else if let Some(rest) = line.strip_prefix(' ') {
1428            // context line
1429            hunk.lines.push(HunkLine::Context(rest.to_string()));
1430            old_seen += 1;
1431            new_seen += 1;
1432        } else if line.starts_with('\\') {
1433            hunk.lines.push(HunkLine::NoNewline);
1434        } else {
1435            // Unknown line type — could be start of something else
1436            break;
1437        }
1438        i += 1;
1439    }
1440
1441    if recount {
1442        hunk.old_count = old_seen;
1443        hunk.new_count = new_seen;
1444    } else if old_seen < old_count || new_seen < new_count {
1445        return Err(ApplyError::CorruptPatch {
1446            input: input_name.to_owned(),
1447            line: i + 1,
1448        }
1449        .into());
1450    }
1451
1452    Ok((hunk, i))
1453}
1454
1455/// Parse "@@ -old_start[,old_count] +new_start[,new_count] @@..."; `None` when malformed.
1456fn parse_hunk_header(line: &str) -> Option<(usize, usize, usize, usize)> {
1457    let trimmed = line.trim_start_matches('@').trim_start();
1458    let end = trimmed.find(" @@").unwrap_or(trimmed.len());
1459    let mut parts = trimmed[..end].split_whitespace();
1460    let (old_start, old_count) = parse_range(parts.next()?.trim_start_matches('-'))?;
1461    let (new_start, new_count) = parse_range(parts.next()?.trim_start_matches('+'))?;
1462    Some((old_start, old_count, new_start, new_count))
1463}
1464
1465/// Parse "N" or "N,M" into (start, count).
1466fn parse_range(s: &str) -> Option<(usize, usize)> {
1467    match s.split_once(',') {
1468        Some((start, count)) => Some((start.parse().ok()?, count.parse().ok()?)),
1469        None => Some((s.parse().ok()?, 1)),
1470    }
1471}
1472
1473mod blob_apply;
1474mod index_apply;
1475
1476pub use blob_apply::{apply_patch_to_blob, BlobApplyOptions};
1477pub use index_apply::{
1478    apply_patch_to_index, apply_patch_to_index_and_write, IndexApplyOptions, IndexApplyOutcome,
1479};
1480
1481#[cfg(test)]
1482mod tests {
1483    use super::*;
1484    use crate::error::DiffError;
1485
1486    #[test]
1487    fn binary_bodies_resume_at_following_git_patch() {
1488        let old = b"before\0";
1489        let new = b"after\0";
1490        let body = write_git_binary_patch(old, new, "a/bin", "b/bin").expect("binary body");
1491        for (header, git_style) in [
1492            ("diff --git a/bin b/bin\n", true),
1493            ("diff --git a/bin b/bin\n--- a/bin\n+++ b/bin\n", true),
1494            ("--- a/bin\n+++ b/bin\n", false),
1495        ] {
1496            let input = format!(
1497                "{header}{body}diff --git a/text b/text\n--- a/text\n+++ b/text\n@@ -1 +1 @@\n-old\n+new\n"
1498            );
1499            let files = parse_patch(&input, 1, "mixed", false, None).expect("parse mixed patch");
1500            assert_eq!(files.len(), 2);
1501            let binary = &files[0];
1502            assert_eq!(binary.effective_path(), Some("bin"));
1503            assert_eq!(binary.is_toplevel_relative, git_style);
1504            assert_eq!(binary.old_oid.is_some(), git_style);
1505            assert!(binary.is_binary);
1506            assert!(binary.hunks.is_empty());
1507            let payload = binary.binary_patch.as_ref().expect("binary payload");
1508            assert_eq!(materialize_binary_patch_forward(payload, old).unwrap(), new);
1509            assert_eq!(materialize_binary_patch_reverse(payload, new).unwrap(), old);
1510            assert_eq!(files[1].effective_path(), Some("text"));
1511            assert!(files[1].is_toplevel_relative);
1512            assert!(!files[1].is_binary);
1513            assert_eq!(files[1].hunks.len(), 1);
1514            assert_eq!(files[1].hunks[0].first_body_line, input.lines().count() - 1);
1515        }
1516    }
1517
1518    #[test]
1519    fn git_headers_keep_index_after_file_headers() {
1520        let input = "diff --git a/f b/f\nold mode 100644\nnew mode 100755\n\
1521                     --- a/f\n+++ b/f\nindex abc..def\nindex def..123\n";
1522        let files = parse_patch(input, 1, "modes", false, None).expect("parse headers");
1523        assert_eq!(files.len(), 1);
1524        assert_eq!(files[0].old_oid.as_deref(), Some("def"));
1525        assert_eq!(files[0].new_oid.as_deref(), Some("123"));
1526        assert_eq!(files[0].old_mode.as_deref(), Some("100644"));
1527        assert_eq!(files[0].new_mode.as_deref(), Some("100755"));
1528        assert_eq!(files[0].old_mode_line, Some(2));
1529        assert_eq!(files[0].new_mode_line, Some(3));
1530        assert!(files[0].saw_old_header && files[0].saw_new_header);
1531        assert!(files[0].hunks.is_empty());
1532    }
1533
1534    #[test]
1535    fn corrupt_hunks_keep_line_numbers_for_both_header_styles() {
1536        for header in [
1537            "--- a/f\n+++ b/f\n",
1538            "diff --git a/f b/f\n--- a/f\n+++ b/f\n",
1539        ] {
1540            let input = format!("{header}@@ -1,3 +1,3 @@\n one\n");
1541            let err = parse_patch(&input, 1, "mixed", false, None).unwrap_err();
1542            assert!(matches!(
1543                err,
1544                Error::Diff(DiffError::Apply(ApplyError::CorruptPatch { input, line }))
1545                    if input == "mixed" && line == header.lines().count() + 3
1546            ));
1547        }
1548    }
1549
1550    #[test]
1551    fn parses_simple_git_diff_into_one_file_patch() {
1552        let input = "diff --git a/foo.txt b/foo.txt\n\
1553                     index e69de29..d95f3ad 100644\n\
1554                     --- a/foo.txt\n\
1555                     +++ b/foo.txt\n\
1556                     @@ -0,0 +1 @@\n\
1557                     +hello\n";
1558        let patches = parse_patch(input, 1, "<test>", false, None).expect("parse");
1559        assert_eq!(patches.len(), 1);
1560        let fp = &patches[0];
1561        assert_eq!(fp.old_path.as_deref(), Some("foo.txt"));
1562        assert_eq!(fp.new_path.as_deref(), Some("foo.txt"));
1563        assert_eq!(fp.hunks.len(), 1);
1564        let hunk = &fp.hunks[0];
1565        assert_eq!(hunk.new_count, 1);
1566        assert!(matches!(hunk.lines.as_slice(), [HunkLine::Add(s)] if s == "hello"));
1567    }
1568
1569    #[test]
1570    fn parses_new_file_mode_and_deletion() {
1571        let new_file = "diff --git a/n b/n\n\
1572                        new file mode 100644\n\
1573                        index 0000000..9daeafb\n\
1574                        --- /dev/null\n\
1575                        +++ b/n\n\
1576                        @@ -0,0 +1 @@\n\
1577                        +x\n";
1578        let patches = parse_patch(new_file, 1, "<test>", false, None).expect("parse");
1579        assert_eq!(patches.len(), 1);
1580        assert!(patches[0].is_new);
1581        assert_eq!(patches[0].new_mode.as_deref(), Some("100644"));
1582
1583        let deleted = "diff --git a/d b/d\n\
1584                       deleted file mode 100644\n\
1585                       index 9daeafb..0000000\n\
1586                       --- a/d\n\
1587                       +++ /dev/null\n\
1588                       @@ -1 +0,0 @@\n\
1589                       -x\n";
1590        let patches = parse_patch(deleted, 1, "<test>", false, None).expect("parse");
1591        assert!(patches[0].is_deleted);
1592    }
1593
1594    #[test]
1595    fn corrupt_hunk_is_reported_with_input_name_and_line() {
1596        // The body provides fewer lines than the header declares.
1597        let input = "--- a/x\n\
1598                     +++ b/x\n\
1599                     @@ -1,3 +1,3 @@\n\
1600                      one\n";
1601        let err = parse_patch(input, 1, "patch", false, None).unwrap_err();
1602        assert!(matches!(
1603            err,
1604            Error::Diff(DiffError::Apply(ApplyError::CorruptPatch {
1605                ref input,
1606                line: 4
1607            })) if input == "patch"
1608        ));
1609        assert_eq!(
1610            err.git_stderr_message(),
1611            crate::diagnostics::error_line("corrupt patch at patch:4")
1612        );
1613    }
1614
1615    #[test]
1616    fn parse_hunk_header_parses_ranges() {
1617        assert_eq!(parse_hunk_header("@@ -1,3 +2,4 @@"), Some((1, 3, 2, 4)));
1618        assert_eq!(parse_hunk_header("@@ -5 +6 @@ ctx"), Some((5, 1, 6, 1)));
1619    }
1620
1621    #[test]
1622    fn invalid_hunk_header_is_typed() {
1623        assert_eq!(parse_hunk_header("@@ -x +1 @@"), None);
1624        assert_eq!(parse_hunk_header("@@ -1 @@"), None);
1625        let err = parse_patch(
1626            "--- a/f\n+++ b/f\n@@ -x +1 @@\n+a\n",
1627            1,
1628            "patch",
1629            false,
1630            None,
1631        )
1632        .unwrap_err();
1633        assert!(matches!(
1634            err,
1635            Error::Diff(DiffError::Apply(ApplyError::InvalidHunkHeader { ref header }))
1636                if header == "@@ -x +1 @@"
1637        ));
1638    }
1639
1640    #[cfg_attr(
1641        not(feature = "full-tests"),
1642        ignore = "starts system git or is heavy; run with --features full-tests"
1643    )]
1644    #[test]
1645    fn write_git_binary_patch_applies_with_system_git() {
1646        use std::fs;
1647        use std::process::Command;
1648
1649        let old = b"\0BIN\0";
1650        let new = b"\0BIN2\0";
1651        let body = write_git_binary_patch(old, new, "a/b", "b/b").expect("write");
1652        let patch = format!("diff --git a/b b/b\n{body}");
1653        let dir = tempfile::tempdir().expect("tempdir");
1654        let b = dir.path().join("b");
1655        fs::write(&b, old).expect("write base");
1656        let patch_path = dir.path().join("p.diff");
1657        fs::write(&patch_path, &patch).expect("write patch");
1658        let check = Command::new("git")
1659            .current_dir(dir.path())
1660            .args(["apply", "--check", patch_path.to_str().expect("utf8")])
1661            .output()
1662            .expect("git apply --check");
1663        assert!(
1664            check.status.success(),
1665            "git apply --check rejected grit binary patch: {}",
1666            String::from_utf8_lossy(&check.stderr)
1667        );
1668        let apply = Command::new("git")
1669            .current_dir(dir.path())
1670            .args(["apply", patch_path.to_str().expect("utf8")])
1671            .output()
1672            .expect("git apply");
1673        assert!(apply.status.success(), "git apply failed");
1674        assert_eq!(fs::read(&b).expect("read"), new);
1675    }
1676
1677    fn shattered_prefix_fixture() -> Vec<u8> {
1678        std::fs::read(
1679            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1680                .join("tests/data/shattered-1-prefix.bin"),
1681        )
1682        .expect("fixture")
1683    }
1684
1685    #[test]
1686    fn apply_accepts_shattered_result_blob_like_git() {
1687        let shattered = shattered_prefix_fixture();
1688        let body = write_git_binary_patch(b"ok", &shattered, "a/f", "b/f").expect("binary patch");
1689        let patch = format!("diff --git a/f b/f\n{body}");
1690        let patches = parse_patch(&patch, 1, "p", false, None).expect("parse");
1691        let payload = patches[0].binary_patch.as_ref().expect("binary payload");
1692        let materialized =
1693            materialize_binary_patch_forward(payload, b"ok").expect("materialize shattered blob");
1694        assert_eq!(materialized, shattered);
1695    }
1696
1697    #[test]
1698    fn write_git_binary_patch_roundtrips_through_parse_and_inflate() {
1699        let old = b"\0BIN\0";
1700        let new = b"\0BIN2\0";
1701        let body = write_git_binary_patch(old, new, "a/b", "b/b").expect("write");
1702        let patch = format!("diff --git a/b b/b\n{body}");
1703        assert!(patch.contains("GIT binary patch"));
1704        let patches = parse_patch(&patch, 1, "p", false, None).expect("parse");
1705        assert_eq!(patches.len(), 1);
1706        let payload = patches[0].binary_patch.as_ref().expect("binary payload");
1707        let forward = materialize_binary_patch_forward(payload, old).expect("materialize new");
1708        let reverse = materialize_binary_patch_reverse(payload, new).expect("materialize old");
1709        assert_eq!(forward, new);
1710        assert_eq!(reverse, old);
1711    }
1712
1713    #[cfg_attr(
1714        not(feature = "full-tests"),
1715        ignore = "starts system git or is heavy; run with --features full-tests"
1716    )]
1717    #[test]
1718    fn git_produced_delta_binary_patch_parses_and_materializes() {
1719        use std::process::Command;
1720
1721        let mut old = Vec::from(&b"\0BIN"[..]);
1722        old.extend((0u8..=255).cycle().take(996));
1723        assert_eq!(old.len(), 1000);
1724        let mut new = old.clone();
1725        new[500..510].copy_from_slice(b"CHANGED!!!");
1726
1727        let dir = tempfile::tempdir().expect("tempdir");
1728        let old_path = dir.path().join("old.bin");
1729        let new_path = dir.path().join("new.bin");
1730        std::fs::write(&old_path, &old).expect("write old");
1731        std::fs::write(&new_path, &new).expect("write new");
1732        let out = Command::new("git")
1733            .args([
1734                "diff",
1735                "--no-index",
1736                "--binary",
1737                old_path.to_str().expect("utf8"),
1738                new_path.to_str().expect("utf8"),
1739            ])
1740            .output()
1741            .expect("git diff");
1742        assert!(
1743            out.status.code() == Some(1) || out.status.success(),
1744            "git diff failed: {}",
1745            String::from_utf8_lossy(&out.stderr)
1746        );
1747        let patch = String::from_utf8_lossy(&out.stdout);
1748        assert!(
1749            patch.contains("delta "),
1750            "expected git to emit delta sections: {patch}"
1751        );
1752        let patches = parse_patch(&patch, 1, "p", false, None).expect("parse git binary patch");
1753        let payload = patches[0].binary_patch.as_ref().expect("binary payload");
1754        assert_eq!(payload.forward.kind, BinaryPatchSectionKind::Delta);
1755        let got = materialize_binary_patch_forward(payload, &old).expect("apply forward delta");
1756        assert_eq!(got, new);
1757    }
1758}