/
pattern-to-regex.js
53 lines (42 loc) 路 1.42 KB
/
pattern-to-regex.js
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
// @flow
import path from "path";
// $FlowIgnore
import escapeRegExp from "./helpers/escape-regexp.cjs";
const sep = `\\${path.sep}`;
const endSep = `(?:${sep}|$)`;
const substitution = `[^${sep}]+`;
const starPat = `(?:${substitution}${sep})`;
const starPatLast = `(?:${substitution}${endSep})`;
const starStarPat = `${starPat}*?`;
const starStarPatLast = `${starPat}*?${starPatLast}?`;
/**
* Implement basic pattern matching that will allow users to do the simple
* tests with * and **. If users want full complex pattern matching, then can
* always use regex matching, or function validation.
*/
export default function pathToPattern(
pattern: string,
dirname: string,
): RegExp {
const parts = path.resolve(dirname, pattern).split(path.sep);
return new RegExp(
[
"^",
...parts.map((part, i) => {
const last = i === parts.length - 1;
// ** matches 0 or more path parts.
if (part === "**") return last ? starStarPatLast : starStarPat;
// * matches 1 path part.
if (part === "*") return last ? starPatLast : starPat;
// *.ext matches a wildcard with an extension.
if (part.indexOf("*.") === 0) {
return (
substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep)
);
}
// Otherwise match the pattern text.
return escapeRegExp(part) + (last ? endSep : sep);
}),
].join(""),
);
}