Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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('findup-sync expects a string or array as the first argument.');
  25. }
  26. return lookup(cwd, patterns, options);
  27. };
  28. function lookup(cwd, patterns, options) {
  29. var len = patterns.length;
  30. var idx = -1;
  31. var res;
  32. while (++idx < len) {
  33. if (isGlob(patterns[idx])) {
  34. res = matchFile(cwd, patterns[idx], options);
  35. } else {
  36. res = findFile(cwd, patterns[idx], options);
  37. }
  38. if (res) {
  39. return res;
  40. }
  41. }
  42. var dir = path.dirname(cwd);
  43. if (dir === cwd) {
  44. return null;
  45. }
  46. return lookup(dir, patterns, options);
  47. }
  48. function matchFile(cwd, pattern, opts) {
  49. var isMatch = mm.matcher(pattern, opts);
  50. var files = tryReaddirSync(cwd);
  51. var len = files.length;
  52. var idx = -1;
  53. while (++idx < len) {
  54. var name = files[idx];
  55. var fp = path.join(cwd, name);
  56. if (isMatch(name) || isMatch(fp)) {
  57. return fp;
  58. }
  59. }
  60. return null;
  61. }
  62. function findFile(cwd, filename, options) {
  63. var fp = cwd ? path.resolve(cwd, filename) : filename;
  64. return detect(fp, options);
  65. }
  66. function tryReaddirSync(fp) {
  67. try {
  68. return fs.readdirSync(fp);
  69. } catch (err) {
  70. // Ignore error
  71. }
  72. return [];
  73. }