forked from antfu-collective/ni
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.ts
94 lines (74 loc) · 2.59 KB
/
parse.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import type { Agent, Command, ResolvedCommand } from 'package-manager-detector'
import { exclude } from './utils'
import type { Runner } from './runner'
import { COMMANDS, constructCommand } from '.'
export class UnsupportedCommand extends Error {
constructor({ agent, command }: { agent: Agent, command: Command }) {
super(`Command "${command}" is not support by agent "${agent}"`)
}
}
export function getCommand(
agent: Agent,
command: Command,
args: string[] = [],
): ResolvedCommand {
if (!COMMANDS[agent])
throw new Error(`Unsupported agent "${agent}"`)
if (!COMMANDS[agent][command])
throw new UnsupportedCommand({ agent, command })
return constructCommand(COMMANDS[agent][command], args)!
}
export const parseNi = <Runner>((agent, args, ctx) => {
// bun use `-d` instead of `-D`, #90
if (agent === 'bun')
args = args.map(i => i === '-D' ? '-d' : i)
if (args.includes('-g'))
return getCommand(agent, 'global', exclude(args, '-g'))
if (args.includes('--frozen-if-present')) {
args = exclude(args, '--frozen-if-present')
return getCommand(agent, ctx?.hasLock ? 'frozen' : 'install', args)
}
if (args.includes('--frozen'))
return getCommand(agent, 'frozen', exclude(args, '--frozen'))
if (args.length === 0 || args.every(i => i.startsWith('-')))
return getCommand(agent, 'install', args)
return getCommand(agent, 'add', args)
})
export const parseNr = <Runner>((agent, args) => {
if (args.length === 0)
args.push('start')
let hasIfPresent = false
if (args.includes('--if-present')) {
args = exclude(args, '--if-present')
hasIfPresent = true
}
const cmd = getCommand(agent, 'run', args)
if (!cmd)
return cmd
if (hasIfPresent)
cmd.args.splice(1, 0, '--if-present')
return cmd
})
export const parseNu = <Runner>((agent, args) => {
if (args.includes('-i'))
return getCommand(agent, 'upgrade-interactive', exclude(args, '-i'))
return getCommand(agent, 'upgrade', args)
})
export const parseNun = <Runner>((agent, args) => {
if (args.includes('-g'))
return getCommand(agent, 'global_uninstall', exclude(args, '-g'))
return getCommand(agent, 'uninstall', args)
})
export const parseNlx = <Runner>((agent, args) => {
return getCommand(agent, 'execute', args)
})
export const parseNa = <Runner>((agent, args) => {
return getCommand(agent, 'agent', args)
})
export function serializeCommand(command?: ResolvedCommand) {
if (!command)
return undefined
if (command.args.length === 0)
return command.command
return `${command.command} ${command.args.map(i => i.includes(' ') ? `"${i}"` : i).join(' ')}`
}