-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
glob.rs
428 lines (387 loc) · 14.7 KB
/
glob.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use std::mem::take;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use turbo_tasks::trace::TraceRawVcs;
#[derive(PartialEq, Eq, Debug, Clone, TraceRawVcs, Serialize, Deserialize)]
enum GlobPart {
/// `/**/`: Matches any path of directories
AnyDirectories,
/// `*`: Matches any filename (no path separator)
AnyFile,
/// `?`: Matches a single filename character (no path separator)
AnyFileChar,
/// `/`: Matches the path separator
PathSeparator,
/// `[abc]`: Matches any char of the list
FileChar(Vec<char>),
/// `abc`: Matches literal filename
File(String),
/// `{a,b,c}`: Matches any of the globs in the list
Alternatives(Vec<Glob>),
}
// Examples:
// - file.js = File(file.js)
// - *.js = AnyFile, File(.js)
// - file*.js = File(file), AnyFile, File(.js)
// - dir/file.js = File(dir), PathSeparator, File(file.js)
// - **/*.js = AnyDirectories, PathSeparator, AnyFile, File(.js)
// - {a/**,*}/file = Alternatives([File(a), PathSeparator, AnyDirectories],
// [AnyFile]), PathSeparator, File(file)
// Note: a/**/b does match a/b, so we need some special logic about path
// separators
#[turbo_tasks::value]
#[derive(Debug, Clone)]
pub struct Glob {
expression: Vec<GlobPart>,
}
impl Glob {
pub fn execute(&self, path: &str) -> bool {
let match_partial = path.ends_with('/');
self.iter_matches(path, true, match_partial)
.any(|result| matches!(result, ("", _)))
}
fn iter_matches<'a>(
&'a self,
path: &'a str,
previous_part_is_path_separator_equivalent: bool,
match_partial: bool,
) -> GlobMatchesIterator<'a> {
GlobMatchesIterator {
current: path,
glob: self,
match_partial,
is_path_separator_equivalent: previous_part_is_path_separator_equivalent,
stack: Vec::new(),
index: 0,
}
}
pub fn parse(input: &str) -> Result<Glob> {
let mut current = input;
let mut expression = Vec::new();
while !current.is_empty() {
let (part, remainder) = GlobPart::parse(current, false)
.with_context(|| anyhow!("Failed to parse glob {input}"))?;
expression.push(part);
current = remainder;
}
Ok(Glob { expression })
}
}
struct GlobMatchesIterator<'a> {
current: &'a str,
glob: &'a Glob,
match_partial: bool,
is_path_separator_equivalent: bool,
stack: Vec<GlobPartMatchesIterator<'a>>,
index: usize,
}
impl<'a> Iterator for GlobMatchesIterator<'a> {
type Item = (&'a str, bool);
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(part) = self.glob.expression.get(self.index) {
let iter = if let Some(iter) = self.stack.get_mut(self.index) {
iter
} else {
let iter = part.iter_matches(
self.current,
self.is_path_separator_equivalent,
self.match_partial,
);
self.stack.push(iter);
self.stack.last_mut().unwrap()
};
if let Some((new_path, new_is_path_separator_equivalent)) = iter.next() {
self.current = new_path;
self.is_path_separator_equivalent = new_is_path_separator_equivalent;
self.index += 1;
if self.match_partial && self.current.is_empty() {
return Some(("", self.is_path_separator_equivalent));
}
} else {
if self.index == 0 {
// failed to match
return None;
}
// backtrack
self.stack.pop();
self.index -= 1;
}
} else {
// end of expression, matched successfully
// backtrack for the next iteration
self.index -= 1;
return Some((self.current, self.is_path_separator_equivalent));
}
}
}
}
impl GlobPart {
/// Iterates over all possible matches of this part with the provided path.
/// The least greedy match is returned first. This is usually used for
/// backtracking. The string slice returned is the remaining part or the
/// path. The boolean flag returned specifies if the matched part should
/// be considered as path-separator equivalent.
fn iter_matches<'a>(
&'a self,
path: &'a str,
previous_part_is_path_separator_equivalent: bool,
match_partial: bool,
) -> GlobPartMatchesIterator<'a> {
GlobPartMatchesIterator {
path,
part: self,
match_partial,
previous_part_is_path_separator_equivalent,
index: 0,
glob_iterator: None,
}
}
fn parse(input: &str, inside_of_braces: bool) -> Result<(GlobPart, &str)> {
debug_assert!(!input.is_empty());
let two_chars = {
let mut chars = input.chars();
(chars.next().unwrap(), chars.next())
};
match two_chars {
('/', _) => Ok((GlobPart::PathSeparator, &input[1..])),
('*', Some('*')) => Ok((GlobPart::AnyDirectories, &input[2..])),
('*', _) => Ok((GlobPart::AnyFile, &input[1..])),
('?', _) => Ok((GlobPart::AnyFileChar, &input[1..])),
('[', Some('[')) => todo!("glob char classes are not implemented yet"),
('[', _) => todo!("glob char sequences are not implemented yet"),
('{', Some(_)) => {
let mut current = &input[1..];
let mut alternatives = Vec::new();
let mut expression = Vec::new();
loop {
let (part, remainder) = GlobPart::parse(current, true)?;
expression.push(part);
current = remainder;
match current.chars().next() {
Some(',') => {
alternatives.push(Glob {
expression: take(&mut expression),
});
current = ¤t[1..];
}
Some('}') => {
alternatives.push(Glob {
expression: take(&mut expression),
});
current = ¤t[1..];
break;
}
None => bail!("Unterminated glob braces"),
_ => {
// next part of the glob
}
}
}
Ok((GlobPart::Alternatives(alternatives), current))
}
('{', None) => {
bail!("Unterminated glob braces")
}
_ => {
let mut is_escaped = false;
let mut literal = String::new();
let mut index = 0;
for c in input.chars() {
if is_escaped {
is_escaped = false;
} else if c == '\\' {
is_escaped = true;
} else if c == '/'
|| c == '*'
|| c == '?'
|| c == '['
|| c == '{'
|| (inside_of_braces && (c == ',' || c == '}'))
{
break;
}
literal.push(c);
index += 1;
}
Ok((GlobPart::File(literal), &input[index..]))
}
}
}
}
struct GlobPartMatchesIterator<'a> {
path: &'a str,
part: &'a GlobPart,
match_partial: bool,
previous_part_is_path_separator_equivalent: bool,
index: usize,
glob_iterator: Option<Box<GlobMatchesIterator<'a>>>,
}
impl<'a> Iterator for GlobPartMatchesIterator<'a> {
type Item = (&'a str, bool);
fn next(&mut self) -> Option<Self::Item> {
match self.part {
GlobPart::AnyDirectories => {
if self.index == 0 {
self.index += 1;
return Some((self.path, true));
}
let mut iter = self.path.chars();
if iter.advance_by(self.index - 1).is_err() {
return None;
}
loop {
self.index += 1;
match iter.next() {
Some('/') => {
return Some((&self.path[self.index - 1..], true));
}
Some(_) => {}
None => {
return Some((&self.path[self.index - 2..], false));
}
}
}
}
GlobPart::AnyFile => {
self.index += 1;
// TODO verify if `*` does match zero chars?
if let Some(slice) = self.path.get(0..self.index) {
if slice.ends_with('/') {
None
} else {
Some((
&self.path[self.index..],
self.previous_part_is_path_separator_equivalent && self.index == 1,
))
}
} else {
None
}
}
GlobPart::AnyFileChar => todo!(),
GlobPart::PathSeparator => {
if self.index == 0 {
self.index = 1;
if self.path.starts_with('/') {
Some((&self.path[1..], true))
} else if self.previous_part_is_path_separator_equivalent {
Some((self.path, true))
} else {
None
}
} else {
None
}
}
GlobPart::FileChar(chars) => loop {
if let Some(c) = chars.get(self.index) {
self.index += 1;
if self.path.starts_with(*c) {
return Some((&self.path[1..], false));
}
} else {
return None;
}
},
GlobPart::File(name) => {
if self.index == 0 && self.path.starts_with(name) {
self.index += 1;
Some((&self.path[name.len()..], false))
} else {
None
}
}
GlobPart::Alternatives(alternatives) => loop {
if let Some(glob_iterator) = &mut self.glob_iterator {
if let Some((path, is_path_separator_equivalent)) = glob_iterator.next() {
return Some((path, is_path_separator_equivalent));
} else {
self.index += 1;
self.glob_iterator = None;
}
} else if let Some(alternative) = alternatives.get(self.index) {
self.glob_iterator = Some(Box::new(alternative.iter_matches(
self.path,
self.previous_part_is_path_separator_equivalent,
self.match_partial,
)));
} else {
return None;
}
},
}
}
}
impl TryFrom<&str> for Glob {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Glob::parse(value)
}
}
#[turbo_tasks::value_impl]
impl GlobVc {
#[turbo_tasks::function]
pub fn new(glob: &str) -> Result<Self> {
Ok(Self::cell(Glob::try_from(glob)?))
}
}
#[cfg(test)]
mod tests {
use rstest::*;
use super::Glob;
#[rstest]
#[case::file("file.js", "file.js")]
#[case::dir_and_file("dir/file.js", "dir/file.js")]
#[case::dir_and_file_partial("dir/file.js", "dir/")]
#[case::file_braces("file.{ts,js}", "file.js")]
#[case::dir_and_file_braces("dir/file.{ts,js}", "dir/file.js")]
#[case::dir_and_file_dir_braces("{dir,other}/file.{ts,js}", "dir/file.js")]
#[case::star("*.js", "file.js")]
#[case::dir_star("dir/*.js", "dir/file.js")]
#[case::dir_star_partial("dir/*.js", "dir/")]
#[case::globstar("**/*.js", "file.js")]
#[case::globstar("**/*.js", "dir/file.js")]
#[case::globstar("**/*.js", "dir/sub/file.js")]
#[case::globstar("**/**/*.js", "file.js")]
#[case::globstar("**/**/*.js", "dir/sub/file.js")]
#[case::globstar_partial("**/**/*.js", "dir/sub/")]
#[case::globstar_partial("**/**/*.js", "dir/")]
#[case::globstar_in_dir("dir/**/sub/file.js", "dir/sub/file.js")]
#[case::globstar_in_dir("dir/**/sub/file.js", "dir/a/sub/file.js")]
#[case::globstar_in_dir("dir/**/sub/file.js", "dir/a/b/sub/file.js")]
#[case::globstar_in_dir_partial("dir/**/sub/file.js", "dir/a/b/sub/")]
#[case::globstar_in_dir_partial("dir/**/sub/file.js", "dir/a/b/")]
#[case::globstar_in_dir_partial("dir/**/sub/file.js", "dir/a/")]
#[case::globstar_in_dir_partial("dir/**/sub/file.js", "dir/")]
#[case::star_dir(
"**/*/next/dist/server/next.js",
"node_modules/next/dist/server/next.js"
)]
#[case::node_modules_root("**/node_modules/**", "node_modules/next/dist/server/next.js")]
#[case::node_modules_nested(
"**/node_modules/**",
"apps/some-app/node_modules/regenerate-unicode-properties/Script_Extensions/Osage.js"
)]
#[case::node_modules_pnpm(
"**/node_modules/**",
"node_modules/.pnpm/regenerate-unicode-properties@9.0.0/node_modules/\
regenerate-unicode-properties/Script_Extensions/Osage.js"
)]
#[case::alternatives_nested1("{a,b/c,d/e/{f,g/h}}", "a")]
#[case::alternatives_nested2("{a,b/c,d/e/{f,g/h}}", "b/c")]
#[case::alternatives_nested3("{a,b/c,d/e/{f,g/h}}", "d/e/f")]
#[case::alternatives_nested4("{a,b/c,d/e/{f,g/h}}", "d/e/g/h")]
fn glob_match(#[case] glob: &str, #[case] path: &str) {
let glob = Glob::parse(glob).unwrap();
println!("{glob:?} {path}");
assert!(glob.execute(path));
}
#[rstest]
#[case::early_end("*.raw", "hello.raw.js")]
fn glob_not_matching(#[case] glob: &str, #[case] path: &str) {
let glob = Glob::parse(glob).unwrap();
println!("{glob:?} {path}");
assert!(!glob.execute(path));
}
}