-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathfind-up.ts
58 lines (49 loc) · 1.39 KB
/
find-up.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { existsSync } from 'fs';
import * as path from 'path';
import { isDirectory } from './is-directory';
export function findUp(names: string | string[], from: string, stopOnNodeModules = false): string | null {
if (!Array.isArray(names)) {
names = [names];
}
const root = path.parse(from).root;
let currentDir = from;
while (currentDir && currentDir !== root) {
for (const name of names) {
const p = path.join(currentDir, name);
if (existsSync(p)) {
return p;
}
}
if (stopOnNodeModules) {
const nodeModuleP = path.join(currentDir, 'node_modules');
if (existsSync(nodeModuleP)) {
return null;
}
}
currentDir = path.dirname(currentDir);
}
return null;
}
export function findAllNodeModules(from: string, root?: string): string[] {
const nodeModules: string[] = [];
let current = from;
while (current && current !== root) {
const potential = path.join(current, 'node_modules');
if (existsSync(potential) && isDirectory(potential)) {
nodeModules.push(potential);
}
const next = path.dirname(current);
if (next === current) {
break;
}
current = next;
}
return nodeModules;
}