Skip to content

Commit

Permalink
add reusable completer function tutorial, add tutorial test for coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
bckohan committed Nov 8, 2024
1 parent 26581c0 commit 1037702
Show file tree
Hide file tree
Showing 7 changed files with 313 additions and 2 deletions.
53 changes: 52 additions & 1 deletion docs/tutorial/options-autocompletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ Hello Sebastian

And the same way as before, we want to provide **completion** for those names. But we don't want to provide the **same names** for completion if they were already given in previous parameters.

For that, we will access and use the "Context". When you create a **Typer** application it uses Click underneath. And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.
For that, we will access and use the "Context". When you create a **Typer** application it uses Click underneath. And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/stable/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.

But you can access the context by declaring a function parameter of type `typer.Context`.

Expand Down Expand Up @@ -404,6 +404,56 @@ It's quite possible that if there's only one option left, your shell will comple

///

## Reusing generic completer functions

You may want to reuse completer functions across CLI applications or within the same CLI application. If you need to filter out previously supplied parameters the completer function will first have to determine which parameter it is being asked to complete.

We can declare a parameter of type <a href="https://click.palletsprojects.com/en/stable/api/#click.Parameter" class="external-link" target="_blank">click.Parameter</a> along with the `click.Context` in our completer function to determine this. For example, lets revisit our above context example where we filter out duplicates but add a second greeter argument that reuses the same completer function:

//// tab | Python 3.7+

```Python hl_lines="15-16"
{!> ../docs_src/options_autocompletion/tutorial010_an.py!}
```

////

//// tab | Python 3.7+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python hl_lines="14-15"
{!> ../docs_src/options_autocompletion/tutorial010.py!}
```

////

/// tip

You may also return <a href="https://click.palletsprojects.com/en/stable/api/#click.shell_completion.CompletionItem" class="external-link" target="_blank">click.shell_completion.CompletionItem</a> objects from completer functions instead of 2-tuples.

///


Check it:

<div class="termy">

```console
$ typer ./main.py run --name Sebastian --greeter Camila --greeter [TAB][TAB]

// Our function returns Sebastian too because it is completing greeter
Carlos -- The writer of scripts.
Sebastian -- The type hints guy.
```

</div>


## Getting the raw *CLI parameters*

You can also get the raw *CLI parameters*, just a `list` of `str` with everything passed in the command line before the incomplete value.
Expand Down Expand Up @@ -561,6 +611,7 @@ You can declare function parameters of these types:

* `str`: for the incomplete value.
* `typer.Context`: for the current context.
* `click.Parameter`: for the CLI parameter being completed.
* `List[str]`: for the raw *CLI parameters*.

It doesn't matter how you name them, in which order, or which ones of the 3 options you declare. It will all "**just work**" ✨
Expand Down
38 changes: 38 additions & 0 deletions docs_src/options_autocompletion/tutorial010.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from typing import List

import click
import typer
from click.shell_completion import CompletionItem

valid_completion_items = [
("Camila", "The reader of books."),
("Carlos", "The writer of scripts."),
("Sebastian", "The type hints guy."),
]


def complete_name(ctx: typer.Context, param: click.Parameter, incomplete: str):
names = (ctx.params.get(param.name) if param.name else []) or []
for name, help_text in valid_completion_items:
if name.startswith(incomplete) and name not in names:
yield CompletionItem(name, help=help_text)


app = typer.Typer()


@app.command()
def main(
name: List[str] = typer.Option(
["World"], help="The name to say hi to.", autocompletion=complete_name
),
greeter: List[str] = typer.Option(
None, help="Who are the greeters?.", autocompletion=complete_name
),
):
for n in name:
print(f"Hello {n}, from {' and '.join(greeter or [])}")


if __name__ == "__main__":
app()
41 changes: 41 additions & 0 deletions docs_src/options_autocompletion/tutorial010_an.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from typing import List

import click
import typer
from click.shell_completion import CompletionItem
from typing_extensions import Annotated

valid_completion_items = [
("Camila", "The reader of books."),
("Carlos", "The writer of scripts."),
("Sebastian", "The type hints guy."),
]


def complete_name(ctx: typer.Context, param: click.Parameter, incomplete: str):
names = (ctx.params.get(param.name) if param.name else []) or []
for name, help_text in valid_completion_items:
if name.startswith(incomplete) and name not in names:
yield CompletionItem(name, help=help_text)


app = typer.Typer()


@app.command()
def main(
name: Annotated[
List[str],
typer.Option(help="The name to say hi to.", autocompletion=complete_name),
] = ["World"],
greeter: Annotated[
List[str],
typer.Option(help="Who are the greeters?.", autocompletion=complete_name),
] = [],
):
for n in name:
print(f"Hello {n}, from {' and '.join(greeter)}")


if __name__ == "__main__":
app()
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ ignore = [
"docs_src/options_autocompletion/tutorial007_an.py" = ["B006"]
"docs_src/options_autocompletion/tutorial008_an.py" = ["B006"]
"docs_src/options_autocompletion/tutorial009_an.py" = ["B006"]
"docs_src/options_autocompletion/tutorial010_an.py" = ["B006"]
"docs_src/parameter_types/enum/tutorial003_an.py" = ["B006"]
# Loop control variable `value` not used within loop body
"docs_src/progressbar/tutorial001.py" = ["B007"]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import os
import subprocess
import sys

from typer.testing import CliRunner

from docs_src.options_autocompletion import tutorial010 as mod

runner = CliRunner()


def test_completion():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL010.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial010.py --name Sebastian --name ",
},
)
assert '"Camila":"The reader of books."' in result.stdout
assert '"Carlos":"The writer of scripts."' in result.stdout
assert '"Sebastian":"The type hints guy."' not in result.stdout


def test_completion_greeter1():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL010.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial010.py --name Sebastian --greeter Ca",
},
)
assert '"Camila":"The reader of books."' in result.stdout
assert '"Carlos":"The writer of scripts."' in result.stdout
assert '"Sebastian":"The type hints guy."' not in result.stdout


def test_completion_greeter2():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL010.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial010.py --name Sebastian --greeter Carlos --greeter ",
},
)
assert '"Camila":"The reader of books."' in result.stdout
assert '"Carlos":"The writer of scripts."' not in result.stdout
assert '"Sebastian":"The type hints guy."' in result.stdout


def test_1():
result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])
assert result.exit_code == 0
assert "Hello Camila" in result.output
assert "Hello Sebastian" in result.output


def test_2():
result = runner.invoke(
mod.app, ["--name", "Camila", "--name", "Sebastian", "--greeter", "Carlos"]
)
assert result.exit_code == 0
assert "Hello Camila, from Carlos" in result.output
assert "Hello Sebastian, from Carlos" in result.output


def test_3():
result = runner.invoke(
mod.app, ["--name", "Camila", "--greeter", "Carlos", "--greeter", "Sebastian"]
)
assert result.exit_code == 0
assert "Hello Camila, from Carlos and Sebastian" in result.output


def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
)
assert "Usage" in result.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import os
import subprocess
import sys

from typer.testing import CliRunner

from docs_src.options_autocompletion import tutorial010_an as mod

runner = CliRunner()


def test_completion():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL010_AN.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial010_an.py --name Sebastian --name ",
},
)
assert '"Camila":"The reader of books."' in result.stdout
assert '"Carlos":"The writer of scripts."' in result.stdout
assert '"Sebastian":"The type hints guy."' not in result.stdout


def test_completion_greeter1():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL010_AN.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial010_an.py --name Sebastian --greeter Ca",
},
)
assert '"Camila":"The reader of books."' in result.stdout
assert '"Carlos":"The writer of scripts."' in result.stdout
assert '"Sebastian":"The type hints guy."' not in result.stdout


def test_completion_greeter2():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, " "],
capture_output=True,
encoding="utf-8",
env={
**os.environ,
"_TUTORIAL010_AN.PY_COMPLETE": "complete_zsh",
"_TYPER_COMPLETE_ARGS": "tutorial010_an.py --name Sebastian --greeter Carlos --greeter ",
},
)
assert '"Camila":"The reader of books."' in result.stdout
assert '"Carlos":"The writer of scripts."' not in result.stdout
assert '"Sebastian":"The type hints guy."' in result.stdout


def test_1():
result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])
assert result.exit_code == 0
assert "Hello Camila" in result.output
assert "Hello Sebastian" in result.output


def test_2():
result = runner.invoke(
mod.app, ["--name", "Camila", "--name", "Sebastian", "--greeter", "Carlos"]
)
assert result.exit_code == 0
assert "Hello Camila, from Carlos" in result.output
assert "Hello Sebastian, from Carlos" in result.output


def test_3():
result = runner.invoke(
mod.app, ["--name", "Camila", "--greeter", "Carlos", "--greeter", "Sebastian"]
)
assert result.exit_code == 0
assert "Hello Camila, from Carlos and Sebastian" in result.output


def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
)
assert "Usage" in result.stdout
2 changes: 1 addition & 1 deletion typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1040,7 +1040,7 @@ def get_param_completion(
elif lenient_issubclass(origin, List):
args_name = param_sig.name
unassigned_params.remove(param_sig)
elif lenient_issubclass(param_sig.annotation, click.core.Parameter):
elif lenient_issubclass(param_sig.annotation, click.Parameter):
param_name = param_sig.name
unassigned_params.remove(param_sig)
elif lenient_issubclass(param_sig.annotation, str):
Expand Down

0 comments on commit 1037702

Please sign in to comment.