Skip to content

Commit

Permalink
Allow to provide the version to antsibull_core.args.get_toplevel_pars…
Browse files Browse the repository at this point in the history
…er() (#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 <[email protected]>

---------

Co-authored-by: Maxwell G <[email protected]>
  • Loading branch information
felixfontein and gotmax23 authored Sep 1, 2023
1 parent de4d58d commit f47b2e8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
2 changes: 2 additions & 0 deletions changelogs/fragments/96-version.yml
Original file line number Diff line number Diff line change
@@ -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)."
28 changes: 20 additions & 8 deletions src/antsibull_core/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit f47b2e8

Please sign in to comment.