-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
59 lines (47 loc) · 2.51 KB
/
index.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
import {color} from '@oclif/color'
import {Hook, toConfiguredId, ux} from '@oclif/core'
import * as Levenshtein from 'fast-levenshtein'
export const closest = (target: string, possibilities: string[]): string =>
possibilities.map(id => ({id, distance: Levenshtein.get(target, id, {useCollator: true})})).sort((a, b) => a.distance - b.distance)[0]?.id ?? ''
const hook: Hook.CommandNotFound = async function (opts) {
const hiddenCommandIds = new Set(opts.config.commands.filter(c => c.hidden).map(c => c.id))
const commandIDs = [
...opts.config.commandIDs,
...opts.config.commands.flatMap(c => c.aliases),
].filter(c => !hiddenCommandIds.has(c))
if (commandIDs.length === 0) return
let binHelp = `${opts.config.bin} help`
const idSplit = opts.id.split(':')
if (opts.config.findTopic(idSplit[0])) {
// if valid topic, update binHelp with topic
binHelp = `${binHelp} ${idSplit[0]}`
}
// alter the suggestion in the help scenario so that help is the first command
// otherwise the user will be presented 'did you mean 'help'?' instead of 'did you mean "help <command>"?'
let suggestion = /:?help:?/.test(opts.id) ? ['help', closest(opts.id.replace(/:?help:?/, ''), commandIDs)].join(':') : closest(opts.id, commandIDs)
const readableSuggestion = toConfiguredId(suggestion, this.config)
const originalCmd = toConfiguredId(opts.id, this.config)
this.warn(`${color.yellow(originalCmd)} is not a ${opts.config.bin} command.`)
let response = ''
try {
response = await ux.prompt(`Did you mean ${color.blueBright(readableSuggestion)}? [y/n]`, {timeout: 10_000})
} catch (error) {
this.log('')
this.debug(error)
}
if (response === 'y') {
// this will split the original command from the suggested replacement, and gather the remaining args as varargs to help with situations like:
// confit set foo-bar -> confit:set:foo-bar -> config:set:foo-bar -> config:set foo-bar
let argv = opts.argv?.length ? opts.argv : opts.id.split(':').slice(suggestion.split(':').length)
if (suggestion.startsWith('help:')) {
// the args are the command/partial command you need help for (package:version)
// we created the suggestion variable to start with "help" so slice the first entry
argv = [...suggestion.split(':').slice(1), ...argv]
// the command is just the word "help"
suggestion = 'help'
}
return this.config.runCommand(suggestion, argv)
}
this.error(`Run ${color.cmd(binHelp)} for a list of available commands.`, {exit: 127})
}
export default hook