| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 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 | |
| 9 | 'use strict'; |
| 10 | |
| 11 | // Nodejs libs. |
| 12 | var path = require('path'); |
| 13 | |
| 14 | // External libs. |
| 15 | var glob = require('glob'); |
| 16 | |
| 17 | // Search for a filename in the given directory or all parent directories. |
| 18 | module.exports = function(patterns, options) { |
| 19 | // Normalize patterns to an array. |
| 20 | if (!Array.isArray(patterns)) { patterns = [patterns]; } |
| 21 | // Create globOptions so that it can be modified without mutating the |
| 22 | // original object. |
| 23 | var globOptions = Object.create(options || {}); |
| 24 | globOptions.maxDepth = 1; |
| 25 | globOptions.cwd = path.resolve(globOptions.cwd || '.'); |
| 26 | |
| 27 | var files, lastpath; |
| 28 | do { |
| 29 | // Search for files matching patterns. |
| 30 | files = patterns.map(function(pattern) { |
| 31 | return glob.sync(pattern, globOptions); |
| 32 | }).reduce(function(a, b) { |
| 33 | return a.concat(b); |
| 34 | }).filter(function(entry, index, arr) { |
| 35 | return index === arr.indexOf(entry); |
| 36 | }); |
| 37 | // Return file if found. |
| 38 | if (files.length > 0) { |
| 39 | return path.resolve(path.join(globOptions.cwd, files[0])); |
| 40 | } |
| 41 | // Go up a directory. |
| 42 | lastpath = globOptions.cwd; |
| 43 | globOptions.cwd = path.resolve(globOptions.cwd, '..'); |
| 44 | // If parentpath is the same as basedir, we can't go any higher. |
| 45 | } while (globOptions.cwd !== lastpath); |
| 46 | |
| 47 | // No files were found! |
| 48 | return null; |
| 49 | }; |