|
| 1 | +import difflib |
1 | 2 | import getpass
|
2 | 3 | import inspect
|
3 | 4 | import json
|
@@ -86,6 +87,12 @@ def core_args(self) -> List["Argument"]:
|
86 | 87 | default=False,
|
87 | 88 | help="Echo executed commands before running.",
|
88 | 89 | ),
|
| 90 | + Argument( |
| 91 | + names=("suggestions", "s"), |
| 92 | + kind=bool, |
| 93 | + default=True, |
| 94 | + help="Show possible commands suggestions.", |
| 95 | + ), |
89 | 96 | Argument(
|
90 | 97 | names=("help", "h"),
|
91 | 98 | optional=True,
|
@@ -403,6 +410,11 @@ def run(self, argv: Optional[List[str]] = None, exit: bool = True) -> None:
|
403 | 410 | # problems.
|
404 | 411 | if isinstance(e, ParseError):
|
405 | 412 | print(e, file=sys.stderr)
|
| 413 | + if self.args.suggestions.value: |
| 414 | + unrecognised_cmd = str(e).replace("No idea what '", "") |
| 415 | + unrecognised_cmd = unrecognised_cmd.replace("' is!", "") |
| 416 | + msg = self._possible_commands_msg(unrecognised_cmd) |
| 417 | + print(msg, file=sys.stderr) |
406 | 418 | if isinstance(e, Exit) and e.message:
|
407 | 419 | print(e.message, file=sys.stderr)
|
408 | 420 | if isinstance(e, UnexpectedExit) and e.result.hide:
|
@@ -985,3 +997,23 @@ def print_columns(
|
985 | 997 | else:
|
986 | 998 | print(spec.rstrip())
|
987 | 999 | print("")
|
| 1000 | + |
| 1001 | + def _possible_commands_msg(self, unknown_cmd: str) -> str: |
| 1002 | + try: |
| 1003 | + all_tasks = self.scoped_collection.task_names |
| 1004 | + except AttributeError: |
| 1005 | + all_tasks = {} |
| 1006 | + |
| 1007 | + possible_cmds = list(all_tasks.keys()) |
| 1008 | + suggestions = difflib.get_close_matches( |
| 1009 | + unknown_cmd, possible_cmds, n=3, cutoff=0.7 |
| 1010 | + ) |
| 1011 | + output_message = f"'{unknown_cmd}' is not an invoke command. " |
| 1012 | + output_message += "See 'invoke --list'.\n" |
| 1013 | + if suggestions: |
| 1014 | + output_message += "\nThe most similar command(s):\n" |
| 1015 | + for cmd in suggestions: |
| 1016 | + output_message += f" {cmd}\n" |
| 1017 | + else: |
| 1018 | + output_message += "\nNo suggestions was found.\n" |
| 1019 | + return output_message |
0 commit comments