fastapi / typer

Typer, build great CLIs. Easy to code. Based on Python type hints.
https://typer.tiangolo.com/
MIT License
15.68k stars 667 forks source link

powershell completion fails with partial word because it includes the incomplete word with completed args #359

Closed patricksurry closed 2 months ago

patricksurry commented 2 years ago

First Check

Commit to Help

Example Code

import typer

valid_names = ["Camila", "Carlos", "Sebastian"]

def complete_name(incomplete: str):
    completion = []
    for name in valid_names:
        if name.startswith(incomplete):
            completion.append(name)
    return completion

def main(
    name: str = typer.Option(
        "World", help="The name to say hi to.", autocompletion=complete_name
    )
):
    typer.echo(f"Hello {name}")

if __name__ == "__main__":
    typer.run(main)

Description

The intro example from the documentation fails in powershell if you start an incomplete name. For example typer ./main.py run --name Ca[TAB][TAB] fails to suggest completions, tho typer ./main.py run --name [TAB][TAB] does.

The powershell completion set args to the full list of arguments including the incomplete word, e.g. args = ['--name', 'Ca'], incomplete='Ca' unlike the bash completion which drops the incomplete word, e.g. args = ['--name'], incomplete='Ca'.

It looks straightforward to use the $cursorPosition variable to figure out where to truncate the string and take all but the last arg up to that point. I'll experiment and make a PR.

Operating System

Windows

Operating System Details

Windows 11, powershell 7

Typer Version

0.4.0

Python Version

3.7.12

Additional Context

No response

tiangolo commented 2 months ago

Thanks for the report @patricksurry! And thanks for the PR https://github.com/fastapi/typer/pull/360

This fix will be available in Typer 0.12.5, released in the next few hours. :tada: