-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind.ts
More file actions
169 lines (163 loc) · 5.83 KB
/
find.ts
File metadata and controls
169 lines (163 loc) · 5.83 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/**
* @file Walk parent directories to locate a file or directory by name. The
* traversal includes the filesystem root (or the caller-supplied `stopAt`
* boundary) — historically the loop exited at `dir === root` _before_
* visiting root itself, so a match at e.g. `/.foo` was never found. The
* current shape visits root, then breaks.
*/
import process from 'node:process'
import { isArray } from '../arrays/predicates'
import { getAbortSignal } from '../process/abort'
import { getNodeFs } from '../node/fs'
import { getNodePath } from '../node/path'
import { normalizePath } from '../paths/normalize'
import { walkUp } from '../paths/walk'
import { getSmolPath } from '../smol/path'
import type { FindUpOptions, FindUpSyncOptions } from './types'
const abortSignal = getAbortSignal()
/**
* Find a file or directory by traversing up parent directories. Searches from
* the starting directory upward to the filesystem root. Useful for finding
* configuration files or project roots.
*
* @example
* ;```ts
* // Find package.json starting from current directory
* const pkgPath = await findUp('package.json')
*
* // Find any of multiple config files
* const configPath = await findUp(['.config.js', '.config.json'])
*
* // Find a directory instead of file
* const nodeModules = await findUp('node_modules', { onlyDirectories: true })
* ```
*
* @param name - Filename(s) to search for.
* @param options - Search options including cwd and type filters.
*
* @returns Normalized absolute path if found, undefined otherwise
*/
export async function findUp(
name: string | string[] | readonly string[],
options?: FindUpOptions | undefined,
): Promise<string | undefined> {
const { cwd = process.cwd(), signal = abortSignal } = {
__proto__: null,
...options,
} as FindUpOptions
let { onlyDirectories = false, onlyFiles = true } = {
__proto__: null,
...options,
} as FindUpOptions
if (onlyDirectories) {
onlyFiles = false
}
if (onlyFiles) {
onlyDirectories = false
}
const fs = getNodeFs()
const path = getNodePath()
const names = isArray(name) ? name : [name as string]
// walkUp computes the ancestor chain synchronously (pure dirname
// math); we await the stat inside. The async findUp has no stopAt
// option in its type, so the walk runs to the filesystem root.
for (const dir of walkUp(cwd)) {
for (const n of names) {
if (signal?.aborted) {
return undefined
}
const thePath = path.join(dir, n)
try {
// eslint-disable-next-line no-await-in-loop
// oxlint-disable-next-line socket/prefer-exists-sync -- needs stat to discriminate file vs directory matches via isFile()/isDirectory().
const stats = await fs.promises.stat(thePath)
if (!onlyDirectories && stats.isFile()) {
return normalizePath(thePath)
}
if (!onlyFiles && stats.isDirectory()) {
return normalizePath(thePath)
}
} catch {}
}
}
return undefined
}
/**
* Synchronously find a file or directory by traversing up parent directories.
* Searches from the starting directory upward to the filesystem root or
* `stopAt` directory. Useful for finding configuration files or project roots
* in synchronous contexts.
*
* @example
* ;```ts
* // Find package.json starting from current directory
* const pkgPath = findUpSync('package.json')
*
* // Find .git directory but stop at home directory
* const gitPath = findUpSync('.git', {
* onlyDirectories: true,
* stopAt: process.env.HOME,
* })
*
* // Find any of multiple config files
* const configPath = findUpSync(['.eslintrc.js', '.eslintrc.json'])
* ```
*
* @param name - Filename(s) to search for.
* @param options - Search options including cwd, stopAt, and type filters.
*
* @returns Normalized absolute path if found, undefined otherwise
*/
export function findUpSync(
name: string | string[] | readonly string[],
options?: FindUpSyncOptions | undefined,
) {
const { cwd = process.cwd(), stopAt } = {
__proto__: null,
...options,
} as FindUpSyncOptions
let { onlyDirectories = false, onlyFiles = true } = {
__proto__: null,
...options,
} as FindUpSyncOptions
if (onlyDirectories) {
onlyFiles = false
}
if (onlyFiles) {
onlyDirectories = false
}
const fs = getNodeFs()
const path = getNodePath()
const names = isArray(name) ? name : [name as string]
// Native in-C++ find-up when available — one binding call instead of N
// JS↔native crossings (a dirname-loop + a stat per candidate). Only the
// no-`stopAt` case maps to the binding's signature; bounded walks keep the
// JS path. Native may be partial (onlyFiles only), so we only delegate when
// the requested shape is expressible.
/* c8 ignore start - native findUp arm only on socket-btm smol binaries; getSmolPath() is undefined on stock Node. */
const smolFindUp = getSmolPath()?.findUp
if (smolFindUp && stopAt === undefined) {
const found = smolFindUp(path.resolve(cwd), names, { onlyDirectories })
return found === undefined ? undefined : normalizePath(found)
}
/* c8 ignore stop */
// walkUp yields each ancestor (incl. root / stopAt) lazily; the
// stopAt boundary that used to need a duplicated tail block is now
// just the generator's `stopAt` option.
for (const dir of walkUp(cwd, { stopAt })) {
for (const n of names) {
const thePath = path.join(dir, n)
try {
// oxlint-disable-next-line socket/prefer-exists-sync -- needs stat to discriminate file vs directory matches via isFile()/isDirectory().
const stats = fs.statSync(thePath)
if (!onlyDirectories && stats.isFile()) {
return normalizePath(thePath)
}
if (!onlyFiles && stats.isDirectory()) {
return normalizePath(thePath)
}
} catch {}
}
}
return undefined
}