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        Self(
285            std::iter::once(0)
286                .chain(
287                    source
288                        .bytes()
289                        .enumerate()
290                        .filter(|&(_, byte)| byte == b'\n')
291                        .map(|(offset, _)| offset + 1),
292                )
293                .collect(),
294        )
295    }
296
297    pub(crate) fn line_of(&self, offset: usize) -> usize {
298        self.0.partition_point(|&start| start <= offset)
299    }
300
301    pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
302        let offset = if source.is_char_boundary(offset) {
303            offset
304        } else {
305            source.len()
306        };
307        let line = self.line_of(offset);
308        let column = source[self.0[line - 1]..offset].chars().count() + 1;
309        (line, column)
310    }
311
312    pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
313        // As in the unindexed lookup, out-of-range lines and columns clamp to EOF.
314        let start = self
315            .0
316            .get(line.checked_sub(1)?)
317            .copied()
318            .unwrap_or(source.len());
319        let column = column.checked_sub(1)?;
320        if column == 0 {
321            return Some(start);
322        }
323        let rest = &source[start..];
324        let capped = column.min(rest.len());
325        let within = if rest.as_bytes()[..capped].is_ascii() {
326            capped
327        } else {
328            rest.char_indices()
329                .nth(column)
330                .map_or(rest.len(), |(offset, _)| offset)
331        };
332        Some(start + within)
333    }
334}
335
336/// 1-based line of the byte at `offset`.
337pub fn line_of(source: &str, offset: usize) -> usize {
338    source.as_bytes()[..offset.min(source.len())]
339        .iter()
340        .filter(|b| **b == b'\n')
341        .count()
342        + 1
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    fn specs(list: &[&str]) -> Vec<String> {
350        list.iter().map(|s| s.to_string()).collect()
351    }
352
353    #[test]
354    fn line_specs() {
355        let scope =
356            Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
357        // Inside, on both boundaries, overlapping, and outside.
358        assert!(scope.touches("src/a.rs", 12, 13));
359        assert!(scope.touches("src/a.rs", 1, 10));
360        assert!(scope.touches("src/a.rs", 20, 25));
361        assert!(scope.touches("src/a.rs", 5, 40));
362        assert!(scope.touches("src/a.rs", 30, 30));
363        assert!(!scope.touches("src/a.rs", 1, 9));
364        assert!(!scope.touches("src/a.rs", 21, 29));
365        assert!(!scope.touches("src/a.rs", 31, 99));
366        assert!(scope.touches("src/b.rs", 7, 7));
367        assert!(!scope.touches("src/c.rs", 7, 7));
368        assert!(
369            scope.touches("src\\b.rs", 1, 1),
370            "separators are normalised"
371        );
372        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
373        assert!(!scope.is_empty());
374        assert!(Scope::default().is_empty());
375
376        for bad in [
377            "src/a.rs:0",
378            "src/a.rs:5-3",
379            "src/a.rs:4-3",
380            "src/a.rs:1-x",
381            ":3",
382            "src/a.rs:3-",
383        ] {
384            assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
385        }
386        // A Windows drive letter or a name with a colon is a file, not a range.
387        let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
388        assert!(odd.touches("dir:name/a.rs", 1, 1));
389    }
390
391    #[test]
392    fn diff_hunks() {
393        let diff = "\
394diff --git a/src/a.rs b/src/a.rs
395index 111..222 100644
396--- a/src/a.rs
397+++ b/src/a.rs
398@@ -10,2 +10,3 @@ fn changed() {
399-old
400-old
401+new
402+new
403+new
404@@ -30 +31 @@
405-x
406+y
407@@ -40,3 +40,0 @@ fn deleted_lines() {
408-gone
409-gone
410-gone
411@@ -0,0 +1,2 @@
412+top
413+top
414diff --git a/src/gone.rs b/src/gone.rs
415deleted file mode 100644
416--- a/src/gone.rs
417+++ /dev/null
418@@ -1,5 +0,0 @@
419-all 1
420-all 2
421-all 3
422-all 4
423-all 5
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 1
430+fresh 2
431+fresh 3
432+fresh 4
433";
434        let scope = Scope::from_diff(diff);
435        // Changed: 10..=12. Single line: 31. Pure deletion after line 40: 40 and 41.
436        for (line, expected) in [
437            (9, false),
438            (10, true),
439            (12, true),
440            (13, false),
441            (31, true),
442            (32, false),
443            (39, false),
444            (40, true),
445            (41, true),
446            (42, false),
447            (1, true),
448            (2, true),
449            (3, false),
450        ] {
451            assert_eq!(
452                scope.touches("src/a.rs", line, line),
453                expected,
454                "line {line}"
455            );
456        }
457        assert!(
458            !scope.touches("src/gone.rs", 1, 100),
459            "a deleted file has no lines left"
460        );
461        assert!(scope.touches("src/new.rs", 4, 4));
462        assert!(!scope.touches("src/new.rs", 5, 5));
463        assert_eq!(Scope::from_diff(""), Scope::default());
464    }
465
466    #[test]
467    fn paths_are_read_as_git_writes_them() {
468        // A path with a space is followed by a tab; one with other bytes is quoted, with
469        // the prefix inside the quotes and octal for what is not ASCII.
470        let diff = "\
471--- a/src/two words.rs\t
472+++ b/src/two words.rs\t
473@@ -3 +3 @@
474-old
475+new
476--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
477+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
478@@ -5 +5 @@
479-old
480+new
481--- \"a/src/a\\\"b\\\\c\\td e.rs\"
482+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
483@@ -7 +7 @@
484-old
485+new
486--- a/src/価格.rs
487+++ b/src/価格.rs
488@@ -9 +9 @@
489-old
490+new
491--- \"a/src/gone \\303\\251.rs\"
492+++ /dev/null
493@@ -1 +0,0 @@
494-old
495--- \"a/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
496+++ \"b/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
497@@ -2 +2 @@
498-old
499+new
500";
501        let scope = Scope::from_diff(diff);
502        assert_eq!(
503            scope.files().collect::<Vec<_>>(),
504            [
505                // Stored with `/`, as every path is (a Windows separator).
506                "src/a\"b/c\td e.rs",
507                "src/two words.rs",
508                "src/価格 表.rs",
509                "src/価格.rs"
510            ]
511        );
512        // Quoted for its bytes and followed by a tab for its space.
513        assert!(scope.touches("src/価格 表.rs", 2, 2));
514        assert!(scope.touches("src/two words.rs", 3, 3));
515        // Quoted or not (`core.quotePath`), the same file.
516        assert!(scope.touches("src/価格.rs", 5, 5));
517        assert!(scope.touches("src/価格.rs", 9, 9));
518        assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
519    }
520
521    #[test]
522    fn a_quoted_path_is_what_its_escapes_spell() {
523        for (quoted, path) in [
524            (r#""plain""#, Some("plain")),
525            (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
526            (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
527            (r#""\343\201\202\101""#, Some("あA")),
528            // Not closed, an escape git does not write, octal cut short, bytes that
529            // are no text: nothing is guessed.
530            (r#""open"#, None),
531            (r#""a\qb""#, None),
532            (r#""\34""#, None),
533            (r#""\377""#, None),
534            (r#""a"b""#, None),
535            ("bare", None),
536        ] {
537            assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
538        }
539    }
540
541    /// The old and new text of one row of the table.
542    fn revert_case(row: &[&str]) -> (String, String) {
543        let [shape, position, old_newline, new_newline, hunks, dashes] = row else {
544            panic!("{row:?}")
545        };
546        let line = |name: &str| match *dashes {
547            "plain" => format!("{name}\n"),
548            _ => format!("-- {name}\n"),
549        };
550        let keep = |n: usize| format!("kept {n}\n");
551        let change = |old: &mut String, new: &mut String, tag: &str| match *shape {
552            "replace" => {
553                old.push_str(&line(&format!("old {tag}")));
554                new.push_str(&line(&format!("new {tag}")));
555            }
556            "add" => new.push_str(&line(&format!("new {tag}"))),
557            _ => old.push_str(&line(&format!("old {tag}"))),
558        };
559        let (mut old, mut new) = (String::new(), String::new());
560        let both = |old: &mut String, new: &mut String, text: String| {
561            old.push_str(&text);
562            new.push_str(&text);
563        };
564        let two = *hunks == "two";
565        match *position {
566            "first" => {
567                change(&mut old, &mut new, "a");
568                both(&mut old, &mut new, keep(1) + &keep(2));
569                if two {
570                    change(&mut old, &mut new, "b");
571                    both(&mut old, &mut new, keep(3));
572                }
573            }
574            "middle" => {
575                both(&mut old, &mut new, keep(1));
576                change(&mut old, &mut new, "a");
577                both(&mut old, &mut new, keep(2));
578            }
579            _ => {
580                if two {
581                    both(&mut old, &mut new, keep(0));
582                    change(&mut old, &mut new, "b");
583                }
584                both(&mut old, &mut new, keep(1) + &keep(2));
585                change(&mut old, &mut new, "a");
586            }
587        }
588        for (text, newline) in [(&mut old, old_newline), (&mut new, new_newline)] {
589            if *newline == "no" {
590                text.pop();
591            }
592        }
593        (old, new)
594    }
595
596    #[test]
597    fn undoing_the_hunks_of_a_diff_gives_the_old_text() {
598        let dir = std::env::temp_dir().join(format!("tmt-reverts-{}", std::process::id()));
599        std::fs::create_dir_all(&dir).unwrap();
600        let table = include_str!("../tests/data/reverts.pict.tsv");
601        let mut rows = 0;
602        for row in table.lines().skip(1) {
603            let row: Vec<&str> = row.split('\t').collect();
604            let (old, new) = revert_case(&row);
605            std::fs::write(dir.join("old"), &old).unwrap();
606            std::fs::write(dir.join("new"), &new).unwrap();
607            let output = std::process::Command::new("git")
608                .current_dir(&dir)
609                .args(["diff", "--no-index", "-U0", "--no-color", "--no-ext-diff"])
610                .args(["--src-prefix=a/", "--dst-prefix=b/", "old", "new"])
611                .output()
612                .unwrap();
613            let diff = String::from_utf8(output.stdout).unwrap();
614            let found = hunks(&diff);
615            // A line end that comes or goes at the end is a hunk of its own, or part of
616            // the one that changes the last line.
617            let changes = if row[4] == "two" { 2 } else { 1 };
618            assert!(
619                (changes..=changes + 1).contains(&found.len())
620                    || (found.len() == 1 && row[1] == "last"),
621                "{row:?}\n{diff}\n{found:?}"
622            );
623            assert!(found.iter().all(|hunk| hunk.file == "new"), "{found:?}");
624            let all: Vec<&Hunk> = found.iter().collect();
625            assert_eq!(
626                undo(&new, &all).as_deref(),
627                Some(old.as_str()),
628                "{row:?}\n{diff}"
629            );
630            // One hunk alone: the old lines there, the rest as it is now.
631            if let [first, second] = &found[..] {
632                let only_first = undo(&new, &[first]).unwrap();
633                let only_second = undo(&new, &[second]).unwrap();
634                assert_ne!(only_first, old, "{row:?}");
635                assert_ne!(only_first, new, "{row:?}");
636                assert_ne!(only_first, only_second, "{row:?}");
637            }
638            rows += 1;
639        }
640        std::fs::remove_dir_all(&dir).unwrap();
641        assert_eq!(rows, 23);
642    }
643
644    #[test]
645    fn a_hunk_that_does_not_fit_the_text_is_not_applied() {
646        let hunk = |start, count| Hunk {
647            file: "f".into(),
648            start,
649            count,
650            old: "old\n".into(),
651        };
652        assert_eq!(undo("a\nb\n", &[&hunk(2, 1)]).as_deref(), Some("a\nold\n"));
653        assert_eq!(
654            undo("a\nb\n", &[&hunk(0, 0)]).as_deref(),
655            Some("old\na\nb\n")
656        );
657        assert_eq!(
658            undo("a\nb\n", &[&hunk(2, 0)]).as_deref(),
659            Some("a\nb\nold\n")
660        );
661        assert_eq!(undo("a\nb", &[&hunk(2, 0)]).as_deref(), Some("a\nb\nold\n"));
662        // Lines the text does not have, and two hunks of the same lines.
663        assert_eq!(undo("a\nb\n", &[&hunk(3, 1)]), None);
664        assert_eq!(undo("a\nb\n", &[&hunk(1, 2), &hunk(2, 1)]), None);
665        assert_eq!(hunks("@@ nonsense @@\n@@ -1 +x @@\n"), []);
666        // A hunk before any file is of no file; one of a deleted file has no new lines.
667        assert_eq!(hunks("@@ -1 +1 @@\n-a\n+b\n"), []);
668        assert_eq!(hunks("--- a/f\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n"), []);
669    }
670
671    #[test]
672    fn merging_and_whole_files() {
673        let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
674        let mut other = Scope::default();
675        other.add_whole_file("b.rs");
676        other.add("a.rs", (9, 9));
677        scope.merge(other);
678        assert!(
679            scope.touches("a.rs", 9, 9)
680                && scope.touches("a.rs", 2, 2)
681                && !scope.touches("a.rs", 5, 5)
682        );
683        assert!(scope.touches("b.rs", 12345, 12345));
684    }
685
686    #[test]
687    fn indexed_positions_match_the_previous_scans() {
688        for row in include_str!("../tests/data/source-positions.pict.tsv")
689            .lines()
690            .skip(1)
691        {
692            let fields: Vec<_> = row.split('\t').collect();
693            let [text, newline, ending, query] = fields.as_slice() else {
694                panic!("invalid fixture row {row}");
695            };
696            let word = if *text == "unicode" { "é🦀" } else { "xyz" };
697            let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
698            let source = match *ending {
699                "empty" => String::new(),
700                "newline" => format!("{word}{newline}{word}{newline}"),
701                "none" => format!("{word}{newline}{word}"),
702                _ => panic!("invalid ending in {row}"),
703            };
704            let lines = LineIndex::new(&source);
705            for offset in 0..=source.len() + 1 {
706                assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
707                let prefix = source.get(..offset).unwrap_or(&source);
708                let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
709                assert_eq!(
710                    lines.position(&source, offset),
711                    (line_of(prefix, prefix.len()), column),
712                    "{row}"
713                );
714            }
715            let (line, column) = match *query {
716                "first" => (1, 1),
717                "boundary" => (2, 2),
718                "beyond" => (20, 99),
719                "zero" => (1, 0),
720                _ => panic!("invalid query in {row}"),
721            };
722            assert_eq!(
723                lines.offset_of(&source, line, column),
724                crate::instrument::offset_of(&source, line, column),
725                "{row}"
726            );
727        }
728    }
729
730    #[test]
731    fn long_ascii_prefix_before_multibyte_columns() {
732        let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
733        let lines = LineIndex::new(&source);
734        for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
735            assert_eq!(
736                lines.offset_of(&source, 2, column),
737                crate::instrument::offset_of(&source, 2, column)
738            );
739        }
740    }
741
742    #[test]
743    fn lines_of_offsets() {
744        let source = "a\nbc\n\nd";
745        assert_eq!(
746            [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
747            [1, 1, 2, 2, 3, 4, 4, 4]
748        );
749    }
750
751    #[test]
752    fn from_diff_ignores_header_like_lines_inside_hunk_body() {
753        let diff = "\
754diff --git a/src/a.rs b/src/a.rs
755--- a/src/a.rs
756+++ b/src/a.rs
757@@ -2,1 +3,3 @@
758--- a/src/fake.rs
759+let header = \"++\";
760+++ /dev/null
761+++ b/src/hijacked.rs
762@@ -10 +13 @@
763--- a/src/another.rs
764+++ b/src/another.rs
765@@ -20 +23 @@
766-old
767+new
768";
769        let scope = Scope::from_diff(diff);
770        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs"]);
771        assert!(scope.touches("src/a.rs", 3, 5));
772        assert!(scope.touches("src/a.rs", 13, 13));
773        assert!(scope.touches("src/a.rs", 23, 23));
774        assert!(!scope.touches("src/hijacked.rs", 1, 100));
775        assert!(!scope.touches("src/another.rs", 1, 100));
776    }
777
778    #[test]
779    fn hunks_and_from_diff_handle_inter_hunk_context_from_git() {
780        let dir =
781            std::env::temp_dir().join(format!("tmt-inter-hunk-context-{}", std::process::id()));
782        let _ = std::fs::remove_dir_all(&dir);
783        std::fs::create_dir_all(&dir).unwrap();
784        let old = "line 1\nkeep A\nkeep B\nold tail\n";
785        let new = "line 1 changed\nkeep A\nkeep B\n++ b/hijacked.rs\n";
786        std::fs::write(dir.join("a.rs"), old).unwrap();
787        std::fs::write(dir.join("b.rs"), new).unwrap();
788        let output = std::process::Command::new("git")
789            .current_dir(&dir)
790            .args([
791                "-c",
792                "diff.interHunkContext=10",
793                "diff",
794                "--no-index",
795                "-U0",
796                "--no-color",
797                "--no-ext-diff",
798                "--src-prefix=a/",
799                "--dst-prefix=b/",
800                "a.rs",
801                "b.rs",
802            ])
803            .output()
804            .unwrap();
805        let diff = String::from_utf8(output.stdout).unwrap();
806        assert!(
807            diff.contains("\n keep A\n"),
808            "expected context line:\n{diff}"
809        );
810        let scope = Scope::from_diff(&diff);
811        assert_eq!(scope.files().collect::<Vec<_>>(), ["b.rs"]);
812        assert!(scope.touches("b.rs", 1, 4));
813        assert!(!scope.touches("hijacked.rs", 1, 100));
814        let parsed = hunks(&diff);
815        assert_eq!(parsed.len(), 1, "{parsed:?}");
816        assert_eq!(undo(new, &[&parsed[0]]).as_deref(), Some(old));
817
818        // `diff.suppressBlankEmpty=true` omits the leading space on blank context lines.
819        let old_blank = "line 1\n\nold tail\n";
820        let new_blank = "line 1 changed\n\n++ b/hijacked.rs\n";
821        std::fs::write(dir.join("c.rs"), old_blank).unwrap();
822        std::fs::write(dir.join("d.rs"), new_blank).unwrap();
823        let output = std::process::Command::new("git")
824            .current_dir(&dir)
825            .args([
826                "-c",
827                "diff.interHunkContext=10",
828                "-c",
829                "diff.suppressBlankEmpty=true",
830                "diff",
831                "--no-index",
832                "-U0",
833                "--no-color",
834                "--no-ext-diff",
835                "--src-prefix=a/",
836                "--dst-prefix=b/",
837                "c.rs",
838                "d.rs",
839            ])
840            .output()
841            .unwrap();
842        let diff = String::from_utf8(output.stdout).unwrap();
843        assert!(
844            diff.contains("\n\n"),
845            "expected bare blank context line:\n{diff}"
846        );
847        let parsed = hunks(&diff);
848        assert_eq!(parsed.len(), 1, "{parsed:?}");
849        assert_eq!(undo(new_blank, &[&parsed[0]]).as_deref(), Some(old_blank));
850        std::fs::remove_dir_all(&dir).unwrap();
851    }
852}