1use std::collections::BTreeMap;
4
5use anyhow::{Result, bail};
6
7#[derive(Debug, Default, Clone, PartialEq, Eq)]
9pub struct Scope {
10 files: BTreeMap<String, Vec<(usize, usize)>>,
11}
12
13impl Scope {
14 pub fn parse_lines(specs: &[String]) -> Result<Scope> {
16 let mut scope = Scope::default();
17 for spec in specs {
18 if spec.starts_with(':') {
19 bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
20 }
21 let (file, range) = match spec.rsplit_once(':') {
22 Some((file, lines))
23 if lines.starts_with(|c: char| c.is_ascii_digit()) =>
25 {
26 let (from, to) = lines.split_once('-').unwrap_or((lines, lines));
27 let parse = |text: &str| text.parse::<usize>().ok().filter(|n| *n > 0);
28 match (parse(from), parse(to)) {
29 (Some(from), Some(to)) if from <= to => (file, (from, to)),
30 _ => bail!("not a line range: `{spec}` (expected FILE:FROM-TO)"),
31 }
32 }
33 _ => (spec.as_str(), (1, usize::MAX)),
34 };
35 if file.is_empty() {
36 bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
37 }
38 scope.add(file, range);
39 }
40 Ok(scope)
41 }
42
43 pub fn from_diff(diff: &str) -> Scope {
47 let mut scope = Scope::default();
48 let mut file: Option<String> = None;
49 for line in diff.lines() {
50 if let Some(path) = line.strip_prefix("+++ ") {
51 file = path.strip_prefix("b/").map(str::to_string);
53 } else if line.starts_with("@@ ")
54 && let Some(file) = &file
55 && let Some(added) = line.split(' ').find_map(|part| part.strip_prefix('+'))
56 {
57 let (start, count) = added.split_once(',').unwrap_or((added, "1"));
58 let (Ok(start), Ok(count)) = (start.parse::<usize>(), count.parse::<usize>())
59 else {
60 continue;
61 };
62 let range = if count == 0 {
63 (start.max(1), start + 1)
65 } else {
66 (start, start + count - 1)
67 };
68 scope.add(file, range);
69 }
70 }
71 scope
72 }
73
74 pub fn add(&mut self, file: &str, range: (usize, usize)) {
75 self.files
76 .entry(file.replace('\\', "/"))
77 .or_default()
78 .push(range);
79 }
80
81 pub fn add_whole_file(&mut self, file: &str) {
82 self.add(file, (1, usize::MAX));
83 }
84
85 pub fn merge(&mut self, other: Scope) {
86 for (file, ranges) in other.files {
87 self.files.entry(file).or_default().extend(ranges);
88 }
89 }
90
91 pub fn is_empty(&self) -> bool {
92 self.files.is_empty()
93 }
94
95 pub fn files(&self) -> impl Iterator<Item = &str> {
96 self.files.keys().map(String::as_str)
97 }
98
99 pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
101 self.files
102 .get(&file.replace('\\', "/"))
103 .is_some_and(|ranges| {
104 ranges
105 .iter()
106 .any(|(from, to)| first <= *to && *from <= last)
107 })
108 }
109}
110
111pub fn line_of(source: &str, offset: usize) -> usize {
113 source.as_bytes()[..offset.min(source.len())]
114 .iter()
115 .filter(|b| **b == b'\n')
116 .count()
117 + 1
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123
124 fn specs(list: &[&str]) -> Vec<String> {
125 list.iter().map(|s| s.to_string()).collect()
126 }
127
128 #[test]
129 fn line_specs() {
130 let scope =
131 Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
132 assert!(scope.touches("src/a.rs", 12, 13));
134 assert!(scope.touches("src/a.rs", 1, 10));
135 assert!(scope.touches("src/a.rs", 20, 25));
136 assert!(scope.touches("src/a.rs", 5, 40));
137 assert!(scope.touches("src/a.rs", 30, 30));
138 assert!(!scope.touches("src/a.rs", 1, 9));
139 assert!(!scope.touches("src/a.rs", 21, 29));
140 assert!(!scope.touches("src/a.rs", 31, 99));
141 assert!(scope.touches("src/b.rs", 7, 7));
142 assert!(!scope.touches("src/c.rs", 7, 7));
143 assert!(
144 scope.touches("src\\b.rs", 1, 1),
145 "separators are normalised"
146 );
147 assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
148 assert!(!scope.is_empty());
149 assert!(Scope::default().is_empty());
150
151 for bad in [
152 "src/a.rs:0",
153 "src/a.rs:5-3",
154 "src/a.rs:4-3",
155 "src/a.rs:1-x",
156 ":3",
157 "src/a.rs:3-",
158 ] {
159 assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
160 }
161 let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
163 assert!(odd.touches("dir:name/a.rs", 1, 1));
164 }
165
166 #[test]
167 fn diff_hunks() {
168 let diff = "\
169diff --git a/src/a.rs b/src/a.rs
170index 111..222 100644
171--- a/src/a.rs
172+++ b/src/a.rs
173@@ -10,2 +10,3 @@ fn changed() {
174-old
175-old
176+new
177+new
178+new
179@@ -30 +31 @@
180-x
181+y
182@@ -40,3 +40,0 @@ fn deleted_lines() {
183-gone
184-gone
185-gone
186@@ -0,0 +1,2 @@
187+top
188+top
189diff --git a/src/gone.rs b/src/gone.rs
190deleted file mode 100644
191--- a/src/gone.rs
192+++ /dev/null
193@@ -1,5 +0,0 @@
194-all
195diff --git a/src/new.rs b/src/new.rs
196new file mode 100644
197--- /dev/null
198+++ b/src/new.rs
199@@ -0,0 +1,4 @@
200+fresh
201";
202 let scope = Scope::from_diff(diff);
203 for (line, expected) in [
205 (9, false),
206 (10, true),
207 (12, true),
208 (13, false),
209 (31, true),
210 (32, false),
211 (39, false),
212 (40, true),
213 (41, true),
214 (42, false),
215 (1, true),
216 (2, true),
217 (3, false),
218 ] {
219 assert_eq!(
220 scope.touches("src/a.rs", line, line),
221 expected,
222 "line {line}"
223 );
224 }
225 assert!(
226 !scope.touches("src/gone.rs", 1, 100),
227 "a deleted file has no lines left"
228 );
229 assert!(scope.touches("src/new.rs", 4, 4));
230 assert!(!scope.touches("src/new.rs", 5, 5));
231 assert_eq!(Scope::from_diff(""), Scope::default());
232 }
233
234 #[test]
235 fn merging_and_whole_files() {
236 let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
237 let mut other = Scope::default();
238 other.add_whole_file("b.rs");
239 other.add("a.rs", (9, 9));
240 scope.merge(other);
241 assert!(
242 scope.touches("a.rs", 9, 9)
243 && scope.touches("a.rs", 2, 2)
244 && !scope.touches("a.rs", 5, 5)
245 );
246 assert!(scope.touches("b.rs", 12345, 12345));
247 }
248
249 #[test]
250 fn lines_of_offsets() {
251 let source = "a\nbc\n\nd";
252 assert_eq!(
253 [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
254 [1, 1, 2, 2, 3, 4, 4, 4]
255 );
256 }
257}