diff --git a/README.md b/README.md index 04640ce..dfd33a8 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,14 @@ entry.isDirectory() // => true if directory // => ['one.txt', 'subdir/two.txt'] ``` +* `ignore`: An array of globs. Files and directories that match at least one + of the provided globs will be pruned while searching. + + ```js + var paths = walkSync('project', { ignore: ['subdir'] }) + // => ['one.txt'] + ``` + ## Background `walkSync(baseDir)` is a faster substitute for diff --git a/index.js b/index.js index ff4c16d..4552f4a 100644 --- a/index.js +++ b/index.js @@ -45,20 +45,30 @@ function _walkSync(baseDir, options, _relativePath) { // https://github.com/joyent/node/pull/6929 var relativePath = handleRelativePath(_relativePath); var globs = options.globs; - var m; + var ignorePatterns = options.ignore; + var globMatcher, ignoreMatcher; + var results = []; + + if (ignorePatterns) { + ignoreMatcher = new MatcherCollection(ignorePatterns); + } if (globs) { - m = new MatcherCollection(globs); + globMatcher = new MatcherCollection(globs); } - var results = []; - if (m && !m.mayContain(relativePath)) { + if (globMatcher && !globMatcher.mayContain(relativePath)) { return results; } var names = fs.readdirSync(baseDir + '/' + relativePath); var entries = names.map(function (name) { var entryRelativePath = relativePath + name; + + if (ignoreMatcher && ignoreMatcher.match(entryRelativePath)) { + return; + } + var fullPath = baseDir + '/' + entryRelativePath; var stats = getStat(fullPath); @@ -86,12 +96,12 @@ function _walkSync(baseDir, options, _relativePath) { var entry = sortedEntries[i]; if (entry.isDirectory()) { - if (options.directories !== false && (!m || m.match(entry.relativePath))) { + if (options.directories !== false && (!globMatcher || globMatcher.match(entry.relativePath))) { results.push(entry); } results = results.concat(_walkSync(baseDir, options, entry.relativePath)); } else { - if (!m || m.match(entry.relativePath)) { + if (!globMatcher || globMatcher.match(entry.relativePath)) { results.push(entry); } } diff --git a/test/test.js b/test/test.js index d91ad0e..cae425a 100644 --- a/test/test.js +++ b/test/test.js @@ -231,3 +231,45 @@ test('walkSync with matchers', function (t) { t.end(); }); + +test('walksync with ignore pattern', function (t) { + t.deepEqual(walkSync('test/fixtures', { + ignore: ['dir'] + }), [ + 'foo.txt', + 'foo/', + 'foo/a.js', + 'some-other-dir/', + 'some-other-dir/qux.txt', + 'symlink1/', + 'symlink1/qux.txt', + 'symlink2' + ]); + + t.deepEqual(walkSync('test/fixtures', { + ignore: ['**/subdir'] + }), [ + 'dir/', + 'dir/bar.txt', + 'dir/zzz.txt', + 'foo.txt', + 'foo/', + 'foo/a.js', + 'some-other-dir/', + 'some-other-dir/qux.txt', + 'symlink1/', + 'symlink1/qux.txt', + 'symlink2' + ]); + + t.deepEqual(walkSync('test/fixtures', { + globs: ['**/*.txt'], + ignore: ['dir'] + }), [ + 'foo.txt', + 'some-other-dir/qux.txt', + 'symlink1/qux.txt' + ]); + + t.end(); +});