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
Provenance
- Commit
27b3ee2- Tree
7449a14- Author
Zhihua Lai <zhihualai@microsoft.com>- Committer
Zhihua Lai <zhihualai@microsoft.com>- Parent
679a7a0
4 files changed+157 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+95 added
195 unmodified lines196 complete --no-files --command %(prog_name)s --arguments \197 "(%(complete_func)s)";198 """199 200+# 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 = """\206+Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock {207+ param($wordToComplete, $commandAst, $cursorPosition)208 209+ $prev_complete = $env:%(complete_var)s210+ $prev_words = $env:COMP_WORDS211+ $prev_cword = $env:COMP_CWORD212+213+ $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+ }220+221+ 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+ }228+229+ if (-not $response) { return }230+231+ $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 }237+238+ 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+"""259+260+261 class 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 lines498 499 return f"{item.type},{item.value}"500 501 502+class PowerShellComplete(ShellComplete):503+ """Shell completion for PowerShell (Windows PowerShell 5.1+ and pwsh 7+).504+505+ .. versionadded:: 8.5506+ """507+508+ name: t.ClassVar[str] = "powershell"509+ source_template: t.ClassVar[str] = _SOURCE_POWERSHELL510+511+ 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]515+516+ try:517+ incomplete = cwords[cword]518+ except IndexError:519+ incomplete = ""520+521+ return args, incomplete522+523+ 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_}"534+535+536 ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")537 538 539 _available_shells: dict[str, type[ShellComplete]] = {540 "bash": BashComplete,541 "fish": FishComplete,542+ "powershell": PowerShellComplete,543 "zsh": ZshComplete,544 }545 546 229 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`1557 unmodified lines