Merge pull request #1683 from pallets/complete-order
Before adoption: this commit came in with the history the project adopted, so no landing records it.
swap order of completion instruction
authored by David Lord · committed by GitHub · parents bc3dd47, 7e4a27f · Browse files · 4 files·+31 added−32 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+31 added−32 removed
- tests:+4 added−4 removed
- other:+27 added−28 removed
Provenance
- Commit
d15d0cd- Tree
92f4662- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
bc3dd47- Parent 2
7e4a27f
4 files changed+31 added−32 removed
modified:docs/shell-completion.rst+18 added-22 removed
29 unmodified lines30 31 In order for completion to be used, the user needs to register a special32 function with their shell. The script is different for every shell, and33 Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34-``source_{shell}``. ``{PROG_NAME}`` is the executable name in uppercase34+``{shell}_source``. ``{PROG_NAME}`` is the executable name in uppercase35 with dashes replaced by underscores. The built-in shells are ``bash``,36 ``zsh``, and ``fish``.37 38 Provide your users with the following instructions customized to your6 unmodified lines45 Add this to ``~/.bashrc``:46 47 .. code-block:: bash48 49- eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"49+ eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"50 51 .. group-tab:: Zsh52 53 Add this to ``~/.zshrc``:54 55 .. code-block:: zsh56 57- eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"57+ eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"58 59 .. group-tab:: Fish60 61 Add this to ``~/.config/fish/completions/foo-bar.fish``:62 63 .. code-block:: fish64 65- eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)65+ eval (env _FOO_BAR_COMPLETE=fish_source foo-bar)66 67 This is the same file used for the activation script method68 below. For Fish it's probably always easier to use that method.69 10 unmodified lines80 Save the script somewhere.81 82 .. code-block:: bash83 84- _FOO_BAR_COMPLETE=source_bash foo-bar > ~/.foo-bar-complete.bash84+ _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash85 86 Source the file in ``~/.bashrc``.87 88 .. code-block:: bash5 unmodified lines94 Save the script somewhere.95 96 .. code-block:: bash97 98- _FOO_BAR_COMPLETE=source_zsh foo-bar > ~/.foo-bar-complete.zsh98+ _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh99 100 Source the file in ``~/.zshrc``.101 102 .. code-block:: bash5 unmodified lines108 Save the script to ``~/.config/fish/completions/foo-bar.fish``:109 110 .. code-block:: fish111 112- _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar.fish112+ _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish113 114 After modifying the shell config, you need to start a new shell in order115 for the changes to be loaded.116 75 unmodified lines192 193 First, you'll need to figure out how your shell's completion system194 works and write a script to integrate it with Click. It must invoke your195 program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to196-``complete_{shell}`` and pass the complete args and incomplete value.196+``{shell}_complete`` and pass the complete args and incomplete value.197 How it passes those values, and the format of the completion response198 from Click is up to you.199 200 In your subclass, set :attr:`~ShellComplete.source_template` to the2 unmodified lines203 204 - ``complete_func`` - A safe name for the completion function defined205 in the script.206 - ``complete_var`` - The environment variable name for passing the207- ``complete_{shell}`` value.207+ ``{shell}_complete`` instruction.208 - ``prog_name`` - The name of the executable being completed.209 210 The example code is for a made up shell "My Shell" or "mysh" for short.211 3 unmodified lines215 from click.shell_completion import ShellComplete216 217 _mysh_source = """\218 %(complete_func)s {219- response=$(%(complete_var)s=complete_mysh %(prog_name)s)219+ response=$(%(complete_var)s=mysh_complete %(prog_name)s)220 # parse response and set completions somehow221 }222 call-on-complete %(prog_name)s %(complete_func)s223 """27 unmodified lines251 252 return args, ""253 254 Finally, implement :meth:`~ShellComplete.format_completion`. This is255-called to format each ``(type, value, help)`` tuples returned by Click256-into a string. For example, the Bash implementation returns257-``f"{type},{value}`` (it doesn't support help strings), and the Zsh258-implementation returns each part separated by a newline, replacing empty259-help with a ``_`` placeholder. This format is entirely up to what you260-parse with your completion script.255+called to format each :class:`CompletionItem` into a string. For256+example, the Bash implementation returns ``f"{item.type},{item.value}``257+(it doesn't support help strings), and the Zsh implementation returns258+each part separated by a newline, replacing empty help with a ``_``259+placeholder. This format is entirely up to what you parse with your260+completion script.261 262 The ``type`` value is usually ``plain``, but it can be another value263 that the completion script can switch on. For example, ``file`` or264 ``dir`` can tell the shell to handle path completion, since the shell is265 better at that than Click.266 267 .. code-block:: python268 269- import os270- from click.parser import split_arg_string271-269 class MyshComplete(ShellComplete):270 ...271 272 def format_completion(self, item):276- type, value, _ = item277- return f"{type}\t{value}"273+ return f"{item.type}\t{item.value}"274 275 With those three things implemented, the new shell support is ready. In276 case those weren't sufficient, there are more parts that can be277 overridden, but that probably isn't necessary.3 unmodified lines281 the shell somehow.282 283 .. code-block:: text284 289- _FOO_BAR_COMPLETE=source_mysh foo-bar285+ _FOO_BAR_COMPLETE=mysh_source foo-barmodified:src/click/shell_completion.py+6 added-6 removed
19 unmodified lines20 :param instruction: Value of ``complete_var`` with the completion21 instruction and shell, in the form ``instruction_shell``.22 :return: Status code to exit with.23 """24- instruction, _, shell = instruction.partition("_")24+ shell, _, instruction = instruction.partition("_")25 comp_cls = get_completion_class(shell)26 27 if comp_cls is None:28 return 148 unmodified lines77 local IFS=$'\\n'78 local response79 80 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \81-%(complete_var)s=complete_bash $1)81+%(complete_var)s=bash_complete $1)82 83 for completion in $response; do84 IFS=',' read type value <<< "$completion"85 27 unmodified lines113 local -a response114 (( ! $+commands[%(prog_name)s] )) && return 1115 116 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \117-%(complete_var)s=complete_zsh %(prog_name)s)}")117+%(complete_var)s=zsh_complete %(prog_name)s)}")118 119 for type key descr in ${response}; do120 if [[ "$type" == "plain" ]]; then121 if [[ "$descr" == "_" ]]; then23 unmodified lines145 _SOURCE_FISH = """\146 function %(complete_func)s;147 set -l response;148 149- for value in (env %(complete_var)s=complete_fish COMP_WORDS=(commandline -cp) \149+ for value in (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \150 COMP_CWORD=(commandline -t) %(prog_name)s);151 set response $response $value;152 end;153 29 unmodified lines183 """184 185 name = None186 """Name to register the shell as with :func:`add_completion_class`.187- This is used in completion instructions (``source_{name}`` and188- ``complete_{name}``).187+ This is used in completion instructions (``{name}_source`` and188+ ``{name}_complete``).189 """190 source_template = None191 """Completion script template formatted by :meth:`source`. This must192 be provided by subclasses.348 unmodified linesmodified:tests/test_shell_completion.py+4 added-4 removed
252 unmodified lines253 )254 @pytest.mark.usefixtures("_patch_for_completion")255 def test_full_source(runner, shell):256 cli = Group("cli", commands=[Command("a"), Command("b")])257- result = runner.invoke(cli, env={"_CLI_COMPLETE": f"source_{shell}"})258- assert f"_CLI_COMPLETE=complete_{shell}" in result.output257+ result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})258+ assert f"_CLI_COMPLETE={shell}_complete" in result.output259 260 261 @pytest.mark.parametrize(262 ("shell", "env", "expect"),8 unmodified lines271 )272 @pytest.mark.usefixtures("_patch_for_completion")273 def test_full_complete(runner, shell, env, expect):274 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])275- env["_CLI_COMPLETE"] = f"complete_{shell}"275+ env["_CLI_COMPLETE"] = f"{shell}_complete"276 result = runner.invoke(cli, env=env)277 assert result.output == expect278 279 5 unmodified lines285 cli = Command("cli", params=[Argument("x", shell_complete=complete)])286 result = runner.invoke(287 cli,288 obj={"choices": ["a", "b"]},289- env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "complete_bash"},289+ env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},290 )291 assert result.output == "plain,a\nplain,b\n"modified:CHANGES.rst+3 added
101 unmodified lines102 ``ctx, param, incomplete``, must do matching rather than return103 all values, and must return a list of strings or a list of104 ``ShellComplete``. The old name and behavior is deprecated and105 will be removed in 8.1.106+ - The env var values used to start completion have changed order.107+ The shell now comes first, such as ``{shell}_source`` rather108+ than ``source_{shell}``, and is always required.109 110 - Extra context settings (``obj=...``, etc.) are passed on to the111 completion system. :issue:`942`112 - Include ``--help`` option in completion. :pr:`1504`639 unmodified lines