Debian Codegraph @

src/uu/csplit/src/patterns.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (regex) SKIPTO UPTO ; (vars) ntimes
7
8 use std::ops::Range;
9
10 use crate::csplit_error::{CsplitError, PatternProblem};
11 use regex::Regex;
12 use uucore::show_warning;
13 use uucore::translate;
14
15 /// The definition of a pattern to match on a line.
16 #[derive(Debug)]
17 pub enum Pattern {
18 /// Copy the file's content to a split up to, not including, the given line number. The number
19 /// of times the pattern is executed is detailed in [`ExecutePattern`].
20 UpToLine(usize, ExecutePattern),
21 /// Copy the file's content to a split up to, not including, the line matching the regex. The
22 /// integer is an offset relative to the matched line of what to include (if positive) or
23 /// to exclude (if negative). The number of times the pattern is executed is detailed in
24 /// [`ExecutePattern`].
25 UpToMatch(Regex, i32, ExecutePattern),
26 /// Skip the file's content up to, not including, the line matching the regex. The integer
27 /// is an offset relative to the matched line of what to include (if positive) or to exclude
28 /// (if negative). The number of times the pattern is executed is detailed in [`ExecutePattern`].
29 SkipToMatch(Regex, i32, ExecutePattern),
30 }
31
32 impl std::fmt::Display for Pattern {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 match self {
35 Self::UpToLine(n, _) => write!(f, "{n}"),
36 Self::UpToMatch(regex, 0, _) => write!(f, "/{}/", regex.as_str()),
37 Self::UpToMatch(regex, offset, _) => write!(f, "/{}/{offset:+}", regex.as_str()),
38 Self::SkipToMatch(regex, 0, _) => write!(f, "%{}%", regex.as_str()),
39 Self::SkipToMatch(regex, offset, _) => write!(f, "%{}%{offset:+}", regex.as_str()),
40 }
41 }
42 }
43
44 /// The number of times a pattern can be used.
45 #[derive(Debug)]
46 pub enum ExecutePattern {
47 /// Execute the pattern as many times as possible
48 Always,
49 /// Execute the pattern a fixed number of times
50 Times(usize),
51 }
52
53 impl ExecutePattern {
54 pub fn iter(&self) -> ExecutePatternIter {
55 match self {
56 Self::Times(n) => ExecutePatternIter::new(Some(*n)),
57 Self::Always => ExecutePatternIter::new(None),
58 }
59 }
60 }
61
62 pub struct ExecutePatternIter {
63 max: Option<usize>,
64 cur: usize,
65 }
66
67 impl ExecutePatternIter {
68 fn new(max: Option<usize>) -> Self {
69 Self { max, cur: 0 }
70 }
71 }
72
73 impl Iterator for ExecutePatternIter {
74 type Item = (Option<usize>, usize);
75
76 fn next(&mut self) -> Option<(Option<usize>, usize)> {
77 if let Some(m) = self.max {
78 // iterate until m is reached
79 if self.cur == m {
80 None
81 } else {
82 self.cur += 1;
83 Some((self.max, self.cur))
84 }
85 } else {
86 // no limit, just increment a counter
87 self.cur += 1;
88 Some((None, self.cur))
89 }
90 }
91 }
92
93 /// Parses the definitions of patterns given on the command line into a list of [`Pattern`]s.
94 ///
95 /// # Errors
96 ///
97 /// If a pattern is incorrect, a [`CsplitError::InvalidPattern`] error is returned, which may be
98 /// due to, e.g.,:
99 /// - an invalid regular expression;
100 /// - an invalid number for, e.g., the offset.
101 pub fn get_patterns(args: &[&str]) -> Result<Vec<Pattern>, CsplitError> {
102 let patterns = extract_patterns(args)?;
103 validate_line_numbers(&patterns)?;
104 Ok(patterns)
105 }
106
107 fn extract_patterns(args: &[&str]) -> Result<Vec<Pattern>, CsplitError> {
108 let mut patterns = Vec::with_capacity(args.len());
109 let to_match_reg =
110 Regex::new(r"^(/(?P<UPTO>.+)/|%(?P<SKIPTO>.+)%)(?P<OFFSET>[\+-]?[0-9]+)?$").unwrap();
111 let execute_ntimes_reg = Regex::new(r"^\{(?P<TIMES>[0-9]+)|\*\}$").unwrap();
112 let mut iter = args.iter().copied().peekable();
113
114 while let Some(arg) = iter.next() {
115 // get the number of times a pattern is repeated, which is at least once plus whatever is
116 // in the quantifier.
117 let execute_ntimes = match iter.peek() {
118 None => ExecutePattern::Times(1),
119 Some(&next_item) => {
120 match execute_ntimes_reg.captures(next_item) {
121 None => ExecutePattern::Times(1),
122 Some(r) => {
123 // skip the next item
124 iter.next();
125 if let Some(times) = r.name("TIMES") {
126 ExecutePattern::Times(times.as_str().parse::<usize>().unwrap() + 1)
127 } else {
128 ExecutePattern::Always
129 }
130 }
131 }
132 }
133 };
134
135 // get the pattern definition
136 if let Some(captures) = to_match_reg.captures(arg) {
137 let offset = match captures.name("OFFSET") {
138 None => 0,
139 Some(m) => m.as_str().parse().unwrap(),
140 };
141 if let Some(up_to_match) = captures.name("UPTO") {
142 let pattern = Regex::new(up_to_match.as_str())
143 .map_err(|e| invalid_regex(arg, up_to_match.range(), &e))?;
144 patterns.push(Pattern::UpToMatch(pattern, offset, execute_ntimes));
145 } else if let Some(skip_to_match) = captures.name("SKIPTO") {
146 let pattern = Regex::new(skip_to_match.as_str())
147 .map_err(|e| invalid_regex(arg, skip_to_match.range(), &e))?;
148 patterns.push(Pattern::SkipToMatch(pattern, offset, execute_ntimes));
149 }
150 } else if let Ok(line_number) = arg.parse::<usize>() {
151 patterns.push(Pattern::UpToLine(line_number, execute_ntimes));
152 } else {
153 // Nothing about the operand parsed, so the whole of it is at fault.
154 return Err(CsplitError::InvalidPattern(
155 arg.to_owned(),
156 Some(PatternProblem {
157 span: 0..arg.len(),
158 label: None,
159 }),
160 ));
161 }
162 }
163 Ok(patterns)
164 }
165
166 /// The error for a `/REGEXP/` or `%REGEXP%` operand whose regex did not
167 /// compile, told where inside `arg` the caret belongs.
168 ///
169 /// # Arguments
170 ///
171 /// * `arg` - The pattern operand as typed.
172 /// * `body` - Byte range of the regex inside `arg`, delimiters excluded.
173 /// * `error` - What the regex engine returned.
174 fn invalid_regex(arg: &str, body: Range<usize>, error: &regex::Error) -> CsplitError {
175 let text = error.to_string();
176 let span = caret_span(&text, &arg[body.clone()])
177 .map_or(body.clone(), |s| body.start + s.start..body.start + s.end);
178 CsplitError::InvalidPattern(
179 arg.to_owned(),
180 Some(PatternProblem {
181 span,
182 label: text
183 .lines()
184 .find_map(|line| line.strip_prefix("error: "))
185 .map(str::to_owned),
186 }),
187 )
188 }
189
190 /// The range of `regex` that the engine's own caret line marks.
191 ///
192 /// A regex error is rendered as the pattern echoed under a four-space indent
193 /// with a row of carets beneath it, which is exactly the span wanted here. It
194 /// is read back rather than trusted: the echoed line has to be the regex as
195 /// passed, or `None` is returned and the caller falls back to the whole of it.
196 ///
197 /// # Arguments
198 ///
199 /// * `text` - The engine's message.
200 /// * `regex` - The regex it was given.
201 fn caret_span(text: &str, regex: &str) -> Option<Range<usize>> {
202 const INDENT: &str = " ";
203 let echoed = format!("{INDENT}{regex}");
204 let mut lines = text.lines();
205 while let Some(line) = lines.next() {
206 if line != echoed {
207 continue;
208 }
209 let carets = lines.next()?;
210 let start = carets.find('^')?;
211 let width = carets[start..].bytes().take_while(|&b| b == b'^').count();
212 return start.checked_sub(INDENT.len()).map(|s| s..s + width);
213 }
214 None
215 }
216
217 /// Asserts the line numbers are in increasing order, starting at 1.
218 fn validate_line_numbers(patterns: &[Pattern]) -> Result<(), CsplitError> {
219 patterns
220 .iter()
221 .filter_map(|pattern| match pattern {
222 Pattern::UpToLine(line_number, _) => Some(line_number),
223 _ => None,
224 })
225 .try_fold(0, |prev_ln, &current_ln| match (prev_ln, current_ln) {
226 // a line number cannot be zero
227 (_, 0) => Err(CsplitError::LineNumberIsZero),
228 // two consecutive numbers should not be equal
229 (n, m) if n == m => {
230 show_warning!(
231 "{}",
232 translate!("csplit-warning-line-number-same-as-previous", "line_number" => n)
233 );
234 Ok(n)
235 }
236 // a number cannot be greater than the one that follows
237 (n, m) if n > m => Err(CsplitError::LineNumberSmallerThanPrevious(m, n)),
238 (_, m) => Ok(m),
239 })?;
240 Ok(())
241 }
242
243 #[cfg(test)]
244 mod tests {
245 use super::*;
246
247 #[test]
248 fn bad_pattern() {
249 let input = ["bad"];
250 assert!(get_patterns(&input).is_err());
251 }
252
253 #[test]
254 fn up_to_line_pattern() {
255 let input = ["24", "42", "{*}", "50", "{4}"];
256 let patterns = get_patterns(&input).unwrap();
257 assert_eq!(patterns.len(), 3);
258 match patterns.first() {
259 Some(Pattern::UpToLine(24, ExecutePattern::Times(1))) => (),
260 _ => panic!("expected UpToLine pattern"),
261 }
262 match patterns.get(1) {
263 Some(Pattern::UpToLine(42, ExecutePattern::Always)) => (),
264 _ => panic!("expected UpToLine pattern"),
265 }
266 match patterns.get(2) {
267 Some(Pattern::UpToLine(50, ExecutePattern::Times(5))) => (),
268 _ => panic!("expected UpToLine pattern"),
269 }
270 }
271
272 #[test]
273 #[allow(clippy::cognitive_complexity)]
274 fn up_to_match_pattern() {
275 let input = [
276 "/test1.*end$/",
277 "/test2.*end$/",
278 "{*}",
279 "/test3.*end$/",
280 "{4}",
281 "/test4.*end$/3",
282 "/test5.*end$/+3",
283 "/test6.*end$/-3",
284 ];
285 let patterns = get_patterns(&input).unwrap();
286 assert_eq!(patterns.len(), 6);
287 match patterns.first() {
288 Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Times(1))) => {
289 let parsed_reg = format!("{reg}");
290 assert_eq!(parsed_reg, "test1.*end$");
291 }
292 _ => panic!("expected UpToMatch pattern"),
293 }
294 match patterns.get(1) {
295 Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Always)) => {
296 let parsed_reg = format!("{reg}");
297 assert_eq!(parsed_reg, "test2.*end$");
298 }
299 _ => panic!("expected UpToMatch pattern"),
300 }
301 match patterns.get(2) {
302 Some(Pattern::UpToMatch(reg, 0, ExecutePattern::Times(5))) => {
303 let parsed_reg = format!("{reg}");
304 assert_eq!(parsed_reg, "test3.*end$");
305 }
306 _ => panic!("expected UpToMatch pattern"),
307 }
308 match patterns.get(3) {
309 Some(Pattern::UpToMatch(reg, 3, ExecutePattern::Times(1))) => {
310 let parsed_reg = format!("{reg}");
311 assert_eq!(parsed_reg, "test4.*end$");
312 }
313 _ => panic!("expected UpToMatch pattern"),
314 }
315 match patterns.get(4) {
316 Some(Pattern::UpToMatch(reg, 3, ExecutePattern::Times(1))) => {
317 let parsed_reg = format!("{reg}");
318 assert_eq!(parsed_reg, "test5.*end$");
319 }
320 _ => panic!("expected UpToMatch pattern"),
321 }
322 match patterns.get(5) {
323 Some(Pattern::UpToMatch(reg, -3, ExecutePattern::Times(1))) => {
324 let parsed_reg = format!("{reg}");
325 assert_eq!(parsed_reg, "test6.*end$");
326 }
327 _ => panic!("expected UpToMatch pattern"),
328 }
329 }
330
331 #[test]
332 #[allow(clippy::cognitive_complexity)]
333 fn skip_to_match_pattern() {
334 let input = [
335 "%test1.*end$%",
336 "%test2.*end$%",
337 "{*}",
338 "%test3.*end$%",
339 "{4}",
340 "%test4.*end$%3",
341 "%test5.*end$%+3",
342 "%test6.*end$%-3",
343 ];
344 let patterns = get_patterns(&input).unwrap();
345 assert_eq!(patterns.len(), 6);
346 match patterns.first() {
347 Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Times(1))) => {
348 let parsed_reg = format!("{reg}");
349 assert_eq!(parsed_reg, "test1.*end$");
350 }
351 _ => panic!("expected SkipToMatch pattern"),
352 }
353 match patterns.get(1) {
354 Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Always)) => {
355 let parsed_reg = format!("{reg}");
356 assert_eq!(parsed_reg, "test2.*end$");
357 }
358 _ => panic!("expected SkipToMatch pattern"),
359 }
360 match patterns.get(2) {
361 Some(Pattern::SkipToMatch(reg, 0, ExecutePattern::Times(5))) => {
362 let parsed_reg = format!("{reg}");
363 assert_eq!(parsed_reg, "test3.*end$");
364 }
365 _ => panic!("expected SkipToMatch pattern"),
366 }
367 match patterns.get(3) {
368 Some(Pattern::SkipToMatch(reg, 3, ExecutePattern::Times(1))) => {
369 let parsed_reg = format!("{reg}");
370 assert_eq!(parsed_reg, "test4.*end$");
371 }
372 _ => panic!("expected SkipToMatch pattern"),
373 }
374 match patterns.get(4) {
375 Some(Pattern::SkipToMatch(reg, 3, ExecutePattern::Times(1))) => {
376 let parsed_reg = format!("{reg}");
377 assert_eq!(parsed_reg, "test5.*end$");
378 }
379 _ => panic!("expected SkipToMatch pattern"),
380 }
381 match patterns.get(5) {
382 Some(Pattern::SkipToMatch(reg, -3, ExecutePattern::Times(1))) => {
383 let parsed_reg = format!("{reg}");
384 assert_eq!(parsed_reg, "test6.*end$");
385 }
386 _ => panic!("expected SkipToMatch pattern"),
387 }
388 }
389
390 #[test]
391 fn line_number_zero() {
392 let patterns = vec![Pattern::UpToLine(0, ExecutePattern::Times(1))];
393 match validate_line_numbers(&patterns) {
394 Err(CsplitError::LineNumberIsZero) => (),
395 _ => panic!("expected LineNumberIsZero error"),
396 }
397 }
398
399 #[test]
400 fn line_number_smaller_than_previous() {
401 let input = ["10", "5"];
402 match get_patterns(&input) {
403 Err(CsplitError::LineNumberSmallerThanPrevious(5, 10)) => (),
404 _ => panic!("expected LineNumberSmallerThanPrevious error"),
405 }
406 }
407
408 #[test]
409 fn line_number_smaller_than_previous_separate() {
410 let input = ["10", "/20/", "5"];
411 match get_patterns(&input) {
412 Err(CsplitError::LineNumberSmallerThanPrevious(5, 10)) => (),
413 _ => panic!("expected LineNumberSmallerThanPrevious error"),
414 }
415 }
416
417 #[test]
418 fn line_number_zero_separate() {
419 let input = ["10", "/20/", "0"];
420 match get_patterns(&input) {
421 Err(CsplitError::LineNumberIsZero) => (),
422 _ => panic!("expected LineNumberIsZero error"),
423 }
424 }
425 }