From 319cfdbcea2cd0b0d0a9505b6879c4652156966d Mon Sep 17 00:00:00 2001 From: Guillaume Mulocher Date: Fri, 21 Jul 2023 16:34:05 +0200 Subject: [PATCH] feat: Allow --help for subcommands (#267) * NOTE - this may impact performance so maybe needs to be reassessed --- anta/cli/__init__.py | 5 +++-- anta/cli/utils.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/anta/cli/__init__.py b/anta/cli/__init__.py index 323caded5..3986b8d4f 100644 --- a/anta/cli/__init__.py +++ b/anta/cli/__init__.py @@ -15,11 +15,12 @@ from anta.cli.exec import commands as exec_commands from anta.cli.get import commands as get_commands from anta.cli.nrfu import commands as check_commands -from anta.cli.utils import parse_catalog, parse_inventory, setup_logging +from anta.cli.utils import IgnoreRequiredWithHelp, parse_catalog, parse_inventory, setup_logging from anta.result_manager.models import TestResult -@click.group() +# @click.group() +@click.group(cls=IgnoreRequiredWithHelp) @click.pass_context @click.version_option(__version__) @click.option( diff --git a/anta/cli/utils.py b/anta/cli/utils.py index f5dd0ad50..7a5e55f25 100644 --- a/anta/cli/utils.py +++ b/anta/cli/utils.py @@ -47,6 +47,10 @@ def parse_inventory(ctx: click.Context, path: Path) -> AntaInventory: """ Helper function parse an ANTA inventory YAML file """ + if ctx.obj.get("_anta_help"): + # Currently looking for help for a subcommand so no + # need to parse the Inventory, return an empty one + return AntaInventory() try: inventory = AntaInventory.parse( inventory_file=str(path), @@ -135,3 +139,30 @@ def return_code(result_manager: ResultManager, ignore_error: bool, ignore_status logger.error("Please gather logs and open an issue on Github.") raise ValueError(f"Unknown status returned by the ResultManager: {status}. Please gather logs and open an issue on Github.") + + +class IgnoreRequiredWithHelp(click.Group): + """ + https://stackoverflow.com/questions/55818737/python-click-application-required-parameters-have-precedence-over-sub-command-he + Solution to allow help without required options on subcommand + + This is not planned to be fixed in click as per: https://github.com/pallets/click/issues/295#issuecomment-708129734 + """ + + def parse_args(self, ctx: click.Context, args: List[str]) -> List[str]: + """ + Ignore MissingParameter exception when parsing arguments if `--help` + is present for a subcommand + """ + try: + return super().parse_args(ctx, args) + except click.MissingParameter: + if "--help" not in args: + raise + + # remove the required params so that help can display + for param in self.params: + param.required = False + # Adding a flag for potential callbacks + ctx.obj["_anta_help"] = True + return super().parse_args(ctx, args)