forked from sindresorhus/globby
/
gitignore.js
121 lines (93 loc) · 2.59 KB
/
gitignore.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import {promisify} from 'node:util';
import fs from 'node:fs';
import path from 'node:path';
import fastGlob from 'fast-glob';
import gitIgnore from 'ignore';
import slash from 'slash';
const DEFAULT_IGNORE = [
'**/node_modules/**',
'**/flow-typed/**',
'**/coverage/**',
'**/.git',
];
const readFileP = promisify(fs.readFile);
const mapGitIgnorePatternTo = base => ignore => {
if (ignore.startsWith('!')) {
return '!' + path.posix.join(base, ignore.slice(1));
}
return path.posix.join(base, ignore);
};
const parseGitIgnore = (content, options) => {
const base = slash(path.relative(options.cwd, path.dirname(options.fileName)));
return content
.split(/\r?\n/)
.filter(Boolean)
.filter(line => !line.startsWith('#'))
.map(mapGitIgnorePatternTo(base));
};
const reduceIgnore = files => {
const ignores = gitIgnore();
for (const file of files) {
ignores.add(parseGitIgnore(file.content, {
cwd: file.cwd,
fileName: file.filePath,
}));
}
return ignores;
};
const ensureAbsolutePathForCwd = (cwd, p) => {
cwd = slash(cwd);
if (path.isAbsolute(p)) {
if (slash(p).startsWith(cwd)) {
return p;
}
throw new Error(`Path ${p} is not in cwd ${cwd}`);
}
return path.join(cwd, p);
};
const getIsIgnoredPredecate = (ignores, cwd) => p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p))));
const getFile = async (file, cwd) => {
const filePath = path.join(cwd, file);
const content = await readFileP(filePath, 'utf8');
return {
cwd,
filePath,
content,
};
};
const getFileSync = (file, cwd) => {
const filePath = path.join(cwd, file);
const content = fs.readFileSync(filePath, 'utf8');
return {
cwd,
filePath,
content,
};
};
const normalizeOptions = ({
ignore = [],
cwd = slash(process.cwd()),
} = {}) => ({ignore, cwd});
export const gitignore = async options => {
options = normalizeOptions(options);
const paths = await fastGlob('**/.gitignore', {
ignore: DEFAULT_IGNORE.concat(options.ignore),
cwd: options.cwd,
});
const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
const ignores = reduceIgnore(files);
return getIsIgnoredPredecate(ignores, options.cwd);
};
export const gitignoreSync = options => {
options = normalizeOptions(options);
const paths = fastGlob.sync('**/.gitignore', {
ignore: DEFAULT_IGNORE.concat(options.ignore),
cwd: options.cwd,
});
const files = paths.map(file => getFileSync(file, options.cwd));
const ignores = reduceIgnore(files);
return getIsIgnoredPredecate(ignores, options.cwd);
};
// Legacy API
gitignore.sync = gitignoreSync;
export default gitignore;