Skip to content
Myr

Add built-in PowerShell shell completion support

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Zhihua Lai · committed by Zhihua Lai · parent 679a7a0 · Browse files · 4 files+157 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+157 added−1 removed

  • tests:+31 added−0 removed
  • other:+126 added−1 removed

4 files+157 added−1 removed

modified:docs/shell-completion.md+27 added-1 removed
27 unmodified lines
28depending 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 is30conventional but not strictly required for environment variable names to be in upper case. This convention helps31distinguish environment variables from regular shell variables and commands, making scripts and configuration files more32readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.32readable and easier to maintain. The built-in shells are `bash`, `zsh`, `fish`, and `powershell`.3334Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.3536```{eval-rst}
24 unmodified lines
61 _FOO_BAR_COMPLETE=fish_source foo-bar | source6263 This is the same file used for the activation script method64 below. For Fish it's probably always easier to use that method.6566 .. group-tab:: PowerShell6768 Add this to your PowerShell profile (the path of ``$PROFILE``):6970 .. code-block:: powershell7172 $env:_FOO_BAR_COMPLETE = 'powershell_source'73 foo-bar | Out-String | Invoke-Expression74 Remove-Item Env:_FOO_BAR_COMPLETE75```7677Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell78responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead
36 unmodified lines
115116 .. code-block:: fish117118 _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish119120 .. group-tab:: PowerShell121122 Save the script somewhere.123124 .. code-block:: powershell125126 $env:_FOO_BAR_COMPLETE = 'powershell_source'127 foo-bar | Out-File -Encoding utf8 ~/.foo-bar-complete.ps1128 Remove-Item Env:_FOO_BAR_COMPLETE129130 Source the file in your PowerShell profile (the path of ``$PROFILE``):131132 .. code-block:: powershell133134 . ~/.foo-bar-complete.ps1135```136137After modifying the shell config, you need to start a new shell in order for the changes to be loaded.138
137 unmodified lines
modified:src/click/shell_completion.py+95 added
195 unmodified lines
196complete --no-files --command %(prog_name)s --arguments \197"(%(complete_func)s)";198"""199200# Compatible with Windows PowerShell 5.1+ and PowerShell (pwsh) 7+.201# Uses Register-ArgumentCompleter -Native, which receives the command AST202# as parsed by PowerShell. The command text is forwarded verbatim through203# COMP_WORDS so the Python side can reuse the same shlex-based splitting204# used by the bash/zsh completers.205_SOURCE_POWERSHELL = """\206Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock {207 param($wordToComplete, $commandAst, $cursorPosition)208209 $prev_complete = $env:%(complete_var)s210 $prev_words = $env:COMP_WORDS211 $prev_cword = $env:COMP_CWORD212213 $env:%(complete_var)s = 'powershell_complete'214 $env:COMP_WORDS = $commandAst.ToString()215 if ($wordToComplete) {216 $env:COMP_CWORD = $commandAst.CommandElements.Count - 1217 } else {218 $env:COMP_CWORD = $commandAst.CommandElements.Count219 }220221 try {222 $response = & %(prog_name)s 2>$null223 } finally {224 $env:%(complete_var)s = $prev_complete225 $env:COMP_WORDS = $prev_words226 $env:COMP_CWORD = $prev_cword227 }228229 if (-not $response) { return }230231 $lines = $response -split "`n"232 for ($i = 0; $i + 2 -lt $lines.Count; $i += 3) {233 $type = $lines[$i]234 $value = $lines[$i + 1]235 $descr = $lines[$i + 2]236 if (-not $type) { continue }237238 if ($type -eq 'plain') {239 $tip = if ($descr -and $descr -ne '_') { $descr } else { $value }240 [System.Management.Automation.CompletionResult]::new(241 $value, $value, 'ParameterValue', $tip)242 } elseif ($type -eq 'dir') {243 Get-ChildItem -Directory -Path "$wordToComplete*" -ErrorAction SilentlyContinue |244 ForEach-Object {245 [System.Management.Automation.CompletionResult]::new(246 $_.FullName, $_.Name, 'ProviderContainer', $_.FullName)247 }248 } elseif ($type -eq 'file') {249 Get-ChildItem -Path "$wordToComplete*" -ErrorAction SilentlyContinue |250 ForEach-Object {251 $kind = if ($_.PSIsContainer) { 'ProviderContainer' } else { 'ProviderItem' }252 [System.Management.Automation.CompletionResult]::new(253 $_.FullName, $_.Name, $kind, $_.FullName)254 }255 }256 }257}258"""259260261class ShellComplete:262 """Base class for providing shell completion support. A subclass for263 a given shell will override attributes and methods to implement the264 completion instructions (``source`` and ``complete``).
233 unmodified lines
498499 return f"{item.type},{item.value}"500501502class PowerShellComplete(ShellComplete):503 """Shell completion for PowerShell (Windows PowerShell 5.1+ and pwsh 7+).504505 .. versionadded:: 8.5506 """507508 name: t.ClassVar[str] = "powershell"509 source_template: t.ClassVar[str] = _SOURCE_POWERSHELL510511 def get_completion_args(self) -> tuple[list[str], str]:512 cwords = split_arg_string(os.environ["COMP_WORDS"])513 cword = int(os.environ["COMP_CWORD"])514 args = cwords[1:cword]515516 try:517 incomplete = cwords[cword]518 except IndexError:519 incomplete = ""520521 return args, incomplete522523 def format_completion(self, item: CompletionItem) -> str:524 # PowerShell parses the response by splitting on newlines and525 # consuming three lines per completion (type, value, help).526 # Multi-line help text would break that framing, so collapse527 # newlines and carriage returns to spaces. The literal "_"528 # sentinel matches what ZshComplete uses for "no help text".529 if item.help:530 help_ = item.help.replace("\r", " ").replace("\n", " ")531 else:532 help_ = "_"533 return f"{item.type}\n{item.value}\n{help_}"534535536ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")537538539_available_shells: dict[str, type[ShellComplete]] = {540 "bash": BashComplete,541 "fish": FishComplete,542 "powershell": PowerShellComplete,543 "zsh": ZshComplete,544}545546
229 unmodified lines
modified:tests/test_shell_completion.py+31 added
11 unmodified lines
12from click.core import Option13from click.shell_completion import add_completion_class14from click.shell_completion import CompletionItem15from click.shell_completion import FishComplete16from click.shell_completion import PowerShellComplete17from click.shell_completion import shell_complete18from click.shell_completion import ShellComplete19from click.types import Choice20from click.types import File
332 unmodified lines
353 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})354 assert f"_CLI_COMPLETE={shell}_complete" in result.output355356357def 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.output366367368@pytest.mark.parametrize(369 ("shell", "env", "expect"),370 [371 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),
2 unmodified lines
374 ("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")387def test_full_complete(runner, shell, env, expect):
214 unmodified lines
602 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"606607608def 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.023Unreleased45- 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`
1557 unmodified lines