-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile-match.js
83 lines (68 loc) · 1.79 KB
/
file-match.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
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
var util = require('utils-extend');
/**
* @description
* @example
* `**\/*` match all files
* `*.js` only match current dir files
* '**\/*.js' match all js files
* 'path/*.js' match js files in path
* '!*.js' exclude js files
*/
function fileMatch(filter, ignore) {
if (filter === null) {
return function() {
return true;
};
} else if (filter === '' || (util.isArray(filter) && !filter.length)) {
return function() {
return false;
};
}
if (util.isString(filter)) {
filter = [filter];
}
var match = [];
var negate = [];
var isIgnore = ignore ? 'i' : '';
filter.forEach(function(item) {
var isNegate = item.indexOf('!') === 0;
item = item
.replace(/^!/, '')
.replace(/\*(?![\/*])/, '[^/]*?')
.replace('**\/', '([^/]+\/)*')
.replace(/\{([^\}]+)\}/g, function($1, $2) {
var collection = $2.split(',');
var length = collection.length;
var result = '(?:';
collection.forEach(function(item, index) {
result += '(' + item.trim() + ')';
if (index + 1 !== length) {
result += '|';
}
});
result += ')';
return result;
})
.replace(/([\/\.])/g, '\\$1');
item = '(^' + item + '$)';
if (isNegate) {
negate.push(item);
} else {
match.push(item);
}
});
match = match.length ? new RegExp(match.join('|'), isIgnore) : null;
negate = negate.length ? new RegExp(negate.join('|'), isIgnore) : null;
return function(filepath) {
// Normalize \\ paths to / paths.
filepath = util.path.unixifyPath(filepath);
if (negate && negate.test(filepath)) {
return false;
}
if (match && match.test(filepath)) {
return true;
}
return false;
};
}
module.exports = fileMatch;