@@ -4,7 +4,7 @@ import execa from 'execa'
4
4
import findUp from 'find-up'
5
5
import terminalLink from 'terminal-link'
6
6
import prompts from 'prompts'
7
- import { LOCKS , INSTALL_PAGE , Agent } from './agents'
7
+ import { LOCKS , INSTALL_PAGE , Agent , AGENTS } from './agents'
8
8
import { cmdExists } from './utils'
9
9
10
10
export interface DetectOptions {
@@ -13,28 +13,41 @@ export interface DetectOptions {
13
13
}
14
14
15
15
export async function detect ( { autoInstall, cwd } : DetectOptions ) {
16
- const result = await findUp ( Object . keys ( LOCKS ) , { cwd } )
17
-
18
16
let agent : Agent | null = null
19
- // handle "packageManager"
20
- if ( result ) {
21
- const packageJSON = path . resolve ( result , '../package.json' )
22
- if ( fs . existsSync ( packageJSON ) ) {
23
- try {
24
- const pkg = JSON . parse ( fs . readFileSync ( packageJSON , 'utf8' ) )
25
- if ( pkg . packageManager ) {
26
- const [ name , version ] = pkg . packageManager . split ( '@' )
27
- if ( name === 'yarn' && parseInt ( version ) > 1 ) agent = 'yarn@berry'
28
- }
17
+
18
+ const lockPath = await findUp ( Object . keys ( LOCKS ) , { cwd } )
19
+ let packageJsonPath : string | undefined
20
+
21
+ if ( lockPath )
22
+ packageJsonPath = path . resolve ( lockPath , '../package.json' )
23
+ else
24
+ packageJsonPath = await findUp ( Object . keys ( 'package.json' ) , { cwd } )
25
+
26
+ // read `packageManager` field in package.json
27
+ if ( packageJsonPath && fs . existsSync ( packageJsonPath ) ) {
28
+ try {
29
+ const pkg = JSON . parse ( fs . readFileSync ( packageJsonPath , 'utf8' ) )
30
+ if ( typeof pkg . packageManager === 'string' ) {
31
+ const [ name , version ] = pkg . packageManager . split ( '@' )
32
+ if ( name === 'yarn' && parseInt ( version ) > 1 )
33
+ agent = 'yarn@berry'
34
+ else if ( name in AGENTS )
35
+ agent = name
36
+ else
37
+ console . warn ( '[ni] Unknown packageManager:' , pkg . packageManager )
29
38
}
30
- catch { }
31
39
}
32
- agent ||= LOCKS [ path . basename ( result ) ]
40
+ catch { }
33
41
}
34
42
43
+ // detect based on lock
44
+ if ( ! agent && lockPath )
45
+ agent = LOCKS [ path . basename ( lockPath ) ]
46
+
47
+ // auto install
35
48
if ( agent && ! cmdExists ( agent . split ( '@' ) [ 0 ] ) ) {
36
49
if ( ! autoInstall ) {
37
- console . warn ( `Detected ${ agent } but it doesn't seem to be installed.\n` )
50
+ console . warn ( `[ni] Detected ${ agent } but it doesn't seem to be installed.\n` )
38
51
39
52
if ( process . env . CI )
40
53
process . exit ( 1 )
0 commit comments