Debian Codegraph @

rust/hg-core/src/file_patterns.rs

raw
1 // file_patterns.rs
2 //
3 // Copyright 2019 Raphaël Gomès <[email protected]>
4 //
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
7
8 //! Handling of Mercurial-specific patterns.
9
10 use std::fmt;
11 use std::mem;
12 use std::ops::Deref;
13 use std::path::Path;
14 use std::path::PathBuf;
15 use std::vec::Vec;
16
17 use lazy_static::lazy_static;
18 use regex::bytes::NoExpand;
19 use regex::bytes::Regex;
20
21 use crate::pre_regex::PreRegex;
22 use crate::utils::files::canonical_path;
23 use crate::utils::files::get_bytes_from_path;
24 use crate::utils::files::get_path_from_bytes;
25 use crate::utils::hg_path::path_to_hg_path_buf;
26 use crate::utils::hg_path::HgPathBuf;
27 use crate::utils::hg_path::HgPathError;
28 use crate::utils::strings::SliceExt;
29 use crate::warnings::HgWarningSender;
30 use crate::FastHashMap;
31
32 #[derive(Debug, derive_more::From)]
33 pub enum PatternError {
34 #[from]
35 Path(HgPathError),
36 UnsupportedSyntax(String),
37 UnsupportedSyntaxInFile(String, String, usize),
38 TooLong(usize),
39 // TODO reduce the wide "IO error" to a more specific enumeration of cases
40 // we expect so we can stop caring about `std::io::Error` being annoying
41 #[from]
42 IO(std::io::Error),
43 /// Needed a pattern that can be turned into a regex but got one that
44 /// can't. This should only happen through programmer error.
45 NonRegexPattern(FilePattern),
46 }
47
48 // TODO remove this once we simplify the `IO` variant (see its declaration)
49 impl PartialEq for PatternError {
50 fn eq(&self, other: &Self) -> bool {
51 match (self, other) {
52 (Self::Path(l0), Self::Path(r0)) => l0 == r0,
53 (Self::UnsupportedSyntax(l0), Self::UnsupportedSyntax(r0)) => {
54 l0 == r0
55 }
56 (
57 Self::UnsupportedSyntaxInFile(l0, l1, l2),
58 Self::UnsupportedSyntaxInFile(r0, r1, r2),
59 ) => l0 == r0 && l1 == r1 && l2 == r2,
60 (Self::TooLong(l0), Self::TooLong(r0)) => l0 == r0,
61 (Self::IO(_), Self::IO(_)) => false,
62 (Self::NonRegexPattern(l0), Self::NonRegexPattern(r0)) => l0 == r0,
63 _ => false,
64 }
65 }
66 }
67
68 impl fmt::Display for PatternError {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 match self {
71 PatternError::UnsupportedSyntax(syntax) => {
72 write!(f, "Unsupported syntax {}", syntax)
73 }
74 PatternError::UnsupportedSyntaxInFile(syntax, file_path, line) => {
75 write!(
76 f,
77 "{}:{}: unsupported syntax {}",
78 file_path, line, syntax
79 )
80 }
81 PatternError::TooLong(size) => {
82 write!(f, "matcher pattern is too long ({} bytes)", size)
83 }
84 PatternError::IO(error) => error.fmt(f),
85 PatternError::Path(error) => error.fmt(f),
86 PatternError::NonRegexPattern(pattern) => {
87 write!(f, "'{:?}' cannot be turned into a regex", pattern)
88 }
89 }
90 }
91 }
92
93 lazy_static! {
94 static ref RE_ESCAPE: Vec<Vec<u8>> = {
95 let mut v: Vec<Vec<u8>> = (0..=255).map(|byte| vec![byte]).collect();
96 let to_escape = b"()[]{}?*+-|^$\\.&~#\t\n\r\x0b\x0c";
97 for byte in to_escape {
98 v[*byte as usize].insert(0, b'\\');
99 }
100 v
101 };
102 }
103
104 #[derive(Debug, Clone, PartialEq, Eq)]
105 pub enum PatternSyntax {
106 /// A regular expression
107 Regexp,
108 /// Glob that matches at the front of the path
109 RootGlob,
110 /// Glob that matches at any suffix of the path (still anchored at
111 /// slashes)
112 Glob,
113 /// a path relative to repository root, which is matched recursively
114 Path,
115 /// a single exact path relative to repository root
116 FilePath,
117 /// A path relative to cwd
118 RelPath,
119 /// an unrooted glob (*.rs matches Rust files in all dirs)
120 RelGlob,
121 /// A regexp that needn't match the start of a name
122 RelRegexp,
123 /// A path relative to repository root, which is matched non-recursively
124 /// (will not match subdirectories)
125 RootFilesIn,
126 /// A file of patterns to read and include
127 Include,
128 /// A file of patterns to match against files under the same directory
129 SubInclude,
130 /// SubInclude with the result of parsing the included file
131 ///
132 /// Note: there is no ExpandedInclude because that expansion can be done
133 /// in place by replacing the Include pattern by the included patterns.
134 /// SubInclude requires more handling.
135 ///
136 /// Note: `Box` is used to minimize size impact on other enum variants
137 ExpandedSubInclude(Box<SubInclude>),
138 }
139
140 /// A wildcard parsed from a glob
141 #[derive(Debug, Clone, Copy)]
142 enum GlobWildcard {
143 /// `**/` matches any sequence of characters ending at a path
144 /// component boundary
145 AnyComponents,
146 /// `*`: matches any sequence of characters within one path component
147 AnyNonSlash,
148 /// `**`: matches any sequence of characters including slashes
149 Anything,
150 }
151 impl GlobWildcard {
152 /// Optimization to simplify the regex prefixes for unrooted globs.
153 /// It's unclear if this is worth it for performance, but it also has
154 /// some cosmetic effect by making these regexes easier to understand.
155 fn make_unrooted(wildcard: Option<GlobWildcard>) -> GlobWildcard {
156 match wildcard {
157 None => Self::AnyComponents,
158 Some(Self::AnyComponents) => Self::AnyComponents,
159 Some(Self::AnyNonSlash) => Self::Anything,
160 Some(Self::Anything) => Self::Anything,
161 }
162 }
163
164 fn to_re(self) -> PreRegex {
165 match self {
166 Self::AnyComponents => PreRegex::preceding_dir_components(),
167 Self::AnyNonSlash => PreRegex::NonslashStar,
168 Self::Anything => PreRegex::DotStar,
169 }
170 }
171 }
172
173 fn glob_parse_after_star(input: &mut &[u8]) -> GlobWildcard {
174 if let Some((b'*', rest)) = input.split_first() {
175 if let Some((b'/', rest)) = rest.split_first() {
176 *input = rest;
177 GlobWildcard::AnyComponents
178 } else {
179 *input = rest;
180 GlobWildcard::Anything
181 }
182 } else {
183 GlobWildcard::AnyNonSlash
184 }
185 }
186
187 /// The result of glob to re conversion.
188 /// The start of the regular expression `start` is tracked
189 /// separately for a pattern simplification opportunity
190 /// (see `GlobWildcard::make_unrooted`)
191 pub struct GlobToRe {
192 start: Option<GlobWildcard>,
193 rest: Vec<PreRegex>,
194 }
195
196 impl GlobToRe {
197 /// Convert to a regex. `rooted` specifies if the glob should match
198 /// at the root of the repo (true), or anywhere in the repo (false)
199 fn into_re(self, rooted: bool) -> PreRegex {
200 let wildcard = if !rooted {
201 Some(GlobWildcard::make_unrooted(self.start))
202 } else {
203 self.start
204 };
205
206 let mut res: Vec<_> = wildcard.into_iter().map(|x| x.to_re()).collect();
207 res.extend(self.rest);
208 PreRegex::Sequence(res)
209 }
210 }
211
212 /// Transforms a glob pattern into a regex.
213 pub fn glob_to_re(pat: &[u8]) -> PatternResult<GlobToRe> {
214 let mut start = None;
215 let mut res: Vec<PreRegex> = vec![];
216 let mut input = pat;
217
218 let mut group_stack = vec![];
219
220 let add_byte = |out: &mut Vec<PreRegex>, b: u8| match out.last_mut() {
221 Some(PreRegex::Bytes(v)) => {
222 v.push(b);
223 }
224 _ => out.push(PreRegex::Bytes(vec![b])),
225 };
226
227 while let Some((c, rest)) = input.split_first() {
228 input = rest;
229
230 match c {
231 b'*' => {
232 let wildcard = glob_parse_after_star(&mut input);
233 if res.is_empty() && start.is_none() {
234 start = Some(wildcard)
235 } else {
236 res.push(wildcard.to_re())
237 }
238 }
239 b'?' => res.push(PreRegex::Dot),
240 b'[' => {
241 match input.iter().skip(1).position(|b| *b == b']') {
242 None => res.push(PreRegex::Byte(b'[')),
243 Some(end) => {
244 // Account for the one we skipped
245 let end = end + 1;
246
247 // TODO: parse charsets ourselves?
248 let mut class = vec![];
249 class.extend(b"[");
250
251 for (i, b) in input[..end].iter().enumerate() {
252 if *b == b'!' && i == 0 {
253 class.extend(b"^")
254 } else if *b == b'^' && i == 0 {
255 class.extend(b"\\^")
256 } else if *b == b'\\' {
257 class.extend(b"\\\\")
258 } else {
259 class.push(*b)
260 }
261 }
262 class.extend(b"]");
263
264 res.push(PreRegex::parse(&class)?);
265
266 input = &input[end + 1..];
267 }
268 }
269 }
270 b'{' => {
271 group_stack.push((mem::take(&mut res), vec![]));
272 }
273 b'}' if !group_stack.is_empty() => {
274 let hir = PreRegex::Sequence(mem::take(&mut res));
275 let (old_res, mut alt) = group_stack.pop().unwrap();
276 alt.push(hir);
277 res = old_res;
278 res.push(PreRegex::Alternation(alt));
279 }
280 b',' if !group_stack.is_empty() => {
281 let frame = group_stack.last_mut().unwrap();
282 frame.1.push(PreRegex::Sequence(mem::take(&mut res)));
283 }
284 b'\\' => {
285 let c = {
286 if let Some((c, rest)) = input.split_first() {
287 input = rest;
288 c
289 } else {
290 c
291 }
292 };
293 add_byte(&mut res, *c)
294 }
295 _ => add_byte(&mut res, *c),
296 }
297 }
298 if !group_stack.is_empty() {
299 return Err(PatternError::UnsupportedSyntax(
300 "error: invalid glob, has unclosed alternation ('{')".to_string(),
301 ));
302 }
303 Ok(GlobToRe { start, rest: res })
304 }
305
306 pub fn parse_pattern_syntax_kind(
307 kind: &[u8],
308 ) -> Result<PatternSyntax, PatternError> {
309 match kind {
310 b"re" => Ok(PatternSyntax::Regexp),
311 b"path" => Ok(PatternSyntax::Path),
312 b"filepath" => Ok(PatternSyntax::FilePath),
313 b"relpath" => Ok(PatternSyntax::RelPath),
314 b"rootfilesin" => Ok(PatternSyntax::RootFilesIn),
315 b"relglob" => Ok(PatternSyntax::RelGlob),
316 b"relre" => Ok(PatternSyntax::RelRegexp),
317 b"glob" => Ok(PatternSyntax::Glob),
318 b"rootglob" => Ok(PatternSyntax::RootGlob),
319 b"include" => Ok(PatternSyntax::Include),
320 b"subinclude" => Ok(PatternSyntax::SubInclude),
321 _ => Err(PatternError::UnsupportedSyntax(
322 String::from_utf8_lossy(kind).to_string(),
323 )),
324 }
325 }
326
327 lazy_static! {
328 static ref FLAG_RE: Regex = Regex::new(r"^\(\?[aiLmsux]+\)").unwrap();
329 }
330
331 /// Extra path components to match at the end of the pattern
332 #[derive(Clone, Copy)]
333 pub enum GlobSuffix {
334 /// `Empty` means the pattern only matches files, not directories,
335 /// so the path needs to match exactly.
336 Empty,
337 /// `MoreComponents` means the pattern matches directories as well,
338 /// so any path that has the pattern as a prefix, should match.
339 MoreComponents,
340 }
341
342 impl GlobSuffix {
343 pub fn to_re(self) -> PreRegex {
344 match self {
345 Self::Empty => PreRegex::Eof,
346 Self::MoreComponents => PreRegex::SlashOrEof,
347 }
348 }
349 }
350
351 /// Builds the regex that corresponds to the given pattern.
352 /// If within a `syntax: regexp` context, returns the pattern,
353 /// otherwise, returns the corresponding regex.
354 fn _build_single_regex(
355 entry: &FilePattern,
356 glob_suffix: GlobSuffix,
357 ) -> PatternResult<PreRegex> {
358 let FilePattern { syntax, raw: pattern, .. } = entry;
359 if pattern.is_empty() {
360 return Ok(PreRegex::Empty);
361 }
362 match syntax {
363 PatternSyntax::Regexp => PreRegex::parse(pattern),
364 PatternSyntax::RelRegexp => {
365 // The `regex` crate accepts `**` while `re2` and Python's `re`
366 // do not. Checking for `*` correctly triggers the same error all
367 // engines.
368 if pattern[0] == b'^'
369 || pattern[0] == b'*'
370 || pattern.starts_with(b".*")
371 {
372 return PreRegex::parse(pattern);
373 }
374 let re = match FLAG_RE.find(pattern) {
375 Some(mat) => {
376 let s = mat.start();
377 let e = mat.end();
378 [
379 &b"(?"[..],
380 &pattern[s + 2..e - 1],
381 &b":"[..],
382 if pattern[e] == b'^'
383 || pattern[e] == b'*'
384 || pattern[e..].starts_with(b".*")
385 {
386 &b""[..]
387 } else {
388 &b".*"[..]
389 },
390 &pattern[e..],
391 &b")"[..],
392 ]
393 .concat()
394 }
395 None => [&b".*"[..], pattern].concat(),
396 };
397 PreRegex::parse(&re)
398 }
399 PatternSyntax::Path | PatternSyntax::RelPath => {
400 if pattern == b"." {
401 return Ok(PreRegex::Empty);
402 }
403 Ok(PreRegex::Sequence(vec![
404 PreRegex::literal(pattern),
405 GlobSuffix::MoreComponents.to_re(),
406 ]))
407 }
408 PatternSyntax::RootFilesIn => {
409 let re = if pattern == b"." {
410 PreRegex::Empty
411 } else {
412 // Pattern is a directory name.
413 let mut pattern = pattern.clone();
414 pattern.push(b'/');
415 PreRegex::Bytes(pattern)
416 };
417
418 // Anything after the pattern must be a non-directory.
419 Ok(PreRegex::Sequence(vec![re, PreRegex::parse(b"[^/]+$")?]))
420 }
421 PatternSyntax::RelGlob => {
422 let glob_re = glob_to_re(pattern)?;
423 Ok(PreRegex::Sequence(vec![
424 glob_re.into_re(false),
425 glob_suffix.to_re(),
426 ]))
427 }
428 PatternSyntax::Glob | PatternSyntax::RootGlob => {
429 let glob_re = glob_to_re(pattern)?;
430 Ok(PreRegex::Sequence(vec![
431 glob_re.into_re(true),
432 glob_suffix.to_re(),
433 ]))
434 }
435 PatternSyntax::Include
436 | PatternSyntax::SubInclude
437 | PatternSyntax::ExpandedSubInclude(_)
438 | PatternSyntax::FilePath => unreachable!(),
439 }
440 }
441
442 const GLOB_SPECIAL_CHARACTERS: [u8; 7] =
443 [b'*', b'?', b'[', b']', b'{', b'}', b'\\'];
444
445 /// TODO support other platforms
446 #[cfg(unix)]
447 pub fn normalize_path_bytes(bytes: &[u8]) -> Vec<u8> {
448 if bytes.is_empty() {
449 return b".".to_vec();
450 }
451 let sep = b'/';
452
453 let mut initial_slashes = bytes.iter().take_while(|b| **b == sep).count();
454 if initial_slashes > 2 {
455 // POSIX allows one or two initial slashes, but treats three or more
456 // as single slash.
457 initial_slashes = 1;
458 }
459 let components = bytes
460 .split(|b| *b == sep)
461 .filter(|c| !(c.is_empty() || c == b"."))
462 .fold(vec![], |mut acc, component| {
463 if component != b".."
464 || (initial_slashes == 0 && acc.is_empty())
465 || (!acc.is_empty() && acc[acc.len() - 1] == b"..")
466 {
467 acc.push(component)
468 } else if !acc.is_empty() {
469 acc.pop();
470 }
471 acc
472 });
473 let mut new_bytes = components.join(&sep);
474
475 if initial_slashes > 0 {
476 let mut buf: Vec<_> = (0..initial_slashes).map(|_| sep).collect();
477 buf.extend(new_bytes);
478 new_bytes = buf;
479 }
480 if new_bytes.is_empty() {
481 b".".to_vec()
482 } else {
483 new_bytes
484 }
485 }
486
487 /// Controls whether we want the emitted regex to cover all cases
488 /// or just the cases that are not covered by optimized code paths.
489 #[derive(Debug, Clone, Copy)]
490 pub enum RegexCompleteness {
491 /// `Complete` emits a regex that handles all files, including the ones
492 /// that are typically handled by a different code path.
493 /// This is used in `hg debugignorerhg -a` to avoid missing some rules.
494 Complete,
495 /// `ExcludeExactFiles` excludes the patterns that correspond to exact
496 /// file matches. This is the normal behavior, and gives a potentially
497 /// much smaller regex.
498 ExcludeExactFiles,
499 }
500
501 impl RegexCompleteness {
502 fn may_exclude_exact_files(self) -> bool {
503 match self {
504 Self::Complete => false,
505 Self::ExcludeExactFiles => true,
506 }
507 }
508 }
509
510 /// Wrapper function to `_build_single_regex` that short-circuits 'exact' globs
511 /// that don't need to be transformed into a regex.
512 pub fn build_single_regex(
513 entry: &FilePattern,
514 glob_suffix: GlobSuffix,
515 regex_config: RegexCompleteness,
516 ) -> Result<Option<PreRegex>, PatternError> {
517 let FilePattern { raw: pattern, syntax, .. } = entry;
518 let pattern = match syntax {
519 PatternSyntax::RootGlob
520 | PatternSyntax::Path
521 | PatternSyntax::RelGlob
522 | PatternSyntax::RelPath
523 | PatternSyntax::RootFilesIn => normalize_path_bytes(pattern),
524 PatternSyntax::Include | PatternSyntax::SubInclude => {
525 return Err(PatternError::NonRegexPattern(entry.clone()))
526 }
527 _ => pattern.to_owned(),
528 };
529 let is_simple_rootglob = *syntax == PatternSyntax::RootGlob
530 && !pattern.iter().any(|b| GLOB_SPECIAL_CHARACTERS.contains(b));
531 if regex_config.may_exclude_exact_files()
532 && (is_simple_rootglob || syntax == &PatternSyntax::FilePath)
533 {
534 Ok(None)
535 } else {
536 let mut entry = entry.clone();
537 entry.raw = pattern;
538 Ok(Some(_build_single_regex(&entry, glob_suffix)?))
539 }
540 }
541
542 lazy_static! {
543 static ref SYNTAXES: FastHashMap<&'static [u8], PatternSyntax> = {
544 let mut m = FastHashMap::default();
545
546 m.insert(b"re:".as_ref(), PatternSyntax::Regexp);
547 m.insert(b"regexp:".as_ref(), PatternSyntax::Regexp);
548 m.insert(b"path:".as_ref(), PatternSyntax::Path);
549 m.insert(b"filepath:".as_ref(), PatternSyntax::FilePath);
550 m.insert(b"relpath:".as_ref(), PatternSyntax::RelPath);
551 m.insert(b"rootfilesin:".as_ref(), PatternSyntax::RootFilesIn);
552 m.insert(b"relglob:".as_ref(), PatternSyntax::RelGlob);
553 m.insert(b"relre:".as_ref(), PatternSyntax::RelRegexp);
554 m.insert(b"glob:".as_ref(), PatternSyntax::Glob);
555 m.insert(b"rootglob:".as_ref(), PatternSyntax::RootGlob);
556 m.insert(b"include:".as_ref(), PatternSyntax::Include);
557 m.insert(b"subinclude:".as_ref(), PatternSyntax::SubInclude);
558
559 m
560 };
561 }
562
563 #[derive(Debug)]
564 pub enum PatternFileWarning {
565 /// (file path, syntax bytes)
566 InvalidSyntax(PathBuf, Vec<u8>),
567 /// File path
568 NoSuchFile(PathBuf),
569 }
570
571 pub fn parse_one_pattern(
572 pattern: &[u8],
573 source: &Path,
574 default: PatternSyntax,
575 normalize: bool,
576 ) -> FilePattern {
577 let mut pattern_bytes: &[u8] = pattern;
578 let mut syntax = default;
579
580 for (s, val) in SYNTAXES.iter() {
581 if let Some(rest) = pattern_bytes.drop_prefix(s) {
582 syntax = val.clone();
583 pattern_bytes = rest;
584 break;
585 }
586 }
587
588 let pattern = match syntax {
589 PatternSyntax::RootGlob
590 | PatternSyntax::Path
591 | PatternSyntax::Glob
592 | PatternSyntax::RelGlob
593 | PatternSyntax::RelPath
594 | PatternSyntax::RootFilesIn
595 if normalize =>
596 {
597 normalize_path_bytes(pattern_bytes)
598 }
599 _ => pattern_bytes.to_vec(),
600 };
601
602 FilePattern { syntax, raw: pattern, source: source.to_owned() }
603 }
604
605 pub fn parse_pattern_file_contents(
606 lines: &[u8],
607 file_path: &Path,
608 default_syntax_override: Option<PatternSyntax>,
609 warn: bool,
610 relativize: bool,
611 warnings: &HgWarningSender,
612 ) -> Result<Vec<FilePattern>, PatternError> {
613 let comment_regex = Regex::new(r"((?:^|[^\\])(?:\\\\)*)#.*").unwrap();
614
615 #[allow(clippy::trivial_regex)]
616 let comment_escape_regex = Regex::new(r"\\#").unwrap();
617 let mut inputs: Vec<FilePattern> = vec![];
618
619 let mut current_syntax =
620 default_syntax_override.unwrap_or(PatternSyntax::RelRegexp);
621
622 for mut line in lines.split(|c| *c == b'\n') {
623 let line_buf;
624 if line.contains(&b'#') {
625 if let Some(cap) = comment_regex.captures(line) {
626 line = &line[..cap.get(1).unwrap().end()]
627 }
628 line_buf = comment_escape_regex.replace_all(line, NoExpand(b"#"));
629 line = &line_buf;
630 }
631
632 let line = line.trim_end();
633
634 if line.is_empty() {
635 continue;
636 }
637
638 if let Some(syntax) = line.drop_prefix(b"syntax:") {
639 let syntax = syntax.trim();
640
641 if let Some(parsed) =
642 SYNTAXES.get([syntax, &b":"[..]].concat().as_slice())
643 {
644 current_syntax = parsed.clone();
645 } else if warn {
646 warnings.send(PatternFileWarning::InvalidSyntax(
647 file_path.to_owned(),
648 syntax.to_owned(),
649 ));
650 }
651 } else {
652 let pattern = parse_one_pattern(
653 line,
654 file_path,
655 current_syntax.clone(),
656 false,
657 );
658 inputs.push(if relativize {
659 pattern.to_relative()
660 } else {
661 pattern
662 })
663 }
664 }
665 Ok(inputs)
666 }
667
668 pub fn parse_pattern_args(
669 patterns: Vec<Vec<u8>>,
670 cwd: &Path,
671 root: &Path,
672 ) -> Result<Vec<FilePattern>, HgPathError> {
673 let mut file_patterns: Vec<FilePattern> = Vec::new();
674 for pattern in patterns {
675 let pattern = parse_one_pattern(
676 &pattern,
677 Path::new("<args>"),
678 PatternSyntax::RelPath,
679 true,
680 );
681 match pattern.syntax {
682 PatternSyntax::RelGlob | PatternSyntax::RelPath => {
683 let name = get_path_from_bytes(&pattern.raw);
684 let canon = canonical_path(root, cwd, name)?;
685 file_patterns.push(FilePattern {
686 syntax: pattern.syntax,
687 raw: get_bytes_from_path(canon),
688 source: pattern.source,
689 })
690 }
691 _ => file_patterns.push(pattern.to_owned()),
692 };
693 }
694 Ok(file_patterns)
695 }
696
697 pub fn read_pattern_file(
698 file_path: &Path,
699 warn: bool,
700 inspect_pattern_bytes: &mut impl FnMut(&Path, &[u8]),
701 warnings: &HgWarningSender,
702 ) -> Result<Vec<FilePattern>, PatternError> {
703 match std::fs::read(file_path) {
704 Ok(contents) => {
705 inspect_pattern_bytes(file_path, &contents);
706 parse_pattern_file_contents(
707 &contents, file_path, None, warn, true, warnings,
708 )
709 }
710 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
711 warnings.send(PatternFileWarning::NoSuchFile(file_path.to_owned()));
712 Ok(vec![])
713 }
714 Err(e) => Err(e.into()),
715 }
716 }
717
718 /// Represents a notation for identifying one or more files at a time.
719 #[derive(Debug, Eq, PartialEq, Clone)]
720 pub struct FilePattern {
721 /// The syntax used for by pattern
722 pub syntax: PatternSyntax,
723 /// The raw bytes without the prefix (e.g. `path:foo` becomes `foo`)
724 pub raw: Vec<u8>,
725 /// The file whence this pattern originates.
726 /// TODO use a more complex `PatternOrigin` enum or something similar to
727 /// remove the need for a bogus path in some cases.
728 pub source: PathBuf,
729 }
730
731 impl FilePattern {
732 pub fn new(syntax: PatternSyntax, pattern: &[u8], source: &Path) -> Self {
733 Self { syntax, raw: pattern.to_owned(), source: source.to_owned() }
734 }
735
736 pub fn to_relative(self) -> Self {
737 let Self { syntax, raw: pattern, source } = self;
738 Self {
739 syntax: match syntax {
740 PatternSyntax::Regexp => PatternSyntax::RelRegexp,
741 PatternSyntax::Glob => PatternSyntax::RelGlob,
742 x => x,
743 },
744 raw: pattern,
745 source,
746 }
747 }
748 }
749
750 pub type PatternResult<T> = Result<T, PatternError>;
751
752 /// Wrapper for `read_pattern_file` that also recursively expands `include:`
753 /// and `subinclude:` patterns.
754 ///
755 /// The former are expanded in place, while `PatternSyntax::ExpandedSubInclude`
756 /// is used for the latter to form a tree of patterns.
757 pub fn get_patterns_from_file(
758 pattern_file: &Path,
759 root_dir: &Path,
760 inspect_pattern_bytes: &mut impl FnMut(&Path, &[u8]),
761 warnings: &HgWarningSender,
762 ) -> PatternResult<Vec<FilePattern>> {
763 let patterns =
764 read_pattern_file(pattern_file, true, inspect_pattern_bytes, warnings)?;
765 let patterns = patterns
766 .into_iter()
767 .flat_map(|entry| -> PatternResult<_> {
768 Ok(match &entry.syntax {
769 PatternSyntax::Include => {
770 let inner_include =
771 root_dir.join(get_path_from_bytes(&entry.raw));
772
773 get_patterns_from_file(
774 &inner_include,
775 root_dir,
776 inspect_pattern_bytes,
777 warnings,
778 )?
779 }
780 PatternSyntax::SubInclude => {
781 let mut sub_include =
782 SubInclude::new(root_dir, &entry.raw, &entry.source)?;
783 let inner_patterns = get_patterns_from_file(
784 &sub_include.path,
785 &sub_include.root,
786 inspect_pattern_bytes,
787 warnings,
788 )?;
789 sub_include.included_patterns = inner_patterns;
790 vec![FilePattern {
791 syntax: PatternSyntax::ExpandedSubInclude(Box::new(
792 sub_include,
793 )),
794 ..entry
795 }]
796 }
797 _ => vec![entry],
798 })
799 })
800 .flatten()
801 .collect();
802
803 Ok(patterns)
804 }
805
806 /// Holds all the information needed to handle a `subinclude:` pattern.
807 #[derive(Debug, PartialEq, Eq, Clone)]
808 pub struct SubInclude {
809 /// Will be used for repository (hg) paths that start with this prefix.
810 /// It is relative to the current working directory, so comparing against
811 /// repository paths is painless.
812 pub prefix: HgPathBuf,
813 /// The file itself, containing the patterns
814 pub path: PathBuf,
815 /// Folder in the filesystem where this it applies
816 pub root: PathBuf,
817
818 pub included_patterns: Vec<FilePattern>,
819 }
820
821 impl SubInclude {
822 pub fn new(
823 root_dir: &Path,
824 pattern: &[u8],
825 source: &Path,
826 ) -> Result<SubInclude, HgPathError> {
827 let normalized_source =
828 normalize_path_bytes(&get_bytes_from_path(source));
829
830 let source_root = get_path_from_bytes(&normalized_source);
831 let source_root = source_root.parent().unwrap_or(source_root);
832
833 let path = source_root.join(get_path_from_bytes(pattern));
834 let new_root = path.parent().unwrap_or_else(|| path.deref());
835
836 let prefix = canonical_path(root_dir, root_dir, new_root)?;
837
838 Ok(Self {
839 prefix: path_to_hg_path_buf(prefix).map(|mut p| {
840 if !p.is_empty() {
841 p.push_byte(b'/');
842 }
843 p
844 })?,
845 path: path.to_owned(),
846 root: new_root.to_owned(),
847 included_patterns: Vec::new(),
848 })
849 }
850 }
851
852 /// Separate and pre-process subincludes from other patterns
853 pub fn filter_subincludes(
854 patterns: Vec<FilePattern>,
855 ) -> Result<(Vec<SubInclude>, Vec<FilePattern>), HgPathError> {
856 let mut subincludes = vec![];
857 let mut others = vec![];
858
859 for pattern in patterns {
860 if let PatternSyntax::ExpandedSubInclude(sub_include) = pattern.syntax {
861 subincludes.push(*sub_include);
862 } else {
863 others.push(pattern)
864 }
865 }
866 Ok((subincludes, others))
867 }
868
869 #[cfg(test)]
870 mod tests {
871 use pretty_assertions::assert_eq;
872
873 use super::*;
874 use crate::warnings::HgWarningContext;
875
876 fn escape_pattern(pattern: &[u8]) -> Vec<u8> {
877 pattern.iter().flat_map(|c| RE_ESCAPE[*c as usize].clone()).collect()
878 }
879
880 #[test]
881 fn escape_pattern_test() {
882 let untouched =
883 br#"!"%',/0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz"#;
884 assert_eq!(escape_pattern(untouched), untouched.to_vec());
885 // All escape codes
886 assert_eq!(
887 escape_pattern(br"()[]{}?*+-|^$\\.&~#\t\n\r\v\f"),
888 br"\(\)\[\]\{\}\?\*\+\-\|\^\$\\\\\.\&\~\#\\t\\n\\r\\v\\f".to_vec()
889 );
890 }
891
892 fn glob_to_re(pat: &[u8]) -> Vec<u8> {
893 super::glob_to_re(pat).unwrap().into_re(true).to_bytes()
894 }
895
896 #[test]
897 fn glob_test() {
898 assert_eq!(glob_to_re(br"?"), br".");
899 assert_eq!(glob_to_re(br"*"), br"[^/]*");
900 assert_eq!(glob_to_re(br"**"), br".*");
901 assert_eq!(glob_to_re(br"**/a"), br"(?:.*/)?a");
902 assert_eq!(glob_to_re(br"a/**/b"), br"a/(?:.*/)?b");
903 assert_eq!(glob_to_re(br"[a*?!^][^b][!c]"), br"[a*?!^][\^b][^c]");
904 assert_eq!(glob_to_re(br"{a,b}"), br"(?:a|b)");
905 assert_eq!(glob_to_re(br".\*\?"), br"\.\*\?");
906 }
907
908 #[test]
909 fn test_parse_pattern_file_contents() {
910 let lines = b"syntax: glob\n*.elc";
911
912 let warning_context = HgWarningContext::new();
913 let warning_sender = warning_context.sender();
914 assert_eq!(
915 parse_pattern_file_contents(
916 lines,
917 Path::new("file_path"),
918 None,
919 false,
920 true,
921 warning_sender,
922 )
923 .unwrap(),
924 vec![FilePattern::new(
925 PatternSyntax::RelGlob,
926 b"*.elc",
927 Path::new("file_path")
928 )],
929 );
930
931 let lines = b"syntax: include\nsyntax: glob";
932
933 assert_eq!(
934 parse_pattern_file_contents(
935 lines,
936 Path::new("file_path"),
937 None,
938 false,
939 true,
940 warning_sender,
941 )
942 .unwrap(),
943 vec![]
944 );
945 let lines = b"glob:**.o";
946 assert_eq!(
947 parse_pattern_file_contents(
948 lines,
949 Path::new("file_path"),
950 None,
951 false,
952 true,
953 warning_sender,
954 )
955 .unwrap(),
956 vec![FilePattern::new(
957 PatternSyntax::RelGlob,
958 b"**.o",
959 Path::new("file_path")
960 )]
961 );
962 }
963
964 pub fn build_single_regex(
965 entry: &FilePattern,
966 glob_suffix: GlobSuffix,
967 ) -> Result<Option<Vec<u8>>, PatternError> {
968 super::build_single_regex(
969 entry,
970 glob_suffix,
971 RegexCompleteness::ExcludeExactFiles,
972 )
973 .map(|re_opt| re_opt.map(|re| re.to_bytes()))
974 }
975
976 #[test]
977 fn test_build_single_regex() {
978 assert_eq!(
979 build_single_regex(
980 &FilePattern::new(
981 PatternSyntax::RelGlob,
982 b"rust/target/",
983 Path::new("")
984 ),
985 GlobSuffix::MoreComponents
986 )
987 .unwrap(),
988 Some(br"(?:.*/)?rust/target(?:/|$)".to_vec()),
989 );
990 assert_eq!(
991 build_single_regex(
992 &FilePattern::new(
993 PatternSyntax::Regexp,
994 br"rust/target/\d+",
995 Path::new("")
996 ),
997 GlobSuffix::MoreComponents
998 )
999 .unwrap(),
1000 Some(br"rust/target/\d+".to_vec()),
1001 );
1002 }
1003
1004 #[test]
1005 fn test_build_single_regex_shortcut() {
1006 assert_eq!(
1007 build_single_regex(
1008 &FilePattern::new(PatternSyntax::RootGlob, b"", Path::new("")),
1009 GlobSuffix::MoreComponents
1010 )
1011 .unwrap(),
1012 None,
1013 );
1014 assert_eq!(
1015 build_single_regex(
1016 &FilePattern::new(
1017 PatternSyntax::RootGlob,
1018 b"whatever",
1019 Path::new("")
1020 ),
1021 GlobSuffix::MoreComponents
1022 )
1023 .unwrap(),
1024 None,
1025 );
1026 assert_eq!(
1027 build_single_regex(
1028 &FilePattern::new(
1029 PatternSyntax::RootGlob,
1030 b"*.o",
1031 Path::new("")
1032 ),
1033 GlobSuffix::MoreComponents
1034 )
1035 .unwrap(),
1036 Some(br"[^/]*\.o(?:/|$)".to_vec()),
1037 );
1038 }
1039
1040 #[test]
1041 fn test_build_single_relregex() {
1042 assert_eq!(
1043 build_single_regex(
1044 &FilePattern::new(
1045 PatternSyntax::RelRegexp,
1046 b"^ba{2}r",
1047 Path::new("")
1048 ),
1049 GlobSuffix::MoreComponents
1050 )
1051 .unwrap(),
1052 Some(b"^ba{2}r".to_vec()),
1053 );
1054 assert_eq!(
1055 build_single_regex(
1056 &FilePattern::new(
1057 PatternSyntax::RelRegexp,
1058 b"ba{2}r",
1059 Path::new("")
1060 ),
1061 GlobSuffix::MoreComponents
1062 )
1063 .unwrap(),
1064 Some(b".*ba{2}r".to_vec()),
1065 );
1066 assert_eq!(
1067 build_single_regex(
1068 &FilePattern::new(
1069 PatternSyntax::RelRegexp,
1070 b"(?i)ba{2}r",
1071 Path::new("")
1072 ),
1073 GlobSuffix::MoreComponents
1074 )
1075 .unwrap(),
1076 Some(b"(?i:.*ba{2}r)".to_vec()),
1077 );
1078 assert_eq!(
1079 build_single_regex(
1080 &FilePattern::new(
1081 PatternSyntax::RelRegexp,
1082 b"(?i)^ba{2}r",
1083 Path::new("")
1084 ),
1085 GlobSuffix::MoreComponents
1086 )
1087 .unwrap(),
1088 Some(b"(?i:^ba{2}r)".to_vec()),
1089 );
1090 }
1091 }