MCPcopy Create free account
hub / github.com/atomicdotdev/atomic / parse_patch_hunks

Function parse_patch_hunks

atomic-cli/src/commands/rpc.rs:2689–2752  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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

Callers 2

print_word_diff_patchFunction · 0.85
print_diff_jsonFunction · 0.85

Calls 6

getMethod · 0.65
parseFunction · 0.50
linesMethod · 0.45
nextMethod · 0.45
parseMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected