UNPKG

1.84 kBJavaScriptView Raw
1'use strict';
2
3const fs = require('fs');
4const mm = require('micromatch');
5
6const matchers = [];
7
8/**
9 * Add glob patterns to ignore matched files and folders.
10 * Creates glob patterns to approximate gitignore patterns.
11 * @param {String} val - the glob or gitignore-style pattern to ignore
12 * @see {@linkplain https://git-scm.com/docs/gitignore#_pattern_format}
13 */
14function addIgnorePattern(val) {
15 if (val && typeof val === 'string' && val[0] !== '#') {
16 let pattern = val;
17 if (pattern.indexOf('/') === -1) {
18 matchers.push('**/' + pattern);
19 } else if (pattern[pattern.length-1] === '/') {
20 matchers.push('**/' + pattern + '**');
21 matchers.push(pattern + '**');
22 }
23 matchers.push(pattern);
24 }
25}
26
27/**
28 * Adds ignore patterns directly from function input
29 * @param {String|Array<String>} input - the ignore patterns
30 */
31function addIgnoreFromInput(input) {
32 let patterns = [];
33 if (input) {
34 patterns = patterns.concat(input);
35 }
36 patterns.forEach(addIgnorePattern);
37}
38
39/**
40 * Adds ignore patterns by reading files
41 * @param {String|Array<String>} input - the paths to the ignore config files
42 */
43function addIgnoreFromFile(input) {
44 let lines = [];
45 let files = [];
46 if (input) {
47 files = files.concat(input);
48 }
49
50 files.forEach(function(config) {
51 const stats = fs.statSync(config);
52 if (stats.isFile()) {
53 const content = fs.readFileSync(config, 'utf8');
54 lines = lines.concat(content.split(/\r?\n/));
55 }
56 });
57
58 lines.forEach(addIgnorePattern);
59}
60
61function shouldIgnore(path) {
62 const matched = matchers.length ? mm.isMatch(path, matchers, { dot:true }) : false;
63 return matched;
64}
65
66exports.add = addIgnoreFromInput;
67exports.addFromFile = addIgnoreFromFile;
68exports.shouldIgnore = shouldIgnore;