From f47b2e80ede40ff7ccad445bfdf25733b51b2cf9 Mon Sep 17 00:00:00 2001 From: Felix Fontein Date: Fri, 1 Sep 2023 22:44:19 +0200 Subject: [PATCH] Allow to provide the version to antsibull_core.args.get_toplevel_parser() (#96) * Allow to provide the version to antsibull_core.args.get_toplevel_parser. * Simplify code. Also allow to override the program name 'antsibull'. * Remove fallback. * Fix typo. Co-authored-by: Maxwell G --------- Co-authored-by: Maxwell G --- changelogs/fragments/96-version.yml | 2 ++ src/antsibull_core/args.py | 28 ++++++++++++++++++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) create mode 100644 changelogs/fragments/96-version.yml diff --git a/changelogs/fragments/96-version.yml b/changelogs/fragments/96-version.yml new file mode 100644 index 0000000..4fd8daa --- /dev/null +++ b/changelogs/fragments/96-version.yml @@ -0,0 +1,2 @@ +minor_changes: + - "Allow to overwrite the version and the program name when using ``antsibull_core.args.get_toplevel_parser()`` (https://github.com/ansible-community/antsibull-core/pull/96)." diff --git a/src/antsibull_core/args.py b/src/antsibull_core/args.py index af4bb3e..98d4b23 100644 --- a/src/antsibull_core/args.py +++ b/src/antsibull_core/args.py @@ -16,27 +16,39 @@ class InvalidArgumentError(Exception): """A problem parsing or validating a command line argument.""" -def get_toplevel_parser(package, **kwargs) -> argparse.ArgumentParser: +def get_toplevel_parser( + package: str, + *, + package_version: str | None = None, + program_name: str | None = None, + **kwargs, +) -> argparse.ArgumentParser: """ Create a toplevel argument parser with options common across all scripts. :arg package: The Python package containing this CLI program. + :arg package_version: If provided, use this instead of the version for ``package`` + provided by ``importlib.metadata.version()``. + :arg program_name: If provided, show a more concrete description for this program. :args kwargs: This function takes any keyword arguments and passes them directly on to the :class:`argparse.ArgumentParser` constructor. :returns: :class:`argparse.ArgumentParser` with common script arguments added. """ - try: - version = metadata.version(package) - except metadata.PackageNotFoundError: - # If there's no metadata foun, assume we're running from source - version = "source" + if package_version is None: + try: + package_version = metadata.version(package) + except metadata.PackageNotFoundError: + # If there's no metadata found, assume we're running from source + package_version = "source" toplevel_parser = argparse.ArgumentParser(**kwargs) toplevel_parser.add_argument( "--version", action="version", - version=version, - help="Print the antsibull version", + version=package_version, + help=f"Print the {program_name} version" + if program_name + else "Print the program's version", ) toplevel_parser.add_argument( "--config-file",