UNPKG

1.94 kBJavaScriptView Raw
1'use strict';
2const path = require('path');
3const locatePath = require('locate-path');
4const pathExists = require('path-exists');
5
6const stop = Symbol('findUp.stop');
7
8module.exports = async (name, options = {}) => {
9 let directory = path.resolve(options.cwd || '');
10 const {root} = path.parse(directory);
11 const paths = [].concat(name);
12
13 const runMatcher = async locateOptions => {
14 if (typeof name !== 'function') {
15 return locatePath(paths, locateOptions);
16 }
17
18 const foundPath = await name(locateOptions.cwd);
19 if (typeof foundPath === 'string') {
20 return locatePath([foundPath], locateOptions);
21 }
22
23 return foundPath;
24 };
25
26 // eslint-disable-next-line no-constant-condition
27 while (true) {
28 // eslint-disable-next-line no-await-in-loop
29 const foundPath = await runMatcher({...options, cwd: directory});
30
31 if (foundPath === stop) {
32 return;
33 }
34
35 if (foundPath) {
36 return path.resolve(directory, foundPath);
37 }
38
39 if (directory === root) {
40 return;
41 }
42
43 directory = path.dirname(directory);
44 }
45};
46
47module.exports.sync = (name, options = {}) => {
48 let directory = path.resolve(options.cwd || '');
49 const {root} = path.parse(directory);
50 const paths = [].concat(name);
51
52 const runMatcher = locateOptions => {
53 if (typeof name !== 'function') {
54 return locatePath.sync(paths, locateOptions);
55 }
56
57 const foundPath = name(locateOptions.cwd);
58 if (typeof foundPath === 'string') {
59 return locatePath.sync([foundPath], locateOptions);
60 }
61
62 return foundPath;
63 };
64
65 // eslint-disable-next-line no-constant-condition
66 while (true) {
67 const foundPath = runMatcher({...options, cwd: directory});
68
69 if (foundPath === stop) {
70 return;
71 }
72
73 if (foundPath) {
74 return path.resolve(directory, foundPath);
75 }
76
77 if (directory === root) {
78 return;
79 }
80
81 directory = path.dirname(directory);
82 }
83};
84
85module.exports.exists = pathExists;
86
87module.exports.sync.exists = pathExists.sync;
88
89module.exports.stop = stop;