/
cli.ts
35 lines (31 loc) · 980 Bytes
/
cli.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
/**
* @module @ddes/cli
*/
import {pickBy} from 'lodash'
import * as parseArgs from 'minimist'
import displayUsage from './displayUsage'
import loadCommands from './loadCommands'
export default async function cli() {
const commandName = process.argv[2]
const commands = await loadCommands()
const matchingCommands = pickBy(commands, (v, k) => k.startsWith(commandName))
let command = commands[commandName]
if (!command && Object.keys(matchingCommands).length === 1) {
command = commands[Object.keys(matchingCommands)[0]]
}
if (!command) {
displayUsage(
Object.keys(matchingCommands).length ? matchingCommands : commands
)
} else {
try {
const params = command.params(parseArgs(process.argv.slice(3)))
await command.handler(params)
} catch (error) {
console.error(`Error: ${error.message}`)
console.log('')
console.log(`Usage:`)
console.log(`ddes ${commandName} ${command.usage()}\n`)
}
}
}