index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. /**
  3. * Module dependencies
  4. */
  5. var fs = require('fs');
  6. var path = require('path');
  7. var isGlob = require('is-glob');
  8. var resolveDir = require('resolve-dir');
  9. var detect = require('detect-file');
  10. var mm = require('micromatch');
  11. /**
  12. * @param {String|Array} `pattern` Glob pattern or file path(s) to match against.
  13. * @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.
  14. * @return {String} Returns the first matching file.
  15. * @api public
  16. */
  17. module.exports = function (patterns, options) {
  18. options = options || {};
  19. var cwd = path.resolve(resolveDir(options.cwd || ''));
  20. if (typeof patterns === 'string') {
  21. return lookup(cwd, [patterns], options);
  22. }
  23. if (!Array.isArray(patterns)) {
  24. throw new TypeError(
  25. 'findup-sync expects a string or array as the first argument.'
  26. );
  27. }
  28. return lookup(cwd, patterns, options);
  29. };
  30. function lookup(cwd, patterns, options) {
  31. var len = patterns.length;
  32. var idx = -1;
  33. var res;
  34. while (++idx < len) {
  35. if (isGlob(patterns[idx])) {
  36. res = matchFile(cwd, patterns[idx], options);
  37. } else {
  38. res = findFile(cwd, patterns[idx], options);
  39. }
  40. if (res) {
  41. return res;
  42. }
  43. }
  44. var dir = path.dirname(cwd);
  45. if (dir === cwd) {
  46. return null;
  47. }
  48. return lookup(dir, patterns, options);
  49. }
  50. function matchFile(cwd, pattern, opts) {
  51. var isMatch = mm.matcher(pattern, opts);
  52. var files = tryReaddirSync(cwd);
  53. var len = files.length;
  54. var idx = -1;
  55. while (++idx < len) {
  56. var name = files[idx];
  57. var fp = path.join(cwd, name);
  58. if (isMatch(name) || isMatch(fp)) {
  59. return fp;
  60. }
  61. }
  62. return null;
  63. }
  64. function findFile(cwd, filename, options) {
  65. var fp = path.resolve(cwd, filename);
  66. return detect(fp, options);
  67. }
  68. function tryReaddirSync(fp) {
  69. try {
  70. return fs.readdirSync(fp);
  71. } catch (err) {
  72. // Ignore error
  73. }
  74. /* istanbul ignore next */
  75. return [];
  76. }