8000 feat: respect packageManager · antfu-collective/ni@566b91c · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Commit 566b91c

Browse files
committed
feat: respect packageManager
1 parent 9600b05 commit 566b91c

File tree

1 file changed

+29
-16
lines changed

1 file changed

+29
-16
lines changed

src/detect.ts

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import execa from 'execa'
44
import findUp from 'find-up'
55
import terminalLink from 'terminal-link'
66
import prompts from 'prompts'
7-
import { LOCKS, INSTALL_PAGE, Agent } from './agents'
7+
import { LOCKS, INSTALL_PAGE, Agent, AGENTS } from './agents'
88
import { cmdExists } from './utils'
99

1010
export interface DetectOptions {
@@ -13,28 +13,41 @@ export interface DetectOptions {
1313
}
1414

1515
export async function detect({ autoInstall, cwd }: DetectOptions) {
16-
const result = await findUp(Object.keys(LOCKS), { cwd })
17-
1816
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)
2938
}
30-
catch {}
3139
}
32-
agent ||= LOCKS[path.basename(result)]
40+
catch {}
3341
}
3442

43+
// detect based on lock
44+
if (!agent && lockPath)
45+
agent = LOCKS[path.basename(lockPath)]
46+
47+
// auto install
3548
if (agent && !cmdExists(agent.split('@')[0])) {
3649
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`)
3851

3952
if (process.env.CI)
4053
process.exit(1)

0 commit comments

Comments
 (0)
0