forked from denoland/std
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glob.ts
301 lines (277 loc) · 8.52 KB
/
glob.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { globrex } from "./globrex.ts";
import { isWindows } from "./path/constants.ts";
import { isAbsolute, join, normalize } from "./path/mod.ts";
import { WalkInfo, walk, walkSync } from "./walk.ts";
const { cwd, stat, statSync } = Deno;
type FileInfo = Deno.FileInfo;
export interface GlobOptions {
extended?: boolean;
globstar?: boolean;
strict?: boolean;
}
export interface GlobToRegExpOptions extends GlobOptions {
flags?: string;
}
/**
* Generate a regex based on glob pattern and options
* This was meant to be using the the `fs.walk` function
* but can be used anywhere else.
* Examples:
*
* Looking for all the `ts` files:
* walkSync(".", {
* match: [globToRegExp("*.ts")]
* })
*
* Looking for all the `.json` files in any subfolder:
* walkSync(".", {
* match: [globToRegExp(join("a", "**", "*.json"),{
* flags: "g",
* extended: true,
* globstar: true
* })]
* })
*
* @param glob - Glob pattern to be used
* @param options - Specific options for the glob pattern
* @returns A RegExp for the glob pattern
*/
export function globToRegExp(
glob: string,
options: GlobToRegExpOptions = {}
): RegExp {
const result = globrex(glob, { ...options, filepath: true });
return result.path!.regex;
}
/** Test whether the given string is a glob */
export function isGlob(str: string): boolean {
const chars: Record<string, string> = { "{": "}", "(": ")", "[": "]" };
/* eslint-disable-next-line max-len */
const regex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
if (str === "") {
return false;
}
let match: RegExpExecArray | null;
while ((match = regex.exec(str))) {
if (match[2]) return true;
let idx = match.index + match[0].length;
// if an open bracket/brace/paren is escaped,
// set the index to the next closing character
const open = match[1];
const close = open ? chars[open] : null;
if (open && close) {
const n = str.indexOf(close, idx);
if (n !== -1) {
idx = n + 1;
}
}
str = str.slice(idx);
}
return false;
}
export interface ExpandGlobOptions extends GlobOptions {
root?: string;
exclude?: string[];
includeDirs?: boolean;
}
const SEP_PATTERN = isWindows ? /[\\/]+/ : /\/+/;
interface SplitPath {
segments: string[];
isAbsolute: boolean;
hasTrailingSep: boolean;
}
// TODO: Maybe make this public somewhere if it can be fixed for Windows.
function split(path: string): SplitPath {
return {
segments: path
.replace(new RegExp(`^${SEP_PATTERN.source}|${SEP_PATTERN.source}$`), "")
.split(SEP_PATTERN),
isAbsolute: isAbsolute(path),
hasTrailingSep: !!path.match(new RegExp(`${SEP_PATTERN.source}$`))
};
}
/**
* Expand the glob string from the specified `root` directory and yield each
* result as a `WalkInfo` object.
*/
// TODO: Use a proper glob expansion algorithm.
// This is a very incomplete solution. The whole directory tree from `root` is
// walked and parent paths are not supported.
export async function* expandGlob(
globString: string,
{
root = cwd(),
exclude = [],
includeDirs = true,
extended = false,
globstar = false,
strict = false
}: ExpandGlobOptions = {}
): AsyncIterableIterator<WalkInfo> {
const resolveFromRoot = (path: string): string =>
isAbsolute(path) ? normalize(path) : join(root, path);
const globOptions: GlobOptions = { extended, globstar, strict };
const excludePatterns = exclude
.map(resolveFromRoot)
.map((s: string): RegExp => globToRegExp(s, globOptions));
const shouldInclude = ({ filename }: WalkInfo): boolean =>
!excludePatterns.some((p: RegExp): boolean => !!filename.match(p));
const { segments, hasTrailingSep } = split(resolveFromRoot(globString));
let fixedRoot = isWindows ? segments.shift()! : "/";
while (segments.length > 0 && !isGlob(segments[0])) {
fixedRoot = join(fixedRoot, segments.shift()!);
}
let fixedRootInfo: WalkInfo;
try {
fixedRootInfo = { filename: fixedRoot, info: await stat(fixedRoot) };
} catch {
return;
}
async function* advanceMatch(
walkInfo: WalkInfo,
globSegment: string
): AsyncIterableIterator<WalkInfo> {
if (!walkInfo.info.isDirectory()) {
return;
} else if (globSegment == "..") {
const parentPath = join(walkInfo.filename, "..");
try {
return yield* [
{ filename: parentPath, info: await stat(parentPath) }
].filter(shouldInclude);
} catch {
return;
}
} else if (globSegment == "**") {
return yield* walk(walkInfo.filename, {
includeFiles: false,
includeDirs: true,
skip: excludePatterns
});
}
yield* walk(walkInfo.filename, {
maxDepth: 1,
includeDirs: true,
match: [globToRegExp(join(walkInfo.filename, globSegment), globOptions)],
skip: excludePatterns
});
}
let currentMatches: WalkInfo[] = [fixedRootInfo];
for (const segment of segments) {
// Advancing the list of current matches may introduce duplicates, so we
// pass everything through this Map.
const nextMatchMap: Map<string, FileInfo> = new Map();
for (const currentMatch of currentMatches) {
for await (const nextMatch of advanceMatch(currentMatch, segment)) {
nextMatchMap.set(nextMatch.filename, nextMatch.info);
}
}
currentMatches = [...nextMatchMap].sort().map(
([filename, info]): WalkInfo => ({
filename,
info
})
);
}
if (hasTrailingSep) {
currentMatches = currentMatches.filter(({ info }): boolean =>
info.isDirectory()
);
}
if (!includeDirs) {
currentMatches = currentMatches.filter(
({ info }): boolean => !info.isDirectory()
);
}
yield* currentMatches;
}
/** Synchronous version of `expandGlob()`. */
// TODO: As `expandGlob()`.
export function* expandGlobSync(
globString: string,
{
root = cwd(),
exclude = [],
includeDirs = true,
extended = false,
globstar = false,
strict = false
}: ExpandGlobOptions = {}
): IterableIterator<WalkInfo> {
const resolveFromRoot = (path: string): string =>
isAbsolute(path) ? normalize(path) : join(root, path);
const globOptions: GlobOptions = { extended, globstar, strict };
const excludePatterns = exclude
.map(resolveFromRoot)
.map((s: string): RegExp => globToRegExp(s, globOptions));
const shouldInclude = ({ filename }: WalkInfo): boolean =>
!excludePatterns.some((p: RegExp): boolean => !!filename.match(p));
const { segments, hasTrailingSep } = split(resolveFromRoot(globString));
let fixedRoot = isWindows ? segments.shift()! : "/";
while (segments.length > 0 && !isGlob(segments[0])) {
fixedRoot = join(fixedRoot, segments.shift()!);
}
let fixedRootInfo: WalkInfo;
try {
fixedRootInfo = { filename: fixedRoot, info: statSync(fixedRoot) };
} catch {
return;
}
function* advanceMatch(
walkInfo: WalkInfo,
globSegment: string
): IterableIterator<WalkInfo> {
if (!walkInfo.info.isDirectory()) {
return;
} else if (globSegment == "..") {
const parentPath = join(walkInfo.filename, "..");
try {
return yield* [
{ filename: parentPath, info: statSync(parentPath) }
].filter(shouldInclude);
} catch {
return;
}
} else if (globSegment == "**") {
return yield* walkSync(walkInfo.filename, {
includeFiles: false,
includeDirs: true,
skip: excludePatterns
});
}
yield* walkSync(walkInfo.filename, {
maxDepth: 1,
includeDirs: true,
match: [globToRegExp(join(walkInfo.filename, globSegment), globOptions)],
skip: excludePatterns
});
}
let currentMatches: WalkInfo[] = [fixedRootInfo];
for (const segment of segments) {
// Advancing the list of current matches may introduce duplicates, so we
// pass everything through this Map.
const nextMatchMap: Map<string, FileInfo> = new Map();
for (const currentMatch of currentMatches) {
for (const nextMatch of advanceMatch(currentMatch, segment)) {
nextMatchMap.set(nextMatch.filename, nextMatch.info);
}
}
currentMatches = [...nextMatchMap].sort().map(
([filename, info]): WalkInfo => ({
filename,
info
})
);
}
if (hasTrailingSep) {
currentMatches = currentMatches.filter(({ info }): boolean =>
info.isDirectory()
);
}
if (!includeDirs) {
currentMatches = currentMatches.filter(
({ info }): boolean => !info.isDirectory()
);
}
yield* currentMatches;
}