2 const fs = require('fs');
3 const path = require('path');
4 const glob = require('glob');
5 const gitIgnore = require('ignore');
6 const pify = require('pify');
7 const slash = require('slash');
9 const globP = pify(glob);
10 const readFileP = pify(fs.readFile);
12 const mapGitIgnorePatternTo = base => ignore => {
13 if (ignore.startsWith('!')) {
14 return '!' + path.posix.join(base, ignore.substr(1));
17 return path.posix.join(base, ignore);
20 const parseGitIgnore = (content, opts) => {
21 const base = slash(path.relative(opts.cwd, path.dirname(opts.fileName)));
26 .filter(l => l.charAt(0) !== '#')
27 .map(mapGitIgnorePatternTo(base));
30 const reduceIgnore = files => {
31 return files.reduce((ignores, file) => {
32 ignores.add(parseGitIgnore(file.content, {
34 fileName: file.filePath
40 const getIsIgnoredPredecate = (ignores, cwd) => {
41 return p => ignores.ignores(slash(path.relative(cwd, p)));
44 const getFile = (file, cwd) => {
45 const filePath = path.join(cwd, file);
46 return readFileP(filePath, 'utf8')
54 const getFileSync = (file, cwd) => {
55 const filePath = path.join(cwd, file);
56 const content = fs.readFileSync(filePath, 'utf8');
65 const normalizeOpts = opts => {
67 const ignore = opts.ignore || [];
68 const cwd = opts.cwd || process.cwd();
72 module.exports = o => {
73 const opts = normalizeOpts(o);
75 return globP('**/.gitignore', {ignore: opts.ignore, cwd: opts.cwd})
76 .then(paths => Promise.all(paths.map(file => getFile(file, opts.cwd))))
77 .then(files => reduceIgnore(files))
78 .then(ignores => getIsIgnoredPredecate(ignores, opts.cwd));
81 module.exports.sync = o => {
82 const opts = normalizeOpts(o);
84 const paths = glob.sync('**/.gitignore', {ignore: opts.ignore, cwd: opts.cwd});
85 const files = paths.map(file => getFileSync(file, opts.cwd));
86 const ignores = reduceIgnore(files);
87 return getIsIgnoredPredecate(ignores, opts.cwd);