Add built-in PowerShell shell completion support (#3637)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents b551fe8, cbc6765 · Browse files · 4 files·+159 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+159 added−1 removed
- tests:+31 added−0 removed
- other:+128 added−1 removed
Provenance
- Commit
7df2f82- Tree
9b604ad- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
b551fe8- Parent 2
cbc6765
4 files changed+159 added−1 removed
modified:docs/shell-completion.md+27 added-1 removed
27 unmodified lines28 depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to29 `{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is30 conventional but not strictly required for environment variable names to be in upper case. This convention helps31 distinguish environment variables from regular shell variables and commands, making scripts and configuration files more32-readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.32+readable and easier to maintain. The built-in shells are `bash`, `zsh`, `fish`, and `powershell`.33 34 Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.35 36 ```{eval-rst}24 unmodified lines61 _FOO_BAR_COMPLETE=fish_source foo-bar | source62 63 This is the same file used for the activation script method64 below. For Fish it's probably always easier to use that method.65+66+ .. group-tab:: PowerShell67+68+ Add this to your PowerShell profile (the path of ``$PROFILE``):69+70+ .. code-block:: powershell71+72+ $env:_FOO_BAR_COMPLETE = 'powershell_source'73+ foo-bar | Out-String | Invoke-Expression74+ Remove-Item Env:_FOO_BAR_COMPLETE75 ```76 77 Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell78 responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead36 unmodified lines115 116 .. code-block:: fish117 118 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish119+120+ .. group-tab:: PowerShell121+122+ Save the script somewhere.123+124+ .. code-block:: powershell125+126+ $env:_FOO_BAR_COMPLETE = 'powershell_source'127+ foo-bar | Out-File -Encoding utf8 ~/.foo-bar-complete.ps1128+ Remove-Item Env:_FOO_BAR_COMPLETE129+130+ Source the file in your PowerShell profile (the path of ``$PROFILE``):131+132+ .. code-block:: powershell133+134+ . ~/.foo-bar-complete.ps1135 ```136 137 After modifying the shell config, you need to start a new shell in order for the changes to be loaded.138 137 unmodified linesmodified:src/click/shell_completion.py+97 added
204 unmodified lines205 complete --no-files --command %(prog_name)s --arguments \206 "(%(complete_func)s)";207 """208 209+# Compatible with Windows PowerShell 5.1+ and PowerShell (pwsh) 7+.210+# Uses Register-ArgumentCompleter -Native, which receives the command AST211+# as parsed by PowerShell. The command text is forwarded verbatim through212+# COMP_WORDS so the Python side can reuse the same shlex-based splitting213+# used by the bash/zsh completers.214+_SOURCE_POWERSHELL = """\215+Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock {216+ param($wordToComplete, $commandAst, $cursorPosition)217 218+ $prev_complete = $env:%(complete_var)s219+ $prev_words = $env:COMP_WORDS220+ $prev_cword = $env:COMP_CWORD221+222+ $env:%(complete_var)s = 'powershell_complete'223+ $env:COMP_WORDS = $commandAst.ToString()224+ if ($wordToComplete) {225+ $env:COMP_CWORD = $commandAst.CommandElements.Count - 1226+ } else {227+ $env:COMP_CWORD = $commandAst.CommandElements.Count228+ }229+230+ try {231+ $response = & %(prog_name)s 2>$null232+ } finally {233+ $env:%(complete_var)s = $prev_complete234+ $env:COMP_WORDS = $prev_words235+ $env:COMP_CWORD = $prev_cword236+ }237+238+ if (-not $response) { return }239+240+ $prefix = "$wordToComplete*"241+ $lines = $response -split "`n"242+ for ($i = 0; $i + 2 -lt $lines.Count; $i += 3) {243+ $type = $lines[$i]244+ $value = $lines[$i + 1]245+ $descr = $lines[$i + 2]246+ if (-not $type) { continue }247+248+ if ($type -eq 'plain') {249+ $tip = if ($descr -and $descr -ne '_') { $descr } else { $value }250+ [System.Management.Automation.CompletionResult]::new(251+ $value, $value, 'ParameterValue', $tip)252+ } elseif ($type -eq 'dir') {253+ Get-ChildItem -Directory -Path $prefix -ErrorAction SilentlyContinue |254+ ForEach-Object {255+ [System.Management.Automation.CompletionResult]::new(256+ $_.FullName, $_.Name, 'ProviderContainer', $_.FullName)257+ }258+ } elseif ($type -eq 'file') {259+ Get-ChildItem -Path $prefix -ErrorAction SilentlyContinue |260+ ForEach-Object {261+ $kind = 'ProviderItem'262+ if ($_.PSIsContainer) { $kind = 'ProviderContainer' }263+ [System.Management.Automation.CompletionResult]::new(264+ $_.FullName, $_.Name, $kind, $_.FullName)265+ }266+ }267+ }268+}269+"""270+271+272 class _SourceVarsDict(t.TypedDict):273 complete_func: str274 complete_var: str275 prog_name: str241 unmodified lines517 518 return f"{item.type},{item.value}"519 520 521+class PowerShellComplete(ShellComplete):522+ """Shell completion for PowerShell (Windows PowerShell 5.1+ and pwsh 7+).523+524+ .. versionadded:: 8.5525+ """526+527+ name: t.ClassVar[str] = "powershell"528+ source_template: t.ClassVar[str] = _SOURCE_POWERSHELL529+530+ def get_completion_args(self) -> tuple[list[str], str]:531+ cwords = split_arg_string(os.environ["COMP_WORDS"])532+ cword = int(os.environ["COMP_CWORD"])533+ args = cwords[1:cword]534+535+ try:536+ incomplete = cwords[cword]537+ except IndexError:538+ incomplete = ""539+540+ return args, incomplete541+542+ def format_completion(self, item: CompletionItem[str]) -> str:543+ # PowerShell parses the response by splitting on newlines and544+ # consuming three lines per completion (type, value, help).545+ # Multi-line help text would break that framing, so collapse546+ # newlines and carriage returns to spaces. The literal "_"547+ # sentinel matches what ZshComplete uses for "no help text".548+ if item.help:549+ help_ = item.help.replace("\r", " ").replace("\n", " ")550+ else:551+ help_ = "_"552+ return f"{item.type}\n{item.value}\n{help_}"553+554+555 _available_shells: t.Final[dict[str, type[ShellComplete]]] = {556 "bash": BashComplete,557 "fish": FishComplete,558+ "powershell": PowerShellComplete,559 "zsh": ZshComplete,560 }561 562 _ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete")239 unmodified linesmodified:tests/test_shell_completion.py+31 added
11 unmodified lines12 from click.core import Option13 from click.shell_completion import add_completion_class14 from click.shell_completion import CompletionItem15 from click.shell_completion import FishComplete16+from click.shell_completion import PowerShellComplete17 from click.shell_completion import shell_complete18 from click.shell_completion import ShellComplete19 from click.types import Choice20 from click.types import File332 unmodified lines353 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})354 assert f"_CLI_COMPLETE={shell}_complete" in result.output355 356 357+def test_full_source_powershell(runner):358+ # The PowerShell source script sets the completion env var via359+ # `$env:_CLI_COMPLETE = 'powershell_complete'`, so the substring360+ # `_CLI_COMPLETE=powershell_complete` used by test_full_source above361+ # is not present. Assert on the PowerShell-specific markers instead.362+ cli = Group("cli", commands=[Command("a"), Command("b")])363+ result = runner.invoke(cli, env={"_CLI_COMPLETE": "powershell_source"})364+ assert "Register-ArgumentCompleter" in result.output365+ assert "powershell_complete" in result.output366+367+368 @pytest.mark.parametrize(369 ("shell", "env", "expect"),370 [371 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),2 unmodified lines374 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),375 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),376 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),377 ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),378+ (379+ "powershell",380+ {"COMP_WORDS": "", "COMP_CWORD": "0"},381+ "plain\na\n_\nplain\nb\nbee\n",382+ ),383+ ("powershell", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),384 ],385 )386 @pytest.mark.usefixtures("_patch_for_completion")387 def test_full_complete(runner, shell, env, expect):214 unmodified lines602 item = CompletionItem("--at", help="first\nsecond\tthird")603 # The newline is escaped to the literal characters backslash-n and the tab604 # becomes a space, so each completion stays on one line for fish.605 assert fc.format_completion(item) == "plain,--at\tfirst\\nsecond third"606+607+608+def test_powershell_format_completion_escapes_help():609+ pc = PowerShellComplete(Command("x"), {}, "x", "_X_COMPLETE")610+ # Newlines (LF and CRLF) collapse to spaces so the help text stays611+ # on a single line and doesn't break the 3-lines-per-item framing612+ # consumed by the PowerShell completion script.613+ item = CompletionItem("--at", help="first\nsecond\r\nthird")614+ assert pc.format_completion(item) == "plain\n--at\nfirst second third"615+ # Items without help text use the "_" sentinel, matching the format616+ # produced by ZshComplete.617+ item = CompletionItem("--at")618+ assert pc.format_completion(item) == "plain\n--at\n_"modified:CHANGES.md+4 added
1 ## Version 8.5.02 3 Unreleased4 5+- Add built-in shell completion support for PowerShell (Windows PowerShell6+ 5.1+ and pwsh 7+) alongside the existing `bash`, `zsh`, and `fish`7+ completers. Use `_FOO_BAR_COMPLETE=powershell_source foo-bar` to generate8+ the completion script.9 - Supported versions of Windows enable ANSI terminal styles by default.10 Colorama is no longer a dependency and is not used. {issue}`2986` {pr}`3505`11 - {class}`Argument` accepts a `help` parameter, and help output includes12 a `Positional arguments` section when argument help is available. {issue}`2983` {pr}`3473`1591 unmodified lines