7 var fs = require('fs');
8 var path = require('path');
9 var isGlob = require('is-glob');
10 var resolveDir = require('resolve-dir');
11 var detect = require('detect-file');
12 var mm = require('micromatch');
15 * @param {String|Array} `pattern` Glob pattern or file path(s) to match against.
16 * @param {Object} `options` Options to pass to [micromatch]. Note that if you want to start in a different directory than the current working directory, specify the `options.cwd` property here.
17 * @return {String} Returns the first matching file.
21 module.exports = function(patterns, options) {
22 options = options || {};
23 var cwd = path.resolve(resolveDir(options.cwd || ''));
25 if (typeof patterns === 'string') {
26 return lookup(cwd, [patterns], options);
29 if (!Array.isArray(patterns)) {
30 throw new TypeError('findup-sync expects a string or array as the first argument.');
33 return lookup(cwd, patterns, options);
36 function lookup(cwd, patterns, options) {
37 var len = patterns.length;
42 if (isGlob(patterns[idx])) {
43 res = matchFile(cwd, patterns[idx], options);
45 res = findFile(cwd, patterns[idx], options);
52 var dir = path.dirname(cwd);
56 return lookup(dir, patterns, options);
59 function matchFile(cwd, pattern, opts) {
60 var isMatch = mm.matcher(pattern, opts);
61 var files = tryReaddirSync(cwd);
62 var len = files.length;
66 var name = files[idx];
67 var fp = path.join(cwd, name);
68 if (isMatch(name) || isMatch(fp)) {
75 function findFile(cwd, filename, options) {
76 var fp = cwd ? path.resolve(cwd, filename) : filename;
77 return detect(fp, options);
80 function tryReaddirSync(fp) {
82 return fs.readdirSync(fp);