Skip to content

Commit 600fb82

Browse files
committed
Add versions module.
1 parent 1901784 commit 600fb82

File tree

4 files changed

+191
-1
lines changed

4 files changed

+191
-1
lines changed

consolekit/versions.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#!/usr/bin/env python3
2+
#
3+
# versions.py
4+
"""
5+
Tool to get software versions.
6+
"""
7+
#
8+
# Copyright © 2023 Dominic Davis-Foster <[email protected]>
9+
#
10+
# Permission is hereby granted, free of charge, to any person obtaining a copy
11+
# of this software and associated documentation files (the "Software"), to deal
12+
# in the Software without restriction, including without limitation the rights
13+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14+
# copies of the Software, and to permit persons to whom the Software is
15+
# furnished to do so, subject to the following conditions:
16+
#
17+
# The above copyright notice and this permission notice shall be included in all
18+
# copies or substantial portions of the Software.
19+
#
20+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23+
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
24+
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
25+
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
26+
# OR OTHER DEALINGS IN THE SOFTWARE.
27+
#
28+
29+
# stdlib
30+
import platform
31+
import sys
32+
import textwrap
33+
from typing import Any, Callable, List, Mapping, Union
34+
35+
# 3rd party
36+
import click
37+
from domdf_python_tools.compat import importlib_metadata
38+
from domdf_python_tools.stringlist import StringList
39+
from domdf_python_tools.words import LF
40+
41+
__all__ = ("get_formatted_versions", "version_callback")
42+
43+
44+
def get_formatted_versions(
45+
dependencies: Union[List[str], Mapping[str, str]],
46+
show_python: bool = True,
47+
show_platform: bool = True,
48+
) -> StringList:
49+
"""
50+
Return the versions of software dependencies, one per line.
51+
52+
:param dependencies: Either a list of dependency names,
53+
or a mapping of dependency name to a more human-readable form.
54+
:param show_python:
55+
:param show_platform:
56+
"""
57+
58+
versions = StringList()
59+
60+
if not isinstance(dependencies, Mapping):
61+
dependencies = {d: d for d in dependencies}
62+
63+
for dependency_name, display_name in dependencies.items():
64+
65+
dep_version = importlib_metadata.version(dependency_name)
66+
versions.append(f"{display_name}: {dep_version}")
67+
68+
if show_python:
69+
versions.append(f"Python: {sys.version.replace(LF, ' ')}")
70+
71+
if show_platform:
72+
versions.append(' '.join(platform.system_alias(platform.system(), platform.release(), platform.version())))
73+
74+
return versions
75+
76+
77+
def get_version_callback(
78+
tool_version: str,
79+
tool_name: str,
80+
dependencies: Union[List[str], Mapping[str, str]],
81+
) -> Callable[[click.Context, click.Option, int], Any]:
82+
"""
83+
Creates a callback for :class:`~.version_option`.
84+
85+
With each ``--version`` argument the callback displays the package version,
86+
then adds the python version, and finally adds dependency versions.
87+
88+
89+
:param tool_version: The version of the tool to show the version of.
90+
:param tool_name: The name of the tool to show the version of.
91+
:param dependencies: Either a list of dependency names,
92+
or a mapping of dependency name to a more human-readable form.
93+
"""
94+
95+
def version_callback(ctx: click.Context, param: click.Option, value: int) -> None:
96+
"""
97+
Callback for displaying the package version (and optionally the Python runtime).
98+
"""
99+
100+
if not value or ctx.resilient_parsing:
101+
return
102+
103+
if value > 2:
104+
versions = textwrap.indent(
105+
get_formatted_versions(dependencies), # type: ignore[arg-type]
106+
" ",
107+
)
108+
click.echo(tool_name)
109+
click.echo(f" Version: {tool_version}")
110+
click.echo(versions)
111+
elif value > 1:
112+
python_version = sys.version.replace('\n', ' ')
113+
click.echo(f"{tool_name} version {tool_version}, Python {python_version}")
114+
else:
115+
click.echo(f"{tool_name} version {tool_version}")
116+
117+
ctx.exit()
118+
119+
return version_callback

doc-source/api/versions.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
=============================
2+
:mod:`consolekit.versions`
3+
=============================
4+
5+
.. automodule:: consolekit.versions

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
click>=7.1.2
22
colorama>=0.4.3; python_version < "3.10" and platform_system == "Windows"
33
deprecation-alias>=0.1.1
4-
domdf-python-tools>=2.6.0
4+
domdf-python-tools>=3.8.0
55
mistletoe>=0.7.2
66
typing-extensions!=3.10.0.1,>=3.10.0.0

tests/test_versions.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# stdlib
2+
import sys
3+
4+
# this package
5+
from consolekit import click_command
6+
from consolekit.options import version_option
7+
from consolekit.testing import CliRunner
8+
from consolekit.versions import get_formatted_versions, get_version_callback
9+
10+
11+
def test_get_formatted_versions():
12+
dependencies = ["click", "deprecation-alias", "domdf-python-tools", "mistletoe", "typing-extensions"]
13+
14+
sl = get_formatted_versions(dependencies)
15+
for line, dep in zip(sl, dependencies):
16+
assert line.startswith(f"{dep}:")
17+
assert sl[-2].startswith("Python: 3.")
18+
19+
sl = get_formatted_versions(dependencies, show_platform=False)
20+
for line, dep in zip(sl, [*dependencies]):
21+
assert line.startswith(f"{dep}:")
22+
assert sl[-1].startswith("Python: 3.")
23+
24+
sl = get_formatted_versions(dependencies, show_python=False)
25+
assert len(sl) == len(dependencies) + 1
26+
27+
sl = get_formatted_versions(dependencies, show_python=False, show_platform=False)
28+
assert len(sl) == len(dependencies)
29+
30+
sl = get_formatted_versions({
31+
"click": "pkg1",
32+
"deprecation-alias": "pkg2",
33+
"domdf-python-tools": "pkg3",
34+
"mistletoe": "pkg4",
35+
"typing-extensions": "pkg5"
36+
})
37+
for line, name in zip(sl, ["pkg1", "pkg2", "pkg3", "pkg4", "pkg5"]):
38+
assert line.startswith(f"{name}:")
39+
assert sl[-2].startswith("Python: 3.")
40+
41+
42+
def test_version_callback(cli_runner: CliRunner):
43+
44+
@version_option(
45+
get_version_callback(
46+
"1.2.3",
47+
"my-tool",
48+
["click", "deprecation-alias", "domdf-python-tools", "mistletoe", "typing-extensions"]
49+
)
50+
)
51+
@click_command()
52+
def main() -> None:
53+
sys.exit(1)
54+
55+
result = cli_runner.invoke(main, args="--version")
56+
assert result.stdout.rstrip() == "my-tool version 1.2.3"
57+
assert result.exit_code == 0
58+
59+
result = cli_runner.invoke(main, args=["--version", "--version"])
60+
assert result.stdout.startswith("my-tool version 1.2.3, Python 3.")
61+
assert result.exit_code == 0
62+
63+
result = cli_runner.invoke(main, args=["--version", "--version", "--version"])
64+
print(result.stdout)
65+
assert result.stdout.startswith("my-tool\n Version: 1.2.3\n click: ")
66+
assert result.exit_code == 0

0 commit comments

Comments
 (0)