diff --git a/src/autocomplete/powershell.ts b/src/autocomplete/powershell.ts new file mode 100644 index 00000000..0d18e9b7 --- /dev/null +++ b/src/autocomplete/powershell.ts @@ -0,0 +1,470 @@ +import * as util from 'util' +import {EOL} from 'os' +import {Config, Interfaces, Command} from '@oclif/core' + +function sanitizeSummary(description?: string): string { + if (description === undefined) { + // PowerShell: + // [System.Management.Automation.CompletionResult] will error out if will error out if you pass in an empty string for the summary. + return ' ' + } + return description + .replace(/"/g, '""') // escape double quotes. + .replace(/`/g, '``') // escape backticks. + .split(EOL)[0] // only use the first line +} + +type CommandCompletion = { + id: string; + summary: string; + flags: CommandFlags; +}; + +type CommandFlags = { + [name: string]: Command.Flag.Cached; +}; + +type Topic = { + name: string; + description: string; +}; + +export default class PowerShellComp { + protected config: Config; + + private topics: Topic[]; + + private _coTopics?: string[]; + + private commands: CommandCompletion[]; + + constructor(config: Config) { + this.config = config + this.topics = this.getTopics() + this.commands = this.getCommands() + } + + private get coTopics(): string[] { + if (this._coTopics) return this._coTopics + + const coTopics: string[] = [] + + for (const topic of this.topics) { + for (const cmd of this.commands) { + if (topic.name === cmd.id) { + coTopics.push(topic.name) + } + } + } + + this._coTopics = coTopics + + return this._coTopics + } + + private genCmdHashtable(cmd: CommandCompletion): string { + const flaghHashtables: string[] = [] + + const flagNames = Object.keys(cmd.flags) + + // Add comp for the global `--help` flag. + if (!flagNames.includes('help')) { + flaghHashtables.push(' "help" = @{ "summary" = "Show help for command" }') + } + + if (flagNames.length > 0) { + for (const flagName of flagNames) { + const f = cmd.flags[flagName] + // skip hidden flags + if (f.hidden) continue + + const flagSummary = sanitizeSummary(f.summary || f.description) + + if (f.type === 'option' && f.multiple) { + flaghHashtables.push( + ` "${f.name}" = @{ + "summary" = "${flagSummary}" + "multiple" = $true +}`, + ) + } else { + flaghHashtables.push( + ` "${f.name}" = @{ "summary" = "${flagSummary}" }`, + ) + } + } + } + + const cmdHashtable = `@{ + "summary" = "${cmd.summary}" + "flags" = @{ +${flaghHashtables.join('\n')} + } +}` + return cmdHashtable + } + + private genHashtable( + key: string, + node: Record, + leafTpl?: string, + ): string { + if (!leafTpl) { + leafTpl = `"${key}" = @{ +%s +} +` + } + + const nodeKeys = Object.keys(node[key]) + + // this is a topic + if (nodeKeys.includes('_summary')) { + let childTpl = `"_summary" = "${node[key]._summary}"\n%s` + + const newKeys = nodeKeys.filter(k => k !== '_summary') + if (newKeys.length > 0) { + const childNodes: string[] = [] + + for (const newKey of newKeys) { + childNodes.push(this.genHashtable(newKey, node[key])) + } + childTpl = util.format(childTpl, childNodes.join('\n')) + + return util.format(leafTpl, childTpl) + } + // last node + return util.format(leafTpl, childTpl) + } + + const childNodes: string[] = [] + for (const k of nodeKeys) { + if (k === '_command') { + const cmd = this.commands.find(c => c.id === node[key][k]) + if (!cmd) throw new Error('no command') + + childNodes.push( + util.format('"_command" = %s', this.genCmdHashtable(cmd)), + ) + } else if (node[key][k]._command) { + const cmd = this.commands.find(c => c.id === node[key][k]._command) + if (!cmd) throw new Error('no command') + + childNodes.push( + util.format(`"${k}" = @{\n"_command" = %s\n}`, this.genCmdHashtable(cmd)), + ) + } else { + const childTpl = `"summary" = "${node[key][k]._summary}"\n"${k}" = @{ \n %s\n }` + childNodes.push( + this.genHashtable(k, node[key], childTpl), + ) + } + } + if (childNodes.length >= 1) { + return util.format(leafTpl, childNodes.join('\n')) + } + + return leafTpl + } + + public generate(): string { + const genNode = (partialId: string): Record => { + const node: Record = {} + + const nextArgs: string[] = [] + + const depth = partialId.split(':').length + + for (const t of this.topics) { + const topicNameSplit = t.name.split(':') + + if ( + t.name.startsWith(partialId + ':') && + topicNameSplit.length === depth + 1 + ) { + nextArgs.push(topicNameSplit[depth]) + + if (this.coTopics.includes(t.name)) { + node[topicNameSplit[depth]] = { + ...genNode(`${partialId}:${topicNameSplit[depth]}`), + } + } else { + node[topicNameSplit[depth]] = { + _summary: t.description, + ...genNode(`${partialId}:${topicNameSplit[depth]}`), + } + } + } + } + + for (const c of this.commands) { + const cmdIdSplit = c.id.split(':') + + if (partialId === c.id && this.coTopics.includes(c.id)) { + node._command = c.id + } + + if ( + c.id.startsWith(partialId + ':') && + cmdIdSplit.length === depth + 1 && + !nextArgs.includes(cmdIdSplit[depth]) + ) { + node[cmdIdSplit[depth]] = { + _command: c.id, + } + } + } + return node + } + + const commandTree: Record = {} + + const topLevelArgs: string[] = [] + + // Collect top-level topics and generate a cmd tree node for each one of them. + this.topics.forEach(t => { + if (!t.name.includes(':')) { + if (this.coTopics.includes(t.name)) { + commandTree[t.name] = { + ...genNode(t.name), + } + } else { + commandTree[t.name] = { + _summary: t.description, + ...genNode(t.name), + } + } + + topLevelArgs.push(t.name) + } + }) + + // Collect top-level commands and add a cmd tree node with the command ID. + this.commands.forEach(c => { + if (!c.id.includes(':') && !this.coTopics.includes(c.id)) { + commandTree[c.id] = { + _command: c.id, + } + + topLevelArgs.push(c.id) + } + }) + + const hashtables: string[] = [] + + for (const topLevelArg of topLevelArgs) { + // Generate all the hashtables for each child node of a top-level arg. + hashtables.push(this.genHashtable(topLevelArg, commandTree)) + } + + const commandsHashtable = ` +@{ +${hashtables.join('\n')} +}` + + const compRegister = ` +using namespace System.Management.Automation +using namespace System.Management.Automation.Language + +$scriptblock = { + param($WordToComplete, $CommandAst, $CursorPosition) + + $Commands = ${commandsHashtable} + + # Get the current mode + $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function + + # Everything in the current line except the CLI executable name. + $CurrentLine = $commandAst.CommandElements[1..$commandAst.CommandElements.Count] -split " " + + # Remove $WordToComplete from the current line. + if ($WordToComplete -ne "") { + if ($CurrentLine.Count -eq 1) { + $CurrentLine = @() + } else { + $CurrentLine = $CurrentLine[0..$CurrentLine.Count] + } + } + + # Save flags in current line without the \`--\` prefix. + $Flags = $CurrentLine | Where-Object { + $_ -Match "^-{1,2}(\\w+)" + } | ForEach-Object { + $_.trim("-") + } + # Set $flags to an empty hashtable if there are no flags in the current line. + if ($Flags -eq $null) { + $Flags = @{} + } + + # No command in the current line, suggest top-level args. + if ($CurrentLine.Count -eq 0) { + $Commands.GetEnumerator() | Where-Object { + $_.Key.StartsWith("$WordToComplete") + } | Sort-Object -Property key | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"), + $_.Key, + "ParameterValue", + "$($_.Value._summary ?? $_.Value._command.summary ?? " ")" + } + } else { + # Start completing command/topic/coTopic + + $NextArg = $null + $PrevNode = $null + + # Iterate over the current line to find the command/topic/coTopic hashtable + $CurrentLine | ForEach-Object { + if ($NextArg -eq $null) { + $NextArg = $Commands[$_] + } elseif ($PrevNode[$_] -ne $null) { + $NextArg = $PrevNode[$_] + } elseif ($_.StartsWith('-')) { + return + } else { + $NextArg = $PrevNode + } + + $PrevNode = $NextArg + } + + # Start completing command. + if ($NextArg._command -ne $null) { + # Complete flags + # \`cli config list -\` + if ($WordToComplete -like '-*') { + $NextArg._command.flags.GetEnumerator() | Sort-Object -Property key + | Where-Object { + # Filter out already used flags (unless \`flag.multiple = true\`). + $_.Key.StartsWith("$($WordToComplete.Trim("-"))") -and ($_.Value.multiple -eq $true -or !$flags.Contains($_.Key)) + } + | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "--$($_.Key) " : "--$($_.Key)"), + $_.Key, + "ParameterValue", + "$($NextArg._command.flags[$_.Key].summary ?? " ")" + } + } else { + # This could be a coTopic. We remove the "_command" hashtable + # from $NextArg and check if there's a command under the current partial ID. + $NextArg.remove("_command") + + if ($NextArg.keys -gt 0) { + $NextArg.GetEnumerator() | Where-Object { + $_.Key.StartsWith("$WordToComplete") + } | Sort-Object -Property key | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"), + $_.Key, + "ParameterValue", + "$($NextArg[$_.Key]._summary ?? " ")" + } + } + } + } else { + # Start completing topic. + + # Topic summary is stored as "_summary" in the hashtable. + # At this stage it is no longer needed so we remove it + # so that $NextArg contains only commands/topics hashtables + + $NextArg.remove("_summary") + + $NextArg.GetEnumerator() | Where-Object { + $_.Key.StartsWith("$WordToComplete") + } | Sort-Object -Property key | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"), + $_.Key, + "ParameterValue", + "$($NextArg[$_.Key]._summary ?? $NextArg[$_.Key]._command.summary ?? " ")" + } + } + } +} +Register-ArgumentCompleter -Native -CommandName ${this.config.bin} -ScriptBlock $scriptblock +` + + return compRegister + } + + private getTopics(): Topic[] { + const topics = this.config.topics + .filter((topic: Interfaces.Topic) => { + // it is assumed a topic has a child if it has children + const hasChild = this.config.topics.some(subTopic => + subTopic.name.includes(`${topic.name}:`), + ) + return hasChild + }) + .sort((a, b) => { + if (a.name < b.name) { + return -1 + } + if (a.name > b.name) { + return 1 + } + return 0 + }) + .map(t => { + const description = t.description ? + sanitizeSummary(t.description) : + `${t.name.replace(/:/g, ' ')} commands` + + return { + name: t.name, + description, + } + }) + + return topics + } + + private getCommands(): CommandCompletion[] { + const cmds: CommandCompletion[] = [] + + this.config.plugins.forEach(p => { + p.commands.forEach(c => { + if (c.hidden) return + const summary = sanitizeSummary(c.summary || c.description) + const flags = c.flags + cmds.push({ + id: c.id, + summary, + flags, + }) + + c.aliases.forEach(a => { + cmds.push({ + id: a, + summary, + flags, + }) + + const split = a.split(':') + + let topic = split[0] + + // Completion funcs are generated from topics: + // `force` -> `force:org` -> `force:org:open|list` + // + // but aliases aren't guaranteed to follow the plugin command tree + // so we need to add any missing topic between the starting point and the alias. + for (let i = 0; i < split.length - 1; i++) { + if (!this.topics.find(t => t.name === topic)) { + this.topics.push({ + name: topic, + description: `${topic.replace(/:/g, ' ')} commands`, + }) + } + topic += `:${split[i + 1]}` + } + }) + }) + }) + + return cmds + } +} diff --git a/src/autocomplete/zsh.ts b/src/autocomplete/zsh.ts index 814b4d81..e79570e8 100644 --- a/src/autocomplete/zsh.ts +++ b/src/autocomplete/zsh.ts @@ -133,7 +133,7 @@ _${this.config.bin} // skip hidden flags if (f.hidden) continue - f.summary = sanitizeSummary(f.summary || f.description) + const flagSummary = sanitizeSummary(f.summary || f.description) let flagSpec = '' @@ -146,7 +146,7 @@ _${this.config.bin} flagSpec += `"(-${f.char} --${f.name})"{-${f.char},--${f.name}}` } - flagSpec += `"[${f.summary}]` + flagSpec += `"[${flagSummary}]` if (f.options) { flagSpec += `:${f.name} options:(${f.options?.join(' ')})"` @@ -159,7 +159,7 @@ _${this.config.bin} flagSpec += '"*"' } - flagSpec += `--${f.name}"[${f.summary}]:` + flagSpec += `--${f.name}"[${flagSummary}]:` if (f.options) { flagSpec += `${f.name} options:(${f.options.join(' ')})"` @@ -169,10 +169,10 @@ _${this.config.bin} } } else if (f.char) { // Flag.Boolean - flagSpec += `"(-${f.char} --${f.name})"{-${f.char},--${f.name}}"[${f.summary}]"` + flagSpec += `"(-${f.char} --${f.name})"{-${f.char},--${f.name}}"[${flagSummary}]"` } else { // Flag.Boolean - flagSpec += `--${f.name}"[${f.summary}]"` + flagSpec += `--${f.name}"[${flagSummary}]"` } flagSpec += ' \\\n' diff --git a/src/base.ts b/src/base.ts index c7f5d47c..c97c818e 100644 --- a/src/base.ts +++ b/src/base.ts @@ -21,22 +21,6 @@ export abstract class AutocompleteBase extends Command { } } - public errorIfWindows() { - if (this.config.windows && !this.isBashOnWindows(this.config.shell)) { - throw new Error('Autocomplete is not currently supported in Windows') - } - } - - public errorIfNotSupportedShell(shell: string) { - if (!shell) { - this.error('Missing required argument shell') - } - this.errorIfWindows() - if (!['bash', 'zsh'].includes(shell)) { - throw new Error(`${shell} is not a supported shell for autocomplete`) - } - } - public get autocompleteCacheDir(): string { return path.join(this.config.cacheDir, 'autocomplete') } diff --git a/src/commands/autocomplete/create.ts b/src/commands/autocomplete/create.ts index 3bcc1f65..138ad556 100644 --- a/src/commands/autocomplete/create.ts +++ b/src/commands/autocomplete/create.ts @@ -4,6 +4,7 @@ import * as fs from 'fs-extra' import bashAutocomplete from '../../autocomplete/bash' import ZshCompWithSpaces from '../../autocomplete/zsh' +import PowerShellComp from '../../autocomplete/powershell' import bashAutocompleteWithSpaces from '../../autocomplete/bash-spaces' import {AutocompleteBase} from '../../base' @@ -34,7 +35,6 @@ export default class Create extends AutocompleteBase { private _commands?: CommandCompletion[] async run() { - this.errorIfWindows() // 1. ensure needed dirs await this.ensureDirs() // 2. save (generated) autocomplete files @@ -48,6 +48,8 @@ export default class Create extends AutocompleteBase { await fs.ensureDir(this.bashFunctionsDir) // ensure autocomplete zsh function dir await fs.ensureDir(this.zshFunctionsDir) + // ensure autocomplete powershell function dir + await fs.ensureDir(this.pwshFunctionsDir) } private async createFiles() { @@ -63,6 +65,8 @@ export default class Create extends AutocompleteBase { } else { const zshCompWithSpaces = new ZshCompWithSpaces(this.config) await fs.writeFile(this.zshCompletionFunctionPath, zshCompWithSpaces.generate()) + const pwshComp = new PowerShellComp(this.config) + await fs.writeFile(this.pwshCompletionFunctionPath, pwshComp.generate()) } } @@ -76,6 +80,11 @@ export default class Create extends AutocompleteBase { return path.join(this.autocompleteCacheDir, 'zsh_setup') } + private get pwshFunctionsDir(): string { + // /autocomplete/functions/powershell + return path.join(this.autocompleteCacheDir, 'functions', 'powershell') + } + private get bashFunctionsDir(): string { // /autocomplete/functions/bash return path.join(this.autocompleteCacheDir, 'functions', 'bash') @@ -86,6 +95,11 @@ export default class Create extends AutocompleteBase { return path.join(this.autocompleteCacheDir, 'functions', 'zsh') } + private get pwshCompletionFunctionPath(): string { + // /autocomplete/functions/powershell/.ps1 + return path.join(this.pwshFunctionsDir, `${this.cliBin}.ps1`) + } + private get bashCompletionFunctionPath(): string { // /autocomplete/functions/bash/.bash return path.join(this.bashFunctionsDir, `${this.cliBin}.bash`) diff --git a/src/commands/autocomplete/index.ts b/src/commands/autocomplete/index.ts index e1a332e1..69c1ac55 100644 --- a/src/commands/autocomplete/index.ts +++ b/src/commands/autocomplete/index.ts @@ -9,7 +9,11 @@ export default class Index extends AutocompleteBase { static description = 'display autocomplete installation instructions' static args = { - shell: Args.string({description: 'shell type', required: false}), + shell: Args.string({ + description: 'Shell type', + options: ['zsh', 'bash', 'powershell'], + required: false, + }), } static flags = { @@ -20,13 +24,13 @@ export default class Index extends AutocompleteBase { '$ <%= config.bin %> autocomplete', '$ <%= config.bin %> autocomplete bash', '$ <%= config.bin %> autocomplete zsh', + '$ <%= config.bin %> autocomplete powershell', '$ <%= config.bin %> autocomplete --refresh-cache', ] async run() { const {args, flags} = await this.parse(Index) const shell = args.shell || this.determineShell(this.config.shell) - this.errorIfNotSupportedShell(shell) ux.action.start(`${chalk.bold('Building the autocomplete cache')}`) await Create.run([], this.config) @@ -35,15 +39,33 @@ export default class Index extends AutocompleteBase { if (!flags['refresh-cache']) { const bin = this.config.bin const tabStr = shell === 'bash' ? '' : '' - 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.' + + const instructions = shell === 'powershell' ? + `New-Item -Type Directory -Path (Split-Path -Parent $PROFILE) -ErrorAction SilentlyContinue +Add-Content -Path $PROFILE -Value (Invoke-Expression -Command "${bin} autocomplete${this.config.topicSeparator}script ${shell}"); .$PROFILE` : + `$ printf "eval $(${bin} autocomplete${this.config.topicSeparator}script ${shell})" >> ~/.${shell}rc; source ~/.${shell}rc` + + let note = '' + + switch (shell) { + case 'zsh': + note = `After sourcing, you can run \`${chalk.cyan('$ compaudit -D')}\` to ensure no permissions conflicts are present` + break + 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 'powershell': + note = `Use the \`MenuComplete\` mode to get matching completions printed below the command line:\n${chalk.cyan('Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete')}` + } this.log(` ${chalk.bold(`Setup Instructions for ${bin.toUpperCase()} CLI Autocomplete ---`)} -1) Add the autocomplete env var to your ${shell} profile and source it -${chalk.cyan(`$ printf "eval $(${bin} autocomplete:script ${shell})" >> ~/.${shell}rc; source ~/.${shell}rc`)} +1) Add the autocomplete ${shell === 'powershell' ? 'file' : 'env var'} to your ${shell} profile and source it + +${chalk.cyan(instructions)} -NOTE: ${note} +${chalk.bold('NOTE')}: ${note} 2) Test it out, e.g.: ${chalk.cyan(`$ ${bin} ${tabStr}`)} # Command completion diff --git a/src/commands/autocomplete/script.ts b/src/commands/autocomplete/script.ts index c92819a1..85f50793 100644 --- a/src/commands/autocomplete/script.ts +++ b/src/commands/autocomplete/script.ts @@ -9,22 +9,38 @@ export default class Script extends AutocompleteBase { static hidden = true static args = { - shell: Args.string({description: 'shell type', required: false}), + shell: Args.string({ + description: 'Shell type', + options: ['zsh', 'bash', 'powershell'], + required: false, + }), } async run() { const {args} = await this.parse(Script) const shell = args.shell || this.config.shell - this.errorIfNotSupportedShell(shell) const binUpcase = this.cliBinEnvVar 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}`, - ) + if (shell === 'powershell') { + const completionFuncPath = path.join( + this.config.cacheDir, + 'autocomplete', + 'functions', + 'powershell', + `${this.cliBin}.ps1`, + ) + this.log( + `. ${completionFuncPath}`, + ) + } else { + 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}`, + ) + } } private get prefix(): string { diff --git a/test/autocomplete/powershell.test.ts b/test/autocomplete/powershell.test.ts new file mode 100644 index 00000000..6a79f210 --- /dev/null +++ b/test/autocomplete/powershell.test.ts @@ -0,0 +1,352 @@ +import {Config, Command} from '@oclif/core' +import * as path from 'path' +import {Plugin as IPlugin} from '@oclif/core/lib/interfaces' +import {expect} from 'chai' +import PowerShellComp from '../../src/autocomplete/powershell' + +class MyCommandClass implements Command.Cached { + [key: string]: unknown; + + args: {[name: string]: Command.Arg.Cached} = {} + + _base = '' + + aliases: string[] = [] + + hidden = false + + id = 'foo:bar' + + flags = {} + + new(): Command.Cached { + // @ts-expect-error this is not the full interface but enough for testing + return { + _run(): Promise { + return Promise.resolve() + }} + } + + run(): PromiseLike { + return Promise.resolve() + } +} + +const commandPluginA: Command.Loadable = { + strict: false, + aliases: [], + args: {}, + flags: { + metadata: { + name: 'metadata', + type: 'option', + char: 'm', + multiple: true, + }, + 'api-version': { + name: 'api-version', + type: 'option', + char: 'a', + multiple: false, + }, + json: { + name: 'json', + type: 'boolean', + summary: 'Format output as "json".', + allowNo: false, + }, + 'ignore-errors': { + name: 'ignore-errors', + type: 'boolean', + char: 'i', + summary: 'Ignore errors.', + allowNo: false, + }, + }, + hidden: false, + id: 'deploy', + summary: 'Deploy a project', + async load(): Promise { + return new MyCommandClass() as unknown as Command.Class + }, + pluginType: 'core', + pluginAlias: '@My/plugina', +} + +const commandPluginB: Command.Loadable = { + strict: false, + aliases: [], + args: {}, + flags: { + branch: { + name: 'branch', + type: 'option', + char: 'b', + multiple: false, + }, + }, + hidden: false, + id: 'deploy:functions', + summary: 'Deploy a function.', + async load(): Promise { + return new MyCommandClass() as unknown as Command.Class + }, + pluginType: 'core', + pluginAlias: '@My/pluginb', +} + +const commandPluginC: Command.Loadable = { + strict: false, + aliases: [], + args: {}, + flags: {}, + hidden: false, + id: 'search', + summary: 'Search for a command', + async load(): Promise { + return new MyCommandClass() as unknown as Command.Class + }, + pluginType: 'core', + pluginAlias: '@My/pluginc', +} + +const commandPluginD: Command.Loadable = { + strict: false, + aliases: [], + args: {}, + flags: {}, + hidden: false, + id: 'app:execute:code', + summary: 'execute code', + async load(): Promise { + return new MyCommandClass() as unknown as Command.Class + }, + pluginType: 'core', + pluginAlias: '@My/plugind', +} + +const pluginA: IPlugin = { + load: async (): Promise => {}, + findCommand: async (): Promise => { + return new MyCommandClass() as unknown as Command.Class + }, + name: '@My/plugina', + alias: '@My/plugina', + commands: [commandPluginA, commandPluginB, commandPluginC, commandPluginD], + _base: '', + pjson: {} as any, + commandIDs: ['deploy'], + root: '', + version: '0.0.0', + type: 'core', + hooks: {}, + topics: [{ + name: 'foo', + description: 'foo commands', + }], + valid: true, + tag: 'tag', +} + +const plugins: IPlugin[] = [pluginA] + +describe('powershell completion', () => { + const root = path.resolve(__dirname, '../../package.json') + const config = new Config({root}) + + before(async () => { + await config.load() + /* eslint-disable require-atomic-updates */ + config.plugins = plugins + config.pjson.oclif.plugins = ['@My/pluginb'] + config.pjson.dependencies = {'@My/pluginb': '0.0.0'} + for (const plugin of config.plugins) { + // @ts-expect-error private method + config.loadCommands(plugin) + // @ts-expect-error private method + config.loadTopics(plugin) + } + }) + + it('generates a valid completion file.', () => { + config.bin = 'test-cli' + const powerShellComp = new PowerShellComp(config as Config) + expect(powerShellComp.generate()).to.equal(` +using namespace System.Management.Automation +using namespace System.Management.Automation.Language + +$scriptblock = { + param($WordToComplete, $CommandAst, $CursorPosition) + + $Commands = +@{ +"app" = @{ +"_summary" = "execute code" +"execute" = @{ +"_summary" = "execute code" +"code" = @{ +"_command" = @{ + "summary" = "execute code" + "flags" = @{ + "help" = @{ "summary" = "Show help for command" } + } +} +} + +} + +} + +"deploy" = @{ +"_command" = @{ + "summary" = "Deploy a project" + "flags" = @{ + "help" = @{ "summary" = "Show help for command" } + "metadata" = @{ + "summary" = " " + "multiple" = $true +} + "api-version" = @{ "summary" = " " } + "json" = @{ "summary" = "Format output as ""json""." } + "ignore-errors" = @{ "summary" = "Ignore errors." } + } +} +"functions" = @{ +"_command" = @{ + "summary" = "Deploy a function." + "flags" = @{ + "help" = @{ "summary" = "Show help for command" } + "branch" = @{ "summary" = " " } + } +} +} +} + +"search" = @{ +"_command" = @{ + "summary" = "Search for a command" + "flags" = @{ + "help" = @{ "summary" = "Show help for command" } + } +} +} + +} + + # Get the current mode + $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function + + # Everything in the current line except the CLI executable name. + $CurrentLine = $commandAst.CommandElements[1..$commandAst.CommandElements.Count] -split " " + + # Remove $WordToComplete from the current line. + if ($WordToComplete -ne "") { + if ($CurrentLine.Count -eq 1) { + $CurrentLine = @() + } else { + $CurrentLine = $CurrentLine[0..$CurrentLine.Count] + } + } + + # Save flags in current line without the \`--\` prefix. + $Flags = $CurrentLine | Where-Object { + $_ -Match "^-{1,2}(\\w+)" + } | ForEach-Object { + $_.trim("-") + } + # Set $flags to an empty hashtable if there are no flags in the current line. + if ($Flags -eq $null) { + $Flags = @{} + } + + # No command in the current line, suggest top-level args. + if ($CurrentLine.Count -eq 0) { + $Commands.GetEnumerator() | Where-Object { + $_.Key.StartsWith("$WordToComplete") + } | Sort-Object -Property key | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"), + $_.Key, + "ParameterValue", + "$($_.Value._summary ?? $_.Value._command.summary ?? " ")" + } + } else { + # Start completing command/topic/coTopic + + $NextArg = $null + $PrevNode = $null + + # Iterate over the current line to find the command/topic/coTopic hashtable + $CurrentLine | ForEach-Object { + if ($NextArg -eq $null) { + $NextArg = $Commands[$_] + } elseif ($PrevNode[$_] -ne $null) { + $NextArg = $PrevNode[$_] + } elseif ($_.StartsWith('-')) { + return + } else { + $NextArg = $PrevNode + } + + $PrevNode = $NextArg + } + + # Start completing command. + if ($NextArg._command -ne $null) { + # Complete flags + # \`cli config list -\` + if ($WordToComplete -like '-*') { + $NextArg._command.flags.GetEnumerator() | Sort-Object -Property key + | Where-Object { + # Filter out already used flags (unless \`flag.multiple = true\`). + $_.Key.StartsWith("$($WordToComplete.Trim("-"))") -and ($_.Value.multiple -eq $true -or !$flags.Contains($_.Key)) + } + | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "--$($_.Key) " : "--$($_.Key)"), + $_.Key, + "ParameterValue", + "$($NextArg._command.flags[$_.Key].summary ?? " ")" + } + } else { + # This could be a coTopic. We remove the "_command" hashtable + # from $NextArg and check if there's a command under the current partial ID. + $NextArg.remove("_command") + + if ($NextArg.keys -gt 0) { + $NextArg.GetEnumerator() | Where-Object { + $_.Key.StartsWith("$WordToComplete") + } | Sort-Object -Property key | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"), + $_.Key, + "ParameterValue", + "$($NextArg[$_.Key]._summary ?? " ")" + } + } + } + } else { + # Start completing topic. + + # Topic summary is stored as "_summary" in the hashtable. + # At this stage it is no longer needed so we remove it + # so that $NextArg contains only commands/topics hashtables + + $NextArg.remove("_summary") + + $NextArg.GetEnumerator() | Where-Object { + $_.Key.StartsWith("$WordToComplete") + } | Sort-Object -Property key | ForEach-Object { + New-Object -Type CompletionResult -ArgumentList \` + $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"), + $_.Key, + "ParameterValue", + "$($NextArg[$_.Key]._summary ?? $NextArg[$_.Key]._command.summary ?? " ")" + } + } + } +} +Register-ArgumentCompleter -Native -CommandName test-cli -ScriptBlock $scriptblock +`) + }) +}) diff --git a/test/base.test.ts b/test/base.test.ts index aabc959d..f1aa1e81 100644 --- a/test/base.test.ts +++ b/test/base.test.ts @@ -10,9 +10,6 @@ import {AutocompleteBase} from '../src/base' Chai.use(SinonChai) const expect = Chai.expect -// autocomplete will throw error on windows -const {default: runtest} = require('./helpers/runtest') - class AutocompleteTest extends AutocompleteBase { async run() { return null @@ -24,7 +21,7 @@ const config = new Config({root}) const cmd = new AutocompleteTest([], config) -runtest('AutocompleteBase', () => { +describe('AutocompleteBase', () => { let fsWriteStub: Sinon.SinonStub let fsOpenSyncStub: Sinon.SinonStub @@ -47,29 +44,6 @@ runtest('AutocompleteBase', () => { }).to.throw() }) - it('#errorIfWindows', async () => { - cmd.config.windows = true - expect(() => { - cmd.errorIfWindows() - }).to.throw('Autocomplete is not currently supported in Windows') - }) - - it('#errorIfWindows no error with bash on windows', async () => { - cmd.config.windows = true - cmd.config.shell = 'C:\\bin\\bash.exe' - expect(() => { - cmd.errorIfWindows() - }).to.not.throw('Autocomplete is not currently supported in Windows') - }) - - it('#errorIfNotSupportedShell', async () => { - try { - cmd.errorIfNotSupportedShell('fish') - } catch (error: any) { - expect(error.message).to.eq('fish is not a supported shell for autocomplete') - } - }) - it('#autocompleteCacheDir', async () => { expect(cmd.autocompleteCacheDir).to.eq(path.join(config.cacheDir, 'autocomplete')) }) diff --git a/test/commands/autocomplete/index.test.ts b/test/commands/autocomplete/index.test.ts index 710bb763..45dc0033 100644 --- a/test/commands/autocomplete/index.test.ts +++ b/test/commands/autocomplete/index.test.ts @@ -13,6 +13,7 @@ skipWindows('autocomplete index', () => { Setup Instructions for OCLIF-EXAMPLE CLI Autocomplete --- 1) Add the autocomplete env var to your bash profile and source it + $ printf \"eval $(oclif-example autocomplete:script bash)\" >> ~/.bashrc; source ~/.bashrc NOTE: If your terminal starts as a login shell you may need to print the init script into ~/.bash_profile or ~/.profile. @@ -35,6 +36,7 @@ Enjoy! Setup Instructions for OCLIF-EXAMPLE CLI Autocomplete --- 1) Add the autocomplete env var to your zsh profile and source it + $ printf \"eval $(oclif-example autocomplete:script zsh)\" >> ~/.zshrc; source ~/.zshrc NOTE: After sourcing, you can run \`$ compaudit -D\` to ensure no permissions conflicts are present diff --git a/test/commands/autocomplete/script.test.ts b/test/commands/autocomplete/script.test.ts index 094f4cf2..84da503e 100644 --- a/test/commands/autocomplete/script.test.ts +++ b/test/commands/autocomplete/script.test.ts @@ -27,12 +27,4 @@ OCLIF_EXAMPLE_AC_ZSH_SETUP_PATH=${ `, ) }) - - test - .stdout() - .command(['autocomplete:script', 'fish']) - .catch(error => { - expect(error.message).to.contain('fish is not a supported shell for autocomplete') - }) - .it('errors on unsupported shell') })