-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleGlob.js
104 lines (88 loc) · 3.29 KB
/
SimpleGlob.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
SimpleGlob - The smallest NodeJS glob file extracter.
Author: Andrews54757
Source: https://github.com/ThreeLetters/SimpleGlob
License: MIT (https://github.com/ThreeLetters/SimpleGlob/blob/master/LICENSE)
Usage:
var files = Glob('/Desktop/SimpleGlob/*.js')
var files = Glob(['/Desktop/SimpleGlob/*.js','/Desktop/Something/*'])
*/
module.exports = function Glob(files) {
var fs = require('fs')
function regexIndexOf(string, regex, startpos) {
var indexOf = string.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
function regexLastIndexOf(string, regex, startpos) {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if (typeof (startpos) == "undefined") {
startpos = string.length;
} else if (startpos < 0) {
startpos = 0;
}
var stringToWorkWith = string.substring(0, startpos + 1);
var lastIndexOf = -1;
var nextStop = 0;
while ((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}
var out = [];
function get(file) {
if (/[*?\[\]]/.test(file)) {
var ind = regexIndexOf(file, /[*?\[\]]/),
ind2 = file.lastIndexOf('/', ind);
var before = file.substring(0, ind2),
after = file.substring(ind2 + 1)
try {
fs.statSync(before);
after = after.split('/');
function walk(path, i) {
try {
var current = fs.readdirSync(path);
var rule = after[i];
if (/[*?\[\]]/.test(rule)) {
var regex = new RegExp(rule.replace(/[*?]/g, function (a) {
return '.' + (a === '*' ? '*' : '')
}));
current.forEach((p) => {
if (regex.test(p)) {
if (i === after.length - 1) {
out.push(path + '/' + p);
} else {
walk(path + '/' + p, i + 1)
}
}
});
} else {
if (current.indexOf(rule) !== -1) {
if (i === after.length - 1) {
out.push(path + '/' + rule);
} else {
walk(path + '/' + rule, i + 1)
}
}
}
} catch (e) {
}
}
walk(before, 0)
} catch (e) {
}
} else {
if (fs.existsSync(file)) {
out.push(file);
}
}
}
if (typeof files === 'object') {
files.forEach((file) => {
get(file)
})
} else {
get(files)
}
return out;
}