Skip to content

Commit

Permalink
Fix: Use breadth-first search (closes #38, closes #39)
Browse files Browse the repository at this point in the history
  • Loading branch information
doowb authored and phated committed Oct 12, 2016
1 parent 05dc6d2 commit c3f231b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 34 deletions.
54 changes: 20 additions & 34 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,41 @@ var mm = require('micromatch');
*/

module.exports = function(patterns, options) {
options = options || {};
var cwd = path.resolve(resolveDir(options.cwd || ''));

if (typeof patterns === 'string') {
return lookup(patterns, options);
return lookup(cwd, [patterns], options);
}

if (!Array.isArray(patterns)) {
throw new TypeError('findup-sync expects a string or array as the first argument.');
}

return lookup(cwd, patterns, options);
};

function lookup(cwd, patterns, options) {
var len = patterns.length;
var idx = -1;
var res;

while (++idx < len) {
var res = lookup(patterns[idx], options);
if (isGlob(patterns[idx])) {
res = matchFile(cwd, patterns[idx], options);
} else {
res = findFile(cwd, patterns[idx], options);
}
if (res) {
return res;
}
}

return null;
};

function lookup(pattern, options) {
options = options || {};
var cwd = path.resolve(resolveDir(options.cwd || ''));
if (isGlob(pattern)) {
return matchFile(cwd, pattern, options);
} else {
return findFile(cwd, pattern, options);
var dir = path.dirname(cwd);
if (dir === cwd) {
return null;
}
return lookup(dir, patterns, options);
}

function matchFile(cwd, pattern, opts) {
Expand All @@ -63,32 +69,12 @@ function matchFile(cwd, pattern, opts) {
return fp;
}
}

var dir = path.dirname(cwd);
if (dir === cwd) {
return null;
}
return matchFile(dir, pattern, opts);
return null;
}

function findFile(cwd, filename, options) {
var res;
var fp = cwd ? path.resolve(cwd, filename) : filename;
if (res = detect(fp, options)) {
return res;
}

var segs = cwd.split(path.sep);
var len = segs.length;

while (len--) {
cwd = segs.slice(0, len).join(path.sep);
fp = path.resolve(cwd, filename);
if (res = detect(fp, options)) {
return res;
}
}
return null;
return detect(fp, options);
}

function tryReaddirSync(fp) {
Expand Down
6 changes: 6 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,4 +293,10 @@ describe('findup-sync', function () {
assert(exists(actual));
assert.dirname(actual, home());
});

it('should match files in cwd before searching up', function() {
var actual = findup(['a.txt', 'a.md'], { cwd: __dirname + '/fixtures/a/b' });
assert.basename(actual, 'a.md');
assert.dirname(actual, 'test/fixtures/a/b');
});
});

0 comments on commit c3f231b

Please sign in to comment.