-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhich.ts
More file actions
285 lines (267 loc) · 9.4 KB
/
which.ts
File metadata and controls
285 lines (267 loc) · 9.4 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* @fileoverview Look up binaries on PATH.
*
* Two pairs of public functions:
*
* `which` / `whichSync` — wrap the upstream `which` package, returning
* the first matching path (or array with `{ all: true }`). Path-like
* inputs (absolute paths, `./relative`, `../relative`) bypass PATH
* resolution and pass through unchanged. Both are tolerant — they
* return `null` for not-found instead of throwing.
*
* `whichReal` / `whichRealSync` — same but resolve the result through
* `resolveRealBinSync` so the caller gets the underlying script path
* (e.g., `npm-cli.js`) rather than the wrapper. Default `nothrow: true`
* so a missing binary returns `undefined` instead of bubbling a
* `which` package error.
*
* Caching matches `_internal.binPathCache` and `binPathAllCache`. Both
* caches validate hits with `existsSync` so a tool reinstall mid-session
* doesn't return a stale path.
*/
import whichModule from '../external/which'
import { isPath } from '../paths/normalize'
import { ArrayIsArray, ArrayPrototypeMap } from '../primordials/array'
import { binPathAllCache, binPathCache, getFs } from './_internal'
import { resolveRealBinSync } from './resolve'
import type { WhichOptions } from './types'
/**
* Find an executable in the system PATH asynchronously.
*
* This function resolves binary names to their full paths by searching the system PATH.
* It should only be used for binary names (not paths). If the input is already a path
* (absolute or relative), it will be returned as-is without PATH resolution.
*
* Binary name vs. path detection:
* - Binary names: 'npm', 'git', 'node' - will be resolved via PATH
* - Absolute paths: '/usr/bin/node', 'C:\\Program Files\\nodejs\\node.exe' - returned as-is
* - Relative paths: './node', '../bin/npm' - returned as-is
*
* @param {string} binName - The binary name to resolve (e.g., 'npm', 'git')
* @param {WhichOptions | undefined} options - Options for resolution
* @returns {Promise<string | string[] | null>} Promise resolving to the full path, the original path, or null if not found
*
* @example
* ```typescript
* // Resolve binary names
* await which('node') // '/usr/local/bin/node'
* await which('npm') // '/usr/local/bin/npm'
* await which('nonexistent') // null
*
* // Paths are returned as-is
* await which('/usr/bin/node') // '/usr/bin/node'
* await which('./local-script') // './local-script'
* ```
*/
export async function which(
binName: string,
options?: WhichOptions,
): Promise<string | string[] | null> {
// If binName is already a path (absolute or relative), return it as-is
if (isPath(binName)) {
return binName
}
try {
// whichModule returns string when found, rejects when not found
// whichModule is imported at the top
/* c8 ignore next - External which call */
const result = await whichModule(
binName,
options as import('../external/which').WhichOptions,
)
return result as string | string[]
} catch {
// Binary not found in PATH. Return type matches upstream `which`
// package contract — public callers `instanceof check` distinguish
// null vs string, so the lint rule's `undefined` recommendation
// would break them.
// oxlint-disable-next-line socket/prefer-undefined-over-null
return null
}
}
/**
* Find a binary in the system PATH and resolve to the real underlying script asynchronously.
* Resolves wrapper scripts (.cmd, .ps1, shell scripts) to the actual .js files they execute.
* @throws {Error} If the binary is not found and nothrow is false.
*
* @example
* ```typescript
* const npmPath = await whichReal('npm')
* // e.g. '/usr/local/lib/node_modules/npm/bin/npm-cli.js'
* ```
*/
export async function whichReal(
binName: string,
options?: WhichOptions,
): Promise<string | string[] | undefined> {
const fs = getFs()
// Default to nothrow: true if not specified to return undefined instead of throwing
const opts = { __proto__: null, nothrow: true, ...options } as WhichOptions
// Use cache - validate with existsSync() which is cheaper than full
// PATH search. opts.all path tested via separate which-all callers;
// stale-cache eviction fires only when a cached binary is removed
// mid-session; result-undefined arm fires only when binary is missing.
/* c8 ignore start */
if (opts.all) {
const cachedAll = binPathAllCache.get(binName)
if (cachedAll && cachedAll.length > 0) {
if (fs.existsSync(cachedAll[0]!)) {
return cachedAll
}
binPathAllCache.delete(binName)
}
} else {
const cached = binPathCache.get(binName)
if (cached) {
if (fs.existsSync(cached)) {
return cached
}
binPathCache.delete(binName)
}
}
/* c8 ignore stop */
// Depending on options `whichModule` may throw if `binName` is not found.
/* c8 ignore next - External which call */
const result = await whichModule(
binName,
opts as import('../external/which').WhichOptions,
)
// opts.all (returns array) and not-found arms.
/* c8 ignore start */
if (opts?.all) {
const paths = ArrayIsArray(result)
? result
: typeof result === 'string'
? [result]
: undefined
if (paths?.length) {
const resolved = ArrayPrototypeMap(paths, p => resolveRealBinSync(p))
binPathAllCache.set(binName, resolved)
return resolved
}
return paths
}
if (!result) {
return undefined
}
/* c8 ignore stop */
const resolved = resolveRealBinSync(result)
// Cache the resolved path.
binPathCache.set(binName, resolved)
return resolved
}
/**
* Find a binary in the system PATH and resolve to the real underlying script synchronously.
* Resolves wrapper scripts (.cmd, .ps1, shell scripts) to the actual .js files they execute.
* @throws {Error} If the binary is not found and nothrow is false.
*
* @example
* ```typescript
* const npmPath = whichRealSync('npm')
* // e.g. '/usr/local/lib/node_modules/npm/bin/npm-cli.js'
* ```
*/
export function whichRealSync(
binName: string,
options?: WhichOptions,
): string | string[] | undefined {
const fs = getFs()
// Default to nothrow: true if not specified to return undefined instead of throwing
const opts = { __proto__: null, nothrow: true, ...options } as WhichOptions
// Use cache. See whichReal for branch reachability rationale.
/* c8 ignore start */
if (opts.all) {
const cachedAll = binPathAllCache.get(binName)
if (cachedAll && cachedAll.length > 0) {
if (fs.existsSync(cachedAll[0]!)) {
return cachedAll
}
binPathAllCache.delete(binName)
}
} else {
const cached = binPathCache.get(binName)
if (cached) {
if (fs.existsSync(cached)) {
return cached
}
binPathCache.delete(binName)
}
}
/* c8 ignore stop */
// Depending on options `which` may throw if `binName` is not found.
// With nothrow: true, it returns null when `binName` is not found.
const result = whichSync(binName, opts)
// opts.all and not-found arms; see whichReal.
/* c8 ignore start */
if (opts.all) {
const paths = ArrayIsArray(result)
? result
: typeof result === 'string'
? [result]
: undefined
if (paths?.length) {
const resolved = ArrayPrototypeMap(paths, p => resolveRealBinSync(p))
binPathAllCache.set(binName, resolved)
return resolved
}
return paths
}
if (!result) {
return undefined
}
/* c8 ignore stop */
const resolved = resolveRealBinSync(result as string)
binPathCache.set(binName, resolved)
return resolved
}
/**
* Find an executable in the system PATH synchronously.
*
* This function resolves binary names to their full paths by searching the system PATH.
* It should only be used for binary names (not paths). If the input is already a path
* (absolute or relative), it will be returned as-is without PATH resolution.
*
* Binary name vs. path detection:
* - Binary names: 'npm', 'git', 'node' - will be resolved via PATH
* - Absolute paths: '/usr/bin/node', 'C:\\Program Files\\nodejs\\node.exe' - returned as-is
* - Relative paths: './node', '../bin/npm' - returned as-is
*
* @param {string} binName - The binary name to resolve (e.g., 'npm', 'git')
* @param {WhichOptions | undefined} options - Options for resolution
* @returns {string | string[] | null} The full path to the binary, the original path if input is a path, or null if not found
*
* @example
* ```typescript
* // Resolve binary names
* whichSync('node') // '/usr/local/bin/node'
* whichSync('npm') // '/usr/local/bin/npm'
* whichSync('nonexistent') // null
*
* // Paths are returned as-is
* whichSync('/usr/bin/node') // '/usr/bin/node'
* whichSync('./local-script') // './local-script'
* ```
*/
export function whichSync(
binName: string,
options?: WhichOptions,
): string | string[] | null {
// If binName is already a path (absolute or relative), return it as-is
if (isPath(binName)) {
return binName
}
try {
// whichModule.sync returns string when found, throws when not found
// whichModule is imported at the top
const result = whichModule.sync(
binName,
options as import('../external/which').WhichOptions,
)
return result as string | string[]
} catch {
// Binary not found in PATH. Return type matches upstream `which`
// package contract.
// oxlint-disable-next-line socket/prefer-undefined-over-null
return null
}
}