Skip to content

Use difflib for potential suggestions in cli error messages #1446

@tirkarthi

Description

@tirkarthi

Currently click only does startswith match at

click/click/parser.py

Lines 328 to 329 in 6c454c8

possibilities = [word for word in self._long_opt
if word.startswith(opt)]
so a typo like using --boun suggests --bount but using --bound doesn't make any suggestions. Using difflib.get_close_matches could get better suggestions and nearest matches.

Sample implementation : https://github.com/tirkarthi/click/tree/difflib-suggestions

import click

@click.option("--count")
@click.option("--bount")
@click.command()
def cli(count, bount):
    click.echo(f"count = {count}, bount = {bount}")

if __name__ == "__main__":
    cli()
python sample.py --boun 1 
Usage: sample.py [OPTIONS]
Try "sample.py --help" for help.

Error: no such option: --boun  Did you mean --bount?
python sample.py --bound 1
Usage: sample.py [OPTIONS]
Try "sample.py --help" for help.

Error: no such option: --bound

Using --bound with difflib.get_close_matches

python sample.py --bound 1
Usage: sample.py [OPTIONS]
Try "sample.py --help" for help.

Error: no such option: --bound  (Possible options: --bount, --count)

Using --counter with difflib.get_close_matches

python sample.py --counter 1
Usage: sample.py [OPTIONS]
Try "sample.py --help" for help.

Error: no such option: --counter  (Possible options: --count, --bount)

Metadata

Metadata

Assignees

No one assigned

    Labels

    f:helpfeature: help text

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions