返回 CodeWhale
review_hunks.rs
根目录 / crates / engine / src / tools / review_hunks.rs
1 //! Unified-diff hunk parsing for GitHub review anchors.
2 //!
3 //! GitHub's "create a review" API rejects the *entire* review with a 422 when
4 //! any single inline comment anchors to a line that is not part of the diff.
5 //! Before this module existed the reviewer only checked that the *file* was
6 //! touched, so one model-estimated line number could make the whole review
7 //! request fail after every other inline comment had already been prepared.
8 //!
9 //! [`DiffHunks::parse`] turns a unified diff into the exact set of RIGHT-side
10 //! (post-image) line numbers GitHub will accept per file, so a bad anchor
11 //! drops one comment instead of the whole review.
12
13 use std::collections::BTreeMap;
14
15 /// A contiguous run of RIGHT-side line numbers, inclusive on both ends.
16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17 struct LineRange {
18 start: u32,
19 end: u32,
20 }
21
22 /// The RIGHT-side lines a unified diff exposes, keyed by post-image path.
23 #[derive(Debug, Clone, Default, PartialEq, Eq)]
24 pub struct DiffHunks {
25 files: BTreeMap<String, FileHunks>,
26 }
27
28 #[derive(Debug, Clone, Default, PartialEq, Eq)]
29 struct FileHunks {
30 /// Every RIGHT-side line inside a hunk: context lines plus added lines.
31 /// These are exactly the lines GitHub accepts with `side: "RIGHT"`.
32 commentable: Vec<LineRange>,
33 }
34
35 /// Cursor state while walking a hunk body.
36 #[derive(Debug, Clone, Copy, Default)]
37 struct HunkCursor {
38 right_line: u32,
39 remaining_old: u32,
40 remaining_new: u32,
41 }
42
43 impl HunkCursor {
44 fn exhausted(self) -> bool {
45 self.remaining_old == 0 && self.remaining_new == 0
46 }
47 }
48
49 impl DiffHunks {
50 /// Parse a unified diff (`git diff`, `gh pr diff`) into per-file
51 /// RIGHT-side line coverage.
52 ///
53 /// Handles multiple hunks per file, added-only and deleted files,
54 /// renames (the post-image path wins), `\ No newline at end of file`
55 /// markers, CRLF line endings, and hunk headers with omitted counts
56 /// (`@@ -1 +1 @@`). Hunk bodies are bounded by the counts in the header
57 /// so a file whose *content* contains `--- `, `+++ `, or `diff --git`
58 /// lines cannot be mistaken for a new file header.
59 #[must_use]
60 pub fn parse(diff: &str) -> Self {
61 let mut files: BTreeMap<String, FileHunks> = BTreeMap::new();
62 let mut current: Option<String> = None;
63 let mut cursor = HunkCursor::default();
64 let mut in_hunk = false;
65
66 for raw in diff.split('\n') {
67 let line = raw.strip_suffix('\r').unwrap_or(raw);
68
69 if in_hunk && !cursor.exhausted() {
70 match consume_hunk_line(line, &mut cursor, current.as_deref(), &mut files) {
71 BodyStep::Consumed => continue,
72 BodyStep::NotABodyLine => in_hunk = false,
73 }
74 }
75
76 if line.starts_with("diff --git ") {
77 current = None;
78 in_hunk = false;
79 } else if let Some(rest) = line.strip_prefix("+++ ") {
80 in_hunk = false;
81 current = post_image_path(rest);
82 if let Some(path) = current.as_ref() {
83 files.entry(path.clone()).or_default();
84 }
85 } else if line.starts_with("--- ") {
86 // Pre-image header; the `+++` that follows decides the path we
87 // anchor against (which is what makes renames work).
88 in_hunk = false;
89 } else if let Some((right_start, old_count, new_count)) = parse_hunk_header(line) {
90 cursor = HunkCursor {
91 right_line: right_start,
92 remaining_old: old_count,
93 remaining_new: new_count,
94 };
95 in_hunk = true;
96 }
97 }
98
99 Self { files }
100 }
101
102 #[must_use]
103 pub fn is_empty(&self) -> bool {
104 self.files.is_empty()
105 }
106
107 /// True when the diff touches `path` at all (post-image path match).
108 #[must_use]
109 pub fn touches_path(&self, path: &str) -> bool {
110 self.files.contains_key(path)
111 }
112
113 /// Post-image paths and hunk ranges from the same parser used to validate
114 /// comments. Context collection must not invent a second diff parser.
115 pub fn paths(&self) -> impl Iterator<Item = &str> {
116 self.files.keys().map(String::as_str)
117 }
118
119 pub fn ranges(&self, path: &str) -> impl Iterator<Item = (u32, u32)> + '_ {
120 self.files.get(path).into_iter().flat_map(|file| {
121 file.commentable
122 .iter()
123 .map(|range| (range.start, range.end))
124 })
125 }
126
127 /// True when `line` is a RIGHT-side line GitHub will accept an inline
128 /// comment on for `path` — a context line or an added line inside a hunk.
129 #[must_use]
130 pub fn contains_line(&self, path: &str, line: u32) -> bool {
131 self.files
132 .get(path)
133 .is_some_and(|file| covers(&file.commentable, line))
134 }
135
136 /// True when every line in `start..=end` is a valid RIGHT-side anchor.
137 /// Gates multi-line committable suggestions: GitHub rejects a
138 /// `start_line`/`line` span that leaves the diff.
139 #[must_use]
140 pub fn contains_span(&self, path: &str, start: u32, end: u32) -> bool {
141 if start > end {
142 return false;
143 }
144 let Some(file) = self.files.get(path) else {
145 return false;
146 };
147 (start..=end).all(|line| covers(&file.commentable, line))
148 }
149 }
150
151 enum BodyStep {
152 Consumed,
153 NotABodyLine,
154 }
155
156 fn consume_hunk_line(
157 line: &str,
158 cursor: &mut HunkCursor,
159 current: Option<&str>,
160 files: &mut BTreeMap<String, FileHunks>,
161 ) -> BodyStep {
162 // `\ No newline at end of file` annotates the previous line and consumes
163 // no line number on either side.
164 if line.starts_with('\\') {
165 return BodyStep::Consumed;
166 }
167 match line.as_bytes().first() {
168 Some(b'+') => {
169 if let Some(path) = current {
170 let entry = files.entry(path.to_string()).or_default();
171 push_line(&mut entry.commentable, cursor.right_line);
172 }
173 cursor.right_line = cursor.right_line.saturating_add(1);
174 cursor.remaining_new = cursor.remaining_new.saturating_sub(1);
175 BodyStep::Consumed
176 }
177 Some(b'-') => {
178 // Deleted: LEFT side only, never a valid RIGHT anchor.
179 cursor.remaining_old = cursor.remaining_old.saturating_sub(1);
180 BodyStep::Consumed
181 }
182 // A context line is " text"; some transports strip the trailing space
183 // from an empty context line, leaving a bare empty line.
184 Some(b' ') | None => {
185 if let Some(path) = current {
186 let entry = files.entry(path.to_string()).or_default();
187 push_line(&mut entry.commentable, cursor.right_line);
188 }
189 cursor.right_line = cursor.right_line.saturating_add(1);
190 cursor.remaining_old = cursor.remaining_old.saturating_sub(1);
191 cursor.remaining_new = cursor.remaining_new.saturating_sub(1);
192 BodyStep::Consumed
193 }
194 Some(_) => BodyStep::NotABodyLine,
195 }
196 }
197
198 fn covers(ranges: &[LineRange], line: u32) -> bool {
199 ranges
200 .iter()
201 .any(|range| line >= range.start && line <= range.end)
202 }
203
204 fn push_line(ranges: &mut Vec<LineRange>, line: u32) {
205 if let Some(last) = ranges.last_mut()
206 && last.end.saturating_add(1) == line
207 {
208 last.end = line;
209 return;
210 }
211 ranges.push(LineRange {
212 start: line,
213 end: line,
214 });
215 }
216
217 /// Extract the post-image path from a `+++ ` header body. Returns `None` for
218 /// `/dev/null` (a deleted file has no RIGHT side to comment on).
219 fn post_image_path(rest: &str) -> Option<String> {
220 // Some diff formats append a tab plus timestamp.
221 let rest = rest.split('\t').next().unwrap_or(rest).trim_end();
222 if rest.is_empty() || rest == "/dev/null" {
223 return None;
224 }
225 // Quoted paths (`"b/we\tird.rs"`) carry C-style escapes; anchoring on a
226 // mangled path would 422 the review, so decline rather than guess.
227 if rest.starts_with('"') {
228 return None;
229 }
230 let path = rest.strip_prefix("b/").unwrap_or(rest);
231 if path.is_empty() || path == "/dev/null" {
232 return None;
233 }
234 Some(path.to_string())
235 }
236
237 /// Parse `@@ -a,b +c,d @@ optional context` into
238 /// `(right_start, old_count, new_count)`. Counts may be omitted
239 /// (`@@ -1 +1 @@` means one line on each side).
240 pub(super) fn parse_hunk_header(line: &str) -> Option<(u32, u32, u32)> {
241 let rest = line.strip_prefix("@@ ")?;
242 let end = rest.find(" @@")?;
243 let ranges = &rest[..end];
244 let mut old_count = None;
245 let mut new_count = None;
246 let mut right_start = None;
247 for part in ranges.split(' ') {
248 if let Some(spec) = part.strip_prefix('-') {
249 old_count = Some(parse_range_count(spec)?);
250 } else if let Some(spec) = part.strip_prefix('+') {
251 let (start, count) = parse_range(spec)?;
252 right_start = Some(start);
253 new_count = Some(count);
254 }
255 }
256 Some((right_start?, old_count?, new_count?))
257 }
258
259 fn parse_range(spec: &str) -> Option<(u32, u32)> {
260 let mut parts = spec.split(',');
261 let start = parts.next()?.parse::<u32>().ok()?;
262 let count = match parts.next() {
263 Some(count) => count.parse::<u32>().ok()?,
264 None => 1,
265 };
266 Some((start, count))
267 }
268
269 fn parse_range_count(spec: &str) -> Option<u32> {
270 parse_range(spec).map(|(_, count)| count)
271 }
272
273 #[cfg(test)]
274 mod tests {
275 use super::*;
276
277 /// Join diff lines verbatim. Written as a slice rather than one string
278 /// literal because a `\` continuation would strip the leading space that
279 /// marks a context line — which is exactly the byte this parser reads.
280 fn diff(lines: &[&str]) -> String {
281 let mut joined = lines.join("\n");
282 joined.push('\n');
283 joined
284 }
285
286 #[test]
287 fn parses_multiple_hunks_in_one_file() {
288 let diff = diff(&[
289 "diff --git a/src/lib.rs b/src/lib.rs",
290 "index 1111111..2222222 100644",
291 "--- a/src/lib.rs",
292 "+++ b/src/lib.rs",
293 "@@ -10,3 +10,4 @@ fn one() {",
294 " context_a",
295 "-removed",
296 "+added_one",
297 "+added_two",
298 " context_b",
299 "@@ -80,2 +81,2 @@ fn two() {",
300 " ctx",
301 "-old",
302 "+new",
303 ]);
304 let hunks = DiffHunks::parse(&diff);
305 assert!(hunks.touches_path("src/lib.rs"));
306 // First hunk covers right lines 10..=13 (ctx, +, +, ctx).
307 for line in 10..=13 {
308 assert!(hunks.contains_line("src/lib.rs", line), "line {line}");
309 }
310 assert!(!hunks.contains_line("src/lib.rs", 9));
311 assert!(!hunks.contains_line("src/lib.rs", 14));
312 // Second hunk: ctx at 81, `-old` consumes no right line, `+new` at 82.
313 assert!(hunks.contains_line("src/lib.rs", 81));
314 assert!(hunks.contains_line("src/lib.rs", 82));
315 assert!(!hunks.contains_line("src/lib.rs", 83));
316 }
317
318 #[test]
319 fn parses_added_only_file() {
320 let diff = diff(&[
321 "diff --git a/new.rs b/new.rs",
322 "new file mode 100644",
323 "index 0000000..3333333",
324 "--- /dev/null",
325 "+++ b/new.rs",
326 "@@ -0,0 +1,3 @@",
327 "+fn a() {}",
328 "+fn b() {}",
329 "+fn c() {}",
330 ]);
331 let hunks = DiffHunks::parse(&diff);
332 assert!(hunks.contains_span("new.rs", 1, 3));
333 assert!(!hunks.contains_line("new.rs", 4));
334 }
335
336 #[test]
337 fn deleted_file_has_no_right_side_anchor() {
338 let diff = diff(&[
339 "diff --git a/gone.rs b/gone.rs",
340 "deleted file mode 100644",
341 "index 3333333..0000000",
342 "--- a/gone.rs",
343 "+++ /dev/null",
344 "@@ -1,2 +0,0 @@",
345 "-fn a() {}",
346 "-fn b() {}",
347 ]);
348 let hunks = DiffHunks::parse(&diff);
349 assert!(!hunks.touches_path("gone.rs"));
350 assert!(!hunks.contains_line("gone.rs", 1));
351 }
352
353 #[test]
354 fn pure_deletion_hunk_exposes_no_right_lines() {
355 let diff = diff(&[
356 "diff --git a/src/a.rs b/src/a.rs",
357 "--- a/src/a.rs",
358 "+++ b/src/a.rs",
359 "@@ -5,3 +4,0 @@",
360 "-one",
361 "-two",
362 "-three",
363 ]);
364 let hunks = DiffHunks::parse(&diff);
365 assert!(hunks.touches_path("src/a.rs"));
366 assert!(!hunks.contains_line("src/a.rs", 4));
367 assert!(!hunks.contains_line("src/a.rs", 5));
368 }
369
370 #[test]
371 fn rename_anchors_on_the_post_image_path() {
372 let diff = diff(&[
373 "diff --git a/old/name.rs b/new/name.rs",
374 "similarity index 92%",
375 "rename from old/name.rs",
376 "rename to new/name.rs",
377 "--- a/old/name.rs",
378 "+++ b/new/name.rs",
379 "@@ -1,2 +1,2 @@",
380 " kept",
381 "-old",
382 "+new",
383 ]);
384 let hunks = DiffHunks::parse(&diff);
385 assert!(hunks.touches_path("new/name.rs"));
386 assert!(!hunks.touches_path("old/name.rs"));
387 assert!(hunks.contains_span("new/name.rs", 1, 2));
388 assert!(!hunks.contains_line("new/name.rs", 3));
389 }
390
391 #[test]
392 fn rename_without_content_change_has_no_anchors() {
393 let diff = diff(&[
394 "diff --git a/old.rs b/new.rs",
395 "similarity index 100%",
396 "rename from old.rs",
397 "rename to new.rs",
398 ]);
399 let hunks = DiffHunks::parse(&diff);
400 // No `+++` header and no hunk: nothing is commentable, and we must not
401 // invent an anchor.
402 assert!(!hunks.touches_path("new.rs"));
403 assert!(!hunks.contains_line("new.rs", 1));
404 }
405
406 #[test]
407 fn no_newline_marker_consumes_no_line_number() {
408 let diff = diff(&[
409 "diff --git a/eof.rs b/eof.rs",
410 "--- a/eof.rs",
411 "+++ b/eof.rs",
412 "@@ -1,2 +1,2 @@",
413 " first",
414 "-last",
415 "\\ No newline at end of file",
416 "+last!",
417 "\\ No newline at end of file",
418 ]);
419 let hunks = DiffHunks::parse(&diff);
420 assert!(hunks.contains_span("eof.rs", 1, 2));
421 assert!(!hunks.contains_line("eof.rs", 3));
422 }
423
424 #[test]
425 fn crlf_diff_parses_paths_and_lines() {
426 let diff = [
427 "diff --git a/crlf.rs b/crlf.rs",
428 "index 1111111..2222222 100644",
429 "--- a/crlf.rs",
430 "+++ b/crlf.rs",
431 "@@ -1,2 +1,3 @@",
432 " ctx",
433 "+added",
434 " tail",
435 ]
436 .join("\r\n")
437 + "\r\n";
438 let hunks = DiffHunks::parse(&diff);
439 assert!(
440 hunks.touches_path("crlf.rs"),
441 "CRLF path must not keep the carriage return"
442 );
443 assert!(hunks.contains_span("crlf.rs", 1, 3));
444 assert!(!hunks.contains_line("crlf.rs", 4));
445 }
446
447 #[test]
448 fn hunk_header_without_counts_is_supported() {
449 let diff = diff(&[
450 "diff --git a/one.rs b/one.rs",
451 "--- a/one.rs",
452 "+++ b/one.rs",
453 "@@ -7 +9 @@",
454 "-old",
455 "+new",
456 ]);
457 let hunks = DiffHunks::parse(&diff);
458 assert!(hunks.contains_line("one.rs", 9));
459 assert!(!hunks.contains_line("one.rs", 8));
460 }
461
462 #[test]
463 fn multi_file_diff_keeps_files_independent() {
464 let diff = diff(&[
465 "diff --git a/a.rs b/a.rs",
466 "--- a/a.rs",
467 "+++ b/a.rs",
468 "@@ -1,0 +1,1 @@",
469 "+alpha",
470 "diff --git a/b.rs b/b.rs",
471 "--- a/b.rs",
472 "+++ b/b.rs",
473 "@@ -50,0 +50,1 @@",
474 "+beta",
475 ]);
476 let hunks = DiffHunks::parse(&diff);
477 assert!(hunks.contains_line("a.rs", 1));
478 assert!(!hunks.contains_line("a.rs", 50));
479 assert!(hunks.contains_line("b.rs", 50));
480 assert!(!hunks.contains_line("b.rs", 1));
481 }
482
483 #[test]
484 fn file_content_that_looks_like_a_diff_header_stays_in_the_hunk() {
485 // A patch that itself edits a stored diff fixture. Naive parsers read
486 // the ` --- a/inner.rs` / ` +++ b/inner.rs` context lines as a new file
487 // header and mis-anchor every later comment.
488 let diff = diff(&[
489 "diff --git a/fixtures/sample.diff b/fixtures/sample.diff",
490 "--- a/fixtures/sample.diff",
491 "+++ b/fixtures/sample.diff",
492 "@@ -1,4 +1,4 @@",
493 " --- a/inner.rs",
494 " +++ b/inner.rs",
495 "-@@ -1 +1 @@",
496 "+@@ -2 +2 @@",
497 " tail",
498 ]);
499 let hunks = DiffHunks::parse(&diff);
500 assert!(hunks.contains_span("fixtures/sample.diff", 1, 4));
501 assert!(!hunks.touches_path("inner.rs"));
502 }
503
504 #[test]
505 fn quoted_path_is_declined_rather_than_mangled() {
506 let diff = diff(&[
507 "diff --git \"a/we\\tird.rs\" \"b/we\\tird.rs\"",
508 "--- \"a/we\\tird.rs\"",
509 "+++ \"b/we\\tird.rs\"",
510 "@@ -1,0 +1,1 @@",
511 "+x",
512 ]);
513 let hunks = DiffHunks::parse(&diff);
514 assert!(hunks.files.is_empty());
515 }
516
517 #[test]
518 fn empty_context_line_still_advances_the_cursor() {
519 // Some transports strip the trailing space from an empty context line.
520 let diff = diff(&[
521 "diff --git a/s.rs b/s.rs",
522 "--- a/s.rs",
523 "+++ b/s.rs",
524 "@@ -1,3 +1,4 @@",
525 " one",
526 "",
527 "+three",
528 " four",
529 ]);
530 let hunks = DiffHunks::parse(&diff);
531 assert!(hunks.contains_span("s.rs", 1, 4));
532 }
533
534 #[test]
535 fn contains_span_rejects_partial_and_inverted_ranges() {
536 let diff = diff(&[
537 "diff --git a/x.rs b/x.rs",
538 "--- a/x.rs",
539 "+++ b/x.rs",
540 "@@ -1,1 +1,2 @@",
541 " a",
542 "+b",
543 ]);
544 let hunks = DiffHunks::parse(&diff);
545 assert!(hunks.contains_span("x.rs", 1, 2));
546 assert!(!hunks.contains_span("x.rs", 1, 3));
547 assert!(!hunks.contains_span("x.rs", 2, 1));
548 assert!(!hunks.contains_span("missing.rs", 1, 1));
549 }
550
551 #[test]
552 fn empty_diff_yields_no_anchors() {
553 let hunks = DiffHunks::parse("");
554 assert!(!hunks.touches_path("anything.rs"));
555 assert!(!hunks.contains_line("anything.rs", 1));
556 }
557 }
558
558 lines RUST