Skip to content
Myr

swap order of instruction string

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

authored by David Lord · committed by David Lord · parent bc3dd47 · 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

4 files+31 added−32 removed

modified:docs/shell-completion.rst+18 added-22 removed
29 unmodified lines
3031In order for completion to be used, the user needs to register a special32function with their shell. The script is different for every shell, and33Click 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 uppercase35with dashes replaced by underscores. The built-in shells are ``bash``,36``zsh``, and ``fish``.3738Provide your users with the following instructions customized to your
6 unmodified lines
45 Add this to ``~/.bashrc``:4647 .. code-block:: bash4849 eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"49 eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"5051 .. group-tab:: Zsh5253 Add this to ``~/.zshrc``:5455 .. code-block:: zsh5657 eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"57 eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"5859 .. group-tab:: Fish6061 Add this to ``~/.config/fish/completions/foo-bar.fish``:6263 .. code-block:: fish6465 eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)65 eval (env _FOO_BAR_COMPLETE=fish_source foo-bar)6667 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 lines
80 Save the script somewhere.8182 .. code-block:: bash8384 _FOO_BAR_COMPLETE=source_bash foo-bar > ~/.foo-bar-complete.bash84 _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash8586 Source the file in ``~/.bashrc``.8788 .. code-block:: bash
5 unmodified lines
94 Save the script somewhere.9596 .. code-block:: bash9798 _FOO_BAR_COMPLETE=source_zsh foo-bar > ~/.foo-bar-complete.zsh98 _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh99100 Source the file in ``~/.zshrc``.101102 .. code-block:: bash
5 unmodified lines
108 Save the script to ``~/.config/fish/completions/foo-bar.fish``:109110 .. code-block:: fish111112 _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.fish113114After modifying the shell config, you need to start a new shell in order115for the changes to be loaded.116
75 unmodified lines
192193First, you'll need to figure out how your shell's completion system194works and write a script to integrate it with Click. It must invoke your195program 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.197How it passes those values, and the format of the completion response198from Click is up to you.199200In your subclass, set :attr:`~ShellComplete.source_template` to the
2 unmodified lines
203204- ``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.209210The example code is for a made up shell "My Shell" or "mysh" for short.211
3 unmodified lines
215 from click.shell_completion import ShellComplete216217 _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 lines
251252 return args, ""253254Finally, implement :meth:`~ShellComplete.format_completion`. This is255called to format each ``(type, value, help)`` tuples returned by Click256into a string. For example, the Bash implementation returns257``f"{type},{value}`` (it doesn't support help strings), and the Zsh258implementation returns each part separated by a newline, replacing empty259help with a ``_`` placeholder. This format is entirely up to what you260parse with your completion script.255called to format each :class:`CompletionItem` into a string. For256example, the Bash implementation returns ``f"{item.type},{item.value}``257(it doesn't support help strings), and the Zsh implementation returns258each part separated by a newline, replacing empty help with a ``_``259placeholder. This format is entirely up to what you parse with your260completion script.261262The ``type`` value is usually ``plain``, but it can be another value263that the completion script can switch on. For example, ``file`` or264``dir`` can tell the shell to handle path completion, since the shell is265better at that than Click.266267.. code-block:: python268269 import os270 from click.parser import split_arg_string271269 class MyshComplete(ShellComplete):270 ...271272 def format_completion(self, item):276 type, value, _ = item277 return f"{type}\t{value}"273 return f"{item.type}\t{item.value}"274275With those three things implemented, the new shell support is ready. In276case those weren't sufficient, there are more parts that can be277overridden, but that probably isn't necessary.
3 unmodified lines
281the shell somehow.282283.. code-block:: text284289 _FOO_BAR_COMPLETE=source_mysh foo-bar285 _FOO_BAR_COMPLETE=mysh_source foo-bar
modified:src/click/shell_completion.py+6 added-6 removed
19 unmodified lines
20 :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)2627 if comp_cls is None:28 return 1
48 unmodified lines
77 local IFS=$'\\n'78 local response7980 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \81%(complete_var)s=complete_bash $1)81%(complete_var)s=bash_complete $1)8283 for completion in $response; do84 IFS=',' read type value <<< "$completion"85
27 unmodified lines
113 local -a response114 (( ! $+commands[%(prog_name)s] )) && return 1115116 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)}")118119 for type key descr in ${response}; do120 if [[ "$type" == "plain" ]]; then121 if [[ "$descr" == "_" ]]; then
23 unmodified lines
145_SOURCE_FISH = """\146function %(complete_func)s;147 set -l response;148149 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) \150COMP_CWORD=(commandline -t) %(prog_name)s);151 set response $response $value;152 end;153
29 unmodified lines
183 """184185 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 lines
modified:tests/test_shell_completion.py+4 added-4 removed
252 unmodified lines
253)254@pytest.mark.usefixtures("_patch_for_completion")255def 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.output259260261@pytest.mark.parametrize(262 ("shell", "env", "expect"),
8 unmodified lines
271)272@pytest.mark.usefixtures("_patch_for_completion")273def 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 == expect278279
5 unmodified lines
285 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 lines
102 ``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.109110- 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