findup-sync.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * findup-sync
  3. * https://github.com/cowboy/node-findup-sync
  4. *
  5. * Copyright (c) 2013 "Cowboy" Ben Alman
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. // Nodejs libs.
  10. var path = require('path');
  11. // External libs.
  12. var glob = require('glob');
  13. // Search for a filename in the given directory or all parent directories.
  14. module.exports = function(patterns, options) {
  15. // Normalize patterns to an array.
  16. if (!Array.isArray(patterns)) { patterns = [patterns]; }
  17. // Create globOptions so that it can be modified without mutating the
  18. // original object.
  19. var globOptions = Object.create(options || {});
  20. globOptions.maxDepth = 1;
  21. globOptions.cwd = path.resolve(globOptions.cwd || '.');
  22. var files, lastpath;
  23. do {
  24. // Search for files matching patterns.
  25. files = patterns.map(function(pattern) {
  26. return glob.sync(pattern, globOptions);
  27. }).reduce(function(a, b) {
  28. return a.concat(b);
  29. }).filter(function(entry, index, arr) {
  30. return index === arr.indexOf(entry);
  31. });
  32. // Return file if found.
  33. if (files.length > 0) {
  34. return path.resolve(path.join(globOptions.cwd, files[0]));
  35. }
  36. // Go up a directory.
  37. lastpath = globOptions.cwd;
  38. globOptions.cwd = path.resolve(globOptions.cwd, '..');
  39. // If parentpath is the same as basedir, we can't go any higher.
  40. } while (globOptions.cwd !== lastpath);
  41. // No files were found!
  42. return null;
  43. };