| 1 |
import path from "path"; |
| 2 |
|
| 3 |
const sep = `\\${path.sep}`; |
| 4 |
const endSep = `(?:${sep}|$)`; |
| 5 |
|
| 6 |
const substitution = `[^${sep}]+`; |
| 7 |
|
| 8 |
const starPat = `(?:${substitution}${sep})`; |
| 9 |
const starPatLast = `(?:${substitution}${endSep})`; |
| 10 |
|
| 11 |
const starStarPat = `${starPat}*?`; |
| 12 |
const starStarPatLast = `${starPat}*?${starPatLast}?`; |
| 13 |
|
| 14 |
function escapeRegExp(string: string) { |
| 15 |
return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* Implement basic pattern matching that will allow users to do the simple |
| 20 |
* tests with * and **. If users want full complex pattern matching, then can |
| 21 |
* always use regex matching, or function validation. |
| 22 |
*/ |
| 23 |
export default function pathToPattern( |
| 24 |
pattern: string, |
| 25 |
dirname: string, |
| 26 |
): RegExp { |
| 27 |
const parts = path.resolve(dirname, pattern).split(path.sep); |
| 28 |
|
| 29 |
return new RegExp( |
| 30 |
[ |
| 31 |
"^", |
| 32 |
...parts.map((part, i) => { |
| 33 |
const last = i === parts.length - 1; |
| 34 |
|
| 35 |
// ** matches 0 or more path parts. |
| 36 |
if (part === "**") return last ? starStarPatLast : starStarPat; |
| 37 |
|
| 38 |
// * matches 1 path part. |
| 39 |
if (part === "*") return last ? starPatLast : starPat; |
| 40 |
|
| 41 |
// *.ext matches a wildcard with an extension. |
| 42 |
if (part.indexOf("*.") === 0) { |
| 43 |
return ( |
| 44 |
substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep) |
| 45 |
); |
| 46 |
} |
| 47 |
|
| 48 |
// Otherwise match the pattern text. |
| 49 |
return escapeRegExp(part) + (last ? endSep : sep); |
| 50 |
}), |
| 51 |
].join(""), |
| 52 |
); |
| 53 |
} |