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
13pub fn parse_line_spec(spec: &str) -> Result<(String, (usize, usize))> {
15 if spec.starts_with(':') {
16 bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
17 }
18 let (file, range) = match spec.rsplit_once(':') {
19 Some((file, lines))
20 if lines.starts_with(|c: char| c.is_ascii_digit()) =>
22 {
23 let (from, to) = lines.split_once('-').unwrap_or((lines, lines));
24 let parse = |text: &str| text.parse::<usize>().ok().filter(|n| *n > 0);
25 match (parse(from), parse(to)) {
26 (Some(from), Some(to)) if from <= to => (file, (from, to)),
27 _ => bail!("not a line range: `{spec}` (expected FILE:FROM-TO)"),
28 }
29 }
30 _ => (spec, (1, usize::MAX)),
31 };
32 if file.is_empty() {
33 bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
34 }
35 Ok((file.replace('\\', "/"), range))
36}
37
38pub fn line_count(source: &str) -> usize {
40 if source.is_empty() {
41 0
42 } else {
43 source.lines().count()
44 }
45}
46
47impl Scope {
48 pub fn parse_lines(specs: &[String]) -> Result<Scope> {
50 let mut scope = Scope::default();
51 for spec in specs {
52 let (file, range) = parse_line_spec(spec)?;
53 scope.add(&file, range);
54 }
55 Ok(scope)
56 }
57
58 pub fn from_diff(diff: &str) -> Scope {
62 let mut scope = Scope::default();
63 for hunk in hunks(diff) {
64 let range = if hunk.count == 0 {
65 (hunk.start.max(1), hunk.start + 1)
67 } else {
68 (hunk.start, hunk.start + hunk.count - 1)
69 };
70 scope.add(&hunk.file, range);
71 }
72 scope
73 }
74
75 pub fn add(&mut self, file: &str, range: (usize, usize)) {
76 self.files
77 .entry(file.replace('\\', "/"))
78 .or_default()
79 .push(range);
80 }
81
82 pub fn add_whole_file(&mut self, file: &str) {
83 self.add(file, (1, usize::MAX));
84 }
85
86 pub fn merge(&mut self, other: Scope) {
87 for (file, ranges) in other.files {
88 self.files.entry(file).or_default().extend(ranges);
89 }
90 }
91
92 pub fn is_empty(&self) -> bool {
93 self.files.is_empty()
94 }
95
96 pub fn files(&self) -> impl Iterator<Item = &str> {
97 self.files.keys().map(String::as_str)
98 }
99
100 pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
102 let ranges = self.files.get(file).or_else(|| {
103 if file.contains('\\') {
104 self.files.get(&file.replace('\\', "/"))
105 } else {
106 None
107 }
108 });
109 ranges.is_some_and(|ranges| {
110 ranges
111 .iter()
112 .any(|(from, to)| first <= *to && *from <= last)
113 })
114 }
115
116 pub fn covers_whole_file(&self, file: &str) -> bool {
118 let ranges = self.files.get(file).or_else(|| {
119 if file.contains('\\') {
120 self.files.get(&file.replace('\\', "/"))
121 } else {
122 None
123 }
124 });
125 ranges.is_some_and(|ranges| {
126 ranges
127 .iter()
128 .any(|&(from, to)| from <= 1 && to == usize::MAX)
129 })
130 }
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct Hunk {
136 pub file: String,
138 pub start: usize,
140 pub count: usize,
142 pub old: String,
145}
146
147pub fn hunks(diff: &str) -> Vec<Hunk> {
150 let mut found = Vec::new();
151 let mut file: Option<String> = None;
152 let mut lines = diff.split_inclusive('\n').peekable();
153 while let Some(line) = lines.next() {
154 let line = line.strip_suffix('\n').unwrap_or(line);
155 if let Some(path) = line.strip_prefix("+++ ") {
156 file = new_path(path);
157 continue;
158 }
159 let Some((old_count, start, count)) = hunk_header(line) else {
160 continue;
161 };
162 let mut old = String::new();
163 let (mut old_left, mut new_left) = (old_count, count);
164 while old_left + new_left > 0 {
165 let Some(body) = lines.next() else { break };
166 match body.as_bytes().first() {
167 Some(b'-') if old_left > 0 => {
168 old.push_str(&body[1..]);
169 old_left -= 1;
170 }
171 Some(b'+') if new_left > 0 => new_left -= 1,
172 Some(b' ') if old_left > 0 && new_left > 0 => {
173 old.push_str(&body[1..]);
174 old_left -= 1;
175 new_left -= 1;
176 }
177 Some(b'\n' | b'\r') if old_left > 0 && new_left > 0 => {
179 old.push_str(body);
180 old_left -= 1;
181 new_left -= 1;
182 }
183 _ => break,
184 }
185 if lines.peek().is_some_and(|next| next.starts_with('\\')) {
186 lines.next();
188 if body.starts_with('-') || body.starts_with(' ') {
189 old.truncate(old.trim_end_matches(['\n', '\r']).len());
190 }
191 }
192 }
193 if let Some(file) = &file {
194 found.push(Hunk {
195 file: file.replace('\\', "/"),
196 start,
197 count,
198 old,
199 });
200 }
201 }
202 found
203}
204
205fn hunk_header(line: &str) -> Option<(usize, usize, usize)> {
207 let mut parts = line.strip_prefix("@@ -")?.split(' ');
208 let pair = |text: &str| -> Option<(usize, usize)> {
209 let (start, count) = text.split_once(',').unwrap_or((text, "1"));
210 Some((start.parse().ok()?, count.parse().ok()?))
211 };
212 let (_, old_count) = pair(parts.next()?)?;
213 let (start, count) = pair(parts.next()?.strip_prefix('+')?)?;
214 Some((old_count, start, count))
215}
216
217fn new_path(path: &str) -> Option<String> {
219 let path = path.strip_suffix('\t').unwrap_or(path);
223 let path = unquote(path).unwrap_or_else(|| path.to_string());
224 path.strip_prefix("b/").map(str::to_string)
225}
226
227pub fn range_of(text: &str, hunk: &Hunk) -> (usize, usize) {
230 let start_of = |line: usize| {
232 if line <= 1 {
233 return 0;
234 }
235 text.match_indices('\n')
236 .nth(line - 2)
237 .map_or(text.len(), |(at, _)| at + 1)
238 };
239 if hunk.count == 0 {
240 let at = start_of(hunk.start + 1);
241 (at, at)
242 } else {
243 (start_of(hunk.start), start_of(hunk.start + hunk.count))
244 }
245}
246
247pub fn undo(text: &str, hunks: &[&Hunk]) -> Option<String> {
250 let mut ordered: Vec<&Hunk> = hunks.to_vec();
251 ordered.sort_by_key(|hunk| (hunk.start, hunk.count));
252 let mut out = String::with_capacity(text.len());
253 let mut done = 0;
254 for hunk in ordered {
255 let (from, to) = range_of(text, hunk);
256 if from < done || to > text.len() || (hunk.count > 0 && from == to) {
257 return None;
258 }
259 out.push_str(&text[done..from]);
260 if from == to && from == text.len() && !text.is_empty() && !text.ends_with('\n') {
262 out.push('\n');
263 }
264 out.push_str(&hunk.old);
265 done = to;
266 }
267 out.push_str(&text[done..]);
268 Some(out)
269}
270
271fn unquote(text: &str) -> Option<String> {
275 let inner = text.strip_prefix('"')?.strip_suffix('"')?;
276 let mut bytes = Vec::with_capacity(inner.len());
277 let mut rest = inner.bytes();
278 while let Some(byte) = rest.next() {
279 if byte == b'"' {
280 return None;
281 }
282 if byte != b'\\' {
283 bytes.push(byte);
284 continue;
285 }
286 bytes.push(match rest.next()? {
287 b'a' => 7,
288 b'b' => 8,
289 b't' => b'\t',
290 b'n' => b'\n',
291 b'v' => 11,
292 b'f' => 12,
293 b'r' => b'\r',
294 b'"' => b'"',
295 b'\\' => b'\\',
296 first @ b'0'..=b'3' => {
297 let mut value = u32::from(first - b'0');
298 for _ in 0..2 {
299 let digit = rest.next().filter(|digit| (b'0'..=b'7').contains(digit))?;
300 value = value * 8 + u32::from(digit - b'0');
301 }
302 u8::try_from(value).ok()?
303 }
304 _ => return None,
305 });
306 }
307 String::from_utf8(bytes).ok()
308}
309
310pub(crate) struct LineIndex(Vec<usize>);
312
313impl LineIndex {
314 pub(crate) fn new(source: &str) -> Self {
315 let bytes = source.as_bytes();
316 let mut starts = Vec::with_capacity(bytes.len() / 32 + 2);
317 starts.push(0);
318 push_newline_starts(bytes, &mut starts);
319 Self(starts)
320 }
321
322 pub(crate) fn line_of(&self, offset: usize) -> usize {
323 self.0.partition_point(|&start| start <= offset)
324 }
325
326 pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
327 let offset = if source.is_char_boundary(offset) {
328 offset
329 } else {
330 source.len()
331 };
332 let line = self.line_of(offset);
333 let column = source[self.0[line - 1]..offset].chars().count() + 1;
334 (line, column)
335 }
336
337 pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
338 let start = self
340 .0
341 .get(line.checked_sub(1)?)
342 .copied()
343 .unwrap_or(source.len());
344 let column = column.checked_sub(1)?;
345 if column == 0 {
346 return Some(start);
347 }
348 let rest = &source[start..];
349 let capped = column.min(rest.len());
350 let within = if rest.as_bytes()[..capped].is_ascii() {
351 capped
352 } else {
353 rest.char_indices()
354 .nth(column)
355 .map_or(rest.len(), |(offset, _)| offset)
356 };
357 Some(start + within)
358 }
359}
360
361pub fn line_of(source: &str, offset: usize) -> usize {
363 source.as_bytes()[..offset.min(source.len())]
364 .iter()
365 .filter(|b| **b == b'\n')
366 .count()
367 + 1
368}
369
370fn normalize_glob_path(input: &str) -> String {
374 #[cfg(windows)]
375 let replaced = input.replace('\\', "/");
376 #[cfg(not(windows))]
377 let replaced = input.to_string();
378 let mut s = replaced.as_str();
379 while let Some(rest) = s.strip_prefix("./") {
380 s = rest;
381 }
382 s.to_string()
383}
384
385pub fn matches_glob(pattern: &str, path: &str) -> bool {
389 let pat_str = normalize_glob_path(pattern);
390 let path_str = normalize_glob_path(path);
391 if pat_str.is_empty() {
392 return false;
393 }
394 let pat: Vec<char> = pat_str.chars().collect();
395 let txt: Vec<char> = path_str.chars().collect();
396 let m = pat.len();
397 let n = txt.len();
398 let mut prev = vec![false; n + 1];
399 let mut curr = vec![false; n + 1];
400 let mut carry = vec![false; n + 1];
402 let mut has_carry = false;
403 prev[0] = true;
404
405 let mut i = 0;
406 while i < m {
407 curr.fill(false);
408 if pat[i] == '*' && i + 1 < m && pat[i + 1] == '*' {
409 let mut next_i = i + 2;
411 while next_i < m && pat[next_i] == '*' {
412 next_i += 1;
413 }
414 let mut active = false;
415 for j in 0..=n {
416 if prev[j] {
417 active = true;
418 }
419 if active {
420 curr[j] = true;
421 }
422 }
423 if next_i < m && pat[next_i] == '/' {
424 carry.copy_from_slice(&prev);
426 has_carry = true;
427 }
428 std::mem::swap(&mut prev, &mut curr);
429 i = next_i;
430 } else if pat[i] == '*' {
431 let mut active = false;
432 for j in 0..=n {
433 if prev[j] {
434 active = true;
435 }
436 if active {
437 curr[j] = true;
438 }
439 if j < n && txt[j] == '/' {
440 active = false;
441 }
442 }
443 std::mem::swap(&mut prev, &mut curr);
444 i += 1;
445 } else if pat[i] == '?' {
446 for j in 0..n {
447 if prev[j] && txt[j] != '/' {
448 curr[j + 1] = true;
449 }
450 }
451 std::mem::swap(&mut prev, &mut curr);
452 i += 1;
453 } else {
454 for j in 0..n {
455 if prev[j] && txt[j] == pat[i] {
456 curr[j + 1] = true;
457 }
458 }
459 if has_carry && pat[i] == '/' {
460 for j in 0..=n {
461 curr[j] |= carry[j];
462 }
463 has_carry = false;
464 }
465 std::mem::swap(&mut prev, &mut curr);
466 i += 1;
467 }
468 }
469 prev[n]
470}
471
472pub fn matches_any_glob(patterns: &[String], path: &str) -> bool {
474 patterns.iter().any(|pattern| matches_glob(pattern, path))
475}
476
477fn push_newline_starts(bytes: &[u8], out: &mut Vec<usize>) {
480 let mut i = 0usize;
481 let len = bytes.len();
482 #[cfg(target_arch = "aarch64")]
483 {
484 use std::arch::aarch64::*;
485 unsafe {
487 let nl = vdupq_n_u8(b'\n');
488 let bit_mask: uint8x16_t =
489 vld1q_u8([1u8, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128].as_ptr());
490 while i + 16 <= len {
491 let chunk = vld1q_u8(bytes.as_ptr().add(i));
492 let eq = vceqq_u8(chunk, nl);
493 if vmaxvq_u8(eq) != 0 {
494 let masked = vandq_u8(eq, bit_mask);
495 let lo = vaddv_u8(vget_low_u8(masked)) as u32;
496 let hi = vaddv_u8(vget_high_u8(masked)) as u32;
497 let mut bits = lo | (hi << 8);
498 while bits != 0 {
499 let tz = bits.trailing_zeros() as usize;
500 out.push(i + tz + 1);
501 bits &= bits - 1;
502 }
503 }
504 i += 16;
505 }
506 }
507 }
508 #[cfg(target_arch = "x86_64")]
509 {
510 use std::arch::x86_64::*;
511 unsafe {
513 let nl = _mm_set1_epi8(b'\n' as i8);
514 while i + 16 <= len {
515 let chunk = _mm_loadu_si128(bytes.as_ptr().add(i).cast());
516 let eq = _mm_cmpeq_epi8(chunk, nl);
517 let mut bits = _mm_movemask_epi8(eq) as u32;
518 while bits != 0 {
519 let tz = bits.trailing_zeros() as usize;
520 out.push(i + tz + 1);
521 bits &= bits - 1;
522 }
523 i += 16;
524 }
525 }
526 }
527 while i < len {
528 if bytes[i] == b'\n' {
529 out.push(i + 1);
530 }
531 i += 1;
532 }
533}
534
535#[cfg(test)]
536mod tests {
537 use super::*;
538
539 fn specs(list: &[&str]) -> Vec<String> {
540 list.iter().map(|s| s.to_string()).collect()
541 }
542
543 #[test]
544 fn line_specs() {
545 let scope =
546 Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
547 assert!(scope.touches("src/a.rs", 12, 13));
549 assert!(scope.touches("src/a.rs", 1, 10));
550 assert!(scope.touches("src/a.rs", 20, 25));
551 assert!(scope.touches("src/a.rs", 5, 40));
552 assert!(scope.touches("src/a.rs", 30, 30));
553 assert!(!scope.touches("src/a.rs", 1, 9));
554 assert!(!scope.touches("src/a.rs", 21, 29));
555 assert!(!scope.touches("src/a.rs", 31, 99));
556 assert!(scope.touches("src/b.rs", 7, 7));
557 assert!(!scope.touches("src/c.rs", 7, 7));
558 assert!(
559 scope.touches("src\\b.rs", 1, 1),
560 "separators are normalised"
561 );
562 assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
563 assert!(!scope.is_empty());
564 assert!(Scope::default().is_empty());
565
566 for bad in [
567 "src/a.rs:0",
568 "src/a.rs:5-3",
569 "src/a.rs:4-3",
570 "src/a.rs:1-x",
571 ":3",
572 "src/a.rs:3-",
573 ] {
574 assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
575 }
576 let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
578 assert!(odd.touches("dir:name/a.rs", 1, 1));
579 }
580
581 #[test]
582 fn diff_hunks() {
583 let diff = "\
584diff --git a/src/a.rs b/src/a.rs
585index 111..222 100644
586--- a/src/a.rs
587+++ b/src/a.rs
588@@ -10,2 +10,3 @@ fn changed() {
589-old
590-old
591+new
592+new
593+new
594@@ -30 +31 @@
595-x
596+y
597@@ -40,3 +40,0 @@ fn deleted_lines() {
598-gone
599-gone
600-gone
601@@ -0,0 +1,2 @@
602+top
603+top
604diff --git a/src/gone.rs b/src/gone.rs
605deleted file mode 100644
606--- a/src/gone.rs
607+++ /dev/null
608@@ -1,5 +0,0 @@
609-all 1
610-all 2
611-all 3
612-all 4
613-all 5
614diff --git a/src/new.rs b/src/new.rs
615new file mode 100644
616--- /dev/null
617+++ b/src/new.rs
618@@ -0,0 +1,4 @@
619+fresh 1
620+fresh 2
621+fresh 3
622+fresh 4
623";
624 let scope = Scope::from_diff(diff);
625 for (line, expected) in [
627 (9, false),
628 (10, true),
629 (12, true),
630 (13, false),
631 (31, true),
632 (32, false),
633 (39, false),
634 (40, true),
635 (41, true),
636 (42, false),
637 (1, true),
638 (2, true),
639 (3, false),
640 ] {
641 assert_eq!(
642 scope.touches("src/a.rs", line, line),
643 expected,
644 "line {line}"
645 );
646 }
647 assert!(
648 !scope.touches("src/gone.rs", 1, 100),
649 "a deleted file has no lines left"
650 );
651 assert!(scope.touches("src/new.rs", 4, 4));
652 assert!(!scope.touches("src/new.rs", 5, 5));
653 assert_eq!(Scope::from_diff(""), Scope::default());
654 }
655
656 #[test]
657 fn paths_are_read_as_git_writes_them() {
658 let diff = "\
661--- a/src/two words.rs\t
662+++ b/src/two words.rs\t
663@@ -3 +3 @@
664-old
665+new
666--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
667+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
668@@ -5 +5 @@
669-old
670+new
671--- \"a/src/a\\\"b\\\\c\\td e.rs\"
672+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
673@@ -7 +7 @@
674-old
675+new
676--- a/src/価格.rs
677+++ b/src/価格.rs
678@@ -9 +9 @@
679-old
680+new
681--- \"a/src/gone \\303\\251.rs\"
682+++ /dev/null
683@@ -1 +0,0 @@
684-old
685--- \"a/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
686+++ \"b/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
687@@ -2 +2 @@
688-old
689+new
690";
691 let scope = Scope::from_diff(diff);
692 assert_eq!(
693 scope.files().collect::<Vec<_>>(),
694 [
695 "src/a\"b/c\td e.rs",
697 "src/two words.rs",
698 "src/価格 表.rs",
699 "src/価格.rs"
700 ]
701 );
702 assert!(scope.touches("src/価格 表.rs", 2, 2));
704 assert!(scope.touches("src/two words.rs", 3, 3));
705 assert!(scope.touches("src/価格.rs", 5, 5));
707 assert!(scope.touches("src/価格.rs", 9, 9));
708 assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
709 }
710
711 #[test]
712 fn a_quoted_path_is_what_its_escapes_spell() {
713 for (quoted, path) in [
714 (r#""plain""#, Some("plain")),
715 (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
716 (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
717 (r#""\343\201\202\101""#, Some("あA")),
718 (r#""open"#, None),
721 (r#""a\qb""#, None),
722 (r#""\34""#, None),
723 (r#""\377""#, None),
724 (r#""a"b""#, None),
725 ("bare", None),
726 ] {
727 assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
728 }
729 }
730
731 fn revert_case(row: &[&str]) -> (String, String) {
733 let [shape, position, old_newline, new_newline, hunks, dashes] = row else {
734 panic!("{row:?}")
735 };
736 let line = |name: &str| match *dashes {
737 "plain" => format!("{name}\n"),
738 _ => format!("-- {name}\n"),
739 };
740 let keep = |n: usize| format!("kept {n}\n");
741 let change = |old: &mut String, new: &mut String, tag: &str| match *shape {
742 "replace" => {
743 old.push_str(&line(&format!("old {tag}")));
744 new.push_str(&line(&format!("new {tag}")));
745 }
746 "add" => new.push_str(&line(&format!("new {tag}"))),
747 _ => old.push_str(&line(&format!("old {tag}"))),
748 };
749 let (mut old, mut new) = (String::new(), String::new());
750 let both = |old: &mut String, new: &mut String, text: String| {
751 old.push_str(&text);
752 new.push_str(&text);
753 };
754 let two = *hunks == "two";
755 match *position {
756 "first" => {
757 change(&mut old, &mut new, "a");
758 both(&mut old, &mut new, keep(1) + &keep(2));
759 if two {
760 change(&mut old, &mut new, "b");
761 both(&mut old, &mut new, keep(3));
762 }
763 }
764 "middle" => {
765 both(&mut old, &mut new, keep(1));
766 change(&mut old, &mut new, "a");
767 both(&mut old, &mut new, keep(2));
768 }
769 _ => {
770 if two {
771 both(&mut old, &mut new, keep(0));
772 change(&mut old, &mut new, "b");
773 }
774 both(&mut old, &mut new, keep(1) + &keep(2));
775 change(&mut old, &mut new, "a");
776 }
777 }
778 for (text, newline) in [(&mut old, old_newline), (&mut new, new_newline)] {
779 if *newline == "no" {
780 text.pop();
781 }
782 }
783 (old, new)
784 }
785
786 #[test]
787 fn undoing_the_hunks_of_a_diff_gives_the_old_text() {
788 let dir = std::env::temp_dir().join(format!("tmt-reverts-{}", std::process::id()));
789 std::fs::create_dir_all(&dir).unwrap();
790 let table = include_str!("../tests/data/reverts.pict.tsv");
791 let mut rows = 0;
792 for row in table.lines().skip(1) {
793 let row: Vec<&str> = row.split('\t').collect();
794 let (old, new) = revert_case(&row);
795 std::fs::write(dir.join("old"), &old).unwrap();
796 std::fs::write(dir.join("new"), &new).unwrap();
797 let output = std::process::Command::new("git")
798 .current_dir(&dir)
799 .args(["diff", "--no-index", "-U0", "--no-color", "--no-ext-diff"])
800 .args(["--src-prefix=a/", "--dst-prefix=b/", "old", "new"])
801 .output()
802 .unwrap();
803 let diff = String::from_utf8(output.stdout).unwrap();
804 let found = hunks(&diff);
805 let changes = if row[4] == "two" { 2 } else { 1 };
808 assert!(
809 (changes..=changes + 1).contains(&found.len())
810 || (found.len() == 1 && row[1] == "last"),
811 "{row:?}\n{diff}\n{found:?}"
812 );
813 assert!(found.iter().all(|hunk| hunk.file == "new"), "{found:?}");
814 let all: Vec<&Hunk> = found.iter().collect();
815 assert_eq!(
816 undo(&new, &all).as_deref(),
817 Some(old.as_str()),
818 "{row:?}\n{diff}"
819 );
820 if let [first, second] = &found[..] {
822 let only_first = undo(&new, &[first]).unwrap();
823 let only_second = undo(&new, &[second]).unwrap();
824 assert_ne!(only_first, old, "{row:?}");
825 assert_ne!(only_first, new, "{row:?}");
826 assert_ne!(only_first, only_second, "{row:?}");
827 }
828 rows += 1;
829 }
830 std::fs::remove_dir_all(&dir).unwrap();
831 assert_eq!(rows, 23);
832 }
833
834 #[test]
835 fn a_hunk_that_does_not_fit_the_text_is_not_applied() {
836 let hunk = |start, count| Hunk {
837 file: "f".into(),
838 start,
839 count,
840 old: "old\n".into(),
841 };
842 assert_eq!(undo("a\nb\n", &[&hunk(2, 1)]).as_deref(), Some("a\nold\n"));
843 assert_eq!(
844 undo("a\nb\n", &[&hunk(0, 0)]).as_deref(),
845 Some("old\na\nb\n")
846 );
847 assert_eq!(
848 undo("a\nb\n", &[&hunk(2, 0)]).as_deref(),
849 Some("a\nb\nold\n")
850 );
851 assert_eq!(undo("a\nb", &[&hunk(2, 0)]).as_deref(), Some("a\nb\nold\n"));
852 assert_eq!(undo("a\nb\n", &[&hunk(3, 1)]), None);
854 assert_eq!(undo("a\nb\n", &[&hunk(1, 2), &hunk(2, 1)]), None);
855 assert_eq!(hunks("@@ nonsense @@\n@@ -1 +x @@\n"), []);
856 assert_eq!(hunks("@@ -1 +1 @@\n-a\n+b\n"), []);
858 assert_eq!(hunks("--- a/f\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n"), []);
859 }
860
861 #[test]
862 fn merging_and_whole_files() {
863 let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
864 let mut other = Scope::default();
865 other.add_whole_file("b.rs");
866 other.add("a.rs", (9, 9));
867 scope.merge(other);
868 assert!(
869 scope.touches("a.rs", 9, 9)
870 && scope.touches("a.rs", 2, 2)
871 && !scope.touches("a.rs", 5, 5)
872 );
873 assert!(scope.touches("b.rs", 12345, 12345));
874 }
875
876 #[test]
877 fn indexed_positions_match_the_previous_scans() {
878 for row in include_str!("../tests/data/source-positions.pict.tsv")
879 .lines()
880 .skip(1)
881 {
882 let fields: Vec<_> = row.split('\t').collect();
883 let [text, newline, ending, query] = fields.as_slice() else {
884 panic!("invalid fixture row {row}");
885 };
886 let word = if *text == "unicode" { "é🦀" } else { "xyz" };
887 let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
888 let source = match *ending {
889 "empty" => String::new(),
890 "newline" => format!("{word}{newline}{word}{newline}"),
891 "none" => format!("{word}{newline}{word}"),
892 _ => panic!("invalid ending in {row}"),
893 };
894 let lines = LineIndex::new(&source);
895 for offset in 0..=source.len() + 1 {
896 assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
897 let prefix = source.get(..offset).unwrap_or(&source);
898 let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
899 assert_eq!(
900 lines.position(&source, offset),
901 (line_of(prefix, prefix.len()), column),
902 "{row}"
903 );
904 }
905 let (line, column) = match *query {
906 "first" => (1, 1),
907 "boundary" => (2, 2),
908 "beyond" => (20, 99),
909 "zero" => (1, 0),
910 _ => panic!("invalid query in {row}"),
911 };
912 assert_eq!(
913 lines.offset_of(&source, line, column),
914 crate::instrument::offset_of(&source, line, column),
915 "{row}"
916 );
917 }
918 }
919
920 #[test]
921 fn long_ascii_prefix_before_multibyte_columns() {
922 let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
923 let lines = LineIndex::new(&source);
924 for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
925 assert_eq!(
926 lines.offset_of(&source, 2, column),
927 crate::instrument::offset_of(&source, 2, column)
928 );
929 }
930 }
931
932 #[test]
933 fn lines_of_offsets() {
934 let source = "a\nbc\n\nd";
935 assert_eq!(
936 [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
937 [1, 1, 2, 2, 3, 4, 4, 4]
938 );
939 }
940
941 #[test]
942 fn from_diff_ignores_header_like_lines_inside_hunk_body() {
943 let diff = "\
944diff --git a/src/a.rs b/src/a.rs
945--- a/src/a.rs
946+++ b/src/a.rs
947@@ -2,1 +3,3 @@
948--- a/src/fake.rs
949+let header = \"++\";
950+++ /dev/null
951+++ b/src/hijacked.rs
952@@ -10 +13 @@
953--- a/src/another.rs
954+++ b/src/another.rs
955@@ -20 +23 @@
956-old
957+new
958";
959 let scope = Scope::from_diff(diff);
960 assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs"]);
961 assert!(scope.touches("src/a.rs", 3, 5));
962 assert!(scope.touches("src/a.rs", 13, 13));
963 assert!(scope.touches("src/a.rs", 23, 23));
964 assert!(!scope.touches("src/hijacked.rs", 1, 100));
965 assert!(!scope.touches("src/another.rs", 1, 100));
966 }
967
968 #[test]
969 fn hunks_and_from_diff_handle_inter_hunk_context_from_git() {
970 let dir =
971 std::env::temp_dir().join(format!("tmt-inter-hunk-context-{}", std::process::id()));
972 let _ = std::fs::remove_dir_all(&dir);
973 std::fs::create_dir_all(&dir).unwrap();
974 let old = "line 1\nkeep A\nkeep B\nold tail\n";
975 let new = "line 1 changed\nkeep A\nkeep B\n++ b/hijacked.rs\n";
976 std::fs::write(dir.join("a.rs"), old).unwrap();
977 std::fs::write(dir.join("b.rs"), new).unwrap();
978 let output = std::process::Command::new("git")
979 .current_dir(&dir)
980 .args([
981 "-c",
982 "diff.interHunkContext=10",
983 "diff",
984 "--no-index",
985 "-U0",
986 "--no-color",
987 "--no-ext-diff",
988 "--src-prefix=a/",
989 "--dst-prefix=b/",
990 "a.rs",
991 "b.rs",
992 ])
993 .output()
994 .unwrap();
995 let diff = String::from_utf8(output.stdout).unwrap();
996 assert!(
997 diff.contains("\n keep A\n"),
998 "expected context line:\n{diff}"
999 );
1000 let scope = Scope::from_diff(&diff);
1001 assert_eq!(scope.files().collect::<Vec<_>>(), ["b.rs"]);
1002 assert!(scope.touches("b.rs", 1, 4));
1003 assert!(!scope.touches("hijacked.rs", 1, 100));
1004 let parsed = hunks(&diff);
1005 assert_eq!(parsed.len(), 1, "{parsed:?}");
1006 assert_eq!(undo(new, &[&parsed[0]]).as_deref(), Some(old));
1007
1008 let old_blank = "line 1\n\nold tail\n";
1010 let new_blank = "line 1 changed\n\n++ b/hijacked.rs\n";
1011 std::fs::write(dir.join("c.rs"), old_blank).unwrap();
1012 std::fs::write(dir.join("d.rs"), new_blank).unwrap();
1013 let output = std::process::Command::new("git")
1014 .current_dir(&dir)
1015 .args([
1016 "-c",
1017 "diff.interHunkContext=10",
1018 "-c",
1019 "diff.suppressBlankEmpty=true",
1020 "diff",
1021 "--no-index",
1022 "-U0",
1023 "--no-color",
1024 "--no-ext-diff",
1025 "--src-prefix=a/",
1026 "--dst-prefix=b/",
1027 "c.rs",
1028 "d.rs",
1029 ])
1030 .output()
1031 .unwrap();
1032 let diff = String::from_utf8(output.stdout).unwrap();
1033 assert!(
1034 diff.contains("\n\n"),
1035 "expected bare blank context line:\n{diff}"
1036 );
1037 let parsed = hunks(&diff);
1038 assert_eq!(parsed.len(), 1, "{parsed:?}");
1039 assert_eq!(undo(new_blank, &[&parsed[0]]).as_deref(), Some(old_blank));
1040 std::fs::remove_dir_all(&dir).unwrap();
1041 }
1042
1043 #[test]
1044 fn simd_line_index_matches_scalar_across_chunk_boundaries() {
1045 let scalar = |source: &str| -> Vec<usize> {
1046 std::iter::once(0)
1047 .chain(
1048 source
1049 .bytes()
1050 .enumerate()
1051 .filter(|&(_, b)| b == b'\n')
1052 .map(|(i, _)| i + 1),
1053 )
1054 .collect()
1055 };
1056 for len in 0..=66 {
1057 let mut buf = "a".repeat(len);
1058 assert_eq!(LineIndex::new(&buf).0, scalar(&buf), "no-nl len={len}");
1059 if len > 0 {
1060 for pos in [0, len / 2, len - 1] {
1062 buf.replace_range(pos..pos + 1, "\n");
1063 assert_eq!(LineIndex::new(&buf).0, scalar(&buf), "len={len} pos={pos}");
1064 buf.replace_range(pos..pos + 1, "a");
1065 }
1066 }
1067 }
1068 let all_nl = "\n".repeat(35);
1069 assert_eq!(LineIndex::new(&all_nl).0, scalar(&all_nl));
1070 let mixed = "猫\r\nαβγ\n".repeat(12);
1071 assert_eq!(LineIndex::new(&mixed).0, scalar(&mixed));
1072 }
1073
1074 #[test]
1075 fn glob_matching_covers_wildcards_segments_and_separators() {
1076 assert!(matches_glob("src/gen.rs", "src/gen.rs"));
1078 assert!(matches_glob("./src/gen.rs", "src/gen.rs"));
1079 #[cfg(windows)]
1080 assert!(matches_glob("src\\gen.rs", "src/gen.rs"));
1081 #[cfg(not(windows))]
1082 assert!(!matches_glob("src/a/b.rs", "src/a\\b.rs"));
1083 assert!(!matches_glob("src/gen.rs", "src/other.rs"));
1084 assert!(!matches_glob("", "src/gen.rs"));
1085
1086 assert!(matches_glob("src/*.rs", "src/gen.rs"));
1088 assert!(!matches_glob("src/*.rs", "src/sub/gen.rs"));
1089
1090 assert!(matches_glob("src/v?.rs", "src/v1.rs"));
1092 assert!(!matches_glob("src/v?.rs", "src/v10.rs"));
1093 assert!(!matches_glob("src/v?.rs", "src/v/.rs"));
1094
1095 assert!(matches_glob("src/**/sample.rs", "src/sample.rs"));
1097 assert!(matches_glob("src/**/sample.rs", "src/a/sample.rs"));
1098 assert!(matches_glob("src/**/sample.rs", "src/a/b/sample.rs"));
1099 assert!(!matches_glob("src/**/sample.rs", "src/xsample.rs"));
1100 assert!(matches_glob("**/sample.rs", "sample.rs"));
1101 assert!(matches_glob("**/sample.rs", "src/features/sample.rs"));
1102 assert!(!matches_glob("**/sample.rs", "src/xsample.rs"));
1103 assert!(matches_glob("src/generated/**", "src/generated/a/b.rs"));
1104 assert!(!matches_glob(
1105 "src/generated/**",
1106 "src/generated_other/a.rs"
1107 ));
1108
1109 assert!(matches_any_glob(
1110 &["src/gen.rs".into(), "src/fixtures/**".into()],
1111 "src/fixtures/data.rs"
1112 ));
1113 assert!(!matches_any_glob(
1114 &["src/gen.rs".into(), "src/fixtures/**".into()],
1115 "src/lib.rs"
1116 ));
1117 }
1118}