-
Notifications
You must be signed in to change notification settings - Fork 58
/
glob.ts
85 lines (79 loc) · 3.01 KB
/
glob.ts
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
/**
* @coreapi
* @module core
*/
/**
* Matches state names using glob-like pattern strings.
*
* Globs can be used in specific APIs including:
*
* - [[StateService.is]]
* - [[StateService.includes]]
* - The first argument to Hook Registration functions like [[TransitionService.onStart]]
* - [[HookMatchCriteria]] and [[HookMatchCriterion]]
*
* A `Glob` string is a pattern which matches state names.
* Nested state names are split into segments (separated by a dot) when processing.
* The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz']
*
* Globs work according to the following rules:
*
* ### Exact match:
*
* The glob `'A.B'` matches the state named exactly `'A.B'`.
*
* | Glob |Matches states named|Does not match state named|
* |:------------|:--------------------|:---------------------|
* | `'A'` | `'A'` | `'B'` , `'A.C'` |
* | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` |
* | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`|
*
* ### Single star (`*`)
*
* A single star (`*`) is a wildcard that matches exactly one segment.
*
* | Glob |Matches states named |Does not match state named |
* |:------------|:---------------------|:--------------------------|
* | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` |
* | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` |
* | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`|
*
* ### Double star (`**`)
*
* A double star (`'**'`) is a wildcard that matches *zero or more segments*
*
* | Glob |Matches states named |Does not match state named |
* |:------------|:----------------------------------------------|:----------------------------------|
* | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) |
* | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` |
* | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` |
* | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` |
*
*/
export class Glob {
text: string;
glob: Array<string>;
regexp: RegExp;
/** Returns true if the string has glob-like characters in it */
static is(text: string) {
return !!/[!,*]+/.exec(text);
}
/** Returns a glob from the string, or null if the string isn't Glob-like */
static fromString(text: string) {
return Glob.is(text) ? new Glob(text) : null;
}
constructor(text: string) {
this.text = text;
this.glob = text.split('.');
const regexpString = this.text.split('.')
.map(seg => {
if (seg === '**') return '(?:|(?:\\.[^.]*)*)';
if (seg === '*') return '\\.[^.]*';
return '\\.' + seg;
}).join('');
this.regexp = new RegExp('^' + regexpString + '$');
}
matches(name: string) {
return this.regexp.test('.' + name);
}
}