##// END OF EJS Templates
rust-filepatterns: improve API and robustness for pattern files parsing...
Raphaël Gomès -
r44784:d42eea9a default
parent child Browse files
Show More
@@ -7,9 +7,7 b''
7 7
8 8 //! Handling of Mercurial-specific patterns.
9 9
10 use crate::{
11 utils::SliceExt, FastHashMap, LineNumber, PatternError, PatternFileError,
12 };
10 use crate::{utils::SliceExt, FastHashMap, PatternError};
13 11 use lazy_static::lazy_static;
14 12 use regex::bytes::{NoExpand, Regex};
15 13 use std::fs::File;
@@ -32,18 +30,28 b' lazy_static! {'
32 30 const GLOB_REPLACEMENTS: &[(&[u8], &[u8])] =
33 31 &[(b"*/", b"(?:.*/)?"), (b"*", b".*"), (b"", b"[^/]*")];
34 32
33 /// Appended to the regexp of globs
34 const GLOB_SUFFIX: &[u8; 7] = b"(?:/|$)";
35
35 36 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
36 37 pub enum PatternSyntax {
38 /// A regular expression
37 39 Regexp,
38 40 /// Glob that matches at the front of the path
39 41 RootGlob,
40 42 /// Glob that matches at any suffix of the path (still anchored at
41 43 /// slashes)
42 44 Glob,
45 /// a path relative to repository root, which is matched recursively
43 46 Path,
47 /// A path relative to cwd
44 48 RelPath,
49 /// an unrooted glob (*.rs matches Rust files in all dirs)
45 50 RelGlob,
51 /// A regexp that needn't match the start of a name
46 52 RelRegexp,
53 /// A path relative to repository root, which is matched non-recursively
54 /// (will not match subdirectories)
47 55 RootFiles,
48 56 }
49 57
@@ -125,16 +133,18 b' fn escape_pattern(pattern: &[u8]) -> Vec'
125 133 .collect()
126 134 }
127 135
128 fn parse_pattern_syntax(kind: &[u8]) -> Result<PatternSyntax, PatternError> {
136 pub fn parse_pattern_syntax(
137 kind: &[u8],
138 ) -> Result<PatternSyntax, PatternError> {
129 139 match kind {
130 b"re" => Ok(PatternSyntax::Regexp),
131 b"path" => Ok(PatternSyntax::Path),
132 b"relpath" => Ok(PatternSyntax::RelPath),
133 b"rootfilesin" => Ok(PatternSyntax::RootFiles),
134 b"relglob" => Ok(PatternSyntax::RelGlob),
135 b"relre" => Ok(PatternSyntax::RelRegexp),
136 b"glob" => Ok(PatternSyntax::Glob),
137 b"rootglob" => Ok(PatternSyntax::RootGlob),
140 b"re:" => Ok(PatternSyntax::Regexp),
141 b"path:" => Ok(PatternSyntax::Path),
142 b"relpath:" => Ok(PatternSyntax::RelPath),
143 b"rootfilesin:" => Ok(PatternSyntax::RootFiles),
144 b"relglob:" => Ok(PatternSyntax::RelGlob),
145 b"relre:" => Ok(PatternSyntax::RelRegexp),
146 b"glob:" => Ok(PatternSyntax::Glob),
147 b"rootglob:" => Ok(PatternSyntax::RootGlob),
138 148 _ => Err(PatternError::UnsupportedSyntax(
139 149 String::from_utf8_lossy(kind).to_string(),
140 150 )),
@@ -144,11 +154,10 b' fn parse_pattern_syntax(kind: &[u8]) -> '
144 154 /// Builds the regex that corresponds to the given pattern.
145 155 /// If within a `syntax: regexp` context, returns the pattern,
146 156 /// otherwise, returns the corresponding regex.
147 fn _build_single_regex(
148 syntax: PatternSyntax,
149 pattern: &[u8],
150 globsuffix: &[u8],
151 ) -> Vec<u8> {
157 fn _build_single_regex(entry: &IgnorePattern) -> Vec<u8> {
158 let IgnorePattern {
159 syntax, pattern, ..
160 } = entry;
152 161 if pattern.is_empty() {
153 162 return vec![];
154 163 }
@@ -158,7 +167,7 b' fn _build_single_regex('
158 167 if pattern[0] == b'^' {
159 168 return pattern.to_owned();
160 169 }
161 [b".*", pattern].concat()
170 [&b".*"[..], pattern].concat()
162 171 }
163 172 PatternSyntax::Path | PatternSyntax::RelPath => {
164 173 if pattern == b"." {
@@ -181,13 +190,13 b' fn _build_single_regex('
181 190 PatternSyntax::RelGlob => {
182 191 let glob_re = glob_to_re(pattern);
183 192 if let Some(rest) = glob_re.drop_prefix(b"[^/]*") {
184 [b".*", rest, globsuffix].concat()
193 [b".*", rest, GLOB_SUFFIX].concat()
185 194 } else {
186 [b"(?:|.*/)", glob_re.as_slice(), globsuffix].concat()
195 [b"(?:|.*/)", glob_re.as_slice(), GLOB_SUFFIX].concat()
187 196 }
188 197 }
189 198 PatternSyntax::Glob | PatternSyntax::RootGlob => {
190 [glob_to_re(pattern).as_slice(), globsuffix].concat()
199 [glob_to_re(pattern).as_slice(), GLOB_SUFFIX].concat()
191 200 }
192 201 }
193 202 }
@@ -195,22 +204,73 b' fn _build_single_regex('
195 204 const GLOB_SPECIAL_CHARACTERS: [u8; 7] =
196 205 [b'*', b'?', b'[', b']', b'{', b'}', b'\\'];
197 206
207 /// TODO support other platforms
208 #[cfg(unix)]
209 pub fn normalize_path_bytes(bytes: &[u8]) -> Vec<u8> {
210 if bytes.is_empty() {
211 return b".".to_vec();
212 }
213 let sep = b'/';
214
215 let mut initial_slashes = bytes.iter().take_while(|b| **b == sep).count();
216 if initial_slashes > 2 {
217 // POSIX allows one or two initial slashes, but treats three or more
218 // as single slash.
219 initial_slashes = 1;
220 }
221 let components = bytes
222 .split(|b| *b == sep)
223 .filter(|c| !(c.is_empty() || c == b"."))
224 .fold(vec![], |mut acc, component| {
225 if component != b".."
226 || (initial_slashes == 0 && acc.is_empty())
227 || (!acc.is_empty() && acc[acc.len() - 1] == b"..")
228 {
229 acc.push(component)
230 } else if !acc.is_empty() {
231 acc.pop();
232 }
233 acc
234 });
235 let mut new_bytes = components.join(&sep);
236
237 if initial_slashes > 0 {
238 let mut buf: Vec<_> = (0..initial_slashes).map(|_| sep).collect();
239 buf.extend(new_bytes);
240 new_bytes = buf;
241 }
242 if new_bytes.is_empty() {
243 b".".to_vec()
244 } else {
245 new_bytes
246 }
247 }
248
198 249 /// Wrapper function to `_build_single_regex` that short-circuits 'exact' globs
199 250 /// that don't need to be transformed into a regex.
200 251 pub fn build_single_regex(
201 kind: &[u8],
202 pat: &[u8],
203 globsuffix: &[u8],
252 entry: &IgnorePattern,
204 253 ) -> Result<Vec<u8>, PatternError> {
205 let enum_kind = parse_pattern_syntax(kind)?;
206 if enum_kind == PatternSyntax::RootGlob
207 && !pat.iter().any(|b| GLOB_SPECIAL_CHARACTERS.contains(b))
254 let IgnorePattern {
255 pattern, syntax, ..
256 } = entry;
257 let pattern = match syntax {
258 PatternSyntax::RootGlob
259 | PatternSyntax::Path
260 | PatternSyntax::RelGlob
261 | PatternSyntax::RootFiles => normalize_path_bytes(&pattern),
262 _ => pattern.to_owned(),
263 };
264 if *syntax == PatternSyntax::RootGlob
265 && !pattern.iter().any(|b| GLOB_SPECIAL_CHARACTERS.contains(b))
208 266 {
209 let mut escaped = escape_pattern(pat);
210 escaped.extend(b"(?:/|$)");
267 let mut escaped = escape_pattern(&pattern);
268 escaped.extend(GLOB_SUFFIX);
211 269 Ok(escaped)
212 270 } else {
213 Ok(_build_single_regex(enum_kind, pat, globsuffix))
271 let mut entry = entry.clone();
272 entry.pattern = pattern;
273 Ok(_build_single_regex(&entry))
214 274 }
215 275 }
216 276
@@ -222,24 +282,29 b' lazy_static! {'
222 282 m.insert(b"regexp".as_ref(), b"relre:".as_ref());
223 283 m.insert(b"glob".as_ref(), b"relglob:".as_ref());
224 284 m.insert(b"rootglob".as_ref(), b"rootglob:".as_ref());
225 m.insert(b"include".as_ref(), b"include".as_ref());
226 m.insert(b"subinclude".as_ref(), b"subinclude".as_ref());
285 m.insert(b"include".as_ref(), b"include:".as_ref());
286 m.insert(b"subinclude".as_ref(), b"subinclude:".as_ref());
227 287 m
228 288 };
229 289 }
230 290
231 pub type PatternTuple = (Vec<u8>, LineNumber, Vec<u8>);
232 type WarningTuple = (PathBuf, Vec<u8>);
291 #[derive(Debug)]
292 pub enum PatternFileWarning {
293 /// (file path, syntax bytes)
294 InvalidSyntax(PathBuf, Vec<u8>),
295 /// File path
296 NoSuchFile(PathBuf),
297 }
233 298
234 299 pub fn parse_pattern_file_contents<P: AsRef<Path>>(
235 300 lines: &[u8],
236 301 file_path: P,
237 302 warn: bool,
238 ) -> (Vec<PatternTuple>, Vec<WarningTuple>) {
303 ) -> Result<(Vec<IgnorePattern>, Vec<PatternFileWarning>), PatternError> {
239 304 let comment_regex = Regex::new(r"((?:^|[^\\])(?:\\\\)*)#.*").unwrap();
240 305 let comment_escape_regex = Regex::new(r"\\#").unwrap();
241 let mut inputs: Vec<PatternTuple> = vec![];
242 let mut warnings: Vec<WarningTuple> = vec![];
306 let mut inputs: Vec<IgnorePattern> = vec![];
307 let mut warnings: Vec<PatternFileWarning> = vec![];
243 308
244 309 let mut current_syntax = b"relre:".as_ref();
245 310
@@ -267,8 +332,10 b' pub fn parse_pattern_file_contents<P: As'
267 332 if let Some(rel_syntax) = SYNTAXES.get(syntax) {
268 333 current_syntax = rel_syntax;
269 334 } else if warn {
270 warnings
271 .push((file_path.as_ref().to_owned(), syntax.to_owned()));
335 warnings.push(PatternFileWarning::InvalidSyntax(
336 file_path.as_ref().to_owned(),
337 syntax.to_owned(),
338 ));
272 339 }
273 340 continue;
274 341 }
@@ -288,34 +355,82 b' pub fn parse_pattern_file_contents<P: As'
288 355 }
289 356 }
290 357
291 inputs.push((
292 [line_syntax, line].concat(),
358 inputs.push(IgnorePattern::new(
359 parse_pattern_syntax(&line_syntax).map_err(|e| match e {
360 PatternError::UnsupportedSyntax(syntax) => {
361 PatternError::UnsupportedSyntaxInFile(
362 syntax,
363 file_path.as_ref().to_string_lossy().into(),
293 364 line_number,
294 line.to_owned(),
365 )
366 }
367 _ => e,
368 })?,
369 &line,
370 &file_path,
295 371 ));
296 372 }
297 (inputs, warnings)
373 Ok((inputs, warnings))
298 374 }
299 375
300 376 pub fn read_pattern_file<P: AsRef<Path>>(
301 377 file_path: P,
302 378 warn: bool,
303 ) -> Result<(Vec<PatternTuple>, Vec<WarningTuple>), PatternFileError> {
304 let mut f = File::open(file_path.as_ref())?;
379 ) -> Result<(Vec<IgnorePattern>, Vec<PatternFileWarning>), PatternError> {
380 let mut f = match File::open(file_path.as_ref()) {
381 Ok(f) => Ok(f),
382 Err(e) => match e.kind() {
383 std::io::ErrorKind::NotFound => {
384 return Ok((
385 vec![],
386 vec![PatternFileWarning::NoSuchFile(
387 file_path.as_ref().to_owned(),
388 )],
389 ))
390 }
391 _ => Err(e),
392 },
393 }?;
305 394 let mut contents = Vec::new();
306 395
307 396 f.read_to_end(&mut contents)?;
308 397
309 Ok(parse_pattern_file_contents(&contents, file_path, warn))
398 Ok(parse_pattern_file_contents(&contents, file_path, warn)?)
399 }
400
401 /// Represents an entry in an "ignore" file.
402 #[derive(Debug, Eq, PartialEq, Clone)]
403 pub struct IgnorePattern {
404 pub syntax: PatternSyntax,
405 pub pattern: Vec<u8>,
406 pub source: PathBuf,
310 407 }
311 408
409 impl IgnorePattern {
410 pub fn new(
411 syntax: PatternSyntax,
412 pattern: &[u8],
413 source: impl AsRef<Path>,
414 ) -> Self {
415 Self {
416 syntax,
417 pattern: pattern.to_owned(),
418 source: source.as_ref().to_owned(),
419 }
420 }
421 }
422
423 pub type PatternResult<T> = Result<T, PatternError>;
424
312 425 #[cfg(test)]
313 426 mod tests {
314 427 use super::*;
428 use pretty_assertions::assert_eq;
315 429
316 430 #[test]
317 431 fn escape_pattern_test() {
318 let untouched = br#"!"%',/0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz"#;
432 let untouched =
433 br#"!"%',/0123456789:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz"#;
319 434 assert_eq!(escape_pattern(untouched), untouched.to_vec());
320 435 // All escape codes
321 436 assert_eq!(
@@ -342,39 +457,78 b' mod tests {'
342 457 let lines = b"syntax: glob\n*.elc";
343 458
344 459 assert_eq!(
345 vec![(b"relglob:*.elc".to_vec(), 2, b"*.elc".to_vec())],
346 460 parse_pattern_file_contents(lines, Path::new("file_path"), false)
461 .unwrap()
347 462 .0,
463 vec![IgnorePattern::new(
464 PatternSyntax::RelGlob,
465 b"*.elc",
466 Path::new("file_path")
467 )],
348 468 );
349 469
350 470 let lines = b"syntax: include\nsyntax: glob";
351 471
352 472 assert_eq!(
353 473 parse_pattern_file_contents(lines, Path::new("file_path"), false)
474 .unwrap()
354 475 .0,
355 476 vec![]
356 477 );
357 478 let lines = b"glob:**.o";
358 479 assert_eq!(
359 480 parse_pattern_file_contents(lines, Path::new("file_path"), false)
481 .unwrap()
360 482 .0,
361 vec![(b"relglob:**.o".to_vec(), 1, b"**.o".to_vec())]
483 vec![IgnorePattern::new(
484 PatternSyntax::RelGlob,
485 b"**.o",
486 Path::new("file_path")
487 )]
488 );
489 }
490
491 #[test]
492 fn test_build_single_regex() {
493 assert_eq!(
494 build_single_regex(&IgnorePattern::new(
495 PatternSyntax::RelGlob,
496 b"rust/target/",
497 Path::new("")
498 ))
499 .unwrap(),
500 br"(?:|.*/)rust/target(?:/|$)".to_vec(),
362 501 );
363 502 }
364 503
365 504 #[test]
366 505 fn test_build_single_regex_shortcut() {
367 506 assert_eq!(
368 br"(?:/|$)".to_vec(),
369 build_single_regex(b"rootglob", b"", b"").unwrap()
507 build_single_regex(&IgnorePattern::new(
508 PatternSyntax::RootGlob,
509 b"",
510 Path::new("")
511 ))
512 .unwrap(),
513 br"\.(?:/|$)".to_vec(),
370 514 );
371 515 assert_eq!(
516 build_single_regex(&IgnorePattern::new(
517 PatternSyntax::RootGlob,
518 b"whatever",
519 Path::new("")
520 ))
521 .unwrap(),
372 522 br"whatever(?:/|$)".to_vec(),
373 build_single_regex(b"rootglob", b"whatever", b"").unwrap()
374 523 );
375 524 assert_eq!(
376 br"[^/]*\.o".to_vec(),
377 build_single_regex(b"rootglob", b"*.o", b"").unwrap()
525 build_single_regex(&IgnorePattern::new(
526 PatternSyntax::RootGlob,
527 b"*.o",
528 Path::new("")
529 ))
530 .unwrap(),
531 br"[^/]*\.o(?:/|$)".to_vec(),
378 532 );
379 533 }
380 534 }
@@ -25,7 +25,8 b' pub mod utils;'
25 25
26 26 use crate::utils::hg_path::{HgPathBuf, HgPathError};
27 27 pub use filepatterns::{
28 build_single_regex, read_pattern_file, PatternSyntax, PatternTuple,
28 parse_pattern_syntax, read_pattern_file, IgnorePattern,
29 PatternFileWarning, PatternSyntax,
29 30 };
30 31 use std::collections::HashMap;
31 32 use twox_hash::RandomXxHashBuilder64;
@@ -115,18 +116,31 b' impl From<DirstatePackError> for Dirstat'
115 116
116 117 #[derive(Debug)]
117 118 pub enum PatternError {
119 Path(HgPathError),
118 120 UnsupportedSyntax(String),
121 UnsupportedSyntaxInFile(String, String, usize),
122 TooLong(usize),
123 IO(std::io::Error),
119 124 }
120 125
121 #[derive(Debug)]
122 pub enum PatternFileError {
123 IO(std::io::Error),
124 Pattern(PatternError, LineNumber),
126 impl ToString for PatternError {
127 fn to_string(&self) -> String {
128 match self {
129 PatternError::UnsupportedSyntax(syntax) => {
130 format!("Unsupported syntax {}", syntax)
125 131 }
126
127 impl From<std::io::Error> for PatternFileError {
128 fn from(e: std::io::Error) -> Self {
129 PatternFileError::IO(e)
132 PatternError::UnsupportedSyntaxInFile(syntax, file_path, line) => {
133 format!(
134 "{}:{}: unsupported syntax {}",
135 file_path, line, syntax
136 )
137 }
138 PatternError::TooLong(size) => {
139 format!("matcher pattern is too long ({} bytes)", size)
140 }
141 PatternError::IO(e) => e.to_string(),
142 PatternError::Path(e) => e.to_string(),
143 }
130 144 }
131 145 }
132 146
@@ -141,3 +155,15 b' impl From<std::io::Error> for DirstateEr'
141 155 DirstateError::IO(e)
142 156 }
143 157 }
158
159 impl From<std::io::Error> for PatternError {
160 fn from(e: std::io::Error) -> Self {
161 PatternError::IO(e)
162 }
163 }
164
165 impl From<HgPathError> for PatternError {
166 fn from(e: HgPathError) -> Self {
167 PatternError::Path(e)
168 }
169 }
General Comments 0
You need to be logged in to leave comments. Login now