Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
107 lines (98 loc) · 2.54 KB
/
Copy pathmain.ts
File metadata and controls
107 lines (98 loc) · 2.54 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
import mri, {
DictionaryObject,
Options as MriOptions,
ArrayOrString,
} from 'mri'
import chalk from 'chalk'
import { dasherizeOption, CommandError } from './util'
import { commands } from './load-commands'
const defaultCommand = 'open'
let args = process.argv.slice(2)
if (!args[0]) {
args[0] = '.'
}
const commandArg = args[0]
args = args.slice(1)
const supportsCommand = (name: string) => Object.hasOwn(commands, name)
;(function attemptRun(name: string) {
try {
if (supportsCommand(name)) {
runCommand(name)
} else if (name.startsWith('--')) {
attemptRun(name.slice(2))
} else {
try {
args.unshift(commandArg)
runCommand(defaultCommand)
} catch (err) {
logError(err)
args = []
runCommand('help')
}
}
} catch (err) {
logError(err)
args = [name]
runCommand('help')
}
})(commandArg)
function logError(err: CommandError) {
console.log(chalk.bgBlack.red('ERR!'), err.message)
if (err.stack && !err.pretty) {
console.log(chalk.gray(err.stack))
}
}
console.log() // nice blank line before the command prompt
interface IMRIOpts extends MriOptions {
alias: DictionaryObject<ArrayOrString>
boolean: Array<string>
default: DictionaryObject
string: Array<string>
}
function runCommand(name: string) {
const command = commands[name]
const opts: IMRIOpts = {
alias: {},
boolean: [],
default: {},
string: [],
}
if (command.options) {
for (const flag of Object.keys(command.options)) {
const flagOptions = command.options[flag]
if (flagOptions.aliases) {
opts.alias[flag] = flagOptions.aliases
}
if (Object.hasOwn(flagOptions, 'default')) {
opts.default[flag] = flagOptions.default
}
switch (flagOptions.type) {
case 'string':
opts.string.push(flag)
break
case 'boolean':
opts.boolean.push(flag)
break
}
}
opts.unknown = command.unknownOptionHandler
}
const parsedArgs = mri(args, opts)
if (command.options) {
for (const flag of Object.keys(parsedArgs)) {
if (!(flag in command.options)) {
continue
}
const value = parsedArgs[flag]
const expectedType = command.options[flag].type
if (typeof value !== expectedType) {
throw new CommandError(
`Value passed to flag ${dasherizeOption(
flag
)} was of type ${typeof value}, but was expected to be of type ${expectedType}`
)
}
}
}
command.handler(parsedArgs, args)
}