-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Expand file tree
/
Copy pathfind-up.ts
More file actions
73 lines (61 loc) · 1.9 KB
/
find-up.ts
File metadata and controls
73 lines (61 loc) · 1.9 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @license
* Copyright Google LLC 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.dev/license
*/
import { existsSync } from 'node:fs';
import { stat } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
/**
* Find a file or directory by walking up the directory tree.
* @param names The name or names of the files or directories to find.
* @param from The directory to start the search from.
* @returns The path to the first match found, or `null` if no match was found.
*/
export async function findUp(names: string | string[], from: string): Promise<string | null> {
const filenames = Array.isArray(names) ? names : [names];
let currentDir = resolve(from);
while (true) {
for (const name of filenames) {
const p = join(currentDir, name);
try {
await stat(p);
return p;
} catch {
// Ignore errors (e.g. file not found).
}
}
const parentDir = dirname(currentDir);
if (parentDir === currentDir) {
break;
}
currentDir = parentDir;
}
return null;
}
/**
* Synchronously find a file or directory by walking up the directory tree.
* @param names The name or names of the files or directories to find.
* @param from The directory to start the search from.
* @returns The path to the first match found, or `null` if no match was found.
*/
export function findUpSync(names: string | string[], from: string): string | null {
const filenames = Array.isArray(names) ? names : [names];
let currentDir = resolve(from);
while (true) {
for (const name of filenames) {
const p = join(currentDir, name);
if (existsSync(p)) {
return p;
}
}
const parentDir = dirname(currentDir);
if (parentDir === currentDir) {
break;
}
currentDir = parentDir;
}
return null;
}