Socket
Socket
Sign inDemoInstall

@oclif/plugin-autocomplete

Package Overview
Dependencies
Maintainers
7
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@oclif/plugin-autocomplete - npm Package Compare versions

Comparing version 1.4.0-beta.1 to 1.4.0

14

lib/base.d.ts

@@ -5,17 +5,9 @@ import { Command } from '@oclif/core';

get cliBinEnvVar(): string;
determineShell(shell: string): string;
errorIfWindows(): void;
errorIfNotSupportedShell(shell: string): void;
get autocompleteCacheDir(): string;
get acLogfilePath(): string;
autocompleteSetupScriptPath(shell: string): string;
autocompleteFunctionDir(shell: string): string;
get bashCompletionFunctionPath(): string;
get zshCompletionFunctionPath(): string;
get powershellCompletionFunctionPath(): string;
get bashSetupScript(): string;
get zshSetupScript(): string;
get powershellSetupScript(): string;
determineShell(shell: string): string;
errorIfNotSupported(shell: string): void;
writeLogFile(msg: string): void;
private completionFunctionPathEnvVar;
private isBashOnWindows;
}

@@ -14,47 +14,2 @@ "use strict";

}
get autocompleteCacheDir() {
return path.join(this.config.cacheDir, 'autocomplete');
}
get acLogfilePath() {
return path.join(this.config.cacheDir, 'autocomplete.log');
}
autocompleteSetupScriptPath(shell) {
// <cachedir>/autocomplete/<shell>_setup
return path.join(this.autocompleteCacheDir, `${shell}_setup`);
}
autocompleteFunctionDir(shell) {
// <cachedir>/autocomplete/functions/<shell>
return path.join(this.autocompleteCacheDir, 'functions', shell);
}
get bashCompletionFunctionPath() {
// <cachedir>/autocomplete/functions/bash/<bin>.bash
return path.join(this.autocompleteFunctionDir('bash'), `${this.cliBin}.bash`);
}
get zshCompletionFunctionPath() {
// <cachedir>/autocomplete/functions/zsh/_<bin>
return path.join(this.autocompleteFunctionDir('zsh'), `_${this.cliBin}`);
}
get powershellCompletionFunctionPath() {
// <cachedir>/autocomplete/functions/powershell/<bin>.ps1
return path.join(this.autocompleteFunctionDir('powershell'), `${this.cliBin}.ps1`);
}
get bashSetupScript() {
const envVar = this.completionFunctionPathEnvVar('bash');
/* eslint-disable-next-line no-useless-escape */
return `${envVar}=${this.bashCompletionFunctionPath} && test -f \$${envVar} && source \$${envVar};`;
}
get zshSetupScript() {
return `
fpath=(
${this.autocompleteFunctionDir('zsh')}
$fpath
);
autoload -Uz compinit;
compinit;
`;
}
get powershellSetupScript() {
const envVar = this.completionFunctionPathEnvVar('powershell');
return `$env:${envVar}="${this.powershellCompletionFunctionPath}"; .$env:${envVar}`;
}
determineShell(shell) {

@@ -71,18 +26,22 @@ if (!shell) {

}
errorIfNotSupported(shell) {
// Error if we don't know what shell is being used
errorIfWindows() {
if (this.config.windows && !this.isBashOnWindows(this.config.shell)) {
throw new Error('Autocomplete is not currently supported in Windows');
}
}
errorIfNotSupportedShell(shell) {
if (!shell) {
this.error('Missing required argument shell');
}
// Error if the shell is not supported with the CLI's topic separator.
if (this.config.topicSeparator !== ':' && shell === 'zsh') {
throw new Error('Autocomplete for zsh is not supported in CLIs with commands separated by spaces');
}
else if (this.config.topicSeparator !== ' ' && shell === 'powershell') {
throw new Error('Autocomplete for powershell is not supported in CLIs with commands separated by colons');
}
if (!['bash', 'zsh', 'powershell'].includes(shell)) {
this.errorIfWindows();
if (!['bash', 'zsh'].includes(shell)) {
throw new Error(`${shell} is not a supported shell for autocomplete`);
}
}
get autocompleteCacheDir() {
return path.join(this.config.cacheDir, 'autocomplete');
}
get acLogfilePath() {
return path.join(this.config.cacheDir, 'autocomplete.log');
}
writeLogFile(msg) {

@@ -93,8 +52,2 @@ const entry = `[${(new Date()).toISOString()}] ${msg}\n`;

}
// Returns the name of an environment variable that points to the completion function file for the given shell.
completionFunctionPathEnvVar(shell) {
const binUpcase = this.cliBinEnvVar.replace(/-/g, '_');
const shellUpcase = shell.toUpperCase();
return `${binUpcase}_AC_${shellUpcase}_COMPFUNC_PATH`;
}
isBashOnWindows(shell) {

@@ -101,0 +54,0 @@ return shell.endsWith('\\bash.exe');

import { AutocompleteBase } from '../../base';
export default class Create extends AutocompleteBase {
static hidden: boolean;
static args: {
name: string;
description: string;
required: boolean;
}[];
static description: string;

@@ -14,12 +9,18 @@ private _commands?;

private createFiles;
private get bashSetupScriptPath();
private get zshSetupScriptPath();
private get bashFunctionsDir();
private get zshFunctionsDir();
private get bashCompletionFunctionPath();
private get zshCompletionFunctionPath();
private get bashSetupScript();
private get zshSetupScript();
private get commands();
private genZshFlagSpecs;
private get genAllCommandsMetaString();
private get genCaseStatementForFlagsMetaString();
private genCmdPublicFlags;
private get bashCommandsWithFlagsList();
private get bashCompletionFunction();
private get zshCompletionFunction();
private get powershellCommands();
private get powershellCompletionFunction();
private genCmdPublicFlags;
private genZshFlagSpecs;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const fs = require("fs-extra");
const bash_1 = require("../../autocomplete/bash");
const bash_spaces_1 = require("../../autocomplete/bash-spaces");
const powershell_1 = require("../../autocomplete/powershell");
const base_1 = require("../../base");

@@ -21,35 +21,62 @@ const debug = require('debug')('autocomplete:create');

async run() {
var _a, _b, _c;
const { args } = await this.parse(Create);
this.errorIfNotSupported((_a = args.shell) !== null && _a !== void 0 ? _a : this.config.shell);
this.errorIfWindows();
// 1. ensure needed dirs
await this.ensureDirs((_b = args.shell) !== null && _b !== void 0 ? _b : this.config.shell);
await this.ensureDirs();
// 2. save (generated) autocomplete files
await this.createFiles((_c = args.shell) !== null && _c !== void 0 ? _c : this.config.shell);
await this.createFiles();
}
async ensureDirs(shell) {
async ensureDirs() {
// ensure autocomplete cache dir
await fs.ensureDir(this.autocompleteCacheDir);
// ensure autocomplete function dir
await fs.ensureDir(this.autocompleteFunctionDir(shell));
// ensure autocomplete bash function dir
await fs.ensureDir(this.bashFunctionsDir);
// ensure autocomplete zsh function dir
await fs.ensureDir(this.zshFunctionsDir);
}
async createFiles(shell) {
switch (shell) {
case 'bash':
// TODO: remove this commented line and other code that references a bashSetupScript, it's not needed anymore
// await fs.writeFile(this.autocompleteSetupScriptPath(shell), this.bashSetupScript)
await fs.writeFile(this.bashCompletionFunctionPath, this.bashCompletionFunction);
break;
case 'zsh':
// TODO: remove this commented line and other code that references a zshSetupScript, it's not needed anymore
// await fs.writeFile(this.autocompleteSetupScriptPath(shell), this.zshSetupScript)
await fs.writeFile(this.zshCompletionFunctionPath, this.zshCompletionFunction);
break;
case 'powershell':
// TODO: remove this commented line and other code that references a powershellSetupScript, it's not needed anymore
// await fs.writeFile(this.autocompleteSetupScriptPath(shell), this.powershellSetupScript)
await fs.writeFile(this.powershellCompletionFunctionPath, this.powershellCompletionFunction);
break;
}
async createFiles() {
await fs.writeFile(this.bashSetupScriptPath, this.bashSetupScript);
await fs.writeFile(this.bashCompletionFunctionPath, this.bashCompletionFunction);
await fs.writeFile(this.zshSetupScriptPath, this.zshSetupScript);
await fs.writeFile(this.zshCompletionFunctionPath, this.zshCompletionFunction);
}
get bashSetupScriptPath() {
// <cachedir>/autocomplete/bash_setup
return path.join(this.autocompleteCacheDir, 'bash_setup');
}
get zshSetupScriptPath() {
// <cachedir>/autocomplete/zsh_setup
return path.join(this.autocompleteCacheDir, 'zsh_setup');
}
get bashFunctionsDir() {
// <cachedir>/autocomplete/functions/bash
return path.join(this.autocompleteCacheDir, 'functions', 'bash');
}
get zshFunctionsDir() {
// <cachedir>/autocomplete/functions/zsh
return path.join(this.autocompleteCacheDir, 'functions', 'zsh');
}
get bashCompletionFunctionPath() {
// <cachedir>/autocomplete/functions/bash/<bin>.bash
return path.join(this.bashFunctionsDir, `${this.cliBin}.bash`);
}
get zshCompletionFunctionPath() {
// <cachedir>/autocomplete/functions/zsh/_<bin>
return path.join(this.zshFunctionsDir, `_${this.cliBin}`);
}
get bashSetupScript() {
const setup = path.join(this.bashFunctionsDir, `${this.cliBin}.bash`);
const bin = this.cliBinEnvVar;
/* eslint-disable-next-line no-useless-escape */
return `${bin}_AC_BASH_COMPFUNC_PATH=${setup} && test -f \$${bin}_AC_BASH_COMPFUNC_PATH && source \$${bin}_AC_BASH_COMPFUNC_PATH;
`;
}
get zshSetupScript() {
return `
fpath=(
${this.zshFunctionsDir}
$fpath
);
autoload -Uz compinit;
compinit;\n`;
}
get commands() {

@@ -90,2 +117,15 @@ if (this._commands)

}
genZshFlagSpecs(Klass) {
return Object.keys(Klass.flags || {})
.filter(flag => Klass.flags && !Klass.flags[flag].hidden)
.map(flag => {
const f = (Klass.flags && Klass.flags[flag]) || { description: '' };
const isBoolean = f.type === 'boolean';
const name = isBoolean ? flag : `${flag}=-`;
const valueCmpl = isBoolean ? '' : ':';
const completion = `--${name}[${sanitizeDescription(f.description)}]${valueCmpl}`;
return `"${completion}"`;
})
.join('\n');
}
/* eslint-disable no-useless-escape */

@@ -113,2 +153,9 @@ get genAllCommandsMetaString() {

}
genCmdPublicFlags(Command) {
const Flags = Command.flags || {};
return Object.keys(Flags)
.filter(flag => !Flags[flag].hidden)
.map(flag => `--${flag}`)
.join(' ');
}
get bashCommandsWithFlagsList() {

@@ -168,34 +215,5 @@ return this.commands.map(c => {

}
get powershellCommands() {
return this.commands.map(c => c.id.replace(/:/g, this.config.topicSeparator)).sort().join(',');
}
get powershellCompletionFunction() {
const cliBin = this.cliBin;
const powershellScript = powershell_1.default;
return powershellScript.replace(/<CLI_BIN>/g, cliBin).replace(/<POWERSHELL_COMMANDS_WITH_FLAGS_LIST>/g, this.powershellCommands);
}
genCmdPublicFlags(Command) {
const Flags = Command.flags || {};
return Object.keys(Flags)
.filter(flag => !Flags[flag].hidden)
.map(flag => `--${flag}`)
.join(' ');
}
genZshFlagSpecs(Klass) {
return Object.keys(Klass.flags || {})
.filter(flag => Klass.flags && !Klass.flags[flag].hidden)
.map(flag => {
const f = (Klass.flags && Klass.flags[flag]) || { description: '' };
const isBoolean = f.type === 'boolean';
const name = isBoolean ? flag : `${flag}=-`;
const valueCmpl = isBoolean ? '' : ':';
const completion = `--${name}[${sanitizeDescription(f.description)}]${valueCmpl}`;
return `"${completion}"`;
})
.join('\n');
}
}
exports.default = Create;
Create.hidden = true;
Create.args = [{ name: 'shell', description: 'The shell for which to create an autocomplete script', required: false }];
Create.description = 'create autocomplete setup scripts and completion functions';

@@ -5,6 +5,4 @@ import { AutocompleteBase } from '../../base';

static args: {
name: string;
description: string;
required: boolean;
}[];
shell: import("@oclif/core/lib/interfaces/parser").Arg<string | undefined, Record<string, unknown>>;
};
static flags: {

@@ -11,0 +9,0 @@ 'refresh-cache': import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const os_1 = require("os");
const core_1 = require("@oclif/core");
const chalk = require("chalk");
const core_1 = require("@oclif/core");
const base_1 = require("../../base");

@@ -12,30 +11,10 @@ const create_1 = require("./create");

const shell = args.shell || this.determineShell(this.config.shell);
this.errorIfNotSupported(shell);
core_1.CliUx.ux.action.start(`${chalk.bold('Building the autocomplete cache')}`);
await create_1.default.run([shell], this.config);
core_1.CliUx.ux.action.stop();
this.errorIfNotSupportedShell(shell);
core_1.ux.action.start(`${chalk.bold('Building the autocomplete cache')}`);
await create_1.default.run([], this.config);
core_1.ux.action.stop();
if (!flags['refresh-cache']) {
const bin = this.config.bin;
const tabStr = shell === 'bash' ? '<TAB><TAB>' : '<TAB>';
const instructions = shell === 'powershell' ?
`> Add-Content -Path $PROFILE -Value (Invoke-Expression -Command "${bin} autocomplete:script ${shell}"); .$PROFILE` :
`$ printf "eval $(${bin} autocomplete:script ${shell})" >> ~/.${shell}rc; source ~/.${shell}rc`;
let note;
let codeNote;
switch (shell) {
case 'bash':
note = 'If your terminal starts as a login shell you may need to print the init script into ~/.bash_profile or ~/.profile.';
break;
case 'zsh':
note = `After sourcing, you can run \`${chalk.cyan('$ compaudit -D')}\` to ensure no permissions conflicts are present`;
break;
case 'powershell':
note = `If your terminal starts as a login shell you may need to print the init script into $PROFILE or $HOME\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1.
If you also want a menu that you can navigate with the arrow keys to show up when using autocomplete add the following to your $PROFILE:`;
codeNote = `
# Shows navigable menu of all options when hitting Tab
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete`;
break;
}
const note = shell === 'zsh' ? `After sourcing, you can run \`${chalk.cyan('$ compaudit -D')}\` to ensure no permissions conflicts are present` : 'If your terminal starts as a login shell you may need to print the init script into ~/.bash_profile or ~/.profile.';
this.log(`

@@ -45,9 +24,9 @@ ${chalk.bold(`Setup Instructions for ${bin.toUpperCase()} CLI Autocomplete ---`)}

1) Add the autocomplete env var to your ${shell} profile and source it
${chalk.cyan(instructions)}
${chalk.cyan(`$ printf "eval $(${bin} autocomplete:script ${shell})" >> ~/.${shell}rc; source ~/.${shell}rc`)}
NOTE: ${note} ${codeNote ? os_1.EOL + chalk.cyan(codeNote) : ''}
NOTE: ${note}
2) Test it out, e.g.:
${chalk.cyan(`${shell === 'powershell' ? '>' : '$'} ${bin} ${tabStr}`)} # Command completion
${chalk.cyan(`${shell === 'powershell' ? '>' : '$'} ${bin} command --${tabStr}`)} # Flag completion
${chalk.cyan(`$ ${bin} ${tabStr}`)} # Command completion
${chalk.cyan(`$ ${bin} command --${tabStr}`)} # Flag completion

@@ -61,3 +40,5 @@ Enjoy!

Index.description = 'display autocomplete installation instructions';
Index.args = [{ name: 'shell', description: 'shell type', required: false }];
Index.args = {
shell: core_1.Args.string({ description: 'shell type', required: false }),
};
Index.flags = {

@@ -70,4 +51,3 @@ 'refresh-cache': core_1.Flags.boolean({ description: 'Refresh cache (ignores displaying instructions)', char: 'r' }),

'$ <%= config.bin %> autocomplete zsh',
'$ <%= config.bin %> autocomplete powershell',
'$ <%= config.bin %> autocomplete --refresh-cache',
];

@@ -6,8 +6,7 @@ import { AutocompleteBase } from '../../base';

static args: {
name: string;
description: string;
required: boolean;
}[];
shell: import("@oclif/core/lib/interfaces/parser").Arg<string | undefined, Record<string, unknown>>;
};
run(): Promise<void>;
private get prefix();
private get suffix();
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@oclif/core");
const path = require("path");
const base_1 = require("../../base");
class Script extends base_1.AutocompleteBase {
async run() {
var _a;
const { args } = await this.parse(Script);
const shell = (_a = args.shell) !== null && _a !== void 0 ? _a : this.config.shell;
this.errorIfNotSupported(shell);
let setupScript;
switch (shell) {
case 'bash':
setupScript = this.bashSetupScript;
break;
case 'zsh':
setupScript = this.zshSetupScript;
break;
case 'powershell':
setupScript = this.powershellSetupScript;
break;
}
this.log(`${this.prefix}${setupScript}`);
const shell = args.shell || this.config.shell;
this.errorIfNotSupportedShell(shell);
const binUpcase = this.cliBinEnvVar.replace(/-/g, '_');
const shellUpcase = shell.toUpperCase();
this.log(`${this.prefix}${binUpcase}_AC_${shellUpcase}_SETUP_PATH=${path.join(this.autocompleteCacheDir, `${shell}_setup`)} && test -f $${binUpcase}_AC_${shellUpcase}_SETUP_PATH && source $${binUpcase}_AC_${shellUpcase}_SETUP_PATH;${this.suffix}`);
}

@@ -27,2 +18,5 @@ get prefix() {

}
get suffix() {
return ` # ${this.cliBin} autocomplete setup\n`;
}
}

@@ -32,2 +26,4 @@ exports.default = Script;

Script.hidden = true;
Script.args = [{ name: 'shell', description: 'shell type', required: false }];
Script.args = {
shell: core_1.Args.string({ description: 'shell type', required: false }),
};

@@ -1,1 +0,1 @@

{"version":"1.4.0-beta.1","commands":{"autocomplete:create":{"id":"autocomplete:create","description":"create autocomplete setup scripts and completion functions","strict":true,"pluginName":"@oclif/plugin-autocomplete","pluginAlias":"@oclif/plugin-autocomplete","pluginType":"core","hidden":true,"aliases":[],"flags":{},"args":[{"name":"shell","description":"The shell for which to create an autocomplete script","required":false}]},"autocomplete":{"id":"autocomplete","description":"display autocomplete installation instructions","strict":true,"pluginName":"@oclif/plugin-autocomplete","pluginAlias":"@oclif/plugin-autocomplete","pluginType":"core","aliases":[],"examples":["$ <%= config.bin %> autocomplete","$ <%= config.bin %> autocomplete bash","$ <%= config.bin %> autocomplete zsh","$ <%= config.bin %> autocomplete powershell","$ <%= config.bin %> autocomplete --refresh-cache"],"flags":{"refresh-cache":{"name":"refresh-cache","type":"boolean","char":"r","description":"Refresh cache (ignores displaying instructions)","allowNo":false}},"args":[{"name":"shell","description":"shell type","required":false}]},"autocomplete:script":{"id":"autocomplete:script","description":"outputs autocomplete config script for shells","strict":true,"pluginName":"@oclif/plugin-autocomplete","pluginAlias":"@oclif/plugin-autocomplete","pluginType":"core","hidden":true,"aliases":[],"flags":{},"args":[{"name":"shell","description":"shell type","required":false}]}}}
{"version":"1.4.0","commands":{"autocomplete:create":{"id":"autocomplete:create","description":"create autocomplete setup scripts and completion functions","strict":true,"pluginName":"@oclif/plugin-autocomplete","pluginAlias":"@oclif/plugin-autocomplete","pluginType":"core","hidden":true,"aliases":[],"flags":{},"args":{}},"autocomplete":{"id":"autocomplete","description":"display autocomplete installation instructions","strict":true,"pluginName":"@oclif/plugin-autocomplete","pluginAlias":"@oclif/plugin-autocomplete","pluginType":"core","aliases":[],"examples":["$ <%= config.bin %> autocomplete","$ <%= config.bin %> autocomplete bash","$ <%= config.bin %> autocomplete zsh","$ <%= config.bin %> autocomplete --refresh-cache"],"flags":{"refresh-cache":{"name":"refresh-cache","type":"boolean","char":"r","description":"Refresh cache (ignores displaying instructions)","allowNo":false}},"args":{"shell":{"name":"shell","description":"shell type","required":false}}},"autocomplete:script":{"id":"autocomplete:script","description":"outputs autocomplete config script for shells","strict":true,"pluginName":"@oclif/plugin-autocomplete","pluginAlias":"@oclif/plugin-autocomplete","pluginType":"core","hidden":true,"aliases":[],"flags":{},"args":{"shell":{"name":"shell","description":"shell type","required":false}}}}}
{
"name": "@oclif/plugin-autocomplete",
"description": "autocomplete plugin for oclif",
"version": "1.4.0-beta.1",
"version": "1.4.0",
"author": "Salesforce",
"bugs": "https://github.com/oclif/plugin-autocomplete/issues",
"dependencies": {
"@oclif/core": "^1.18.0",
"@oclif/core": "^2.0.2-beta.6",
"chalk": "^4.1.0",

@@ -21,3 +21,3 @@ "debug": "^4.3.4",

"@types/node": "^15.14.9",
"@types/sinon-chai": "^3.2.6",
"@types/sinon-chai": "^3.2.9",
"chai": "^4",

@@ -29,5 +29,5 @@ "eslint": "^7.3.1",

"mocha": "^8.2.1",
"nock": "^13.2.4",
"nock": "^13.3.0",
"nyc": "^15.1.0",
"oclif": "^2.3.0",
"oclif": "^3.4.6",
"shx": "^0.3.3",

@@ -34,0 +34,0 @@ "sinon": "^12.0.1",

@@ -46,8 +46,6 @@ @oclif/plugin-autocomplete

$ oclif-example autocomplete powershell
$ oclif-example autocomplete --refresh-cache
```
_See code: [src/commands/autocomplete/index.ts](https://github.com/oclif/plugin-autocomplete/blob/v1.4.0-beta.1/src/commands/autocomplete/index.ts)_
_See code: [src/commands/autocomplete/index.ts](https://github.com/oclif/plugin-autocomplete/blob/v1.4.0/src/commands/autocomplete/index.ts)_
<!-- commandsstop -->
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc