-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
helpers.ts
72 lines (58 loc) · 1.69 KB
/
helpers.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
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
import fs from 'node:fs'
import path from 'node:path'
import { CWD, EXTENSIONS, cjsRequire } from './constants.js'
export const tryPkg = (pkg: string) => {
try {
return cjsRequire.resolve(pkg)
} catch {}
}
export const isPkgAvailable = (pkg: string) => !!tryPkg(pkg)
export const tryFile = (filePath?: string[] | string, includeDir = false) => {
if (typeof filePath === 'string') {
return fs.existsSync(filePath) &&
(includeDir || fs.statSync(filePath).isFile())
? filePath
: ''
}
for (const file of filePath ?? []) {
if (tryFile(file, includeDir)) {
return file
}
}
return ''
}
export const tryExtensions = (filepath: string, extensions = EXTENSIONS) => {
const ext = [...extensions, ''].find(ext => tryFile(filepath + ext))
return ext == null ? '' : filepath + ext
}
export const findUp = (
searchEntry: string,
searchFileOrIncludeDir?: boolean | string,
includeDir?: boolean,
) => {
console.assert(path.isAbsolute(searchEntry))
if (
!tryFile(searchEntry, true) ||
(searchEntry !== CWD && !searchEntry.startsWith(CWD + path.sep))
) {
return ''
}
searchEntry = path.resolve(
fs.statSync(searchEntry).isDirectory()
? searchEntry
: path.resolve(searchEntry, '..'),
)
const isSearchFile = typeof searchFileOrIncludeDir === 'string'
const searchFile = isSearchFile ? searchFileOrIncludeDir : 'package.json'
do {
const searched = tryFile(
path.resolve(searchEntry, searchFile),
isSearchFile && includeDir,
)
if (searched) {
return searched
}
searchEntry = path.resolve(searchEntry, '..')
} while (searchEntry === CWD || searchEntry.startsWith(CWD + path.sep))
return ''
}