Repository navigation
Expand file tree
/
Copy pathparser.rs
More file actions
685 lines (601 loc) · 20.5 KB
/
Copy pathparser.rs
File metadata and controls
685 lines (601 loc) · 20.5 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Patch parsing for multiple formats.
use crate::error::PatchResult;
use crate::hunk::{FileChange, Hunk, HunkLine, SearchReplace};
use std::path::PathBuf;
/// Supported patch formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatchFormat {
/// Standard unified diff format.
UnifiedDiff,
/// Git extended diff format.
GitDiff,
/// Simple search/replace format.
SearchReplace,
/// Unknown format.
Unknown,
}
impl PatchFormat {
/// Detect the format of a patch string.
pub fn detect(patch: &str) -> Self {
let lines: Vec<&str> = patch.lines().collect();
if lines.is_empty() {
return Self::Unknown;
}
// Check for git diff format
if lines.iter().any(|l| l.starts_with("diff --git")) {
return Self::GitDiff;
}
// Check for unified diff format
if lines
.iter()
.any(|l| l.starts_with("--- ") || l.starts_with("+++ "))
{
return Self::UnifiedDiff;
}
// Check for search/replace format (<<<<<<< SEARCH / ======= / >>>>>>> REPLACE)
if lines
.iter()
.any(|l| l.contains("<<<<<<< SEARCH") || l.contains(">>>>>>> REPLACE"))
{
return Self::SearchReplace;
}
Self::Unknown
}
}
/// Parse a patch string into file changes.
pub fn parse_patch(patch: &str) -> PatchResult<Vec<FileChange>> {
let patch = patch.trim();
if patch.is_empty() {
return Ok(vec![]);
}
let format = PatchFormat::detect(patch);
match format {
PatchFormat::GitDiff => parse_git_diff(patch),
PatchFormat::UnifiedDiff => parse_unified_diff(patch),
PatchFormat::SearchReplace => parse_search_replace(patch),
PatchFormat::Unknown => {
// Try unified diff as fallback
parse_unified_diff(patch)
}
}
}
/// Parse a standard unified diff.
pub fn parse_unified_diff(patch: &str) -> PatchResult<Vec<FileChange>> {
let mut file_changes = Vec::new();
let mut current_change: Option<FileChange> = None;
let mut current_hunk: Option<Hunk> = None;
let lines: Vec<&str> = patch.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
// Detect file header: --- path
if let Some(old_str) = line.strip_prefix("--- ") {
// Save previous file change if exists
if let Some(mut change) = current_change.take() {
if let Some(hunk) = current_hunk.take() {
change.hunks.push(hunk);
}
if !change.hunks.is_empty() || change.is_new_file || change.is_deleted {
file_changes.push(change);
}
}
let old_path = parse_file_path(old_str);
// Look for +++ line
if i + 1 < lines.len()
&& let Some(new_str) = lines[i + 1].strip_prefix("+++ ")
{
let new_path = parse_file_path(new_str);
current_change = Some(FileChange::new(old_path, new_path));
i += 2;
continue;
}
// Malformed patch, but try to continue
current_change = Some(FileChange::new(old_path, None));
i += 1;
continue;
}
// Detect hunk header: @@ -start,count +start,count @@
if line.starts_with("@@ ") {
// Save previous hunk
if let Some(ref mut change) = current_change
&& let Some(hunk) = current_hunk.take()
{
change.hunks.push(hunk);
}
current_hunk = parse_hunk_header(line);
i += 1;
continue;
}
// Parse hunk lines
if let Some(ref mut hunk) = current_hunk {
if let Some(content) = line.strip_prefix('+') {
// Addition line - but not the +++ header
if !content.starts_with("++") {
hunk.lines.push(HunkLine::Add(content.to_string()));
}
} else if let Some(content) = line.strip_prefix('-') {
// Removal line - but not the --- header
if !content.starts_with("--") {
hunk.lines.push(HunkLine::Remove(content.to_string()));
}
} else if let Some(content) = line.strip_prefix(' ') {
// Context line
hunk.lines.push(HunkLine::Context(content.to_string()));
} else if line.is_empty() {
// Empty context line
hunk.lines.push(HunkLine::Context(String::new()));
} else if line.starts_with('\\') {
// "\ No newline at end of file" - ignore but don't add as context
}
// Skip other lines (like git metadata)
}
i += 1;
}
// Save final file change and hunk
if let Some(mut change) = current_change.take() {
if let Some(hunk) = current_hunk.take() {
change.hunks.push(hunk);
}
if !change.hunks.is_empty() || change.is_new_file || change.is_deleted {
file_changes.push(change);
}
}
Ok(file_changes)
}
/// Parse a git extended diff format.
pub fn parse_git_diff(patch: &str) -> PatchResult<Vec<FileChange>> {
let mut file_changes = Vec::new();
let mut current_change: Option<FileChange> = None;
let mut current_hunk: Option<Hunk> = None;
let lines: Vec<&str> = patch.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
// Git diff header: diff --git a/path b/path
if line.starts_with("diff --git ") {
// Save previous file change
if let Some(mut change) = current_change.take() {
if let Some(hunk) = current_hunk.take() {
change.hunks.push(hunk);
}
if !change.hunks.is_empty()
|| change.is_new_file
|| change.is_deleted
|| change.is_binary
{
file_changes.push(change);
}
}
// Parse the git diff header
let (old_path, new_path) = parse_git_diff_header(line);
current_change = Some(FileChange::new(old_path, new_path));
i += 1;
continue;
}
// Handle git-specific metadata
if let Some(ref mut change) = current_change {
if let Some(mode) = line.strip_prefix("old mode ") {
change.old_mode = Some(mode.to_string());
i += 1;
continue;
}
if let Some(mode) = line.strip_prefix("new mode ") {
change.new_mode = Some(mode.to_string());
i += 1;
continue;
}
if let Some(mode) = line.strip_prefix("new file mode ") {
change.is_new_file = true;
change.new_mode = Some(mode.to_string());
i += 1;
continue;
}
if let Some(mode) = line.strip_prefix("deleted file mode ") {
change.is_deleted = true;
change.old_mode = Some(mode.to_string());
i += 1;
continue;
}
if let Some(path) = line.strip_prefix("rename from ") {
change.is_rename = true;
change.old_path = Some(PathBuf::from(path));
i += 1;
continue;
}
if let Some(path) = line.strip_prefix("rename to ") {
change.is_rename = true;
change.new_path = Some(PathBuf::from(path));
i += 1;
continue;
}
if line.starts_with("similarity index ") || line.starts_with("dissimilarity index ") {
i += 1;
continue;
}
if line.starts_with("index ") {
i += 1;
continue;
}
if line == "GIT binary patch" || line.starts_with("Binary files ") {
change.is_binary = true;
i += 1;
continue;
}
}
// Standard unified diff parts
if let Some(path_str) = line.strip_prefix("--- ") {
if let Some(ref mut change) = current_change {
let old_path = parse_file_path(path_str);
if old_path
.as_ref()
.is_some_and(|p| p.as_os_str() == "/dev/null")
{
change.is_new_file = true;
change.old_path = None;
} else if change.old_path.is_none() || !change.is_rename {
change.old_path = old_path;
}
}
i += 1;
continue;
}
if let Some(path_str) = line.strip_prefix("+++ ") {
if let Some(ref mut change) = current_change {
let new_path = parse_file_path(path_str);
if new_path
.as_ref()
.is_some_and(|p| p.as_os_str() == "/dev/null")
{
change.is_deleted = true;
change.new_path = None;
} else if change.new_path.is_none() || !change.is_rename {
change.new_path = new_path;
}
}
i += 1;
continue;
}
// Hunk header
if line.starts_with("@@ ") {
if let Some(ref mut change) = current_change
&& let Some(hunk) = current_hunk.take()
{
change.hunks.push(hunk);
}
current_hunk = parse_hunk_header(line);
i += 1;
continue;
}
// Hunk content
if let Some(ref mut hunk) = current_hunk {
if let Some(content) = line.strip_prefix('+') {
hunk.lines.push(HunkLine::Add(content.to_string()));
} else if let Some(content) = line.strip_prefix('-') {
hunk.lines.push(HunkLine::Remove(content.to_string()));
} else if let Some(content) = line.strip_prefix(' ') {
hunk.lines.push(HunkLine::Context(content.to_string()));
} else if line.is_empty() {
hunk.lines.push(HunkLine::Context(String::new()));
}
// Ignore "\ No newline at end of file" and other non-standard lines
}
i += 1;
}
// Save final file change
if let Some(mut change) = current_change.take() {
if let Some(hunk) = current_hunk.take() {
change.hunks.push(hunk);
}
if !change.hunks.is_empty() || change.is_new_file || change.is_deleted || change.is_binary {
file_changes.push(change);
}
}
Ok(file_changes)
}
/// Parse a search/replace format patch.
///
/// Format:
/// ```text
/// path/to/file.txt
/// <<<<<<< SEARCH
/// old content
/// =======
/// new content
/// >>>>>>> REPLACE
/// ```
pub fn parse_search_replace(patch: &str) -> PatchResult<Vec<FileChange>> {
let mut file_changes = Vec::new();
let lines: Vec<&str> = patch.lines().collect();
let mut i = 0;
while i < lines.len() {
// Look for file path followed by SEARCH marker
if i + 1 < lines.len() && lines[i + 1].contains("<<<<<<< SEARCH") {
let file_path = PathBuf::from(lines[i].trim());
i += 2; // Skip file path and SEARCH marker
let mut search_content = String::new();
let mut replace_content = String::new();
let mut in_replace = false;
while i < lines.len() {
let line = lines[i];
if line.contains("=======") {
in_replace = true;
i += 1;
continue;
}
if line.contains(">>>>>>> REPLACE") {
break;
}
if in_replace {
if !replace_content.is_empty() {
replace_content.push('\n');
}
replace_content.push_str(line);
} else {
if !search_content.is_empty() {
search_content.push('\n');
}
search_content.push_str(line);
}
i += 1;
}
// Convert search/replace to a FileChange with hunks
let search_replace = SearchReplace::new(
file_path.clone(),
search_content.clone(),
replace_content.clone(),
);
let change = search_replace_to_file_change(&search_replace)?;
file_changes.push(change);
}
i += 1;
}
Ok(file_changes)
}
/// Convert a SearchReplace to a FileChange.
fn search_replace_to_file_change(sr: &SearchReplace) -> PatchResult<FileChange> {
let mut change = FileChange::new(Some(sr.path.clone()), Some(sr.path.clone()));
// Create a hunk that removes the search content and adds the replace content
let search_lines: Vec<&str> = sr.search.lines().collect();
let replace_lines: Vec<&str> = sr.replace.lines().collect();
let mut hunk = Hunk::new(
1, // Will be updated when applied
search_lines.len(),
1,
replace_lines.len(),
);
for line in &search_lines {
hunk.lines.push(HunkLine::Remove((*line).to_string()));
}
for line in &replace_lines {
hunk.lines.push(HunkLine::Add((*line).to_string()));
}
change.hunks.push(hunk);
Ok(change)
}
/// Parse a file path from a diff header line.
fn parse_file_path(path_str: &str) -> Option<PathBuf> {
let path = path_str.trim();
// Handle various prefixes: a/, b/, or no prefix
let path = path
.strip_prefix("a/")
.or_else(|| path.strip_prefix("b/"))
.unwrap_or(path);
// Remove timestamp if present (e.g., "file.txt\t2024-01-01 00:00:00")
let path = path.split('\t').next().unwrap_or(path).trim();
// Remove trailing whitespace and quotes
let path = path.trim_matches('"');
if path.is_empty() {
None
} else {
Some(PathBuf::from(path))
}
}
/// Parse a git diff header line.
fn parse_git_diff_header(line: &str) -> (Option<PathBuf>, Option<PathBuf>) {
// Format: diff --git a/path b/path
let rest = line.strip_prefix("diff --git ").unwrap_or(line);
// Find the split point between a/path and b/path
// This is tricky because paths can contain spaces
if let Some(b_idx) = rest.find(" b/") {
let a_part = &rest[..b_idx];
let b_part = &rest[b_idx + 1..];
let old_path = a_part.strip_prefix("a/").map(PathBuf::from);
let new_path = b_part.strip_prefix("b/").map(PathBuf::from);
(old_path, new_path)
} else {
// Fallback: split on space
let parts: Vec<&str> = rest.splitn(2, ' ').collect();
let old_path = parts
.first()
.and_then(|p| p.strip_prefix("a/"))
.map(PathBuf::from);
let new_path = parts
.get(1)
.and_then(|p| p.strip_prefix("b/"))
.map(PathBuf::from);
(old_path, new_path)
}
}
/// Parse a hunk header line.
fn parse_hunk_header(line: &str) -> Option<Hunk> {
// Format: @@ -start,count +start,count @@ [section]
let line = line.trim();
if !line.starts_with("@@") {
return None;
}
// Find the closing @@
let end_marker = line[2..].find("@@")?;
let range_part = line[2..2 + end_marker].trim();
let section = if 2 + end_marker + 2 < line.len() {
Some(line[2 + end_marker + 2..].trim().to_string())
} else {
None
};
let parts: Vec<&str> = range_part.split_whitespace().collect();
if parts.len() < 2 {
return None;
}
let (old_start, old_count) = parse_range(parts[0].trim_start_matches('-'))?;
let (new_start, new_count) = parse_range(parts[1].trim_start_matches('+'))?;
let mut hunk = Hunk::new(old_start, old_count, new_start, new_count);
hunk.section_header = section.filter(|s| !s.is_empty());
Some(hunk)
}
/// Parse a range like "1,5" or "1".
fn parse_range(s: &str) -> Option<(usize, usize)> {
let parts: Vec<&str> = s.split(',').collect();
let start: usize = parts.first()?.parse().ok()?;
let count: usize = parts.get(1).and_then(|c| c.parse().ok()).unwrap_or(1);
Some((start, count))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detect_unified_diff() {
let patch = "--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n";
assert_eq!(PatchFormat::detect(patch), PatchFormat::UnifiedDiff);
}
#[test]
fn test_detect_git_diff() {
let patch = "diff --git a/file.txt b/file.txt\nindex abc..def 100644\n";
assert_eq!(PatchFormat::detect(patch), PatchFormat::GitDiff);
}
#[test]
fn test_detect_search_replace() {
let patch = "file.txt\n<<<<<<< SEARCH\nold\n=======\nnew\n>>>>>>> REPLACE\n";
assert_eq!(PatchFormat::detect(patch), PatchFormat::SearchReplace);
}
#[test]
fn test_parse_unified_diff() {
let patch = r#"--- a/test.txt
+++ b/test.txt
@@ -1,3 +1,4 @@
line 1
+new line
line 2
line 3
"#;
let changes = parse_unified_diff(patch).unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0].hunks.len(), 1);
let hunk = &changes[0].hunks[0];
assert_eq!(hunk.old_start, 1);
assert_eq!(hunk.old_count, 3);
assert_eq!(hunk.new_start, 1);
assert_eq!(hunk.new_count, 4);
}
#[test]
fn test_parse_git_diff() {
let patch = r#"diff --git a/test.txt b/test.txt
index abc123..def456 100644
--- a/test.txt
+++ b/test.txt
@@ -1,3 +1,4 @@
line 1
+new line
line 2
line 3
"#;
let changes = parse_git_diff(patch).unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0].hunks.len(), 1);
}
#[test]
fn test_parse_new_file() {
let patch = r#"--- /dev/null
+++ b/new_file.txt
@@ -0,0 +1,2 @@
+line 1
+line 2
"#;
let changes = parse_unified_diff(patch).unwrap();
assert_eq!(changes.len(), 1);
assert!(changes[0].is_new_file);
assert_eq!(changes[0].new_path, Some(PathBuf::from("new_file.txt")));
}
#[test]
fn test_parse_deleted_file() {
let patch = r#"--- a/old_file.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-line 1
-line 2
"#;
let changes = parse_unified_diff(patch).unwrap();
assert_eq!(changes.len(), 1);
assert!(changes[0].is_deleted);
assert_eq!(changes[0].old_path, Some(PathBuf::from("old_file.txt")));
}
#[test]
fn test_parse_hunk_header() {
let hunk = parse_hunk_header("@@ -1,5 +1,6 @@").unwrap();
assert_eq!(hunk.old_start, 1);
assert_eq!(hunk.old_count, 5);
assert_eq!(hunk.new_start, 1);
assert_eq!(hunk.new_count, 6);
}
#[test]
fn test_parse_hunk_header_with_section() {
let hunk = parse_hunk_header("@@ -10,5 +10,6 @@ fn main()").unwrap();
assert_eq!(hunk.old_start, 10);
assert_eq!(hunk.section_header, Some("fn main()".to_string()));
}
#[test]
fn test_parse_file_path() {
assert_eq!(
parse_file_path("a/src/main.rs"),
Some(PathBuf::from("src/main.rs"))
);
assert_eq!(
parse_file_path("b/src/main.rs"),
Some(PathBuf::from("src/main.rs"))
);
assert_eq!(
parse_file_path("src/main.rs"),
Some(PathBuf::from("src/main.rs"))
);
assert_eq!(
parse_file_path("/dev/null"),
Some(PathBuf::from("/dev/null"))
);
}
#[test]
fn test_parse_search_replace() {
let patch = r#"src/file.txt
<<<<<<< SEARCH
old content
more old
=======
new content
more new
even more new
>>>>>>> REPLACE
"#;
let changes = parse_search_replace(patch).unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(
changes[0].effective_path(),
Some(&PathBuf::from("src/file.txt"))
);
let hunk = &changes[0].hunks[0];
assert_eq!(hunk.lines_removed(), 2);
assert_eq!(hunk.lines_added(), 3);
}
#[test]
fn test_multiple_files() {
let patch = r#"--- a/file1.txt
+++ b/file1.txt
@@ -1,1 +1,2 @@
line 1
+new line
--- a/file2.txt
+++ b/file2.txt
@@ -1,1 +1,1 @@
-old
+new
"#;
let changes = parse_unified_diff(patch).unwrap();
assert_eq!(changes.len(), 2);
}
}