@cjser/globby 16.2.0-cjser.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-cjser/index.cjs +1349 -0
- package/ignore.js +868 -0
- package/index.d.ts +413 -0
- package/index.js +680 -0
- package/license +9 -0
- package/package.json +132 -0
- package/readme.md +406 -0
- package/utilities.js +382 -0
package/ignore.js
ADDED
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
import process from 'node:process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import fsPromises from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import fastGlob from 'fast-glob';
|
|
7
|
+
import gitIgnore from 'ignore';
|
|
8
|
+
import isPathInside from '@cjser/is-path-inside';
|
|
9
|
+
import slash from '@cjser/slash';
|
|
10
|
+
import {toPath} from '@cjser/unicorn-magic/node';
|
|
11
|
+
import {
|
|
12
|
+
isNegativePattern,
|
|
13
|
+
bindFsMethod,
|
|
14
|
+
promisifyFsMethod,
|
|
15
|
+
findGitRoot,
|
|
16
|
+
findGitRootSync,
|
|
17
|
+
getParentGitignorePaths,
|
|
18
|
+
} from './utilities.js';
|
|
19
|
+
|
|
20
|
+
const defaultIgnoredDirectories = [
|
|
21
|
+
'**/node_modules',
|
|
22
|
+
'**/flow-typed',
|
|
23
|
+
'**/coverage',
|
|
24
|
+
'**/.git',
|
|
25
|
+
];
|
|
26
|
+
const ignoreFilesGlobOptions = {
|
|
27
|
+
absolute: true,
|
|
28
|
+
dot: true,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const GITIGNORE_FILES_PATTERN = '**/.gitignore';
|
|
32
|
+
|
|
33
|
+
// Maximum depth for [include] chains to prevent stack overflow (git uses 10)
|
|
34
|
+
const MAX_INCLUDE_DEPTH = 10;
|
|
35
|
+
|
|
36
|
+
const getReadFileMethod = fsImplementation =>
|
|
37
|
+
bindFsMethod(fsImplementation?.promises, 'readFile')
|
|
38
|
+
?? bindFsMethod(fsPromises, 'readFile')
|
|
39
|
+
?? promisifyFsMethod(fsImplementation, 'readFile');
|
|
40
|
+
|
|
41
|
+
const getReadFileSyncMethod = fsImplementation =>
|
|
42
|
+
bindFsMethod(fsImplementation, 'readFileSync')
|
|
43
|
+
?? bindFsMethod(fs, 'readFileSync');
|
|
44
|
+
|
|
45
|
+
const shouldSkipIgnoreFileError = (error, suppressErrors) => {
|
|
46
|
+
if (!error) {
|
|
47
|
+
return Boolean(suppressErrors);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return Boolean(suppressErrors);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const createReadError = (kind, filePath, error) => {
|
|
58
|
+
const prefix = `Failed to read ${kind} at ${filePath}`;
|
|
59
|
+
if (error instanceof Error) {
|
|
60
|
+
return new Error(`${prefix}: ${error.message}`, {cause: error});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return new Error(`${prefix}: ${String(error)}`);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const createIgnoreFileReadError = (filePath, error) => createReadError('ignore file', filePath, error);
|
|
67
|
+
const createGitConfigReadError = (filePath, error) => createReadError('git config', filePath, error);
|
|
68
|
+
|
|
69
|
+
const processIgnoreFileCore = (filePath, readMethod, suppressErrors) => {
|
|
70
|
+
try {
|
|
71
|
+
const content = readMethod(filePath, 'utf8');
|
|
72
|
+
return {filePath, content};
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
throw createIgnoreFileReadError(filePath, error);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const readIgnoreFilesSafely = async (paths, readFileMethod, suppressErrors) => {
|
|
83
|
+
const fileResults = await Promise.all(paths.map(async filePath => {
|
|
84
|
+
try {
|
|
85
|
+
const content = await readFileMethod(filePath, 'utf8');
|
|
86
|
+
return {filePath, content};
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
throw createIgnoreFileReadError(filePath, error);
|
|
93
|
+
}
|
|
94
|
+
}));
|
|
95
|
+
|
|
96
|
+
return fileResults.filter(Boolean);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const readIgnoreFilesSafelySync = (paths, readFileSyncMethod, suppressErrors) => paths
|
|
100
|
+
.map(filePath => processIgnoreFileCore(filePath, readFileSyncMethod, suppressErrors))
|
|
101
|
+
.filter(Boolean);
|
|
102
|
+
|
|
103
|
+
const dedupePaths = paths => {
|
|
104
|
+
const seen = new Set();
|
|
105
|
+
return paths.filter(filePath => {
|
|
106
|
+
if (seen.has(filePath)) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
seen.add(filePath);
|
|
111
|
+
return true;
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const globIgnoreFiles = (globFunction, patterns, normalizedOptions) => globFunction(patterns, {
|
|
116
|
+
...normalizedOptions,
|
|
117
|
+
...ignoreFilesGlobOptions, // Must be last to ensure absolute/dot flags stick
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const getParentIgnorePaths = (gitRoot, normalizedOptions) => gitRoot
|
|
121
|
+
? getParentGitignorePaths(gitRoot, normalizedOptions.cwd)
|
|
122
|
+
: [];
|
|
123
|
+
|
|
124
|
+
const combineIgnoreFilePaths = (gitRoot, normalizedOptions, childPaths) => dedupePaths([
|
|
125
|
+
...getParentIgnorePaths(gitRoot, normalizedOptions),
|
|
126
|
+
...childPaths,
|
|
127
|
+
]);
|
|
128
|
+
|
|
129
|
+
const buildIgnoreResult = (files, normalizedOptions, gitRoot) => {
|
|
130
|
+
const baseDir = gitRoot || normalizedOptions.cwd;
|
|
131
|
+
const patterns = getPatternsFromIgnoreFiles(files, baseDir);
|
|
132
|
+
const matcher = createIgnoreMatcher(patterns, normalizedOptions.cwd, baseDir);
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
patterns,
|
|
136
|
+
matcher,
|
|
137
|
+
predicate: fileOrDirectory => matcher(fileOrDirectory).ignored,
|
|
138
|
+
usingGitRoot: Boolean(gitRoot && gitRoot !== normalizedOptions.cwd),
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// Apply base path to gitignore patterns based on .gitignore spec 2.22.1
|
|
143
|
+
// https://git-scm.com/docs/gitignore#_pattern_format
|
|
144
|
+
// See also https://github.com/sindresorhus/globby/issues/146
|
|
145
|
+
const applyBaseToPattern = (pattern, base) => {
|
|
146
|
+
if (!base) {
|
|
147
|
+
return pattern;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const isNegative = isNegativePattern(pattern);
|
|
151
|
+
const cleanPattern = isNegative ? pattern.slice(1) : pattern;
|
|
152
|
+
|
|
153
|
+
// Check if pattern has non-trailing slashes
|
|
154
|
+
const slashIndex = cleanPattern.indexOf('/');
|
|
155
|
+
const hasNonTrailingSlash = slashIndex !== -1 && slashIndex !== cleanPattern.length - 1;
|
|
156
|
+
|
|
157
|
+
let result;
|
|
158
|
+
if (!hasNonTrailingSlash) {
|
|
159
|
+
// "If there is no separator at the beginning or middle of the pattern,
|
|
160
|
+
// then the pattern may also match at any level below the .gitignore level."
|
|
161
|
+
// So patterns like '*.log' or 'temp' or 'build/' (trailing slash) match recursively.
|
|
162
|
+
result = path.posix.join(base, '**', cleanPattern);
|
|
163
|
+
} else if (cleanPattern.startsWith('/')) {
|
|
164
|
+
// "If there is a separator at the beginning [...] of the pattern,
|
|
165
|
+
// then the pattern is relative to the directory level of the particular .gitignore file itself."
|
|
166
|
+
// Leading slash anchors the pattern to the .gitignore's directory.
|
|
167
|
+
result = path.posix.join(base, cleanPattern.slice(1));
|
|
168
|
+
} else {
|
|
169
|
+
// "If there is a separator [...] middle [...] of the pattern,
|
|
170
|
+
// then the pattern is relative to the directory level of the particular .gitignore file itself."
|
|
171
|
+
// Patterns like 'src/foo' are relative to the .gitignore's directory.
|
|
172
|
+
result = path.posix.join(base, cleanPattern);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return isNegative ? '!' + result : result;
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const parseIgnoreFile = (file, cwd) => {
|
|
179
|
+
const base = slash(path.relative(cwd, path.dirname(file.filePath)));
|
|
180
|
+
|
|
181
|
+
return file.content
|
|
182
|
+
.split(/\r?\n/)
|
|
183
|
+
.filter(line => line && !line.startsWith('#'))
|
|
184
|
+
.map(pattern => applyBaseToPattern(pattern, base));
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const toRelativePath = (fileOrDirectory, cwd) => {
|
|
188
|
+
if (path.isAbsolute(fileOrDirectory)) {
|
|
189
|
+
// When paths are equal, path.relative returns empty string which is valid
|
|
190
|
+
// isPathInside returns false for equal paths, so check this case first
|
|
191
|
+
const relativePath = path.relative(cwd, fileOrDirectory);
|
|
192
|
+
if (relativePath && !isPathInside(fileOrDirectory, cwd)) {
|
|
193
|
+
// Path is outside cwd - it cannot be ignored by patterns in cwd
|
|
194
|
+
// Return undefined to indicate this path is outside scope
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return relativePath;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Normalize relative paths:
|
|
202
|
+
// - Git treats './foo' as 'foo' when checking against patterns
|
|
203
|
+
// - Patterns starting with './' in .gitignore are invalid and don't match anything
|
|
204
|
+
// - The ignore library expects normalized paths without './' prefix
|
|
205
|
+
if (fileOrDirectory.startsWith('./')) {
|
|
206
|
+
return fileOrDirectory.slice(2);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Paths with ../ point outside cwd and cannot match patterns from this directory
|
|
210
|
+
// Return undefined to indicate this path is outside scope
|
|
211
|
+
if (fileOrDirectory.startsWith('../')) {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return fileOrDirectory;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const notIgnored = {ignored: false, unignored: false};
|
|
219
|
+
|
|
220
|
+
const createIgnoreMatcher = (patterns, cwd, baseDir) => {
|
|
221
|
+
const ignores = gitIgnore().add(patterns);
|
|
222
|
+
// Normalize to handle path separator and . / .. components consistently
|
|
223
|
+
const resolvedCwd = path.normalize(path.resolve(cwd));
|
|
224
|
+
const resolvedBaseDir = path.normalize(path.resolve(baseDir));
|
|
225
|
+
|
|
226
|
+
return fileOrDirectory => {
|
|
227
|
+
fileOrDirectory = toPath(fileOrDirectory);
|
|
228
|
+
const hasTrailingSeparator = /[/\\]$/.test(fileOrDirectory);
|
|
229
|
+
|
|
230
|
+
// Never ignore the cwd itself - use normalized comparison
|
|
231
|
+
const normalizedPath = path.normalize(path.resolve(fileOrDirectory));
|
|
232
|
+
if (normalizedPath === resolvedCwd) {
|
|
233
|
+
return notIgnored;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Convert to relative path from baseDir (use normalized baseDir)
|
|
237
|
+
let relativePath = toRelativePath(fileOrDirectory, resolvedBaseDir);
|
|
238
|
+
|
|
239
|
+
// If path is outside baseDir (undefined), it can't be ignored by patterns
|
|
240
|
+
if (relativePath === undefined) {
|
|
241
|
+
return notIgnored;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (!relativePath) {
|
|
245
|
+
return notIgnored;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (hasTrailingSeparator && !relativePath.endsWith(path.sep)) {
|
|
249
|
+
relativePath += path.sep;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return ignores.test(slash(relativePath));
|
|
253
|
+
};
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const normalizeOptions = (options = {}) => {
|
|
257
|
+
const ignoreOption = options.ignore
|
|
258
|
+
? (Array.isArray(options.ignore) ? options.ignore : [options.ignore])
|
|
259
|
+
: [];
|
|
260
|
+
|
|
261
|
+
const cwd = toPath(options.cwd) ?? process.cwd();
|
|
262
|
+
|
|
263
|
+
// Adjust deep option for fast-glob: fast-glob's deep counts differently than expected
|
|
264
|
+
// User's deep: 0 = root only -> fast-glob needs: 1
|
|
265
|
+
// User's deep: 1 = root + 1 level -> fast-glob needs: 2
|
|
266
|
+
const deep = typeof options.deep === 'number' ? Math.max(0, options.deep) + 1 : Number.POSITIVE_INFINITY;
|
|
267
|
+
|
|
268
|
+
// Only pass through specific fast-glob options that make sense for finding ignore files
|
|
269
|
+
return {
|
|
270
|
+
cwd,
|
|
271
|
+
suppressErrors: options.suppressErrors ?? false,
|
|
272
|
+
deep,
|
|
273
|
+
ignore: [...ignoreOption, ...defaultIgnoredDirectories],
|
|
274
|
+
followSymbolicLinks: options.followSymbolicLinks ?? true,
|
|
275
|
+
concurrency: options.concurrency,
|
|
276
|
+
throwErrorOnBrokenSymbolicLink: options.throwErrorOnBrokenSymbolicLink ?? false,
|
|
277
|
+
fs: options.fs,
|
|
278
|
+
};
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const unescapeGitQuotedValue = value => value.replaceAll(/\\(["\\abfnrtv])/g, (_match, escapedCharacter) => {
|
|
282
|
+
switch (escapedCharacter) {
|
|
283
|
+
case 'a': {
|
|
284
|
+
return '\u0007';
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
case 'b': {
|
|
288
|
+
return '\b';
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
case 'f': {
|
|
292
|
+
return '\f';
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
case 'n': {
|
|
296
|
+
return '\n';
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
case 'r': {
|
|
300
|
+
return '\r';
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
case 't': {
|
|
304
|
+
return '\t';
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
case 'v': {
|
|
308
|
+
return '\v';
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
default: {
|
|
312
|
+
return escapedCharacter;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
const parseGitConfigValue = value => {
|
|
318
|
+
const trimmedValue = value.trim();
|
|
319
|
+
const quotedMatch = trimmedValue.match(/^"((?:[^"\\]|\\.)*)"\s*(?:[#;].*)?$/);
|
|
320
|
+
|
|
321
|
+
if (quotedMatch) {
|
|
322
|
+
return unescapeGitQuotedValue(quotedMatch[1]);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return trimmedValue.replace(/\s[#;].*$/, '').trim();
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const resolveConfigPath = (filePath, configPath) => {
|
|
329
|
+
if (configPath.startsWith('~/')) {
|
|
330
|
+
const homeDirectory = os.homedir();
|
|
331
|
+
const resolved = path.join(homeDirectory, configPath.slice(2));
|
|
332
|
+
// Ensure the resolved path is within the home directory to prevent traversal via ~/..
|
|
333
|
+
if (!isPathInside(resolved, homeDirectory)) {
|
|
334
|
+
// Invalid path, return a path that won't exist
|
|
335
|
+
return path.join(homeDirectory, '.globby-invalid-path-traversal');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return resolved;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (path.isAbsolute(configPath)) {
|
|
342
|
+
return configPath;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return path.resolve(path.dirname(filePath), configPath);
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const parseGitConfigSection = line => {
|
|
349
|
+
if (!line.startsWith('[')) {
|
|
350
|
+
return undefined;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
let inQuotes = false;
|
|
354
|
+
let isEscaped = false;
|
|
355
|
+
|
|
356
|
+
for (let index = 1; index < line.length; index++) {
|
|
357
|
+
const character = line[index];
|
|
358
|
+
|
|
359
|
+
if (isEscaped) {
|
|
360
|
+
isEscaped = false;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (character === '\\') {
|
|
365
|
+
isEscaped = true;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (character === '"') {
|
|
370
|
+
inQuotes = !inQuotes;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (character === ']' && !inQuotes) {
|
|
375
|
+
const remainder = line.slice(index + 1).trimStart();
|
|
376
|
+
if (remainder && !remainder.startsWith('#') && !remainder.startsWith(';')) {
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return line.slice(1, index).trim();
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
return undefined;
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const parseGitConfigEntry = line => {
|
|
388
|
+
const match = line.match(/^([A-Za-z\d-.]+)\s*=\s*(.*)$/);
|
|
389
|
+
|
|
390
|
+
if (!match) {
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
key: match[1].toLowerCase(),
|
|
396
|
+
value: parseGitConfigValue(match[2]),
|
|
397
|
+
};
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
const parseIncludeIfCondition = section => {
|
|
401
|
+
if (!section) {
|
|
402
|
+
return undefined;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const match = section.match(/^includeif\s+"([^"]+)"$/i);
|
|
406
|
+
return match ? match[1] : undefined;
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
const normalizeGitConfigConditionPattern = (pattern, configFilePath) => {
|
|
410
|
+
if (pattern.startsWith('~/')) {
|
|
411
|
+
pattern = path.join(os.homedir(), pattern.slice(2));
|
|
412
|
+
} else if (pattern.startsWith('./')) {
|
|
413
|
+
pattern = path.resolve(path.dirname(configFilePath), pattern.slice(2));
|
|
414
|
+
} else if (!path.isAbsolute(pattern)) {
|
|
415
|
+
pattern = `**/${pattern}`;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (pattern.endsWith('/')) {
|
|
419
|
+
pattern += '**';
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
return slash(pattern);
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
const gitConfigGlobToRegex = (pattern, flags) => {
|
|
426
|
+
let regex = '';
|
|
427
|
+
|
|
428
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
429
|
+
const character = pattern[index];
|
|
430
|
+
const nextCharacter = pattern[index + 1];
|
|
431
|
+
const nextNextCharacter = pattern[index + 2];
|
|
432
|
+
|
|
433
|
+
if (character === '*' && nextCharacter === '*' && nextNextCharacter === '/') {
|
|
434
|
+
regex += '(?:.*/)?';
|
|
435
|
+
index += 2;
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (character === '*' && nextCharacter === '*') {
|
|
440
|
+
regex += '.*';
|
|
441
|
+
index += 1;
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
if (character === '*') {
|
|
446
|
+
regex += '[^/]*';
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (character === '?') {
|
|
451
|
+
regex += '[^/]';
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (character === '[') {
|
|
456
|
+
const closingBracketIndex = pattern.indexOf(']', index + 1);
|
|
457
|
+
if (closingBracketIndex !== -1) {
|
|
458
|
+
const bracketContent = pattern.slice(index + 1, closingBracketIndex);
|
|
459
|
+
if (bracketContent) {
|
|
460
|
+
const negatedBracketContent = bracketContent[0] === '!' ? `^${bracketContent.slice(1)}` : bracketContent;
|
|
461
|
+
regex += `[${negatedBracketContent}]`;
|
|
462
|
+
index = closingBracketIndex;
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
regex += /[|\\{}()[\]^$+?.]/.test(character) ? `\\${character}` : character;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
try {
|
|
472
|
+
return new RegExp(`^${regex}$`, flags);
|
|
473
|
+
} catch {
|
|
474
|
+
// If regex construction fails (e.g., invalid bracket expression), return a non-matching pattern
|
|
475
|
+
return /(?!)/;
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const matchesIncludeIfCondition = (condition, gitDirectory, configFilePath) => {
|
|
480
|
+
if (!gitDirectory) {
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const match = condition.match(/^(gitdir|gitdir\/i):(.*)$/i);
|
|
485
|
+
if (!match) {
|
|
486
|
+
return false;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const [, keyword, rawPattern] = match;
|
|
490
|
+
const pattern = normalizeGitConfigConditionPattern(rawPattern.trim(), configFilePath);
|
|
491
|
+
const isCaseInsensitive = keyword.toLowerCase() === 'gitdir/i';
|
|
492
|
+
const regularExpression = gitConfigGlobToRegex(pattern, isCaseInsensitive ? 'i' : undefined);
|
|
493
|
+
const normalizedGitDirectory = slash(path.resolve(gitDirectory));
|
|
494
|
+
|
|
495
|
+
return regularExpression.test(normalizedGitDirectory);
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
const shouldIncludeConfigSection = (section, gitDirectory, configFilePath) => {
|
|
499
|
+
if (section?.toLowerCase() === 'include') {
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// `globalGitignore` intentionally keeps `includeIf` support narrow.
|
|
504
|
+
// Only `gitdir:` and `gitdir/i:` conditions are treated as active here.
|
|
505
|
+
// Other Git predicates such as `onbranch:` are outside this feature's
|
|
506
|
+
// supported boundary and are documented as unsupported.
|
|
507
|
+
const condition = parseIncludeIfCondition(section);
|
|
508
|
+
return condition ? matchesIncludeIfCondition(condition, gitDirectory, configFilePath) : false;
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
const createExcludesFileValue = (value, declaringFilePath) => ({
|
|
512
|
+
value,
|
|
513
|
+
declaringFilePath,
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
Parse git config content and return the excludesFile value and any include paths to recurse into.
|
|
518
|
+
The caller is responsible for reading files and recursing (sync or async).
|
|
519
|
+
*/
|
|
520
|
+
const parseGitConfigForExcludesFile = (content, normalizedPath, gitDirectory) => {
|
|
521
|
+
let currentSection;
|
|
522
|
+
let excludesFile;
|
|
523
|
+
const includePaths = [];
|
|
524
|
+
|
|
525
|
+
for (const line of content.split(/\r?\n/)) {
|
|
526
|
+
const trimmed = line.trim();
|
|
527
|
+
|
|
528
|
+
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith(';')) {
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (trimmed.startsWith('[')) {
|
|
533
|
+
currentSection = parseGitConfigSection(trimmed);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const entry = parseGitConfigEntry(trimmed);
|
|
538
|
+
if (!entry) {
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (currentSection?.toLowerCase() === 'core' && entry.key === 'excludesfile') {
|
|
543
|
+
excludesFile = createExcludesFileValue(entry.value, normalizedPath);
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
if (shouldIncludeConfigSection(currentSection, gitDirectory, normalizedPath) && entry.key === 'path' && entry.value) {
|
|
548
|
+
includePaths.push(resolveConfigPath(normalizedPath, entry.value));
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
return {excludesFile, includePaths};
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
const readGitConfigFile = (normalizedPath, readMethod, suppressErrors) => {
|
|
556
|
+
try {
|
|
557
|
+
return readMethod(normalizedPath, 'utf8');
|
|
558
|
+
} catch (error) {
|
|
559
|
+
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
|
|
560
|
+
return undefined;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
throw createGitConfigReadError(normalizedPath, error);
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
const getExcludesFileFromGitConfigSync = (filePath, readFileSync, gitDirectory, options = {}) => {
|
|
568
|
+
const {suppressErrors, includeStack = new Set(), depth = 0} = options;
|
|
569
|
+
const normalizedPath = path.resolve(filePath);
|
|
570
|
+
|
|
571
|
+
if (includeStack.has(normalizedPath)) {
|
|
572
|
+
return undefined;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (depth >= MAX_INCLUDE_DEPTH) {
|
|
576
|
+
return undefined;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
includeStack.add(normalizedPath);
|
|
580
|
+
|
|
581
|
+
const content = readGitConfigFile(normalizedPath, readFileSync, suppressErrors);
|
|
582
|
+
if (content === undefined) {
|
|
583
|
+
includeStack.delete(normalizedPath);
|
|
584
|
+
return undefined;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let {excludesFile, includePaths} = parseGitConfigForExcludesFile(content, normalizedPath, gitDirectory);
|
|
588
|
+
|
|
589
|
+
for (const includePath of includePaths) {
|
|
590
|
+
const includedExcludesFile = getExcludesFileFromGitConfigSync(includePath, readFileSync, gitDirectory, {suppressErrors, includeStack, depth: depth + 1});
|
|
591
|
+
if (includedExcludesFile !== undefined) {
|
|
592
|
+
excludesFile = includedExcludesFile;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
includeStack.delete(normalizedPath);
|
|
597
|
+
return excludesFile;
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
const getExcludesFileFromGitConfigAsync = async (filePath, readFile, gitDirectory, options = {}) => {
|
|
601
|
+
const {suppressErrors, includeStack = new Set(), depth = 0} = options;
|
|
602
|
+
const normalizedPath = path.resolve(filePath);
|
|
603
|
+
|
|
604
|
+
if (includeStack.has(normalizedPath)) {
|
|
605
|
+
return undefined;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (depth >= MAX_INCLUDE_DEPTH) {
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
includeStack.add(normalizedPath);
|
|
613
|
+
|
|
614
|
+
let content;
|
|
615
|
+
try {
|
|
616
|
+
content = await readFile(normalizedPath, 'utf8');
|
|
617
|
+
} catch (error) {
|
|
618
|
+
includeStack.delete(normalizedPath);
|
|
619
|
+
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
|
|
620
|
+
return undefined;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
throw createGitConfigReadError(normalizedPath, error);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
let {excludesFile, includePaths} = parseGitConfigForExcludesFile(content, normalizedPath, gitDirectory);
|
|
627
|
+
|
|
628
|
+
for (const includePath of includePaths) {
|
|
629
|
+
// eslint-disable-next-line no-await-in-loop
|
|
630
|
+
const includedExcludesFile = await getExcludesFileFromGitConfigAsync(includePath, readFile, gitDirectory, {suppressErrors, includeStack, depth: depth + 1});
|
|
631
|
+
if (includedExcludesFile !== undefined) {
|
|
632
|
+
excludesFile = includedExcludesFile;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
includeStack.delete(normalizedPath);
|
|
637
|
+
return excludesFile;
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
const resolveGitDirectoryFromFile = (gitFilePath, content) => {
|
|
641
|
+
const match = content.match(/^gitdir:\s*(.+?)\s*$/i);
|
|
642
|
+
if (!match) {
|
|
643
|
+
return gitFilePath;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
return path.resolve(path.dirname(gitFilePath), match[1]);
|
|
647
|
+
};
|
|
648
|
+
|
|
649
|
+
const getGitDirectorySync = (gitRoot, readFileSync) => {
|
|
650
|
+
if (!gitRoot) {
|
|
651
|
+
return undefined;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const gitFilePath = path.join(gitRoot, '.git');
|
|
655
|
+
|
|
656
|
+
try {
|
|
657
|
+
return resolveGitDirectoryFromFile(gitFilePath, readFileSync(gitFilePath, 'utf8'));
|
|
658
|
+
} catch {
|
|
659
|
+
return gitFilePath;
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
const getGitDirectoryAsync = async (gitRoot, readFile) => {
|
|
664
|
+
if (!gitRoot) {
|
|
665
|
+
return undefined;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const gitFilePath = path.join(gitRoot, '.git');
|
|
669
|
+
|
|
670
|
+
try {
|
|
671
|
+
return resolveGitDirectoryFromFile(gitFilePath, await readFile(gitFilePath, 'utf8'));
|
|
672
|
+
} catch {
|
|
673
|
+
return gitFilePath;
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
const getXdgConfigHome = () => process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
678
|
+
|
|
679
|
+
const getGitConfigPaths = () => {
|
|
680
|
+
// `globalGitignore` intentionally reads only user-level Git config.
|
|
681
|
+
// It does not try to emulate every Git config scope such as repository
|
|
682
|
+
// `.git/config` or system config. This keeps the feature boundary small
|
|
683
|
+
// and predictable while still covering the common user-level excludes file.
|
|
684
|
+
//
|
|
685
|
+
// `GIT_CONFIG_GLOBAL` replaces the user-level config entirely.
|
|
686
|
+
if ('GIT_CONFIG_GLOBAL' in process.env) {
|
|
687
|
+
const value = process.env.GIT_CONFIG_GLOBAL;
|
|
688
|
+
return value ? [value] : [];
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
return [
|
|
692
|
+
path.join(getXdgConfigHome(), 'git', 'config'),
|
|
693
|
+
path.join(os.homedir(), '.gitconfig'),
|
|
694
|
+
];
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
const getDefaultGlobalGitignorePath = () => path.join(getXdgConfigHome(), 'git', 'ignore');
|
|
698
|
+
|
|
699
|
+
const resolveExcludesFilePath = excludesFileConfig => {
|
|
700
|
+
// An explicit empty value disables the global gitignore entirely.
|
|
701
|
+
if (excludesFileConfig?.value === '') {
|
|
702
|
+
return undefined;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// When no core.excludesFile was configured, fall back to Git's default
|
|
706
|
+
// user-level ignore file. This matches Git's behavior: the default path
|
|
707
|
+
// applies even when GIT_CONFIG_GLOBAL="" suppresses config file reading.
|
|
708
|
+
if (excludesFileConfig === undefined) {
|
|
709
|
+
return getDefaultGlobalGitignorePath();
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// Relative core.excludesfile values are resolved from the config file that
|
|
713
|
+
// declared them. Do not resolve them from the repository root.
|
|
714
|
+
return resolveConfigPath(excludesFileConfig.declaringFilePath, excludesFileConfig.value);
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
const readGlobalGitignoreContent = (filePath, readMethod, suppressErrors) => {
|
|
718
|
+
try {
|
|
719
|
+
const content = readMethod(filePath, 'utf8');
|
|
720
|
+
return {filePath, content};
|
|
721
|
+
} catch (error) {
|
|
722
|
+
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
|
|
723
|
+
return undefined;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
throw createIgnoreFileReadError(filePath, error);
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
|
|
730
|
+
export const getGlobalGitignoreFile = (options = {}) => {
|
|
731
|
+
const cwd = toPath(options.cwd) ?? process.cwd();
|
|
732
|
+
const readFileSync = getReadFileSyncMethod(options.fs);
|
|
733
|
+
const gitRoot = findGitRootSync(cwd, options.fs);
|
|
734
|
+
const gitDirectory = getGitDirectorySync(gitRoot, readFileSync);
|
|
735
|
+
let excludesFileConfig;
|
|
736
|
+
|
|
737
|
+
for (const gitConfigPath of getGitConfigPaths()) {
|
|
738
|
+
const value = getExcludesFileFromGitConfigSync(gitConfigPath, readFileSync, gitDirectory, {suppressErrors: options.suppressErrors});
|
|
739
|
+
if (value !== undefined) {
|
|
740
|
+
excludesFileConfig = value;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
const filePath = resolveExcludesFilePath(excludesFileConfig);
|
|
745
|
+
return filePath === undefined ? undefined : readGlobalGitignoreContent(filePath, readFileSync, options.suppressErrors);
|
|
746
|
+
};
|
|
747
|
+
|
|
748
|
+
export const getGlobalGitignoreFileAsync = async (options = {}) => {
|
|
749
|
+
const cwd = toPath(options.cwd) ?? process.cwd();
|
|
750
|
+
const readFile = getReadFileMethod(options.fs);
|
|
751
|
+
const gitRoot = await findGitRoot(cwd, options.fs);
|
|
752
|
+
const gitDirectory = await getGitDirectoryAsync(gitRoot, readFile);
|
|
753
|
+
const excludesFileValues = await Promise.all(getGitConfigPaths().map(gitConfigPath => getExcludesFileFromGitConfigAsync(
|
|
754
|
+
gitConfigPath,
|
|
755
|
+
readFile,
|
|
756
|
+
gitDirectory,
|
|
757
|
+
{suppressErrors: options.suppressErrors},
|
|
758
|
+
)));
|
|
759
|
+
const excludesFileConfig = excludesFileValues.findLast(value => value !== undefined);
|
|
760
|
+
|
|
761
|
+
const filePath = resolveExcludesFilePath(excludesFileConfig);
|
|
762
|
+
if (filePath === undefined) {
|
|
763
|
+
return undefined;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
try {
|
|
767
|
+
const content = await readFile(filePath, 'utf8');
|
|
768
|
+
return {filePath, content};
|
|
769
|
+
} catch (error) {
|
|
770
|
+
if (shouldSkipIgnoreFileError(error, options.suppressErrors)) {
|
|
771
|
+
return undefined;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
throw createIgnoreFileReadError(filePath, error);
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
|
|
778
|
+
export const buildGlobalMatcher = (globalIgnoreFile, cwd, rootDirectory = cwd) => {
|
|
779
|
+
// Passing the file's own directory as cwd gives base='', so patterns stay
|
|
780
|
+
// unchanged and are interpreted relative to the project root (cwd). This
|
|
781
|
+
// matches Git's behavior: patterns without slashes match at any depth,
|
|
782
|
+
// patterns starting with / are anchored to the project root.
|
|
783
|
+
const patterns = parseIgnoreFile(globalIgnoreFile, path.dirname(globalIgnoreFile.filePath));
|
|
784
|
+
return createIgnoreMatcher(patterns, cwd, rootDirectory);
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
export const buildGlobalPredicate = (globalIgnoreFile, cwd, rootDirectory = cwd) => {
|
|
788
|
+
const matcher = buildGlobalMatcher(globalIgnoreFile, cwd, rootDirectory);
|
|
789
|
+
return fileOrDirectory => matcher(fileOrDirectory).ignored;
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
const collectIgnoreFileArtifactsAsync = async (patterns, options, includeParentIgnoreFiles) => {
|
|
793
|
+
const normalizedOptions = normalizeOptions(options);
|
|
794
|
+
const childPaths = await globIgnoreFiles(fastGlob, patterns, normalizedOptions);
|
|
795
|
+
const gitRoot = includeParentIgnoreFiles
|
|
796
|
+
? await findGitRoot(normalizedOptions.cwd, normalizedOptions.fs)
|
|
797
|
+
: undefined;
|
|
798
|
+
const allPaths = combineIgnoreFilePaths(gitRoot, normalizedOptions, childPaths);
|
|
799
|
+
const readFileMethod = getReadFileMethod(normalizedOptions.fs);
|
|
800
|
+
const files = await readIgnoreFilesSafely(allPaths, readFileMethod, normalizedOptions.suppressErrors);
|
|
801
|
+
|
|
802
|
+
return {files, normalizedOptions, gitRoot};
|
|
803
|
+
};
|
|
804
|
+
|
|
805
|
+
const collectIgnoreFileArtifactsSync = (patterns, options, includeParentIgnoreFiles) => {
|
|
806
|
+
const normalizedOptions = normalizeOptions(options);
|
|
807
|
+
const childPaths = globIgnoreFiles(fastGlob.sync, patterns, normalizedOptions);
|
|
808
|
+
const gitRoot = includeParentIgnoreFiles
|
|
809
|
+
? findGitRootSync(normalizedOptions.cwd, normalizedOptions.fs)
|
|
810
|
+
: undefined;
|
|
811
|
+
const allPaths = combineIgnoreFilePaths(gitRoot, normalizedOptions, childPaths);
|
|
812
|
+
const readFileSyncMethod = getReadFileSyncMethod(normalizedOptions.fs);
|
|
813
|
+
const files = readIgnoreFilesSafelySync(allPaths, readFileSyncMethod, normalizedOptions.suppressErrors);
|
|
814
|
+
|
|
815
|
+
return {files, normalizedOptions, gitRoot};
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
export const isIgnoredByIgnoreFiles = async (patterns, options) => {
|
|
819
|
+
const {files, normalizedOptions, gitRoot} = await collectIgnoreFileArtifactsAsync(patterns, options, false);
|
|
820
|
+
return buildIgnoreResult(files, normalizedOptions, gitRoot).predicate;
|
|
821
|
+
};
|
|
822
|
+
|
|
823
|
+
export const isIgnoredByIgnoreFilesSync = (patterns, options) => {
|
|
824
|
+
const {files, normalizedOptions, gitRoot} = collectIgnoreFileArtifactsSync(patterns, options, false);
|
|
825
|
+
return buildIgnoreResult(files, normalizedOptions, gitRoot).predicate;
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
const getPatternsFromIgnoreFiles = (files, baseDir) => files.flatMap(file => parseIgnoreFile(file, baseDir));
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
Read ignore files and return both patterns and predicate.
|
|
832
|
+
This avoids reading the same files twice (once for patterns, once for filtering).
|
|
833
|
+
|
|
834
|
+
@param {string[]} patterns - Patterns to find ignore files
|
|
835
|
+
@param {Object} options - Options object
|
|
836
|
+
@param {boolean} [includeParentIgnoreFiles=false] - Whether to search for parent .gitignore files
|
|
837
|
+
@returns {Promise<{patterns: string[], matcher: Function, predicate: Function, usingGitRoot: boolean}>}
|
|
838
|
+
*/
|
|
839
|
+
export const getIgnorePatternsAndPredicate = async (patterns, options, includeParentIgnoreFiles = false) => {
|
|
840
|
+
const {files, normalizedOptions, gitRoot} = await collectIgnoreFileArtifactsAsync(
|
|
841
|
+
patterns,
|
|
842
|
+
options,
|
|
843
|
+
includeParentIgnoreFiles,
|
|
844
|
+
);
|
|
845
|
+
|
|
846
|
+
return buildIgnoreResult(files, normalizedOptions, gitRoot);
|
|
847
|
+
};
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
Read ignore files and return both patterns and predicate (sync version).
|
|
851
|
+
|
|
852
|
+
@param {string[]} patterns - Patterns to find ignore files
|
|
853
|
+
@param {Object} options - Options object
|
|
854
|
+
@param {boolean} [includeParentIgnoreFiles=false] - Whether to search for parent .gitignore files
|
|
855
|
+
@returns {{patterns: string[], matcher: Function, predicate: Function, usingGitRoot: boolean}}
|
|
856
|
+
*/
|
|
857
|
+
export const getIgnorePatternsAndPredicateSync = (patterns, options, includeParentIgnoreFiles = false) => {
|
|
858
|
+
const {files, normalizedOptions, gitRoot} = collectIgnoreFileArtifactsSync(
|
|
859
|
+
patterns,
|
|
860
|
+
options,
|
|
861
|
+
includeParentIgnoreFiles,
|
|
862
|
+
);
|
|
863
|
+
|
|
864
|
+
return buildIgnoreResult(files, normalizedOptions, gitRoot);
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
export const isGitIgnored = options => isIgnoredByIgnoreFiles(GITIGNORE_FILES_PATTERN, options);
|
|
868
|
+
export const isGitIgnoredSync = options => isIgnoredByIgnoreFilesSync(GITIGNORE_FILES_PATTERN, options);
|