-
-
Notifications
You must be signed in to change notification settings - Fork 575
/
createFilter.ts
executable file
·66 lines (51 loc) · 2.09 KB
/
createFilter.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
import { resolve, posix, isAbsolute } from 'path';
import pm from 'picomatch';
import { CreateFilter } from '../types';
import ensureArray from './utils/ensureArray';
import normalizePath from './normalizePath';
function getMatcherString(id: string, resolutionBase: string | false | null | undefined) {
if (resolutionBase === false || isAbsolute(id) || id.startsWith('*')) {
return id;
}
// resolve('') is valid and will default to process.cwd()
const basePath = normalizePath(resolve(resolutionBase || ''))
// escape all possible (posix + win) path characters that might interfere with regex
.replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
// Note that we use posix.join because:
// 1. the basePath has been normalized to use /
// 2. the incoming glob (id) matcher, also uses /
// otherwise Node will force backslash (\) on windows
return posix.join(basePath, id);
}
const createFilter: CreateFilter = function createFilter(include?, exclude?, options?) {
const resolutionBase = options && options.resolve;
const getMatcher = (id: string | RegExp) =>
id instanceof RegExp
? id
: {
test: (what: string) => {
// this refactor is a tad overly verbose but makes for easy debugging
const pattern = getMatcherString(id, resolutionBase);
const fn = pm(pattern, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
return function result(id: string | unknown): boolean {
if (typeof id !== 'string') return false;
if (/\0/.test(id)) return false;
const pathId = normalizePath(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher.test(pathId)) return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher.test(pathId)) return true;
}
return !includeMatchers.length;
};
};
export { createFilter as default };