This repository was archived by the owner on Nov 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.ts
47 lines (41 loc) · 1.98 KB
/
autocomplete.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
import { Command, CommandArgument, ParsedArgument } from './models/command.model';
import { autocompleteArgumentName, autocompleteArgumentValue } from './argument/autocomplete-argument';
import { autocompleteCommandName, autocompleteCommandValue } from './command/autocomplete-command';
import normalize from './normalize';
import parse from './parser';
/**
* Autocomplete a user-input based on the array of `Command` passed.
* Automatically determinate if the value to autocomplete is an argument or a
* command name/value.
*
* @param input user-input from the terminal
* @param commands an array of commands with a type that extends `Command`
* @returns an array of autocomplete possibilities
*/
function autocomplete<C extends Command>(input: string, commands: C[]): string[] {
const { command, parsedArgs } = parse(input, commands);
const lastParsedArg = parsedArgs[parsedArgs.length - 1] as (ParsedArgument | undefined);
const cleanedInput = normalize(input).split(' ');
const lastInputValue = cleanedInput[cleanedInput.length - 1];
let suggested: string[] = [];
// If the command is not found yet, we need to autocomplete the command name
if (!command) {
const commandName = cleanedInput.slice(0, 1).toString();
suggested = autocompleteCommandName(commandName, commands);
}
// If an argument name is being written, autocomplete the argument name
else if (lastInputValue.startsWith('-')) {
suggested = autocompleteArgumentName(command, lastInputValue);
}
// If an argument requires a value or the value is being typed, autocomplete
// the argument value
else if (lastParsedArg && (lastParsedArg.type === 'ARG_NAME' || lastParsedArg.type === 'ARG_VALUE')) {
suggested = autocompleteArgumentValue(lastParsedArg.reflect as CommandArgument, lastInputValue);
}
// If there is a command, autocomplete the command value
else if (command) {
suggested = autocompleteCommandValue(lastInputValue, command);
}
return suggested;
}
export default autocomplete;