1use std::collections::BTreeMap;
4
5use anyhow::{Result, bail};
6
7#[derive(Debug, Default, Clone, PartialEq, Eq)]
9pub struct Scope {
10 files: BTreeMap<String, Vec<(usize, usize)>>,
11}
12
13impl Scope {
14 pub fn parse_lines(specs: &[String]) -> Result<Scope> {
16 let mut scope = Scope::default();
17 for spec in specs {
18 if spec.starts_with(':') {
19 bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
20 }
21 let (file, range) = match spec.rsplit_once(':') {
22 Some((file, lines))
23 if lines.starts_with(|c: char| c.is_ascii_digit()) =>
25 {
26 let (from, to) = lines.split_once('-').unwrap_or((lines, lines));
27 let parse = |text: &str| text.parse::<usize>().ok().filter(|n| *n > 0);
28 match (parse(from), parse(to)) {
29 (Some(from), Some(to)) if from <= to => (file, (from, to)),
30 _ => bail!("not a line range: `{spec}` (expected FILE:FROM-TO)"),
31 }
32 }
33 _ => (spec.as_str(), (1, usize::MAX)),
34 };
35 if file.is_empty() {
36 bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
37 }
38 scope.add(file, range);
39 }
40 Ok(scope)
41 }
42
43 pub fn from_diff(diff: &str) -> Scope {
47 let mut scope = Scope::default();
48 let mut file: Option<String> = None;
49 for line in diff.lines() {
50 if let Some(path) = line.strip_prefix("+++ ") {
51 file = new_path(path);
53 } else if line.starts_with("@@ ")
54 && let Some(file) = &file
55 && let Some(added) = line.split(' ').find_map(|part| part.strip_prefix('+'))
56 {
57 let (start, count) = added.split_once(',').unwrap_or((added, "1"));
58 let (Ok(start), Ok(count)) = (start.parse::<usize>(), count.parse::<usize>())
59 else {
60 continue;
61 };
62 let range = if count == 0 {
63 (start.max(1), start + 1)
65 } else {
66 (start, start + count - 1)
67 };
68 scope.add(file, range);
69 }
70 }
71 scope
72 }
73
74 pub fn add(&mut self, file: &str, range: (usize, usize)) {
75 self.files
76 .entry(file.replace('\\', "/"))
77 .or_default()
78 .push(range);
79 }
80
81 pub fn add_whole_file(&mut self, file: &str) {
82 self.add(file, (1, usize::MAX));
83 }
84
85 pub fn merge(&mut self, other: Scope) {
86 for (file, ranges) in other.files {
87 self.files.entry(file).or_default().extend(ranges);
88 }
89 }
90
91 pub fn is_empty(&self) -> bool {
92 self.files.is_empty()
93 }
94
95 pub fn files(&self) -> impl Iterator<Item = &str> {
96 self.files.keys().map(String::as_str)
97 }
98
99 pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
101 let ranges = self.files.get(file).or_else(|| {
102 if file.contains('\\') {
103 self.files.get(&file.replace('\\', "/"))
104 } else {
105 None
106 }
107 });
108 ranges.is_some_and(|ranges| {
109 ranges
110 .iter()
111 .any(|(from, to)| first <= *to && *from <= last)
112 })
113 }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct Hunk {
119 pub file: String,
121 pub start: usize,
123 pub count: usize,
125 pub old: String,
128}
129
130pub fn hunks(diff: &str) -> Vec<Hunk> {
133 let mut found = Vec::new();
134 let mut file: Option<String> = None;
135 let mut lines = diff.split_inclusive('\n').peekable();
136 while let Some(line) = lines.next() {
137 let line = line.strip_suffix('\n').unwrap_or(line);
138 if let Some(path) = line.strip_prefix("+++ ") {
139 file = new_path(path);
140 continue;
141 }
142 let Some((old_count, start, count)) = hunk_header(line) else {
143 continue;
144 };
145 let mut old = String::new();
146 let (mut old_left, mut new_left) = (old_count, count);
147 while old_left + new_left > 0 {
148 let Some(body) = lines.next() else { break };
149 match body.as_bytes().first() {
150 Some(b'-') if old_left > 0 => {
151 old.push_str(&body[1..]);
152 old_left -= 1;
153 }
154 Some(b'+') if new_left > 0 => new_left -= 1,
155 _ => break,
156 }
157 if lines.peek().is_some_and(|next| next.starts_with('\\')) {
158 lines.next();
160 if body.starts_with('-') {
161 old.truncate(old.trim_end_matches(['\n', '\r']).len());
162 }
163 }
164 }
165 if let Some(file) = &file {
166 found.push(Hunk {
167 file: file.replace('\\', "/"),
168 start,
169 count,
170 old,
171 });
172 }
173 }
174 found
175}
176
177fn hunk_header(line: &str) -> Option<(usize, usize, usize)> {
179 let mut parts = line.strip_prefix("@@ -")?.split(' ');
180 let pair = |text: &str| -> Option<(usize, usize)> {
181 let (start, count) = text.split_once(',').unwrap_or((text, "1"));
182 Some((start.parse().ok()?, count.parse().ok()?))
183 };
184 let (_, old_count) = pair(parts.next()?)?;
185 let (start, count) = pair(parts.next()?.strip_prefix('+')?)?;
186 Some((old_count, start, count))
187}
188
189fn new_path(path: &str) -> Option<String> {
191 let path = path.strip_suffix('\t').unwrap_or(path);
195 let path = unquote(path).unwrap_or_else(|| path.to_string());
196 path.strip_prefix("b/").map(str::to_string)
197}
198
199pub fn range_of(text: &str, hunk: &Hunk) -> (usize, usize) {
202 let start_of = |line: usize| {
204 if line <= 1 {
205 return 0;
206 }
207 text.match_indices('\n')
208 .nth(line - 2)
209 .map_or(text.len(), |(at, _)| at + 1)
210 };
211 if hunk.count == 0 {
212 let at = start_of(hunk.start + 1);
213 (at, at)
214 } else {
215 (start_of(hunk.start), start_of(hunk.start + hunk.count))
216 }
217}
218
219pub fn undo(text: &str, hunks: &[&Hunk]) -> Option<String> {
222 let mut ordered: Vec<&Hunk> = hunks.to_vec();
223 ordered.sort_by_key(|hunk| (hunk.start, hunk.count));
224 let mut out = String::with_capacity(text.len());
225 let mut done = 0;
226 for hunk in ordered {
227 let (from, to) = range_of(text, hunk);
228 if from < done || to > text.len() || (hunk.count > 0 && from == to) {
229 return None;
230 }
231 out.push_str(&text[done..from]);
232 if from == to && from == text.len() && !text.is_empty() && !text.ends_with('\n') {
234 out.push('\n');
235 }
236 out.push_str(&hunk.old);
237 done = to;
238 }
239 out.push_str(&text[done..]);
240 Some(out)
241}
242
243fn unquote(text: &str) -> Option<String> {
247 let inner = text.strip_prefix('"')?.strip_suffix('"')?;
248 let mut bytes = Vec::with_capacity(inner.len());
249 let mut rest = inner.bytes();
250 while let Some(byte) = rest.next() {
251 if byte == b'"' {
252 return None;
253 }
254 if byte != b'\\' {
255 bytes.push(byte);
256 continue;
257 }
258 bytes.push(match rest.next()? {
259 b'a' => 7,
260 b'b' => 8,
261 b't' => b'\t',
262 b'n' => b'\n',
263 b'v' => 11,
264 b'f' => 12,
265 b'r' => b'\r',
266 b'"' => b'"',
267 b'\\' => b'\\',
268 first @ b'0'..=b'3' => {
269 let mut value = u32::from(first - b'0');
270 for _ in 0..2 {
271 let digit = rest.next().filter(|digit| (b'0'..=b'7').contains(digit))?;
272 value = value * 8 + u32::from(digit - b'0');
273 }
274 u8::try_from(value).ok()?
275 }
276 _ => return None,
277 });
278 }
279 String::from_utf8(bytes).ok()
280}
281
282pub(crate) struct LineIndex(Vec<usize>);
284
285impl LineIndex {
286 pub(crate) fn new(source: &str) -> Self {
287 Self(
288 std::iter::once(0)
289 .chain(
290 source
291 .bytes()
292 .enumerate()
293 .filter(|&(_, byte)| byte == b'\n')
294 .map(|(offset, _)| offset + 1),
295 )
296 .collect(),
297 )
298 }
299
300 pub(crate) fn line_of(&self, offset: usize) -> usize {
301 self.0.partition_point(|&start| start <= offset)
302 }
303
304 pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
305 let offset = if source.is_char_boundary(offset) {
306 offset
307 } else {
308 source.len()
309 };
310 let line = self.line_of(offset);
311 let column = source[self.0[line - 1]..offset].chars().count() + 1;
312 (line, column)
313 }
314
315 pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
316 let start = self
318 .0
319 .get(line.checked_sub(1)?)
320 .copied()
321 .unwrap_or(source.len());
322 let column = column.checked_sub(1)?;
323 if column == 0 {
324 return Some(start);
325 }
326 let rest = &source[start..];
327 let capped = column.min(rest.len());
328 let within = if rest.as_bytes()[..capped].is_ascii() {
329 capped
330 } else {
331 rest.char_indices()
332 .nth(column)
333 .map_or(rest.len(), |(offset, _)| offset)
334 };
335 Some(start + within)
336 }
337}
338
339pub fn line_of(source: &str, offset: usize) -> usize {
341 source.as_bytes()[..offset.min(source.len())]
342 .iter()
343 .filter(|b| **b == b'\n')
344 .count()
345 + 1
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 fn specs(list: &[&str]) -> Vec<String> {
353 list.iter().map(|s| s.to_string()).collect()
354 }
355
356 #[test]
357 fn line_specs() {
358 let scope =
359 Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
360 assert!(scope.touches("src/a.rs", 12, 13));
362 assert!(scope.touches("src/a.rs", 1, 10));
363 assert!(scope.touches("src/a.rs", 20, 25));
364 assert!(scope.touches("src/a.rs", 5, 40));
365 assert!(scope.touches("src/a.rs", 30, 30));
366 assert!(!scope.touches("src/a.rs", 1, 9));
367 assert!(!scope.touches("src/a.rs", 21, 29));
368 assert!(!scope.touches("src/a.rs", 31, 99));
369 assert!(scope.touches("src/b.rs", 7, 7));
370 assert!(!scope.touches("src/c.rs", 7, 7));
371 assert!(
372 scope.touches("src\\b.rs", 1, 1),
373 "separators are normalised"
374 );
375 assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
376 assert!(!scope.is_empty());
377 assert!(Scope::default().is_empty());
378
379 for bad in [
380 "src/a.rs:0",
381 "src/a.rs:5-3",
382 "src/a.rs:4-3",
383 "src/a.rs:1-x",
384 ":3",
385 "src/a.rs:3-",
386 ] {
387 assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
388 }
389 let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
391 assert!(odd.touches("dir:name/a.rs", 1, 1));
392 }
393
394 #[test]
395 fn diff_hunks() {
396 let diff = "\
397diff --git a/src/a.rs b/src/a.rs
398index 111..222 100644
399--- a/src/a.rs
400+++ b/src/a.rs
401@@ -10,2 +10,3 @@ fn changed() {
402-old
403-old
404+new
405+new
406+new
407@@ -30 +31 @@
408-x
409+y
410@@ -40,3 +40,0 @@ fn deleted_lines() {
411-gone
412-gone
413-gone
414@@ -0,0 +1,2 @@
415+top
416+top
417diff --git a/src/gone.rs b/src/gone.rs
418deleted file mode 100644
419--- a/src/gone.rs
420+++ /dev/null
421@@ -1,5 +0,0 @@
422-all
423diff --git a/src/new.rs b/src/new.rs
424new file mode 100644
425--- /dev/null
426+++ b/src/new.rs
427@@ -0,0 +1,4 @@
428+fresh
429";
430 let scope = Scope::from_diff(diff);
431 for (line, expected) in [
433 (9, false),
434 (10, true),
435 (12, true),
436 (13, false),
437 (31, true),
438 (32, false),
439 (39, false),
440 (40, true),
441 (41, true),
442 (42, false),
443 (1, true),
444 (2, true),
445 (3, false),
446 ] {
447 assert_eq!(
448 scope.touches("src/a.rs", line, line),
449 expected,
450 "line {line}"
451 );
452 }
453 assert!(
454 !scope.touches("src/gone.rs", 1, 100),
455 "a deleted file has no lines left"
456 );
457 assert!(scope.touches("src/new.rs", 4, 4));
458 assert!(!scope.touches("src/new.rs", 5, 5));
459 assert_eq!(Scope::from_diff(""), Scope::default());
460 }
461
462 #[test]
463 fn paths_are_read_as_git_writes_them() {
464 let diff = "\
467--- a/src/two words.rs\t
468+++ b/src/two words.rs\t
469@@ -3 +3 @@
470--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
471+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
472@@ -5 +5 @@
473--- \"a/src/a\\\"b\\\\c\\td e.rs\"
474+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
475@@ -7 +7 @@
476--- a/src/価格.rs
477+++ b/src/価格.rs
478@@ -9 +9 @@
479--- \"a/src/gone \\303\\251.rs\"
480+++ /dev/null
481@@ -1 +0,0 @@
482--- \"a/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
483+++ \"b/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
484@@ -2 +2 @@
485";
486 let scope = Scope::from_diff(diff);
487 assert_eq!(
488 scope.files().collect::<Vec<_>>(),
489 [
490 "src/a\"b/c\td e.rs",
492 "src/two words.rs",
493 "src/価格 表.rs",
494 "src/価格.rs"
495 ]
496 );
497 assert!(scope.touches("src/価格 表.rs", 2, 2));
499 assert!(scope.touches("src/two words.rs", 3, 3));
500 assert!(scope.touches("src/価格.rs", 5, 5));
502 assert!(scope.touches("src/価格.rs", 9, 9));
503 assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
504 }
505
506 #[test]
507 fn a_quoted_path_is_what_its_escapes_spell() {
508 for (quoted, path) in [
509 (r#""plain""#, Some("plain")),
510 (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
511 (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
512 (r#""\343\201\202\101""#, Some("あA")),
513 (r#""open"#, None),
516 (r#""a\qb""#, None),
517 (r#""\34""#, None),
518 (r#""\377""#, None),
519 (r#""a"b""#, None),
520 ("bare", None),
521 ] {
522 assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
523 }
524 }
525
526 fn revert_case(row: &[&str]) -> (String, String) {
528 let [shape, position, old_newline, new_newline, hunks, dashes] = row else {
529 panic!("{row:?}")
530 };
531 let line = |name: &str| match *dashes {
532 "plain" => format!("{name}\n"),
533 _ => format!("-- {name}\n"),
534 };
535 let keep = |n: usize| format!("kept {n}\n");
536 let change = |old: &mut String, new: &mut String, tag: &str| match *shape {
537 "replace" => {
538 old.push_str(&line(&format!("old {tag}")));
539 new.push_str(&line(&format!("new {tag}")));
540 }
541 "add" => new.push_str(&line(&format!("new {tag}"))),
542 _ => old.push_str(&line(&format!("old {tag}"))),
543 };
544 let (mut old, mut new) = (String::new(), String::new());
545 let both = |old: &mut String, new: &mut String, text: String| {
546 old.push_str(&text);
547 new.push_str(&text);
548 };
549 let two = *hunks == "two";
550 match *position {
551 "first" => {
552 change(&mut old, &mut new, "a");
553 both(&mut old, &mut new, keep(1) + &keep(2));
554 if two {
555 change(&mut old, &mut new, "b");
556 both(&mut old, &mut new, keep(3));
557 }
558 }
559 "middle" => {
560 both(&mut old, &mut new, keep(1));
561 change(&mut old, &mut new, "a");
562 both(&mut old, &mut new, keep(2));
563 }
564 _ => {
565 if two {
566 both(&mut old, &mut new, keep(0));
567 change(&mut old, &mut new, "b");
568 }
569 both(&mut old, &mut new, keep(1) + &keep(2));
570 change(&mut old, &mut new, "a");
571 }
572 }
573 for (text, newline) in [(&mut old, old_newline), (&mut new, new_newline)] {
574 if *newline == "no" {
575 text.pop();
576 }
577 }
578 (old, new)
579 }
580
581 #[test]
582 fn undoing_the_hunks_of_a_diff_gives_the_old_text() {
583 let dir = std::env::temp_dir().join(format!("tmt-reverts-{}", std::process::id()));
584 std::fs::create_dir_all(&dir).unwrap();
585 let table = include_str!("../tests/data/reverts.pict.tsv");
586 let mut rows = 0;
587 for row in table.lines().skip(1) {
588 let row: Vec<&str> = row.split('\t').collect();
589 let (old, new) = revert_case(&row);
590 std::fs::write(dir.join("old"), &old).unwrap();
591 std::fs::write(dir.join("new"), &new).unwrap();
592 let output = std::process::Command::new("git")
593 .current_dir(&dir)
594 .args(["diff", "--no-index", "-U0", "--no-color", "--no-ext-diff"])
595 .args(["--src-prefix=a/", "--dst-prefix=b/", "old", "new"])
596 .output()
597 .unwrap();
598 let diff = String::from_utf8(output.stdout).unwrap();
599 let found = hunks(&diff);
600 let changes = if row[4] == "two" { 2 } else { 1 };
603 assert!(
604 (changes..=changes + 1).contains(&found.len())
605 || (found.len() == 1 && row[1] == "last"),
606 "{row:?}\n{diff}\n{found:?}"
607 );
608 assert!(found.iter().all(|hunk| hunk.file == "new"), "{found:?}");
609 let all: Vec<&Hunk> = found.iter().collect();
610 assert_eq!(
611 undo(&new, &all).as_deref(),
612 Some(old.as_str()),
613 "{row:?}\n{diff}"
614 );
615 if let [first, second] = &found[..] {
617 let only_first = undo(&new, &[first]).unwrap();
618 let only_second = undo(&new, &[second]).unwrap();
619 assert_ne!(only_first, old, "{row:?}");
620 assert_ne!(only_first, new, "{row:?}");
621 assert_ne!(only_first, only_second, "{row:?}");
622 }
623 rows += 1;
624 }
625 std::fs::remove_dir_all(&dir).unwrap();
626 assert_eq!(rows, 23);
627 }
628
629 #[test]
630 fn a_hunk_that_does_not_fit_the_text_is_not_applied() {
631 let hunk = |start, count| Hunk {
632 file: "f".into(),
633 start,
634 count,
635 old: "old\n".into(),
636 };
637 assert_eq!(undo("a\nb\n", &[&hunk(2, 1)]).as_deref(), Some("a\nold\n"));
638 assert_eq!(
639 undo("a\nb\n", &[&hunk(0, 0)]).as_deref(),
640 Some("old\na\nb\n")
641 );
642 assert_eq!(
643 undo("a\nb\n", &[&hunk(2, 0)]).as_deref(),
644 Some("a\nb\nold\n")
645 );
646 assert_eq!(undo("a\nb", &[&hunk(2, 0)]).as_deref(), Some("a\nb\nold\n"));
647 assert_eq!(undo("a\nb\n", &[&hunk(3, 1)]), None);
649 assert_eq!(undo("a\nb\n", &[&hunk(1, 2), &hunk(2, 1)]), None);
650 assert_eq!(hunks("@@ nonsense @@\n@@ -1 +x @@\n"), []);
651 assert_eq!(hunks("@@ -1 +1 @@\n-a\n+b\n"), []);
653 assert_eq!(hunks("--- a/f\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n"), []);
654 }
655
656 #[test]
657 fn merging_and_whole_files() {
658 let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
659 let mut other = Scope::default();
660 other.add_whole_file("b.rs");
661 other.add("a.rs", (9, 9));
662 scope.merge(other);
663 assert!(
664 scope.touches("a.rs", 9, 9)
665 && scope.touches("a.rs", 2, 2)
666 && !scope.touches("a.rs", 5, 5)
667 );
668 assert!(scope.touches("b.rs", 12345, 12345));
669 }
670
671 #[test]
672 fn indexed_positions_match_the_previous_scans() {
673 for row in include_str!("../tests/data/source-positions.pict.tsv")
674 .lines()
675 .skip(1)
676 {
677 let fields: Vec<_> = row.split('\t').collect();
678 let [text, newline, ending, query] = fields.as_slice() else {
679 panic!("invalid fixture row {row}");
680 };
681 let word = if *text == "unicode" { "é🦀" } else { "xyz" };
682 let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
683 let source = match *ending {
684 "empty" => String::new(),
685 "newline" => format!("{word}{newline}{word}{newline}"),
686 "none" => format!("{word}{newline}{word}"),
687 _ => panic!("invalid ending in {row}"),
688 };
689 let lines = LineIndex::new(&source);
690 for offset in 0..=source.len() + 1 {
691 assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
692 let prefix = source.get(..offset).unwrap_or(&source);
693 let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
694 assert_eq!(
695 lines.position(&source, offset),
696 (line_of(prefix, prefix.len()), column),
697 "{row}"
698 );
699 }
700 let (line, column) = match *query {
701 "first" => (1, 1),
702 "boundary" => (2, 2),
703 "beyond" => (20, 99),
704 "zero" => (1, 0),
705 _ => panic!("invalid query in {row}"),
706 };
707 assert_eq!(
708 lines.offset_of(&source, line, column),
709 crate::instrument::offset_of(&source, line, column),
710 "{row}"
711 );
712 }
713 }
714
715 #[test]
716 fn long_ascii_prefix_before_multibyte_columns() {
717 let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
718 let lines = LineIndex::new(&source);
719 for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
720 assert_eq!(
721 lines.offset_of(&source, 2, column),
722 crate::instrument::offset_of(&source, 2, column)
723 );
724 }
725 }
726
727 #[test]
728 fn lines_of_offsets() {
729 let source = "a\nbc\n\nd";
730 assert_eq!(
731 [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
732 [1, 1, 2, 2, 3, 4, 4, 4]
733 );
734 }
735}