Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to provide the version to antsibull_core.args.get_toplevel_parser() #96

Merged
merged 4 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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",
gotmax23 marked this conversation as resolved.
Show resolved Hide resolved
)
toplevel_parser.add_argument(
"--config-file",
Expand Down