lib/completion.ts
414 LOC · 414 covered · 0 uncovered · 109 ranges · 1119 concepts · 44 introducers · 788 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
import {PlatformShim, assertNotStrictEqual} from './typings/common-types.js';
import * as templates from './completion-templates.js';
import {isPromise} from './utils/is-promise.js';
import {parseCommand} from './parse-command.js';
import {UsageInstance} from './usage.js';
import {YargsInstance} from './yargs-factory.js';
import {Arguments, DetailedArguments} from './typings/yargs-parser-types.js';
// add bash completions to your
// yargs-powered applications.
type CompletionCallback = (
err: Error | null,
completions: string[] | undefined
) => void;
/** Instance of the completion module. */
export interface CompletionInstance {
completionKey: string;
generateCompletionScript($0: string, cmd: string): string;
getCompletion(
args: string[],
done: (err: Error | null, completions: string[] | undefined) => void
): any;
registerFunction(fn: CompletionFunction): void;
setParsed(parsed: DetailedArguments): void;
}
export class Completion implements CompletionInstance {
completionKey = 'get-yargs-completions';
private aliases: DetailedArguments['aliases'] | null = null;
private customCompletionFunction: CompletionFunction | null = null;
private indexAfterLastReset = 0;
private readonly zshShell: boolean;
constructor(
private readonly usage: UsageInstance,
private readonly command: CommandInstance,
private readonly shim: PlatformShim
) {
this.zshShell =
(this.shim.getEnv('SHELL')?.includes('zsh') ||
this.shim.getEnv('ZSH_NAME')?.includes('zsh')) ??
false;
}
private defaultCompletion(
argv: Arguments,
current: string,
done: CompletionCallback
): Arguments | void {
const handlers = this.command.getCommandHandlers();
for (let i = 0, ii = args.length; i < ii; ++i) {
if (isCommandBuilderCallback(builder)) {
const y = this.yargs.getInternalMethods().reset();
builder(y, true);
return y.argv;
}
const completions: string[] = [];
this.commandCompletions(completions, args, current);
this.optionCompletions(completions, args, argv, current);
this.choicesFromOptionsCompletions(completions, args, argv, current);
this.choicesFromPositionalsCompletions(completions, args, argv, current);
done(null, completions);
}
// Default completions for commands
private commandCompletions(
args: string[],
current: string
) {
const parentCommands = this.yargs
.getInternalMethods()
.getContext().commands;
if (
!current.match(/^-/) &&
parentCommands[parentCommands.length - 1] !== current &&
if (args.indexOf(commandName) === -1) {
if (!this.zshShell) {
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
}
}
// Default completions for - and -- options
private optionCompletions(
args: string[],
argv: Arguments,
current: string
) {
if (
(current.match(/^-/) || (current === '' && completions.length === 0)) &&
const positionalKeys =
this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
Object.keys(options.key).forEach(key => {
!!options.configuration['boolean-negation'] &&
options.boolean.includes(key);
const isPositionalKey = positionalKeys.includes(key);
// If the key is not positional and its aliases aren't in 'args', add the key to 'completions'
if (
!isPositionalKey &&
!options.hiddenOptions.includes(key) &&
key,
completions,
current,
negable && !!options.default[key]
);
}
}
private choicesFromOptionsCompletions(
args: string[],
argv: Arguments,
current: string
) {
if (this.previousArgHasChoices(args)) {
if (choices && choices.length > 0) {
completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
}
}
private choicesFromPositionalsCompletions(
args: string[],
argv: Arguments,
current: string
) {
if (
current === '' &&
completions.length > 0 &&
}
const positionalKeys =
const offset = Math.max(
this.indexAfterLastReset,
this.yargs.getInternalMethods().getContext().commands.length +
/* name of the script is first param */ 1
);
const positionalKey = positionalKeys[argv._.length - offset - 1];
if (!positionalKey) {
}
for (const choice of choices) {
completions.push(choice.replace(/:/g, '\\:'));
}
}
private getPreviousArgChoices(args: string[]): string[] | void {
let filter = '';
// use second to last argument if the last one is not an option starting with --
previousArg = args[args.length - 2];
}
const options = this.yargs.getOptions();
const possibleAliases = [
previousArgKey,
];
let choices: string[] | undefined;
// Find choices across all possible aliases
for (const possibleAlias of possibleAliases) {
Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
break;
}
if (choices) {
}
private previousArgHasChoices(args: string[]): boolean {
return choices !== undefined && choices.length > 0;
}
private argsContainKey(
key: string,
negable: boolean
): boolean {
const argsContains = (s: string) =>
args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
if (argsContains(key)) return true;
if (negable && argsContains(`no-${key}`)) return true;
for (const alias of this.aliases[key]) {
}
return false;
}
// Add completion for a single - or -- option
private completeOptionKey(
completions: string[],
current: string,
negable: boolean
) {
let keyWithDesc = key;
if (this.zshShell) {
const aliasKey = this?.aliases?.[key]?.find(alias => {
return typeof desc === 'string' && desc.length > 0;
const descFromAlias = aliasKey ? descs[aliasKey] : undefined;
const desc = descs[key] ?? descFromAlias ?? '';
keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc
.replace('__yargsString__:', '')
.replace(/(\r\n|\n|\r)/gm, ' ')}`;
}
const startsByTwoDashes = (s: string) => /^--/.test(s);
const isShortOption = (s: string) => /^[^0-9]$/.test(s);
const dashes =
!startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
completions.push(dashes + keyWithDesc);
if (negable) {
}
// a custom completion function can be provided
// to completion().
private customCompletion(
argv: Arguments,
current: string,
done: CompletionCallback
) {
assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
if (isSyncCompletionFunction(this.customCompletionFunction)) {
// promise based completion function.
if (isPromise(result)) {
.then(list => {
done(null, list);
});
.catch(err => {
done(err, undefined);
});
}
return done(null, result);
current,
argv,
(onCompleted = done) =>
this.defaultCompletion(args, argv, current, onCompleted),
completions => {
}
current,
argv,
completions => {
done(null, completions);
}
);
}
// get a list of completion commands.
// 'args' is the array of strings from the line to be completed
getCompletion(args: string[], done: CompletionCallback): any {
const argv = this.yargs.parse(args, true);
const completionFunction = this.customCompletionFunction
? (argv: Arguments) => this.customCompletion(args, argv, current, done)
: (argv: Arguments) => this.defaultCompletion(args, argv, current, done);
return isPromise(argv)
? argv.then(completionFunction)
: completionFunction(argv);
}
// generate the completion script to add to your .bashrc.
generateCompletionScript($0: string, cmd: string): string {
? templates.completionZshTemplate
: templates.completionShTemplate;
const name = this.shim.path.basename($0);
// add ./ to applications not yet installed as bin.
if ($0.match(/\.js$/)) $0 = `./${$0}`;
script = script.replace(/{{app_name}}/g, name);
script = script.replace(/{{completion_command}}/g, cmd);
return script.replace(/{{app_path}}/g, $0);
}
// register a function to perform your own custom
// completions. this function can be either
// synchronous or asynchronous.
registerFunction(fn: CompletionFunction) {
}
setParsed(parsed: DetailedArguments) {
}
// For backwards compatibility
export function completion(
usage: UsageInstance,
command: CommandInstance,
shim: PlatformShim
): CompletionInstance {
return new Completion(yargs, usage, command, shim);
}
export type CompletionFunction =
SyncCompletionFunction | AsyncCompletionFunction | FallbackCompletionFunction;
interface SyncCompletionFunction {
(current: string, argv: Arguments): string[] | Promise<string[]>;
}
interface AsyncCompletionFunction {
(current: string, argv: Arguments, done: (completions: string[]) => any): any;
}
interface FallbackCompletionFunction {
(
current: string,
argv: Arguments,
completionFilter: (onCompleted?: CompletionCallback) => any,
done: (completions: string[]) => any
): any;
}
completionFunction: CompletionFunction
): completionFunction is SyncCompletionFunction {
return completionFunction.length < 3;
}
completionFunction: CompletionFunction
): completionFunction is FallbackCompletionFunction {
return completionFunction.length > 3;
}