findup-sync.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. var _ = require('lodash');
  14. // Search for a filename in the given directory or all parent directories.
  15. module.exports = function(patterns, options) {
  16. // Normalize patterns to an array.
  17. if (!Array.isArray(patterns)) { patterns = [patterns]; }
  18. // Create globOptions so that it can be modified without mutating the
  19. // original object.
  20. var globOptions = Object.create(options || {});
  21. globOptions.maxDepth = 1;
  22. globOptions.cwd = path.resolve(globOptions.cwd || '.');
  23. var files, lastpath;
  24. do {
  25. // Search for files matching patterns.
  26. files = _(patterns).map(function(pattern) {
  27. return glob.sync(pattern, globOptions);
  28. }).flatten().uniq().value();
  29. // Return file if found.
  30. if (files.length > 0) {
  31. return path.resolve(path.join(globOptions.cwd, files[0]));
  32. }
  33. // Go up a directory.
  34. lastpath = globOptions.cwd;
  35. globOptions.cwd = path.resolve(globOptions.cwd, '..');
  36. // If parentpath is the same as basedir, we can't go any higher.
  37. } while (globOptions.cwd !== lastpath);
  38. // No files were found!
  39. return null;
  40. };