-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwalk.ts
More file actions
77 lines (72 loc) · 2.51 KB
/
walk.ts
File metadata and controls
77 lines (72 loc) · 2.51 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
74
75
76
77
/**
* @file Walk parent directories. `walkUp` is the lazy ancestor generator that
* `fs/find-up` and package-root lookups build on: given a starting path it
* yields that path, then each parent, up to and INCLUDING the filesystem root
* (or a caller-supplied `stopAt` boundary). Lazy so a caller can stop early
* without computing the whole chain.
*/
import process from 'node:process'
import { getNodePath } from '../node/path'
import { getSmolPath } from '../smol/path'
import { normalizePath } from './normalize'
export interface WalkUpOptions {
/**
* Starting directory. Relative `from` values are resolved against this.
* Defaults to `process.cwd()`.
*/
cwd?: string | undefined
/**
* Last directory to yield (INCLUSIVE). Traversal stops after this path is
* emitted. Defaults to the filesystem root.
*/
stopAt?: string | undefined
}
/**
* Lazily yield `from` and each of its ancestor directories, up to and including
* the filesystem root (or `stopAt`). Each yielded path is normalized to forward
* slashes.
*
* @example
* ;```ts
* for (const dir of walkUp('/a/b/c')) {
* // '/a/b/c', '/a/b', '/a', '/'
* }
*
* // Stop at a boundary (inclusive):
* [...walkUp('/a/b/c', { stopAt: '/a' })] // ['/a/b/c', '/a/b', '/a']
* ```
*
* @param from - Path to start from. Relative values resolve against `cwd`.
* @param options - `cwd` and `stopAt` boundary.
*
* @returns Generator of normalized absolute directory paths.
*/
export function* walkUp(
from: string,
options?: WalkUpOptions | undefined,
): Generator<string> {
const { cwd = process.cwd(), stopAt } = {
__proto__: null,
...options,
} as WalkUpOptions
const path = getNodePath()
// Native `dirname` via node:smol-path (one-byte Fast API) when available —
// this is the hot inner-loop call for findUp / findPackageJson. Falls back
// to node:path on stock Node. `getSmolPath()` is undefined on stock Node,
// so `dirname` is `path.dirname` in every non-smol environment (incl.
// tests); the native binding is exercised by socket-btm's own tests.
/* c8 ignore next 2 - native binding only on socket-btm smol binaries. */
const smol = getSmolPath()
const dirname = smol?.dirname ?? path.dirname
let dir = path.resolve(cwd, from)
const stopDir = stopAt ? path.resolve(cwd, stopAt) : undefined
let prev: string | undefined
while (dir !== prev) {
yield normalizePath(dir)
if (stopDir !== undefined && dir === stopDir) {
return
}
prev = dir
dir = dirname(dir)
}
}