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 = match unquote(path) {
194 Some(path) => path,
195 None => path.strip_suffix('\t').unwrap_or(path).to_string(),
196 };
197 path.strip_prefix("b/").map(str::to_string)
198}
199
200pub fn range_of(text: &str, hunk: &Hunk) -> (usize, usize) {
203 let start_of = |line: usize| {
205 if line <= 1 {
206 return 0;
207 }
208 text.match_indices('\n')
209 .nth(line - 2)
210 .map_or(text.len(), |(at, _)| at + 1)
211 };
212 if hunk.count == 0 {
213 let at = start_of(hunk.start + 1);
214 (at, at)
215 } else {
216 (start_of(hunk.start), start_of(hunk.start + hunk.count))
217 }
218}
219
220pub fn undo(text: &str, hunks: &[&Hunk]) -> Option<String> {
223 let mut ordered: Vec<&Hunk> = hunks.to_vec();
224 ordered.sort_by_key(|hunk| (hunk.start, hunk.count));
225 let mut out = String::with_capacity(text.len());
226 let mut done = 0;
227 for hunk in ordered {
228 let (from, to) = range_of(text, hunk);
229 if from < done || to > text.len() || (hunk.count > 0 && from == to) {
230 return None;
231 }
232 out.push_str(&text[done..from]);
233 if from == to && from == text.len() && !text.is_empty() && !text.ends_with('\n') {
235 out.push('\n');
236 }
237 out.push_str(&hunk.old);
238 done = to;
239 }
240 out.push_str(&text[done..]);
241 Some(out)
242}
243
244fn unquote(text: &str) -> Option<String> {
248 let inner = text.strip_prefix('"')?.strip_suffix('"')?;
249 let mut bytes = Vec::with_capacity(inner.len());
250 let mut rest = inner.bytes();
251 while let Some(byte) = rest.next() {
252 if byte == b'"' {
253 return None;
254 }
255 if byte != b'\\' {
256 bytes.push(byte);
257 continue;
258 }
259 bytes.push(match rest.next()? {
260 b'a' => 7,
261 b'b' => 8,
262 b't' => b'\t',
263 b'n' => b'\n',
264 b'v' => 11,
265 b'f' => 12,
266 b'r' => b'\r',
267 b'"' => b'"',
268 b'\\' => b'\\',
269 first @ b'0'..=b'3' => {
270 let mut value = u32::from(first - b'0');
271 for _ in 0..2 {
272 let digit = rest.next().filter(|digit| (b'0'..=b'7').contains(digit))?;
273 value = value * 8 + u32::from(digit - b'0');
274 }
275 u8::try_from(value).ok()?
276 }
277 _ => return None,
278 });
279 }
280 String::from_utf8(bytes).ok()
281}
282
283pub(crate) struct LineIndex(Vec<usize>);
285
286impl LineIndex {
287 pub(crate) fn new(source: &str) -> Self {
288 Self(
289 std::iter::once(0)
290 .chain(
291 source
292 .bytes()
293 .enumerate()
294 .filter(|&(_, byte)| byte == b'\n')
295 .map(|(offset, _)| offset + 1),
296 )
297 .collect(),
298 )
299 }
300
301 pub(crate) fn line_of(&self, offset: usize) -> usize {
302 self.0.partition_point(|&start| start <= offset)
303 }
304
305 pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
306 let offset = if source.is_char_boundary(offset) {
307 offset
308 } else {
309 source.len()
310 };
311 let line = self.line_of(offset);
312 let column = source[self.0[line - 1]..offset].chars().count() + 1;
313 (line, column)
314 }
315
316 pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
317 let start = self
319 .0
320 .get(line.checked_sub(1)?)
321 .copied()
322 .unwrap_or(source.len());
323 let column = column.checked_sub(1)?;
324 if column == 0 {
325 return Some(start);
326 }
327 let rest = &source[start..];
328 let capped = column.min(rest.len());
329 let within = if rest.as_bytes()[..capped].is_ascii() {
330 capped
331 } else {
332 rest.char_indices()
333 .nth(column)
334 .map_or(rest.len(), |(offset, _)| offset)
335 };
336 Some(start + within)
337 }
338}
339
340pub fn line_of(source: &str, offset: usize) -> usize {
342 source.as_bytes()[..offset.min(source.len())]
343 .iter()
344 .filter(|b| **b == b'\n')
345 .count()
346 + 1
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 fn specs(list: &[&str]) -> Vec<String> {
354 list.iter().map(|s| s.to_string()).collect()
355 }
356
357 #[test]
358 fn line_specs() {
359 let scope =
360 Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
361 assert!(scope.touches("src/a.rs", 12, 13));
363 assert!(scope.touches("src/a.rs", 1, 10));
364 assert!(scope.touches("src/a.rs", 20, 25));
365 assert!(scope.touches("src/a.rs", 5, 40));
366 assert!(scope.touches("src/a.rs", 30, 30));
367 assert!(!scope.touches("src/a.rs", 1, 9));
368 assert!(!scope.touches("src/a.rs", 21, 29));
369 assert!(!scope.touches("src/a.rs", 31, 99));
370 assert!(scope.touches("src/b.rs", 7, 7));
371 assert!(!scope.touches("src/c.rs", 7, 7));
372 assert!(
373 scope.touches("src\\b.rs", 1, 1),
374 "separators are normalised"
375 );
376 assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
377 assert!(!scope.is_empty());
378 assert!(Scope::default().is_empty());
379
380 for bad in [
381 "src/a.rs:0",
382 "src/a.rs:5-3",
383 "src/a.rs:4-3",
384 "src/a.rs:1-x",
385 ":3",
386 "src/a.rs:3-",
387 ] {
388 assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
389 }
390 let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
392 assert!(odd.touches("dir:name/a.rs", 1, 1));
393 }
394
395 #[test]
396 fn diff_hunks() {
397 let diff = "\
398diff --git a/src/a.rs b/src/a.rs
399index 111..222 100644
400--- a/src/a.rs
401+++ b/src/a.rs
402@@ -10,2 +10,3 @@ fn changed() {
403-old
404-old
405+new
406+new
407+new
408@@ -30 +31 @@
409-x
410+y
411@@ -40,3 +40,0 @@ fn deleted_lines() {
412-gone
413-gone
414-gone
415@@ -0,0 +1,2 @@
416+top
417+top
418diff --git a/src/gone.rs b/src/gone.rs
419deleted file mode 100644
420--- a/src/gone.rs
421+++ /dev/null
422@@ -1,5 +0,0 @@
423-all
424diff --git a/src/new.rs b/src/new.rs
425new file mode 100644
426--- /dev/null
427+++ b/src/new.rs
428@@ -0,0 +1,4 @@
429+fresh
430";
431 let scope = Scope::from_diff(diff);
432 for (line, expected) in [
434 (9, false),
435 (10, true),
436 (12, true),
437 (13, false),
438 (31, true),
439 (32, false),
440 (39, false),
441 (40, true),
442 (41, true),
443 (42, false),
444 (1, true),
445 (2, true),
446 (3, false),
447 ] {
448 assert_eq!(
449 scope.touches("src/a.rs", line, line),
450 expected,
451 "line {line}"
452 );
453 }
454 assert!(
455 !scope.touches("src/gone.rs", 1, 100),
456 "a deleted file has no lines left"
457 );
458 assert!(scope.touches("src/new.rs", 4, 4));
459 assert!(!scope.touches("src/new.rs", 5, 5));
460 assert_eq!(Scope::from_diff(""), Scope::default());
461 }
462
463 #[test]
464 fn paths_are_read_as_git_writes_them() {
465 let diff = "\
468--- a/src/two words.rs\t
469+++ b/src/two words.rs\t
470@@ -3 +3 @@
471--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
472+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
473@@ -5 +5 @@
474--- \"a/src/a\\\"b\\\\c\\td e.rs\"
475+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
476@@ -7 +7 @@
477--- a/src/価格.rs
478+++ b/src/価格.rs
479@@ -9 +9 @@
480--- \"a/src/gone \\303\\251.rs\"
481+++ /dev/null
482@@ -1 +0,0 @@
483";
484 let scope = Scope::from_diff(diff);
485 assert_eq!(
486 scope.files().collect::<Vec<_>>(),
487 [
488 "src/a\"b/c\td e.rs",
490 "src/two words.rs",
491 "src/価格.rs"
492 ]
493 );
494 assert!(scope.touches("src/two words.rs", 3, 3));
495 assert!(scope.touches("src/価格.rs", 5, 5));
497 assert!(scope.touches("src/価格.rs", 9, 9));
498 assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
499 }
500
501 #[test]
502 fn a_quoted_path_is_what_its_escapes_spell() {
503 for (quoted, path) in [
504 (r#""plain""#, Some("plain")),
505 (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
506 (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
507 (r#""\343\201\202\101""#, Some("あA")),
508 (r#""open"#, None),
511 (r#""a\qb""#, None),
512 (r#""\34""#, None),
513 (r#""\377""#, None),
514 (r#""a"b""#, None),
515 ("bare", None),
516 ] {
517 assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
518 }
519 }
520
521 fn revert_case(row: &[&str]) -> (String, String) {
523 let [shape, position, old_newline, new_newline, hunks, dashes] = row else {
524 panic!("{row:?}")
525 };
526 let line = |name: &str| match *dashes {
527 "plain" => format!("{name}\n"),
528 _ => format!("-- {name}\n"),
529 };
530 let keep = |n: usize| format!("kept {n}\n");
531 let change = |old: &mut String, new: &mut String, tag: &str| match *shape {
532 "replace" => {
533 old.push_str(&line(&format!("old {tag}")));
534 new.push_str(&line(&format!("new {tag}")));
535 }
536 "add" => new.push_str(&line(&format!("new {tag}"))),
537 _ => old.push_str(&line(&format!("old {tag}"))),
538 };
539 let (mut old, mut new) = (String::new(), String::new());
540 let both = |old: &mut String, new: &mut String, text: String| {
541 old.push_str(&text);
542 new.push_str(&text);
543 };
544 let two = *hunks == "two";
545 match *position {
546 "first" => {
547 change(&mut old, &mut new, "a");
548 both(&mut old, &mut new, keep(1) + &keep(2));
549 if two {
550 change(&mut old, &mut new, "b");
551 both(&mut old, &mut new, keep(3));
552 }
553 }
554 "middle" => {
555 both(&mut old, &mut new, keep(1));
556 change(&mut old, &mut new, "a");
557 both(&mut old, &mut new, keep(2));
558 }
559 _ => {
560 if two {
561 both(&mut old, &mut new, keep(0));
562 change(&mut old, &mut new, "b");
563 }
564 both(&mut old, &mut new, keep(1) + &keep(2));
565 change(&mut old, &mut new, "a");
566 }
567 }
568 for (text, newline) in [(&mut old, old_newline), (&mut new, new_newline)] {
569 if *newline == "no" {
570 text.pop();
571 }
572 }
573 (old, new)
574 }
575
576 #[test]
577 fn undoing_the_hunks_of_a_diff_gives_the_old_text() {
578 let dir = std::env::temp_dir().join(format!("tmt-reverts-{}", std::process::id()));
579 std::fs::create_dir_all(&dir).unwrap();
580 let table = include_str!("../tests/data/reverts.pict.tsv");
581 let mut rows = 0;
582 for row in table.lines().skip(1) {
583 let row: Vec<&str> = row.split('\t').collect();
584 let (old, new) = revert_case(&row);
585 std::fs::write(dir.join("old"), &old).unwrap();
586 std::fs::write(dir.join("new"), &new).unwrap();
587 let output = std::process::Command::new("git")
588 .current_dir(&dir)
589 .args(["diff", "--no-index", "-U0", "--no-color", "--no-ext-diff"])
590 .args(["--src-prefix=a/", "--dst-prefix=b/", "old", "new"])
591 .output()
592 .unwrap();
593 let diff = String::from_utf8(output.stdout).unwrap();
594 let found = hunks(&diff);
595 let changes = if row[4] == "two" { 2 } else { 1 };
598 assert!(
599 (changes..=changes + 1).contains(&found.len())
600 || (found.len() == 1 && row[1] == "last"),
601 "{row:?}\n{diff}\n{found:?}"
602 );
603 assert!(found.iter().all(|hunk| hunk.file == "new"), "{found:?}");
604 let all: Vec<&Hunk> = found.iter().collect();
605 assert_eq!(
606 undo(&new, &all).as_deref(),
607 Some(old.as_str()),
608 "{row:?}\n{diff}"
609 );
610 if let [first, second] = &found[..] {
612 let only_first = undo(&new, &[first]).unwrap();
613 let only_second = undo(&new, &[second]).unwrap();
614 assert_ne!(only_first, old, "{row:?}");
615 assert_ne!(only_first, new, "{row:?}");
616 assert_ne!(only_first, only_second, "{row:?}");
617 }
618 rows += 1;
619 }
620 std::fs::remove_dir_all(&dir).unwrap();
621 assert_eq!(rows, 23);
622 }
623
624 #[test]
625 fn a_hunk_that_does_not_fit_the_text_is_not_applied() {
626 let hunk = |start, count| Hunk {
627 file: "f".into(),
628 start,
629 count,
630 old: "old\n".into(),
631 };
632 assert_eq!(undo("a\nb\n", &[&hunk(2, 1)]).as_deref(), Some("a\nold\n"));
633 assert_eq!(
634 undo("a\nb\n", &[&hunk(0, 0)]).as_deref(),
635 Some("old\na\nb\n")
636 );
637 assert_eq!(
638 undo("a\nb\n", &[&hunk(2, 0)]).as_deref(),
639 Some("a\nb\nold\n")
640 );
641 assert_eq!(undo("a\nb", &[&hunk(2, 0)]).as_deref(), Some("a\nb\nold\n"));
642 assert_eq!(undo("a\nb\n", &[&hunk(3, 1)]), None);
644 assert_eq!(undo("a\nb\n", &[&hunk(1, 2), &hunk(2, 1)]), None);
645 assert_eq!(hunks("@@ nonsense @@\n@@ -1 +x @@\n"), []);
646 assert_eq!(hunks("@@ -1 +1 @@\n-a\n+b\n"), []);
648 assert_eq!(hunks("--- a/f\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n"), []);
649 }
650
651 #[test]
652 fn merging_and_whole_files() {
653 let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
654 let mut other = Scope::default();
655 other.add_whole_file("b.rs");
656 other.add("a.rs", (9, 9));
657 scope.merge(other);
658 assert!(
659 scope.touches("a.rs", 9, 9)
660 && scope.touches("a.rs", 2, 2)
661 && !scope.touches("a.rs", 5, 5)
662 );
663 assert!(scope.touches("b.rs", 12345, 12345));
664 }
665
666 #[test]
667 fn indexed_positions_match_the_previous_scans() {
668 for row in include_str!("../tests/data/source-positions.pict.tsv")
669 .lines()
670 .skip(1)
671 {
672 let fields: Vec<_> = row.split('\t').collect();
673 let [text, newline, ending, query] = fields.as_slice() else {
674 panic!("invalid fixture row {row}");
675 };
676 let word = if *text == "unicode" { "é🦀" } else { "xyz" };
677 let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
678 let source = match *ending {
679 "empty" => String::new(),
680 "newline" => format!("{word}{newline}{word}{newline}"),
681 "none" => format!("{word}{newline}{word}"),
682 _ => panic!("invalid ending in {row}"),
683 };
684 let lines = LineIndex::new(&source);
685 for offset in 0..=source.len() + 1 {
686 assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
687 let prefix = source.get(..offset).unwrap_or(&source);
688 let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
689 assert_eq!(
690 lines.position(&source, offset),
691 (line_of(prefix, prefix.len()), column),
692 "{row}"
693 );
694 }
695 let (line, column) = match *query {
696 "first" => (1, 1),
697 "boundary" => (2, 2),
698 "beyond" => (20, 99),
699 "zero" => (1, 0),
700 _ => panic!("invalid query in {row}"),
701 };
702 assert_eq!(
703 lines.offset_of(&source, line, column),
704 crate::instrument::offset_of(&source, line, column),
705 "{row}"
706 );
707 }
708 }
709
710 #[test]
711 fn long_ascii_prefix_before_multibyte_columns() {
712 let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
713 let lines = LineIndex::new(&source);
714 for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
715 assert_eq!(
716 lines.offset_of(&source, 2, column),
717 crate::instrument::offset_of(&source, 2, column)
718 );
719 }
720 }
721
722 #[test]
723 fn lines_of_offsets() {
724 let source = "a\nbc\n\nd";
725 assert_eq!(
726 [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
727 [1, 1, 2, 2, 3, 4, 4, 4]
728 );
729 }
730}