-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdiff_parser.rs
More file actions
602 lines (546 loc) · 19.7 KB
/
diff_parser.rs
File metadata and controls
602 lines (546 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
use anyhow::Result;
use serde::{Deserialize, Serialize};
use similar::TextDiff;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedDiff {
pub file_path: PathBuf,
pub old_content: Option<String>,
pub new_content: Option<String>,
pub hunks: Vec<DiffHunk>,
pub is_binary: bool,
pub is_deleted: bool,
pub is_new: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiffHunk {
pub old_start: usize,
pub old_lines: usize,
pub new_start: usize,
pub new_lines: usize,
pub context: String,
pub changes: Vec<DiffLine>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiffLine {
pub old_line_no: Option<usize>,
pub new_line_no: Option<usize>,
pub change_type: ChangeType,
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ChangeType {
Added,
Removed,
Context,
}
pub struct DiffParser;
impl DiffParser {
pub fn parse_unified_diff(diff_content: &str) -> Result<Vec<UnifiedDiff>> {
let mut diffs = Vec::new();
let lines: Vec<&str> = diff_content.lines().collect();
let mut i = 0;
while i < lines.len() {
if lines[i].starts_with("diff --git") {
let diff = Self::parse_single_file_diff(&lines, &mut i)?;
diffs.push(diff);
} else if lines[i].starts_with("--- ")
&& i + 1 < lines.len()
&& lines[i + 1].starts_with("+++ ")
{
let diff = Self::parse_simple_file_diff(&lines, &mut i)?;
diffs.push(diff);
} else {
i += 1;
}
}
Ok(diffs)
}
pub fn parse_text_diff(
old_content: &str,
new_content: &str,
file_path: PathBuf,
) -> Result<UnifiedDiff> {
let diff = TextDiff::from_lines(old_content, new_content);
let mut hunks = Vec::new();
for group in diff.grouped_ops(3) {
let mut hunk_lines = Vec::new();
let mut old_start = None;
let mut new_start = None;
let mut old_count = 0;
let mut new_count = 0;
for op in group {
match op.tag() {
similar::DiffTag::Delete => {
for old_idx in op.old_range() {
if old_start.is_none() {
old_start = Some(old_idx + 1);
}
old_count += 1;
hunk_lines.push(DiffLine {
old_line_no: Some(old_idx + 1),
new_line_no: None,
change_type: ChangeType::Removed,
content: diff.old_slices()[old_idx].to_string(),
});
}
}
similar::DiffTag::Insert => {
for new_idx in op.new_range() {
if new_start.is_none() {
new_start = Some(new_idx + 1);
}
new_count += 1;
hunk_lines.push(DiffLine {
old_line_no: None,
new_line_no: Some(new_idx + 1),
change_type: ChangeType::Added,
content: diff.new_slices()[new_idx].to_string(),
});
}
}
similar::DiffTag::Equal => {
for (old_idx, new_idx) in op.old_range().zip(op.new_range()) {
if old_start.is_none() {
old_start = Some(old_idx + 1);
}
if new_start.is_none() {
new_start = Some(new_idx + 1);
}
old_count += 1;
new_count += 1;
hunk_lines.push(DiffLine {
old_line_no: Some(old_idx + 1),
new_line_no: Some(new_idx + 1),
change_type: ChangeType::Context,
content: diff.old_slices()[old_idx].to_string(),
});
}
}
similar::DiffTag::Replace => {
for old_idx in op.old_range() {
if old_start.is_none() {
old_start = Some(old_idx + 1);
}
old_count += 1;
hunk_lines.push(DiffLine {
old_line_no: Some(old_idx + 1),
new_line_no: None,
change_type: ChangeType::Removed,
content: diff.old_slices()[old_idx].to_string(),
});
}
for new_idx in op.new_range() {
if new_start.is_none() {
new_start = Some(new_idx + 1);
}
new_count += 1;
hunk_lines.push(DiffLine {
old_line_no: None,
new_line_no: Some(new_idx + 1),
change_type: ChangeType::Added,
content: diff.new_slices()[new_idx].to_string(),
});
}
}
}
}
if !hunk_lines.is_empty() {
hunks.push(DiffHunk {
old_start: old_start.unwrap_or(1),
old_lines: old_count,
new_start: new_start.unwrap_or(1),
new_lines: new_count,
context: format!(
"@@ -{},{} +{},{} @@",
old_start.unwrap_or(1),
old_count,
new_start.unwrap_or(1),
new_count
),
changes: hunk_lines,
});
}
}
Ok(UnifiedDiff {
file_path,
old_content: Some(old_content.to_string()),
new_content: Some(new_content.to_string()),
hunks,
is_binary: false,
is_deleted: new_content.is_empty() && !old_content.is_empty(),
is_new: old_content.is_empty() && !new_content.is_empty(),
})
}
fn parse_single_file_diff(lines: &[&str], i: &mut usize) -> Result<UnifiedDiff> {
let file_line = lines[*i];
let file_path = Self::extract_file_path(file_line)?;
*i += 1;
let mut is_binary = false;
let mut is_deleted = false;
let mut is_new = false;
while *i < lines.len()
&& !lines[*i].starts_with("@@")
&& !lines[*i].starts_with("diff --git")
{
let line = lines[*i];
if line.starts_with("Binary files") || line.starts_with("GIT binary patch") {
is_binary = true;
}
if line.starts_with("deleted file mode") {
is_deleted = true;
}
if line.starts_with("new file mode") {
is_new = true;
}
if line.starts_with("--- ") {
if let Ok(path) = Self::extract_path_from_header(line, "--- ") {
if path == "/dev/null" {
is_new = true;
}
}
}
if line.starts_with("+++ ") {
if let Ok(path) = Self::extract_path_from_header(line, "+++ ") {
if path == "/dev/null" {
is_deleted = true;
}
}
}
*i += 1;
}
let mut hunks = Vec::new();
while *i < lines.len() && lines[*i].starts_with("@@") {
let hunk = Self::parse_hunk(lines, i)?;
hunks.push(hunk);
}
Ok(UnifiedDiff {
file_path: PathBuf::from(file_path),
old_content: None,
new_content: None,
hunks,
is_binary,
is_deleted,
is_new,
})
}
fn parse_simple_file_diff(lines: &[&str], i: &mut usize) -> Result<UnifiedDiff> {
let old_line = lines[*i];
let new_line = lines.get(*i + 1).unwrap_or(&"");
let old_path = Self::extract_path_from_header(old_line, "--- ")?;
let new_path = Self::extract_path_from_header(new_line, "+++ ")?;
let is_new = old_path == "/dev/null";
let is_deleted = new_path == "/dev/null";
let file_path = if new_path != "/dev/null" {
new_path
} else {
old_path
};
*i += 2;
let mut hunks = Vec::new();
let mut is_binary = false;
while *i < lines.len()
&& !lines[*i].starts_with("diff --git")
&& !(lines[*i].starts_with("--- ")
&& *i + 1 < lines.len()
&& lines[*i + 1].starts_with("+++ "))
{
if lines[*i].starts_with("Binary files") || lines[*i].starts_with("GIT binary patch") {
is_binary = true;
}
if lines[*i].starts_with("@@") {
let hunk = Self::parse_hunk(lines, i)?;
hunks.push(hunk);
} else {
*i += 1;
}
}
Ok(UnifiedDiff {
file_path: PathBuf::from(file_path),
old_content: None,
new_content: None,
hunks,
is_binary,
is_deleted,
is_new,
})
}
fn extract_file_path(line: &str) -> Result<String> {
let re = regex::Regex::new(r#"^diff --git (?:"a/(.*?)"|a/(\S+)) (?:"b/(.*?)"|b/(\S+))"#)?;
if let Some(caps) = re.captures(line) {
let a_path = caps
.get(1)
.or_else(|| caps.get(2))
.map(|m| m.as_str())
.unwrap_or("");
let b_path = caps
.get(3)
.or_else(|| caps.get(4))
.map(|m| m.as_str())
.unwrap_or("");
let chosen = if !b_path.is_empty() && b_path != "/dev/null" {
b_path
} else {
a_path
};
return Ok(chosen.to_string());
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 4 {
let a_path = parts[2].trim_start_matches("a/");
let b_path = parts[3].trim_start_matches("b/");
let chosen = if b_path != "/dev/null" {
b_path
} else {
a_path
};
Ok(chosen.to_string())
} else {
anyhow::bail!("Invalid diff header: {}", line)
}
}
fn extract_path_from_header(line: &str, prefix: &str) -> Result<String> {
let raw = line
.strip_prefix(prefix)
.ok_or_else(|| anyhow::anyhow!("Invalid file header: {}", line))?
.trim();
let path = if let Some(stripped) = raw.strip_prefix('"') {
if let Some(end) = stripped.find('"') {
&stripped[..end]
} else {
stripped
}
} else {
raw.split_whitespace().next().unwrap_or(raw)
};
Ok(path
.trim_start_matches("a/")
.trim_start_matches("b/")
.to_string())
}
fn parse_hunk(lines: &[&str], i: &mut usize) -> Result<DiffHunk> {
let header = lines[*i];
let (old_start, old_lines, new_start, new_lines) = Self::parse_hunk_header(header)?;
*i += 1;
let mut changes = Vec::new();
let mut old_line = old_start;
let mut new_line = new_start;
while *i < lines.len()
&& !lines[*i].starts_with("@@")
&& !lines[*i].starts_with("diff --git")
&& !lines[*i].starts_with("--- ")
&& !lines[*i].starts_with("+++ ")
{
let line = lines[*i];
if line.starts_with("\\ No newline at end of file") {
*i += 1;
continue;
}
let (change_type, content) = if line.is_empty() {
// Some diff tools emit truly empty lines for empty context lines
// (omitting the leading space). Treat as context to keep line numbers in sync.
(ChangeType::Context, "")
} else {
match line.chars().next() {
Some('+') => (ChangeType::Added, &line[1..]),
Some('-') => (ChangeType::Removed, &line[1..]),
Some(' ') => (ChangeType::Context, &line[1..]),
_ => (ChangeType::Context, line),
}
};
let diff_line = match change_type {
ChangeType::Added => {
let line_no = new_line;
new_line += 1;
DiffLine {
old_line_no: None,
new_line_no: Some(line_no),
change_type,
content: content.to_string(),
}
}
ChangeType::Removed => {
let line_no = old_line;
old_line += 1;
DiffLine {
old_line_no: Some(line_no),
new_line_no: None,
change_type,
content: content.to_string(),
}
}
ChangeType::Context => {
let old_no = old_line;
let new_no = new_line;
old_line += 1;
new_line += 1;
DiffLine {
old_line_no: Some(old_no),
new_line_no: Some(new_no),
change_type,
content: content.to_string(),
}
}
};
changes.push(diff_line);
*i += 1;
}
Ok(DiffHunk {
old_start,
old_lines,
new_start,
new_lines,
context: header.to_string(),
changes,
})
}
fn parse_hunk_header(header: &str) -> Result<(usize, usize, usize, usize)> {
let re = regex::Regex::new(r"@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@")?;
let caps = re
.captures(header)
.ok_or_else(|| anyhow::anyhow!("Invalid hunk header: {}", header))?;
let old_start = caps.get(1).unwrap().as_str().parse()?;
let old_lines = caps.get(2).map_or(1, |m| m.as_str().parse().unwrap_or(1));
let new_start = caps.get(3).unwrap().as_str().parse()?;
let new_lines = caps.get(4).map_or(1, |m| m.as_str().parse().unwrap_or(1));
Ok((old_start, old_lines, new_start, new_lines))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_text_diff() {
let old = "line1\nline2\nline3";
let new = "line1\nmodified\nline3\nline4";
let diff = DiffParser::parse_text_diff(old, new, PathBuf::from("test.txt")).unwrap();
assert_eq!(diff.file_path, PathBuf::from("test.txt"));
assert!(!diff.hunks.is_empty());
}
#[test]
fn test_parse_unified_diff_without_git_header() {
let diff_text = "\
--- a/foo.txt\n\
+++ b/foo.txt\n\
@@ -1,1 +1,1 @@\n\
-hello\n\
+world\n";
let diffs = DiffParser::parse_unified_diff(diff_text).unwrap();
assert_eq!(diffs.len(), 1);
assert_eq!(diffs[0].file_path, PathBuf::from("foo.txt"));
assert_eq!(diffs[0].hunks.len(), 1);
}
#[test]
fn test_parse_diff_header_with_spaces() {
let diff_text = "\
diff --git \"a/foo bar.txt\" \"b/foo bar.txt\"\n\
index 83db48f..f735c20 100644\n\
--- \"a/foo bar.txt\"\n\
+++ \"b/foo bar.txt\"\n\
@@ -1,1 +1,1 @@\n\
-hello\n\
+world\n";
let diffs = DiffParser::parse_unified_diff(diff_text).unwrap();
assert_eq!(diffs.len(), 1);
assert_eq!(diffs[0].file_path, PathBuf::from("foo bar.txt"));
}
#[test]
fn test_parse_no_newline_marker() {
let diff_text = "\
diff --git a/foo.txt b/foo.txt\n\
index 83db48f..f735c20 100644\n\
--- a/foo.txt\n\
+++ b/foo.txt\n\
@@ -1,1 +1,1 @@\n\
-hello\n\
\\ No newline at end of file\n\
+world\n";
let diffs = DiffParser::parse_unified_diff(diff_text).unwrap();
assert_eq!(diffs.len(), 1);
assert_eq!(diffs[0].hunks.len(), 1);
}
#[test]
fn test_parse_deleted_file() {
let diff_text = "\
diff --git a/foo.txt b/foo.txt\n\
deleted file mode 100644\n\
index 83db48f..0000000\n\
--- a/foo.txt\n\
+++ /dev/null\n\
@@ -1,1 +0,0 @@\n\
-hello\n";
let diffs = DiffParser::parse_unified_diff(diff_text).unwrap();
assert_eq!(diffs.len(), 1);
assert!(diffs[0].is_deleted);
assert!(!diffs[0].is_new);
}
#[test]
fn test_parse_new_file() {
let diff_text = "\
diff --git a/foo.txt b/foo.txt\n\
new file mode 100644\n\
index 0000000..f735c20\n\
--- /dev/null\n\
+++ b/foo.txt\n\
@@ -0,0 +1,1 @@\n\
+hello\n";
let diffs = DiffParser::parse_unified_diff(diff_text).unwrap();
assert_eq!(diffs.len(), 1);
assert!(diffs[0].is_new);
assert!(!diffs[0].is_deleted);
}
#[test]
fn test_parse_hunk_empty_lines_not_skipped() {
// Regression: empty lines in diff body were previously skipped.
// An empty line (no leading space) in some diff tools represents an empty
// context line. The parser should treat it as context, not skip it.
let diff_text = "\
diff --git a/test.txt b/test.txt\n\
index abc..def 100644\n\
--- a/test.txt\n\
+++ b/test.txt\n\
@@ -1,4 +1,4 @@\n\
line1\n\
\n\
-old_line3\n\
+new_line3\n";
// The empty line (between "line1" and "-old_line3") should be treated as
// context line 2. Without it, line numbers after the empty line are wrong.
let diffs = DiffParser::parse_unified_diff(diff_text).unwrap();
assert_eq!(diffs.len(), 1);
let hunk = &diffs[0].hunks[0];
// Find the removed line — it should be on line 3, not line 2
let removed = hunk
.changes
.iter()
.find(|c| c.change_type == ChangeType::Removed)
.expect("Should have a removed line");
assert_eq!(
removed.old_line_no,
Some(3),
"Removed line should be on old line 3 (after the empty context line 2), got {:?}",
removed.old_line_no
);
}
#[test]
fn test_parse_text_diff_sets_is_new_for_new_file() {
// Regression: parse_text_diff must set is_new when old_content is empty
let diff =
DiffParser::parse_text_diff("", "new content\n", PathBuf::from("new_file.rs")).unwrap();
assert!(
diff.is_new,
"parse_text_diff with empty old content should set is_new=true"
);
}
#[test]
fn test_parse_text_diff_sets_is_deleted_for_deleted_file() {
// Regression: parse_text_diff must set is_deleted when new_content is empty
let diff =
DiffParser::parse_text_diff("old content\n", "", PathBuf::from("deleted_file.rs"))
.unwrap();
assert!(
diff.is_deleted,
"parse_text_diff with empty new content should set is_deleted=true"
);
}
}