Skip to content

Commit

Permalink
feat: Allow --help for subcommands (#267)
Browse files Browse the repository at this point in the history
* NOTE - this may impact performance so maybe needs to be reassessed
  • Loading branch information
gmuloc authored and titom73 committed Jul 24, 2023
1 parent 7512eb6 commit 319cfdb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
5 changes: 3 additions & 2 deletions anta/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
31 changes: 31 additions & 0 deletions anta/cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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)

0 comments on commit 319cfdb

Please sign in to comment.