Add support for user autocompletion functions
:sparkles: Add support for user autocompletion functions.
The current implementation provides completion for options, arguments, and sub-commands with help strings. But if the user provides an autocompletion function it is not used. Although it would be used by plain Click (only in Bash and Zsh).
This PR continues the idea from @chrisjsewell in #27. And adds the ideas in the review from @Konubinix.
I added comments to the sections I added that are a direct copy from Click, to try and minimize confusion by the duplicate code. I updated a couple of parts with logic from Click that is not yet here.
I made get_choices return a list instead of using yield, this allows returning early with get_user_autocompletions.
Here's an example small app that I used to test it. I wrote it with Typer but I can adapt it to use Click directly if you prefer, if the Typer parts are confusing, etc.
typertest/main.py:
import typer
app = typer.Typer()
def complete(ctx, args, incomplete):
return [("asdf", "some asdf"), ("qwer", "some quer")]
@app.command()
def one(arg: str = typer.Argument(..., autocompletion=complete)):
typer.echo("Running one")
@app.command()
def two(arg: str = typer.Argument(..., autocompletion=complete)):
typer.echo("Running two")
If you create a file pyproject.toml with:
[tool.poetry]
name = "typertest"
version = "0.1.0"
description = ""
authors = ["Sebastián Ramírez <[email protected]>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.6"
typer = "^0.0.8"
click-completion = "^0.5.2"
[tool.poetry.dev-dependencies]
pytest = "^5.2"
[tool.poetry.scripts]
typertest = "typertest.main:app"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
And a file typertest/__init__.py
Then you can install it with:
$ poetry install
With that, you can test with:
$ typertest <TAB><TAB>
one two
// Without this PR, this doesn't work
$ typertest one <TAB><TAB>
asdf -- some asdf
qwer -- some quer
nice 👍
Out of curiosity, is this PR still relevant? I have the feeling that this is now done on click.
Yep, I'm pretty sure this is no longer relevant, implemented in Click directly, and also a bit rewritten in Typer.
So I"ll close this PR now. Thanks!