Skip to main content

targeted_mutation/
scope.rs

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