-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathignore.js
More file actions
868 lines (704 loc) · 26.3 KB
/
ignore.js
File metadata and controls
868 lines (704 loc) · 26.3 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
import process from 'node:process';
import fs from 'node:fs';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import fastGlob from 'fast-glob';
import gitIgnore from 'ignore';
import isPathInside from 'is-path-inside';
import slash from 'slash';
import {toPath} from 'unicorn-magic/node';
import {
isNegativePattern,
bindFsMethod,
promisifyFsMethod,
findGitRoot,
findGitRootSync,
getParentGitignorePaths,
} from './utilities.js';
const defaultIgnoredDirectories = [
'**/node_modules',
'**/flow-typed',
'**/coverage',
'**/.git',
];
const ignoreFilesGlobOptions = {
absolute: true,
dot: true,
};
export const GITIGNORE_FILES_PATTERN = '**/.gitignore';
// Maximum depth for [include] chains to prevent stack overflow (git uses 10)
const MAX_INCLUDE_DEPTH = 10;
const getReadFileMethod = fsImplementation =>
bindFsMethod(fsImplementation?.promises, 'readFile')
?? bindFsMethod(fsPromises, 'readFile')
?? promisifyFsMethod(fsImplementation, 'readFile');
const getReadFileSyncMethod = fsImplementation =>
bindFsMethod(fsImplementation, 'readFileSync')
?? bindFsMethod(fs, 'readFileSync');
const shouldSkipIgnoreFileError = (error, suppressErrors) => {
if (!error) {
return Boolean(suppressErrors);
}
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
return true;
}
return Boolean(suppressErrors);
};
const createReadError = (kind, filePath, error) => {
const prefix = `Failed to read ${kind} at ${filePath}`;
if (error instanceof Error) {
return new Error(`${prefix}: ${error.message}`, {cause: error});
}
return new Error(`${prefix}: ${String(error)}`);
};
const createIgnoreFileReadError = (filePath, error) => createReadError('ignore file', filePath, error);
const createGitConfigReadError = (filePath, error) => createReadError('git config', filePath, error);
const processIgnoreFileCore = (filePath, readMethod, suppressErrors) => {
try {
const content = readMethod(filePath, 'utf8');
return {filePath, content};
} catch (error) {
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
return undefined;
}
throw createIgnoreFileReadError(filePath, error);
}
};
const readIgnoreFilesSafely = async (paths, readFileMethod, suppressErrors) => {
const fileResults = await Promise.all(paths.map(async filePath => {
try {
const content = await readFileMethod(filePath, 'utf8');
return {filePath, content};
} catch (error) {
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
return undefined;
}
throw createIgnoreFileReadError(filePath, error);
}
}));
return fileResults.filter(Boolean);
};
const readIgnoreFilesSafelySync = (paths, readFileSyncMethod, suppressErrors) => paths
.map(filePath => processIgnoreFileCore(filePath, readFileSyncMethod, suppressErrors))
.filter(Boolean);
const dedupePaths = paths => {
const seen = new Set();
return paths.filter(filePath => {
if (seen.has(filePath)) {
return false;
}
seen.add(filePath);
return true;
});
};
const globIgnoreFiles = (globFunction, patterns, normalizedOptions) => globFunction(patterns, {
...normalizedOptions,
...ignoreFilesGlobOptions, // Must be last to ensure absolute/dot flags stick
});
const getParentIgnorePaths = (gitRoot, normalizedOptions) => gitRoot
? getParentGitignorePaths(gitRoot, normalizedOptions.cwd)
: [];
const combineIgnoreFilePaths = (gitRoot, normalizedOptions, childPaths) => dedupePaths([
...getParentIgnorePaths(gitRoot, normalizedOptions),
...childPaths,
]);
const buildIgnoreResult = (files, normalizedOptions, gitRoot) => {
const baseDir = gitRoot || normalizedOptions.cwd;
const patterns = getPatternsFromIgnoreFiles(files, baseDir);
const matcher = createIgnoreMatcher(patterns, normalizedOptions.cwd, baseDir);
return {
patterns,
matcher,
predicate: fileOrDirectory => matcher(fileOrDirectory).ignored,
usingGitRoot: Boolean(gitRoot && gitRoot !== normalizedOptions.cwd),
};
};
// Apply base path to gitignore patterns based on .gitignore spec 2.22.1
// https://git-scm.com/docs/gitignore#_pattern_format
// See also https://github.com/sindresorhus/globby/issues/146
const applyBaseToPattern = (pattern, base) => {
if (!base) {
return pattern;
}
const isNegative = isNegativePattern(pattern);
const cleanPattern = isNegative ? pattern.slice(1) : pattern;
// Check if pattern has non-trailing slashes
const slashIndex = cleanPattern.indexOf('/');
const hasNonTrailingSlash = slashIndex !== -1 && slashIndex !== cleanPattern.length - 1;
let result;
if (!hasNonTrailingSlash) {
// "If there is no separator at the beginning or middle of the pattern,
// then the pattern may also match at any level below the .gitignore level."
// So patterns like '*.log' or 'temp' or 'build/' (trailing slash) match recursively.
result = path.posix.join(base, '**', cleanPattern);
} else if (cleanPattern.startsWith('/')) {
// "If there is a separator at the beginning [...] of the pattern,
// then the pattern is relative to the directory level of the particular .gitignore file itself."
// Leading slash anchors the pattern to the .gitignore's directory.
result = path.posix.join(base, cleanPattern.slice(1));
} else {
// "If there is a separator [...] middle [...] of the pattern,
// then the pattern is relative to the directory level of the particular .gitignore file itself."
// Patterns like 'src/foo' are relative to the .gitignore's directory.
result = path.posix.join(base, cleanPattern);
}
return isNegative ? '!' + result : result;
};
const parseIgnoreFile = (file, cwd) => {
const base = slash(path.relative(cwd, path.dirname(file.filePath)));
return file.content
.split(/\r?\n/)
.filter(line => line && !line.startsWith('#'))
.map(pattern => applyBaseToPattern(pattern, base));
};
const toRelativePath = (fileOrDirectory, cwd) => {
if (path.isAbsolute(fileOrDirectory)) {
// When paths are equal, path.relative returns empty string which is valid
// isPathInside returns false for equal paths, so check this case first
const relativePath = path.relative(cwd, fileOrDirectory);
if (relativePath && !isPathInside(fileOrDirectory, cwd)) {
// Path is outside cwd - it cannot be ignored by patterns in cwd
// Return undefined to indicate this path is outside scope
return undefined;
}
return relativePath;
}
// Normalize relative paths:
// - Git treats './foo' as 'foo' when checking against patterns
// - Patterns starting with './' in .gitignore are invalid and don't match anything
// - The ignore library expects normalized paths without './' prefix
if (fileOrDirectory.startsWith('./')) {
return fileOrDirectory.slice(2);
}
// Paths with ../ point outside cwd and cannot match patterns from this directory
// Return undefined to indicate this path is outside scope
if (fileOrDirectory.startsWith('../')) {
return undefined;
}
return fileOrDirectory;
};
const notIgnored = {ignored: false, unignored: false};
const createIgnoreMatcher = (patterns, cwd, baseDir) => {
const ignores = gitIgnore().add(patterns);
// Normalize to handle path separator and . / .. components consistently
const resolvedCwd = path.normalize(path.resolve(cwd));
const resolvedBaseDir = path.normalize(path.resolve(baseDir));
return fileOrDirectory => {
fileOrDirectory = toPath(fileOrDirectory);
const hasTrailingSeparator = /[/\\]$/.test(fileOrDirectory);
// Never ignore the cwd itself - use normalized comparison
const normalizedPath = path.normalize(path.resolve(fileOrDirectory));
if (normalizedPath === resolvedCwd) {
return notIgnored;
}
// Convert to relative path from baseDir (use normalized baseDir)
let relativePath = toRelativePath(fileOrDirectory, resolvedBaseDir);
// If path is outside baseDir (undefined), it can't be ignored by patterns
if (relativePath === undefined) {
return notIgnored;
}
if (!relativePath) {
return notIgnored;
}
if (hasTrailingSeparator && !relativePath.endsWith(path.sep)) {
relativePath += path.sep;
}
return ignores.test(slash(relativePath));
};
};
const normalizeOptions = (options = {}) => {
const ignoreOption = options.ignore
? (Array.isArray(options.ignore) ? options.ignore : [options.ignore])
: [];
const cwd = toPath(options.cwd) ?? process.cwd();
// Adjust deep option for fast-glob: fast-glob's deep counts differently than expected
// User's deep: 0 = root only -> fast-glob needs: 1
// User's deep: 1 = root + 1 level -> fast-glob needs: 2
const deep = typeof options.deep === 'number' ? Math.max(0, options.deep) + 1 : Number.POSITIVE_INFINITY;
// Only pass through specific fast-glob options that make sense for finding ignore files
return {
cwd,
suppressErrors: options.suppressErrors ?? false,
deep,
ignore: [...ignoreOption, ...defaultIgnoredDirectories],
followSymbolicLinks: options.followSymbolicLinks ?? true,
concurrency: options.concurrency,
throwErrorOnBrokenSymbolicLink: options.throwErrorOnBrokenSymbolicLink ?? false,
fs: options.fs,
};
};
const unescapeGitQuotedValue = value => value.replaceAll(/\\(["\\abfnrtv])/g, (_match, escapedCharacter) => {
switch (escapedCharacter) {
case 'a': {
return '\u0007';
}
case 'b': {
return '\b';
}
case 'f': {
return '\f';
}
case 'n': {
return '\n';
}
case 'r': {
return '\r';
}
case 't': {
return '\t';
}
case 'v': {
return '\v';
}
default: {
return escapedCharacter;
}
}
});
const parseGitConfigValue = value => {
const trimmedValue = value.trim();
const quotedMatch = trimmedValue.match(/^"((?:[^"\\]|\\.)*)"\s*(?:[#;].*)?$/);
if (quotedMatch) {
return unescapeGitQuotedValue(quotedMatch[1]);
}
return trimmedValue.replace(/\s[#;].*$/, '').trim();
};
const resolveConfigPath = (filePath, configPath) => {
if (configPath.startsWith('~/')) {
const homeDirectory = os.homedir();
const resolved = path.join(homeDirectory, configPath.slice(2));
// Ensure the resolved path is within the home directory to prevent traversal via ~/..
if (!isPathInside(resolved, homeDirectory)) {
// Invalid path, return a path that won't exist
return path.join(homeDirectory, '.globby-invalid-path-traversal');
}
return resolved;
}
if (path.isAbsolute(configPath)) {
return configPath;
}
return path.resolve(path.dirname(filePath), configPath);
};
const parseGitConfigSection = line => {
if (!line.startsWith('[')) {
return undefined;
}
let inQuotes = false;
let isEscaped = false;
for (let index = 1; index < line.length; index++) {
const character = line[index];
if (isEscaped) {
isEscaped = false;
continue;
}
if (character === '\\') {
isEscaped = true;
continue;
}
if (character === '"') {
inQuotes = !inQuotes;
continue;
}
if (character === ']' && !inQuotes) {
const remainder = line.slice(index + 1).trimStart();
if (remainder && !remainder.startsWith('#') && !remainder.startsWith(';')) {
return undefined;
}
return line.slice(1, index).trim();
}
}
return undefined;
};
const parseGitConfigEntry = line => {
const match = line.match(/^([A-Za-z\d-.]+)\s*=\s*(.*)$/);
if (!match) {
return undefined;
}
return {
key: match[1].toLowerCase(),
value: parseGitConfigValue(match[2]),
};
};
const parseIncludeIfCondition = section => {
if (!section) {
return undefined;
}
const match = section.match(/^includeif\s+"([^"]+)"$/i);
return match ? match[1] : undefined;
};
const normalizeGitConfigConditionPattern = (pattern, configFilePath) => {
if (pattern.startsWith('~/')) {
pattern = path.join(os.homedir(), pattern.slice(2));
} else if (pattern.startsWith('./')) {
pattern = path.resolve(path.dirname(configFilePath), pattern.slice(2));
} else if (!path.isAbsolute(pattern)) {
pattern = `**/${pattern}`;
}
if (pattern.endsWith('/')) {
pattern += '**';
}
return slash(pattern);
};
const gitConfigGlobToRegex = (pattern, flags) => {
let regex = '';
for (let index = 0; index < pattern.length; index++) {
const character = pattern[index];
const nextCharacter = pattern[index + 1];
const nextNextCharacter = pattern[index + 2];
if (character === '*' && nextCharacter === '*' && nextNextCharacter === '/') {
regex += '(?:.*/)?';
index += 2;
continue;
}
if (character === '*' && nextCharacter === '*') {
regex += '.*';
index += 1;
continue;
}
if (character === '*') {
regex += '[^/]*';
continue;
}
if (character === '?') {
regex += '[^/]';
continue;
}
if (character === '[') {
const closingBracketIndex = pattern.indexOf(']', index + 1);
if (closingBracketIndex !== -1) {
const bracketContent = pattern.slice(index + 1, closingBracketIndex);
if (bracketContent) {
const negatedBracketContent = bracketContent[0] === '!' ? `^${bracketContent.slice(1)}` : bracketContent;
regex += `[${negatedBracketContent}]`;
index = closingBracketIndex;
continue;
}
}
}
regex += /[|\\{}()[\]^$+?.]/.test(character) ? `\\${character}` : character;
}
try {
return new RegExp(`^${regex}$`, flags);
} catch {
// If regex construction fails (e.g., invalid bracket expression), return a non-matching pattern
return /(?!)/;
}
};
const matchesIncludeIfCondition = (condition, gitDirectory, configFilePath) => {
if (!gitDirectory) {
return false;
}
const match = condition.match(/^(gitdir|gitdir\/i):(.*)$/i);
if (!match) {
return false;
}
const [, keyword, rawPattern] = match;
const pattern = normalizeGitConfigConditionPattern(rawPattern.trim(), configFilePath);
const isCaseInsensitive = keyword.toLowerCase() === 'gitdir/i';
const regularExpression = gitConfigGlobToRegex(pattern, isCaseInsensitive ? 'i' : undefined);
const normalizedGitDirectory = slash(path.resolve(gitDirectory));
return regularExpression.test(normalizedGitDirectory);
};
const shouldIncludeConfigSection = (section, gitDirectory, configFilePath) => {
if (section?.toLowerCase() === 'include') {
return true;
}
// `globalGitignore` intentionally keeps `includeIf` support narrow.
// Only `gitdir:` and `gitdir/i:` conditions are treated as active here.
// Other Git predicates such as `onbranch:` are outside this feature's
// supported boundary and are documented as unsupported.
const condition = parseIncludeIfCondition(section);
return condition ? matchesIncludeIfCondition(condition, gitDirectory, configFilePath) : false;
};
const createExcludesFileValue = (value, declaringFilePath) => ({
value,
declaringFilePath,
});
/**
Parse git config content and return the excludesFile value and any include paths to recurse into.
The caller is responsible for reading files and recursing (sync or async).
*/
const parseGitConfigForExcludesFile = (content, normalizedPath, gitDirectory) => {
let currentSection;
let excludesFile;
const includePaths = [];
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith(';')) {
continue;
}
if (trimmed.startsWith('[')) {
currentSection = parseGitConfigSection(trimmed);
continue;
}
const entry = parseGitConfigEntry(trimmed);
if (!entry) {
continue;
}
if (currentSection?.toLowerCase() === 'core' && entry.key === 'excludesfile') {
excludesFile = createExcludesFileValue(entry.value, normalizedPath);
continue;
}
if (shouldIncludeConfigSection(currentSection, gitDirectory, normalizedPath) && entry.key === 'path' && entry.value) {
includePaths.push(resolveConfigPath(normalizedPath, entry.value));
}
}
return {excludesFile, includePaths};
};
const readGitConfigFile = (normalizedPath, readMethod, suppressErrors) => {
try {
return readMethod(normalizedPath, 'utf8');
} catch (error) {
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
return undefined;
}
throw createGitConfigReadError(normalizedPath, error);
}
};
const getExcludesFileFromGitConfigSync = (filePath, readFileSync, gitDirectory, options = {}) => {
const {suppressErrors, includeStack = new Set(), depth = 0} = options;
const normalizedPath = path.resolve(filePath);
if (includeStack.has(normalizedPath)) {
return undefined;
}
if (depth >= MAX_INCLUDE_DEPTH) {
return undefined;
}
includeStack.add(normalizedPath);
const content = readGitConfigFile(normalizedPath, readFileSync, suppressErrors);
if (content === undefined) {
includeStack.delete(normalizedPath);
return undefined;
}
let {excludesFile, includePaths} = parseGitConfigForExcludesFile(content, normalizedPath, gitDirectory);
for (const includePath of includePaths) {
const includedExcludesFile = getExcludesFileFromGitConfigSync(includePath, readFileSync, gitDirectory, {suppressErrors, includeStack, depth: depth + 1});
if (includedExcludesFile !== undefined) {
excludesFile = includedExcludesFile;
}
}
includeStack.delete(normalizedPath);
return excludesFile;
};
const getExcludesFileFromGitConfigAsync = async (filePath, readFile, gitDirectory, options = {}) => {
const {suppressErrors, includeStack = new Set(), depth = 0} = options;
const normalizedPath = path.resolve(filePath);
if (includeStack.has(normalizedPath)) {
return undefined;
}
if (depth >= MAX_INCLUDE_DEPTH) {
return undefined;
}
includeStack.add(normalizedPath);
let content;
try {
content = await readFile(normalizedPath, 'utf8');
} catch (error) {
includeStack.delete(normalizedPath);
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
return undefined;
}
throw createGitConfigReadError(normalizedPath, error);
}
let {excludesFile, includePaths} = parseGitConfigForExcludesFile(content, normalizedPath, gitDirectory);
for (const includePath of includePaths) {
// eslint-disable-next-line no-await-in-loop
const includedExcludesFile = await getExcludesFileFromGitConfigAsync(includePath, readFile, gitDirectory, {suppressErrors, includeStack, depth: depth + 1});
if (includedExcludesFile !== undefined) {
excludesFile = includedExcludesFile;
}
}
includeStack.delete(normalizedPath);
return excludesFile;
};
const resolveGitDirectoryFromFile = (gitFilePath, content) => {
const match = content.match(/^gitdir:\s*(.+?)\s*$/i);
if (!match) {
return gitFilePath;
}
return path.resolve(path.dirname(gitFilePath), match[1]);
};
const getGitDirectorySync = (gitRoot, readFileSync) => {
if (!gitRoot) {
return undefined;
}
const gitFilePath = path.join(gitRoot, '.git');
try {
return resolveGitDirectoryFromFile(gitFilePath, readFileSync(gitFilePath, 'utf8'));
} catch {
return gitFilePath;
}
};
const getGitDirectoryAsync = async (gitRoot, readFile) => {
if (!gitRoot) {
return undefined;
}
const gitFilePath = path.join(gitRoot, '.git');
try {
return resolveGitDirectoryFromFile(gitFilePath, await readFile(gitFilePath, 'utf8'));
} catch {
return gitFilePath;
}
};
const getXdgConfigHome = () => process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
const getGitConfigPaths = () => {
// `globalGitignore` intentionally reads only user-level Git config.
// It does not try to emulate every Git config scope such as repository
// `.git/config` or system config. This keeps the feature boundary small
// and predictable while still covering the common user-level excludes file.
//
// `GIT_CONFIG_GLOBAL` replaces the user-level config entirely.
if ('GIT_CONFIG_GLOBAL' in process.env) {
const value = process.env.GIT_CONFIG_GLOBAL;
return value ? [value] : [];
}
return [
path.join(getXdgConfigHome(), 'git', 'config'),
path.join(os.homedir(), '.gitconfig'),
];
};
const getDefaultGlobalGitignorePath = () => path.join(getXdgConfigHome(), 'git', 'ignore');
const resolveExcludesFilePath = excludesFileConfig => {
// An explicit empty value disables the global gitignore entirely.
if (excludesFileConfig?.value === '') {
return undefined;
}
// When no core.excludesFile was configured, fall back to Git's default
// user-level ignore file. This matches Git's behavior: the default path
// applies even when GIT_CONFIG_GLOBAL="" suppresses config file reading.
if (excludesFileConfig === undefined) {
return getDefaultGlobalGitignorePath();
}
// Relative core.excludesfile values are resolved from the config file that
// declared them. Do not resolve them from the repository root.
return resolveConfigPath(excludesFileConfig.declaringFilePath, excludesFileConfig.value);
};
const readGlobalGitignoreContent = (filePath, readMethod, suppressErrors) => {
try {
const content = readMethod(filePath, 'utf8');
return {filePath, content};
} catch (error) {
if (shouldSkipIgnoreFileError(error, suppressErrors)) {
return undefined;
}
throw createIgnoreFileReadError(filePath, error);
}
};
export const getGlobalGitignoreFile = (options = {}) => {
const cwd = toPath(options.cwd) ?? process.cwd();
const readFileSync = getReadFileSyncMethod(options.fs);
const gitRoot = findGitRootSync(cwd, options.fs);
const gitDirectory = getGitDirectorySync(gitRoot, readFileSync);
let excludesFileConfig;
for (const gitConfigPath of getGitConfigPaths()) {
const value = getExcludesFileFromGitConfigSync(gitConfigPath, readFileSync, gitDirectory, {suppressErrors: options.suppressErrors});
if (value !== undefined) {
excludesFileConfig = value;
}
}
const filePath = resolveExcludesFilePath(excludesFileConfig);
return filePath === undefined ? undefined : readGlobalGitignoreContent(filePath, readFileSync, options.suppressErrors);
};
export const getGlobalGitignoreFileAsync = async (options = {}) => {
const cwd = toPath(options.cwd) ?? process.cwd();
const readFile = getReadFileMethod(options.fs);
const gitRoot = await findGitRoot(cwd, options.fs);
const gitDirectory = await getGitDirectoryAsync(gitRoot, readFile);
const excludesFileValues = await Promise.all(getGitConfigPaths().map(gitConfigPath => getExcludesFileFromGitConfigAsync(
gitConfigPath,
readFile,
gitDirectory,
{suppressErrors: options.suppressErrors},
)));
const excludesFileConfig = excludesFileValues.findLast(value => value !== undefined);
const filePath = resolveExcludesFilePath(excludesFileConfig);
if (filePath === undefined) {
return undefined;
}
try {
const content = await readFile(filePath, 'utf8');
return {filePath, content};
} catch (error) {
if (shouldSkipIgnoreFileError(error, options.suppressErrors)) {
return undefined;
}
throw createIgnoreFileReadError(filePath, error);
}
};
export const buildGlobalMatcher = (globalIgnoreFile, cwd, rootDirectory = cwd) => {
// Passing the file's own directory as cwd gives base='', so patterns stay
// unchanged and are interpreted relative to the project root (cwd). This
// matches Git's behavior: patterns without slashes match at any depth,
// patterns starting with / are anchored to the project root.
const patterns = parseIgnoreFile(globalIgnoreFile, path.dirname(globalIgnoreFile.filePath));
return createIgnoreMatcher(patterns, cwd, rootDirectory);
};
export const buildGlobalPredicate = (globalIgnoreFile, cwd, rootDirectory = cwd) => {
const matcher = buildGlobalMatcher(globalIgnoreFile, cwd, rootDirectory);
return fileOrDirectory => matcher(fileOrDirectory).ignored;
};
const collectIgnoreFileArtifactsAsync = async (patterns, options, includeParentIgnoreFiles) => {
const normalizedOptions = normalizeOptions(options);
const childPaths = await globIgnoreFiles(fastGlob, patterns, normalizedOptions);
const gitRoot = includeParentIgnoreFiles
? await findGitRoot(normalizedOptions.cwd, normalizedOptions.fs)
: undefined;
const allPaths = combineIgnoreFilePaths(gitRoot, normalizedOptions, childPaths);
const readFileMethod = getReadFileMethod(normalizedOptions.fs);
const files = await readIgnoreFilesSafely(allPaths, readFileMethod, normalizedOptions.suppressErrors);
return {files, normalizedOptions, gitRoot};
};
const collectIgnoreFileArtifactsSync = (patterns, options, includeParentIgnoreFiles) => {
const normalizedOptions = normalizeOptions(options);
const childPaths = globIgnoreFiles(fastGlob.sync, patterns, normalizedOptions);
const gitRoot = includeParentIgnoreFiles
? findGitRootSync(normalizedOptions.cwd, normalizedOptions.fs)
: undefined;
const allPaths = combineIgnoreFilePaths(gitRoot, normalizedOptions, childPaths);
const readFileSyncMethod = getReadFileSyncMethod(normalizedOptions.fs);
const files = readIgnoreFilesSafelySync(allPaths, readFileSyncMethod, normalizedOptions.suppressErrors);
return {files, normalizedOptions, gitRoot};
};
export const isIgnoredByIgnoreFiles = async (patterns, options) => {
const {files, normalizedOptions, gitRoot} = await collectIgnoreFileArtifactsAsync(patterns, options, false);
return buildIgnoreResult(files, normalizedOptions, gitRoot).predicate;
};
export const isIgnoredByIgnoreFilesSync = (patterns, options) => {
const {files, normalizedOptions, gitRoot} = collectIgnoreFileArtifactsSync(patterns, options, false);
return buildIgnoreResult(files, normalizedOptions, gitRoot).predicate;
};
const getPatternsFromIgnoreFiles = (files, baseDir) => files.flatMap(file => parseIgnoreFile(file, baseDir));
/**
Read ignore files and return both patterns and predicate.
This avoids reading the same files twice (once for patterns, once for filtering).
@param {string[]} patterns - Patterns to find ignore files
@param {Object} options - Options object
@param {boolean} [includeParentIgnoreFiles=false] - Whether to search for parent .gitignore files
@returns {Promise<{patterns: string[], matcher: Function, predicate: Function, usingGitRoot: boolean}>}
*/
export const getIgnorePatternsAndPredicate = async (patterns, options, includeParentIgnoreFiles = false) => {
const {files, normalizedOptions, gitRoot} = await collectIgnoreFileArtifactsAsync(
patterns,
options,
includeParentIgnoreFiles,
);
return buildIgnoreResult(files, normalizedOptions, gitRoot);
};
/**
Read ignore files and return both patterns and predicate (sync version).
@param {string[]} patterns - Patterns to find ignore files
@param {Object} options - Options object
@param {boolean} [includeParentIgnoreFiles=false] - Whether to search for parent .gitignore files
@returns {{patterns: string[], matcher: Function, predicate: Function, usingGitRoot: boolean}}
*/
export const getIgnorePatternsAndPredicateSync = (patterns, options, includeParentIgnoreFiles = false) => {
const {files, normalizedOptions, gitRoot} = collectIgnoreFileArtifactsSync(
patterns,
options,
includeParentIgnoreFiles,
);
return buildIgnoreResult(files, normalizedOptions, gitRoot);
};
export const isGitIgnored = options => isIgnoredByIgnoreFiles(GITIGNORE_FILES_PATTERN, options);
export const isGitIgnoredSync = options => isIgnoredByIgnoreFilesSync(GITIGNORE_FILES_PATTERN, options);