-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
detect.ts
69 lines (62 loc) · 1.59 KB
/
detect.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
import process from 'node:process'
import prompts from '@posva/prompts'
import { detect as detectPM } from 'package-manager-detector'
import { INSTALL_PAGE } from 'package-manager-detector/constants'
import terminalLink from 'terminal-link'
import { x } from 'tinyexec'
import { cmdExists } from './utils'
export interface DetectOptions {
autoInstall?: boolean
programmatic?: boolean
cwd?: string
/**
* Should use Volta when present
*
* @see https://volta.sh/
* @default true
*/
detectVolta?: boolean
}
export async function detect({ autoInstall, programmatic, cwd }: DetectOptions = {}) {
const {
name,
agent,
version,
} = await detectPM({
cwd,
onUnknown: (packageManager) => {
if (!programmatic) {
console.warn('[ni] Unknown packageManager:', packageManager)
}
return undefined
},
}) || {}
// auto install
if (name && !cmdExists(name) && !programmatic) {
if (!autoInstall) {
console.warn(`[ni] Detected ${name} but it doesn't seem to be installed.\n`)
if (process.env.CI)
process.exit(1)
const link = terminalLink(name, INSTALL_PAGE[name])
const { tryInstall } = await prompts({
name: 'tryInstall',
type: 'confirm',
message: `Would you like to globally install ${link}?`,
})
if (!tryInstall)
process.exit(1)
}
await x(
'npm',
['i', '-g', `${name}${version ? `@${version}` : ''}`],
{
nodeOptions: {
stdio: 'inherit',
cwd,
},
throwOnError: true,
},
)
}
return agent
}