Skip to content

Commit

Permalink
Implement custom argparse action for version display
Browse files Browse the repository at this point in the history
Substituted the simple version argument with a custom argparse VersionAction in main.py, enhancing the version output information. This new VersionAction class fetches version information from the __about__ file, combining it with the Python version, and formats it appropriately for output.
  • Loading branch information
dvershinin committed Apr 2, 2024
1 parent d7142d5 commit e644e9e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
29 changes: 29 additions & 0 deletions src/pip_safe/argparse_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Provides a custom argparse action to show program's version and exit."""
import logging
import sys as _sys
from argparse import SUPPRESS, Action

from .__about__ import __version__


log = logging.getLogger(__name__)


class VersionAction(Action):
"""Custom argparse action to show program's version and exit."""

def __init__(self, **kwargs):
# Set default values if not provided in kwargs
kwargs.setdefault("dest", SUPPRESS)
kwargs.setdefault("default", SUPPRESS)
kwargs.setdefault("nargs", 0)
kwargs.setdefault("help", "show program's version number and exit")
super().__init__(**kwargs)
self.version = kwargs.get("version2")

def __call__(self, parser, namespace, values, option_string=None):
version = f"%(prog)s {__version__}, Python {_sys.version_info.major}.{_sys.version_info.minor}"
formatter = parser.formatter_class(prog=parser.prog)
formatter.add_text(version)
_sys.stdout.write(formatter.format_help())
parser.exit()
9 changes: 3 additions & 6 deletions src/pip_safe/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import six
from tabulate import tabulate

from pip_safe.__about__ import __version__
from pip_safe.argparse_version import VersionAction
from pip_safe.utils import (
symlink,
make_sure_path_exists,
Expand Down Expand Up @@ -361,11 +361,8 @@ def main():
parser.add_argument(
"--system", dest="system", action="store_true", help="Install for all users"
)
parser.add_argument(
"--version",
action="version",
version="%(prog)s {version}".format(version=__version__),
)

parser.add_argument("--version", action=VersionAction)
parser.set_defaults(verbose=False, verbose_more=False, system=False)
args = parser.parse_args()

Expand Down

0 comments on commit e644e9e

Please sign in to comment.