-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwalk.ts
42 lines (36 loc) · 914 Bytes
/
walk.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
import { dirname } from 'node:path';
import { absolute } from 'empathic/resolve';
export type Options = {
/**
* The CWD for the operation.
* @default "." (process.cwd)
*/
cwd?: string;
/**
* The directory to stop at.
*
* > [NOTE]
* > This directory WILL NOT be included in the results.
*
* @default <none> (continue to system root)
*/
stop?: string;
};
/**
* Get all parent directories of {@link base}.
* Stops at {@link Options['stop']} else system root ("/").
*
* @returns An array of absolute paths of all parent directories.
*/
export function up(base: string, options?: Options): string[] {
let { stop, cwd } = options || {};
let tmp = absolute(base, cwd), root = !stop;
let prev: string, arr: string[] = [];
if (stop) stop = absolute(stop, cwd);
while (root || tmp !== stop) {
arr.push(tmp);
tmp = dirname(prev = tmp);
if (tmp === prev) break;
}
return arr;
}