wallet-core/node_modules/findup-sync/index.js

86 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-10-10 03:43:44 +02:00
'use strict';
/**
* Module dependencies
*/
var fs = require('fs');
var path = require('path');
var isGlob = require('is-glob');
var resolveDir = require('resolve-dir');
var detect = require('detect-file');
var mm = require('micromatch');
/**
* @param {String|Array} `pattern` Glob pattern or file path(s) to match against.
* @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.
* @return {String} Returns the first matching file.
* @api public
*/
module.exports = function(patterns, options) {
2016-11-03 01:33:53 +01:00
options = options || {};
var cwd = path.resolve(resolveDir(options.cwd || ''));
2016-10-10 03:43:44 +02:00
if (typeof patterns === 'string') {
2016-11-03 01:33:53 +01:00
return lookup(cwd, [patterns], options);
2016-10-10 03:43:44 +02:00
}
if (!Array.isArray(patterns)) {
throw new TypeError('findup-sync expects a string or array as the first argument.');
}
2016-11-03 01:33:53 +01:00
return lookup(cwd, patterns, options);
};
function lookup(cwd, patterns, options) {
2016-10-10 03:43:44 +02:00
var len = patterns.length;
var idx = -1;
2016-11-03 01:33:53 +01:00
var res;
2016-10-10 03:43:44 +02:00
while (++idx < len) {
2016-11-03 01:33:53 +01:00
if (isGlob(patterns[idx])) {
res = matchFile(cwd, patterns[idx], options);
} else {
res = findFile(cwd, patterns[idx], options);
}
2016-10-10 03:43:44 +02:00
if (res) {
return res;
}
}
2016-11-03 01:33:53 +01:00
var dir = path.dirname(cwd);
if (dir === cwd) {
return null;
2016-10-10 03:43:44 +02:00
}
2016-11-03 01:33:53 +01:00
return lookup(dir, patterns, options);
2016-10-10 03:43:44 +02:00
}
function matchFile(cwd, pattern, opts) {
var isMatch = mm.matcher(pattern, opts);
var files = tryReaddirSync(cwd);
var len = files.length;
var idx = -1;
while (++idx < len) {
var name = files[idx];
var fp = path.join(cwd, name);
if (isMatch(name) || isMatch(fp)) {
return fp;
}
}
2016-11-03 01:33:53 +01:00
return null;
2016-10-10 03:43:44 +02:00
}
function findFile(cwd, filename, options) {
var fp = cwd ? path.resolve(cwd, filename) : filename;
2016-11-03 01:33:53 +01:00
return detect(fp, options);
2016-10-10 03:43:44 +02:00
}
function tryReaddirSync(fp) {
try {
return fs.readdirSync(fp);
} catch(err) {}
return [];
}