-
-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathindex.js
More file actions
488 lines (385 loc) · 15.1 KB
/
index.js
File metadata and controls
488 lines (385 loc) · 15.1 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import process from 'node:process';
import fs from 'node:fs';
import nodePath from 'node:path';
import {Readable} from 'node:stream';
import mergeStreams from '@sindresorhus/merge-streams';
import fastGlob from 'fast-glob';
import {toPath} from 'unicorn-magic/node';
import {
GITIGNORE_FILES_PATTERN,
getIgnorePatternsAndPredicate,
getIgnorePatternsAndPredicateSync,
} from './ignore.js';
import {
bindFsMethod,
promisifyFsMethod,
isNegativePattern,
getStaticAbsolutePathPrefix,
normalizeNegativePattern,
normalizeDirectoryPatternForFastGlob,
adjustIgnorePatternsForParentDirectories,
convertPatternsForFastGlob,
} from './utilities.js';
const assertPatternsInput = patterns => {
if (patterns.some(pattern => typeof pattern !== 'string')) {
throw new TypeError('Patterns must be a string or an array of strings');
}
};
const getStatMethod = fsImplementation =>
bindFsMethod(fsImplementation?.promises, 'stat')
?? bindFsMethod(fs.promises, 'stat')
?? promisifyFsMethod(fsImplementation, 'stat');
const getStatSyncMethod = fsImplementation =>
bindFsMethod(fsImplementation, 'statSync')
?? bindFsMethod(fs, 'statSync');
const isDirectory = async (path, fsImplementation) => {
try {
const stats = await getStatMethod(fsImplementation)(path);
return stats.isDirectory();
} catch {
return false;
}
};
const isDirectorySync = (path, fsImplementation) => {
try {
const stats = getStatSyncMethod(fsImplementation)(path);
return stats.isDirectory();
} catch {
return false;
}
};
const normalizePathForDirectoryGlob = (filePath, cwd) => {
const path = isNegativePattern(filePath) ? filePath.slice(1) : filePath;
return nodePath.isAbsolute(path) ? path : nodePath.join(cwd, path);
};
const shouldExpandGlobstarDirectory = pattern => {
const match = pattern?.match(/\*\*\/([^/]+)$/);
if (!match) {
return false;
}
const dirname = match[1];
const hasWildcards = /[*?[\]{}]/.test(dirname);
const hasExtension = nodePath.extname(dirname) && !dirname.startsWith('.');
return !hasWildcards && !hasExtension;
};
const getDirectoryGlob = ({directoryPath, files, extensions}) => {
const extensionGlob = extensions?.length > 0 ? `.${extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]}` : '';
return files
? files.map(file => nodePath.posix.join(directoryPath, `**/${nodePath.extname(file) ? file : `${file}${extensionGlob}`}`))
: [nodePath.posix.join(directoryPath, `**${extensionGlob ? `/*${extensionGlob}` : ''}`)];
};
const directoryToGlob = async (directoryPaths, {
cwd = process.cwd(),
files,
extensions,
fs: fsImplementation,
} = {}) => {
const globs = await Promise.all(directoryPaths.map(async directoryPath => {
// Check pattern without negative prefix
const checkPattern = isNegativePattern(directoryPath) ? directoryPath.slice(1) : directoryPath;
// Expand globstar directory patterns like **/dirname to **/dirname/**
if (shouldExpandGlobstarDirectory(checkPattern)) {
return getDirectoryGlob({directoryPath, files, extensions});
}
// Original logic for checking actual directories
const pathToCheck = normalizePathForDirectoryGlob(directoryPath, cwd);
return (await isDirectory(pathToCheck, fsImplementation)) ? getDirectoryGlob({directoryPath, files, extensions}) : directoryPath;
}));
return globs.flat();
};
const directoryToGlobSync = (directoryPaths, {
cwd = process.cwd(),
files,
extensions,
fs: fsImplementation,
} = {}) => directoryPaths.flatMap(directoryPath => {
// Check pattern without negative prefix
const checkPattern = isNegativePattern(directoryPath) ? directoryPath.slice(1) : directoryPath;
// Expand globstar directory patterns like **/dirname to **/dirname/**
if (shouldExpandGlobstarDirectory(checkPattern)) {
return getDirectoryGlob({directoryPath, files, extensions});
}
// Original logic for checking actual directories
const pathToCheck = normalizePathForDirectoryGlob(directoryPath, cwd);
return isDirectorySync(pathToCheck, fsImplementation) ? getDirectoryGlob({directoryPath, files, extensions}) : directoryPath;
});
const toPatternsArray = patterns => {
patterns = [...new Set([patterns].flat())];
assertPatternsInput(patterns);
return patterns;
};
const checkCwdOption = (cwd, fsImplementation = fs) => {
if (!cwd || !fsImplementation.statSync) {
return;
}
let stats;
try {
stats = fsImplementation.statSync(cwd);
} catch {
// If stat fails (e.g., path doesn't exist), let fast-glob handle it
return;
}
if (!stats.isDirectory()) {
throw new Error(`The \`cwd\` option must be a path to a directory, got: ${cwd}`);
}
};
const normalizeOptions = (options = {}) => {
// Normalize ignore to an array (fast-glob accepts string but we need array internally)
const ignore = options.ignore
? (Array.isArray(options.ignore) ? options.ignore : [options.ignore])
: [];
options = {
...options,
ignore,
expandDirectories: options.expandDirectories ?? true,
cwd: toPath(options.cwd),
};
checkCwdOption(options.cwd, options.fs);
return options;
};
const normalizeArguments = function_ => async (patterns, options) => function_(toPatternsArray(patterns), normalizeOptions(options));
const normalizeArgumentsSync = function_ => (patterns, options) => function_(toPatternsArray(patterns), normalizeOptions(options));
const getIgnoreFilesPatterns = options => {
const {ignoreFiles, gitignore} = options;
const patterns = ignoreFiles ? toPatternsArray(ignoreFiles) : [];
if (gitignore) {
patterns.push(GITIGNORE_FILES_PATTERN);
}
return patterns;
};
/**
Apply gitignore patterns to options and return filter predicate.
When negation patterns are present (e.g., '!important.log'), we cannot pass positive patterns to fast-glob because it would filter out files before our predicate can re-include them. In this case, we rely entirely on the predicate for filtering, which handles negations correctly.
When there are no negations, we optimize by passing patterns to fast-glob's ignore option to skip directories during traversal (performance optimization).
All patterns (including negated) are always used in the filter predicate to ensure correct Git-compatible behavior.
@returns {Promise<{options: Object, filter: Function}>}
*/
const applyIgnoreFilesAndGetFilter = async options => {
const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
if (ignoreFilesPatterns.length === 0) {
return {
options,
filter: createFilterFunction(false, options.cwd),
};
}
// Read ignore files once and get both patterns and predicate
// Enable parent .gitignore search when using gitignore option
const includeParentIgnoreFiles = options.gitignore === true;
const {patterns, predicate, usingGitRoot} = await getIgnorePatternsAndPredicate(ignoreFilesPatterns, options, includeParentIgnoreFiles);
// Convert patterns to fast-glob format (may return empty array if predicate should handle everything)
const patternsForFastGlob = convertPatternsForFastGlob(patterns, usingGitRoot, normalizeDirectoryPatternForFastGlob);
const modifiedOptions = {
...options,
ignore: [...options.ignore, ...patternsForFastGlob],
};
return {
options: modifiedOptions,
filter: createFilterFunction(predicate, options.cwd),
};
};
/**
Apply gitignore patterns to options and return filter predicate (sync version).
@returns {{options: Object, filter: Function}}
*/
const applyIgnoreFilesAndGetFilterSync = options => {
const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
if (ignoreFilesPatterns.length === 0) {
return {
options,
filter: createFilterFunction(false, options.cwd),
};
}
// Read ignore files once and get both patterns and predicate
// Enable parent .gitignore search when using gitignore option
const includeParentIgnoreFiles = options.gitignore === true;
const {patterns, predicate, usingGitRoot} = getIgnorePatternsAndPredicateSync(ignoreFilesPatterns, options, includeParentIgnoreFiles);
// Convert patterns to fast-glob format (may return empty array if predicate should handle everything)
const patternsForFastGlob = convertPatternsForFastGlob(patterns, usingGitRoot, normalizeDirectoryPatternForFastGlob);
const modifiedOptions = {
...options,
ignore: [...options.ignore, ...patternsForFastGlob],
};
return {
options: modifiedOptions,
filter: createFilterFunction(predicate, options.cwd),
};
};
const createFilterFunction = (isIgnored, cwd) => {
const seen = new Set();
const basePath = cwd || process.cwd();
const pathCache = new Map(); // Cache for resolved paths
return fastGlobResult => {
const pathKey = nodePath.normalize(fastGlobResult.path ?? fastGlobResult);
// Check seen set first (fast path)
if (seen.has(pathKey)) {
return false;
}
// Only compute absolute path and check predicate if needed
if (isIgnored) {
let absolutePath = pathCache.get(pathKey);
if (absolutePath === undefined) {
absolutePath = nodePath.isAbsolute(pathKey) ? pathKey : nodePath.resolve(basePath, pathKey);
pathCache.set(pathKey, absolutePath);
// Only clear path cache if it gets too large
// Never clear 'seen' as it's needed for deduplication
if (pathCache.size > 10_000) {
pathCache.clear();
}
}
if (isIgnored(absolutePath)) {
return false;
}
}
seen.add(pathKey);
return true;
};
};
const unionFastGlobResults = (results, filter) => results.flat().filter(fastGlobResult => filter(fastGlobResult));
const convertNegativePatterns = (patterns, options) => {
// If all patterns are negative and expandNegationOnlyPatterns is enabled (default),
// prepend a positive catch-all pattern to make negation-only patterns work intuitively
// (e.g., '!*.json' matches all files except JSON)
if (patterns.length > 0 && patterns.every(pattern => isNegativePattern(pattern))) {
if (options.expandNegationOnlyPatterns === false) {
return [];
}
patterns = ['**/*', ...patterns];
}
const positiveAbsolutePathPrefixes = [];
let hasRelativePositivePattern = false;
const normalizedPatterns = [];
for (const pattern of patterns) {
if (isNegativePattern(pattern)) {
normalizedPatterns.push(`!${normalizeNegativePattern(pattern.slice(1), positiveAbsolutePathPrefixes, hasRelativePositivePattern)}`);
continue;
}
normalizedPatterns.push(pattern);
const staticAbsolutePathPrefix = getStaticAbsolutePathPrefix(pattern);
if (staticAbsolutePathPrefix === undefined) {
hasRelativePositivePattern = true;
continue;
}
positiveAbsolutePathPrefixes.push(staticAbsolutePathPrefix);
}
patterns = normalizedPatterns;
const tasks = [];
while (patterns.length > 0) {
const index = patterns.findIndex(pattern => isNegativePattern(pattern));
if (index === -1) {
tasks.push({patterns, options});
break;
}
const ignorePattern = patterns[index].slice(1);
for (const task of tasks) {
task.options.ignore.push(ignorePattern);
}
if (index !== 0) {
tasks.push({
patterns: patterns.slice(0, index),
options: {
...options,
ignore: [
...options.ignore,
ignorePattern,
],
},
});
}
patterns = patterns.slice(index + 1);
}
return tasks;
};
const applyParentDirectoryIgnoreAdjustments = tasks => tasks.map(task => ({
patterns: task.patterns,
options: {
...task.options,
ignore: adjustIgnorePatternsForParentDirectories(task.patterns, task.options.ignore),
},
}));
const normalizeExpandDirectoriesOption = (options, cwd) => ({
...(cwd ? {cwd} : {}),
...(Array.isArray(options) ? {files: options} : options),
});
const generateTasks = async (patterns, options) => {
const globTasks = convertNegativePatterns(patterns, options);
const {cwd, expandDirectories, fs: fsImplementation} = options;
if (!expandDirectories) {
return applyParentDirectoryIgnoreAdjustments(globTasks);
}
const directoryToGlobOptions = {
...normalizeExpandDirectoriesOption(expandDirectories, cwd),
fs: fsImplementation,
};
return Promise.all(globTasks.map(async task => {
let {patterns, options} = task;
[
patterns,
options.ignore,
] = await Promise.all([
directoryToGlob(patterns, directoryToGlobOptions),
directoryToGlob(options.ignore, {cwd, fs: fsImplementation}),
]);
// Adjust ignore patterns for parent directory references
options.ignore = adjustIgnorePatternsForParentDirectories(patterns, options.ignore);
return {patterns, options};
}));
};
const generateTasksSync = (patterns, options) => {
const globTasks = convertNegativePatterns(patterns, options);
const {cwd, expandDirectories, fs: fsImplementation} = options;
if (!expandDirectories) {
return applyParentDirectoryIgnoreAdjustments(globTasks);
}
const directoryToGlobSyncOptions = {
...normalizeExpandDirectoriesOption(expandDirectories, cwd),
fs: fsImplementation,
};
return globTasks.map(task => {
let {patterns, options} = task;
patterns = directoryToGlobSync(patterns, directoryToGlobSyncOptions);
options.ignore = directoryToGlobSync(options.ignore, {cwd, fs: fsImplementation});
// Adjust ignore patterns for parent directory references
options.ignore = adjustIgnorePatternsForParentDirectories(patterns, options.ignore);
return {patterns, options};
});
};
export const globby = normalizeArguments(async (patterns, options) => {
// Apply ignore files and get filter (reads .gitignore files once)
const {options: modifiedOptions, filter} = await applyIgnoreFilesAndGetFilter(options);
// Generate tasks with modified options (includes gitignore patterns in ignore option)
const tasks = await generateTasks(patterns, modifiedOptions);
const results = await Promise.all(tasks.map(task => fastGlob(task.patterns, task.options)));
return unionFastGlobResults(results, filter);
});
export const globbySync = normalizeArgumentsSync((patterns, options) => {
// Apply ignore files and get filter (reads .gitignore files once)
const {options: modifiedOptions, filter} = applyIgnoreFilesAndGetFilterSync(options);
// Generate tasks with modified options (includes gitignore patterns in ignore option)
const tasks = generateTasksSync(patterns, modifiedOptions);
const results = tasks.map(task => fastGlob.sync(task.patterns, task.options));
return unionFastGlobResults(results, filter);
});
export const globbyStream = normalizeArgumentsSync((patterns, options) => {
// Apply ignore files and get filter (reads .gitignore files once)
const {options: modifiedOptions, filter} = applyIgnoreFilesAndGetFilterSync(options);
// Generate tasks with modified options (includes gitignore patterns in ignore option)
const tasks = generateTasksSync(patterns, modifiedOptions);
const streams = tasks.map(task => fastGlob.stream(task.patterns, task.options));
if (streams.length === 0) {
return Readable.from([]);
}
const stream = mergeStreams(streams).filter(fastGlobResult => filter(fastGlobResult));
// Returning a web stream will require revisiting once Readable.toWeb integration is viable.
// return Readable.toWeb(stream);
return stream;
});
export const isDynamicPattern = normalizeArgumentsSync((patterns, options) => patterns.some(pattern => fastGlob.isDynamicPattern(pattern, options)));
export const generateGlobTasks = normalizeArguments(generateTasks);
export const generateGlobTasksSync = normalizeArgumentsSync(generateTasksSync);
export {
isGitIgnored,
isGitIgnoredSync,
isIgnoredByIgnoreFiles,
isIgnoredByIgnoreFilesSync,
} from './ignore.js';
export const {convertPathToPattern} = fastGlob;