Parse a unified-diff patch into hunks. Each line is `(marker, content, old_line, new_line)` with the markers ' ', '-', '+'; line numbers follow the unified header's running counters, exactly as the local renderer numbers its computed hunks.
(patch: &str)
| 2686 | /// line numbers follow the unified header's running counters, exactly as |
| 2687 | /// the local renderer numbers its computed hunks. |
| 2688 | fn parse_patch_hunks(patch: &str) -> Vec<WireHunk> { |
| 2689 | let mut hunks = Vec::new(); |
| 2690 | let mut current: Option<WireHunk> = None; |
| 2691 | let mut old_counter = 0usize; |
| 2692 | let mut new_counter = 0usize; |
| 2693 | for line in patch.lines() { |
| 2694 | if let Some(header) = line.strip_prefix("@@") { |
| 2695 | // "@@ -a,b +c,d @@ ..." — the ranges ride before the closing @@. |
| 2696 | let body = header.split("@@").next().unwrap_or(""); |
| 2697 | let mut parts = body.split_whitespace(); |
| 2698 | let parse = |spec: &str| -> (usize, usize) { |
| 2699 | let stripped = spec |
| 2700 | .strip_prefix('-') |
| 2701 | .or_else(|| spec.strip_prefix('+')) |
| 2702 | .unwrap_or(spec); |
| 2703 | let (start, count) = stripped.split_once(',').unwrap_or((stripped, "1")); |
| 2704 | (start.parse().unwrap_or(0), count.parse().unwrap_or(1)) |
| 2705 | }; |
| 2706 | let (old_start, old_count) = parse(parts.next().unwrap_or("-0,0")); |
| 2707 | let (new_start, new_count) = parse(parts.next().unwrap_or("+0,0")); |
| 2708 | old_counter = old_start; |
| 2709 | new_counter = new_start; |
| 2710 | if let Some(previous) = current.take() { |
| 2711 | hunks.push(previous); |
| 2712 | } |
| 2713 | current = Some(WireHunk { |
| 2714 | old_start, |
| 2715 | old_count, |
| 2716 | new_start, |
| 2717 | new_count, |
| 2718 | lines: Vec::new(), |
| 2719 | }); |
| 2720 | continue; |
| 2721 | } |
| 2722 | if line.starts_with("---") || line.starts_with("+++") || line.starts_with("diff ") { |
| 2723 | continue; // defensive: file headers never carry change lines |
| 2724 | } |
| 2725 | let Some(hunk) = current.as_mut() else { |
| 2726 | continue; // preamble before the first @@ header |
| 2727 | }; |
| 2728 | let marker = line.chars().next().unwrap_or(' '); |
| 2729 | let content = line.get(1..).unwrap_or_default().to_string(); |
| 2730 | match marker { |
| 2731 | '-' => { |
| 2732 | hunk.lines.push(('-', content, Some(old_counter), None)); |
| 2733 | old_counter = old_counter.saturating_add(1); |
| 2734 | } |
| 2735 | '+' => { |
| 2736 | hunk.lines.push(('+', content, None, Some(new_counter))); |
| 2737 | new_counter = new_counter.saturating_add(1); |
| 2738 | } |
| 2739 | _ => { |
| 2740 | hunk.lines |
| 2741 | .push((' ', content, Some(old_counter), Some(new_counter))); |
| 2742 | old_counter = old_counter.saturating_add(1); |
| 2743 | new_counter = new_counter.saturating_add(1); |
| 2744 | } |
| 2745 | } |