lockss-pybasic 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lockss_pybasic-0.1.0/CHANGELOG.rst +19 -0
- lockss_pybasic-0.1.0/LICENSE +27 -0
- lockss_pybasic-0.1.0/PKG-INFO +99 -0
- lockss_pybasic-0.1.0/README.rst +75 -0
- lockss_pybasic-0.1.0/pyproject.toml +73 -0
- lockss_pybasic-0.1.0/src/lockss/pybasic/__init__.py +39 -0
- lockss_pybasic-0.1.0/src/lockss/pybasic/cliutil.py +242 -0
- lockss_pybasic-0.1.0/src/lockss/pybasic/errorutil.py +45 -0
- lockss_pybasic-0.1.0/src/lockss/pybasic/fileutil.py +73 -0
- lockss_pybasic-0.1.0/src/lockss/pybasic/outpututil.py +57 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without
|
|
4
|
+
modification, are permitted provided that the following conditions are met:
|
|
5
|
+
|
|
6
|
+
1. Redistributions of source code must retain the above copyright notice,
|
|
7
|
+
this list of conditions and the following disclaimer.
|
|
8
|
+
|
|
9
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
10
|
+
this list of conditions and the following disclaimer in the documentation
|
|
11
|
+
and/or other materials provided with the distribution.
|
|
12
|
+
|
|
13
|
+
3. Neither the name of the copyright holder nor the names of its contributors
|
|
14
|
+
may be used to endorse or promote products derived from this software without
|
|
15
|
+
specific prior written permission.
|
|
16
|
+
|
|
17
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
18
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
19
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
20
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
21
|
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
22
|
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
23
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
24
|
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
25
|
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
26
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
27
|
+
POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: lockss-pybasic
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Basic Python utilities
|
|
5
|
+
License: BSD-3-Clause
|
|
6
|
+
Author: Thib Guicherd-Callin
|
|
7
|
+
Author-email: thib@cs.stanford.edu
|
|
8
|
+
Maintainer: Thib Guicherd-Callin
|
|
9
|
+
Maintainer-email: thib@cs.stanford.edu
|
|
10
|
+
Requires-Python: >=3.9,<4.0
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Framework :: Pydantic :: 2
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
16
|
+
Classifier: Programming Language :: Python
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
18
|
+
Requires-Dist: pydantic (>=2.11.0,<3.0.0)
|
|
19
|
+
Requires-Dist: pydantic-argparse (>=0.10.0,<0.11.0)
|
|
20
|
+
Requires-Dist: rich-argparse (>=1.7.0,<1.8.0)
|
|
21
|
+
Requires-Dist: tabulate (>=0.9.0,<0.10.0)
|
|
22
|
+
Project-URL: Repository, https://github.com/lockss/lockss-pybasic
|
|
23
|
+
Description-Content-Type: text/x-rst
|
|
24
|
+
|
|
25
|
+
==============
|
|
26
|
+
lockss-pybasic
|
|
27
|
+
==============
|
|
28
|
+
|
|
29
|
+
.. |RELEASE| replace:: 0.1.0
|
|
30
|
+
.. |RELEASE_DATE| replace:: 2025-07-01
|
|
31
|
+
|
|
32
|
+
**Latest release:** |RELEASE| (|RELEASE_DATE|)
|
|
33
|
+
|
|
34
|
+
``lockss-pybasic`` provides basic utilities for various LOCKSS projects written in Python.
|
|
35
|
+
|
|
36
|
+
-------
|
|
37
|
+
Modules
|
|
38
|
+
-------
|
|
39
|
+
|
|
40
|
+
``lockss.pybasic.cliutil``
|
|
41
|
+
Command line utilities.
|
|
42
|
+
|
|
43
|
+
* ``BaseCli`` is a base class for command line interfaces that uses `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ to define arguments and subcommands, and `rich-argparse <https://pypi.org/project/rich-argparse/>`_ to display help messages. For each command ``x-y-z`` induced by a ``pydantic-argparse`` field named ``x_y_z`` deriving from ``BaseModel`` , the ``dispatch()`` method expects a method named ``_x_y_z``.
|
|
44
|
+
|
|
45
|
+
* ``StringCommand`` provides a `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ way to define a subcommand whose only purpose is printing a string, with ``COPYRIGHT_DESCRIPTION``, ``LICENSE_DESCRIPTION`` and ``VERSION_DESCRIPTION`` constants provided for convenience. Example:
|
|
46
|
+
|
|
47
|
+
.. code-block:: python
|
|
48
|
+
|
|
49
|
+
class MyCliModel(BaseModel):
|
|
50
|
+
copyright: Optional[StringCommand.type(my_copyright_string)] = Field(description=COPYRIGHT_DESCRIPTION)
|
|
51
|
+
|
|
52
|
+
* ``at_most_one_from_enum`` and ``get_from_enum`` provide a facility for defining a `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ model that defines one command line option per constant of an ``Enum``, using an ``enum`` keyword argument in the ``Field`` definition. Example:
|
|
53
|
+
|
|
54
|
+
.. code-block:: python
|
|
55
|
+
|
|
56
|
+
class Orientation(Enum):
|
|
57
|
+
horizontal = 1
|
|
58
|
+
vertical = 2
|
|
59
|
+
diagonal = 3
|
|
60
|
+
|
|
61
|
+
DEFAULT_ORIENTATION = Orientation.horizontal
|
|
62
|
+
|
|
63
|
+
class MyCliModel(BaseModel):
|
|
64
|
+
diagonal: Optional[bool] = Field(False, description='display diagonally', enum=Orientation)
|
|
65
|
+
horizontal: Optional[bool] = Field(False, description='display horizontally', enum=Orientation)
|
|
66
|
+
unrelated: Optional[bool] = Field(...)
|
|
67
|
+
vertical: Optional[bool] = Field(False, description='display vertically', enum=Orientation)
|
|
68
|
+
|
|
69
|
+
@root_validator
|
|
70
|
+
def _at_most_one_orientation(cls, values):
|
|
71
|
+
return at_most_one_from_enum(cls, values, Orientation)
|
|
72
|
+
|
|
73
|
+
def get_orientation(self) -> Orientation:
|
|
74
|
+
return get_from_enum(self, Orientation, DEFAULT_ORIENTATION)
|
|
75
|
+
|
|
76
|
+
``lockss.pybasic.errorutil``
|
|
77
|
+
Error and exception utilities.
|
|
78
|
+
|
|
79
|
+
* ``InternalError`` is a no-arg subclass of ``RuntimeError``.
|
|
80
|
+
|
|
81
|
+
``lockss.pybasic.fileutil``
|
|
82
|
+
File and path utilities.
|
|
83
|
+
|
|
84
|
+
* ``file_lines`` returns the non-empty lines of a file stripped of comments that begin with ``#`` and run to the end of a line.
|
|
85
|
+
|
|
86
|
+
* ``path`` takes a string or ``PurePath`` and returns a ``Path`` for which ``Path.expanduser()`` and ``Path.resolve()`` have been called.
|
|
87
|
+
|
|
88
|
+
``lockss.pybasic.outpututil``
|
|
89
|
+
Utilities to work with `tabulate <https://pypi.org/project/tabulate/>`_.
|
|
90
|
+
|
|
91
|
+
* ``OutputFormat`` is an ``Enum`` of all the output formats from ``tabulate.tabulate_formats``.
|
|
92
|
+
|
|
93
|
+
* ``OutputFormatOptions`` defines a `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ model for setting an output format from ``OutputFormat``.
|
|
94
|
+
|
|
95
|
+
-------------
|
|
96
|
+
Release Notes
|
|
97
|
+
-------------
|
|
98
|
+
|
|
99
|
+
See `<CHANGELOG.rst>`_.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
==============
|
|
2
|
+
lockss-pybasic
|
|
3
|
+
==============
|
|
4
|
+
|
|
5
|
+
.. |RELEASE| replace:: 0.1.0
|
|
6
|
+
.. |RELEASE_DATE| replace:: 2025-07-01
|
|
7
|
+
|
|
8
|
+
**Latest release:** |RELEASE| (|RELEASE_DATE|)
|
|
9
|
+
|
|
10
|
+
``lockss-pybasic`` provides basic utilities for various LOCKSS projects written in Python.
|
|
11
|
+
|
|
12
|
+
-------
|
|
13
|
+
Modules
|
|
14
|
+
-------
|
|
15
|
+
|
|
16
|
+
``lockss.pybasic.cliutil``
|
|
17
|
+
Command line utilities.
|
|
18
|
+
|
|
19
|
+
* ``BaseCli`` is a base class for command line interfaces that uses `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ to define arguments and subcommands, and `rich-argparse <https://pypi.org/project/rich-argparse/>`_ to display help messages. For each command ``x-y-z`` induced by a ``pydantic-argparse`` field named ``x_y_z`` deriving from ``BaseModel`` , the ``dispatch()`` method expects a method named ``_x_y_z``.
|
|
20
|
+
|
|
21
|
+
* ``StringCommand`` provides a `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ way to define a subcommand whose only purpose is printing a string, with ``COPYRIGHT_DESCRIPTION``, ``LICENSE_DESCRIPTION`` and ``VERSION_DESCRIPTION`` constants provided for convenience. Example:
|
|
22
|
+
|
|
23
|
+
.. code-block:: python
|
|
24
|
+
|
|
25
|
+
class MyCliModel(BaseModel):
|
|
26
|
+
copyright: Optional[StringCommand.type(my_copyright_string)] = Field(description=COPYRIGHT_DESCRIPTION)
|
|
27
|
+
|
|
28
|
+
* ``at_most_one_from_enum`` and ``get_from_enum`` provide a facility for defining a `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ model that defines one command line option per constant of an ``Enum``, using an ``enum`` keyword argument in the ``Field`` definition. Example:
|
|
29
|
+
|
|
30
|
+
.. code-block:: python
|
|
31
|
+
|
|
32
|
+
class Orientation(Enum):
|
|
33
|
+
horizontal = 1
|
|
34
|
+
vertical = 2
|
|
35
|
+
diagonal = 3
|
|
36
|
+
|
|
37
|
+
DEFAULT_ORIENTATION = Orientation.horizontal
|
|
38
|
+
|
|
39
|
+
class MyCliModel(BaseModel):
|
|
40
|
+
diagonal: Optional[bool] = Field(False, description='display diagonally', enum=Orientation)
|
|
41
|
+
horizontal: Optional[bool] = Field(False, description='display horizontally', enum=Orientation)
|
|
42
|
+
unrelated: Optional[bool] = Field(...)
|
|
43
|
+
vertical: Optional[bool] = Field(False, description='display vertically', enum=Orientation)
|
|
44
|
+
|
|
45
|
+
@root_validator
|
|
46
|
+
def _at_most_one_orientation(cls, values):
|
|
47
|
+
return at_most_one_from_enum(cls, values, Orientation)
|
|
48
|
+
|
|
49
|
+
def get_orientation(self) -> Orientation:
|
|
50
|
+
return get_from_enum(self, Orientation, DEFAULT_ORIENTATION)
|
|
51
|
+
|
|
52
|
+
``lockss.pybasic.errorutil``
|
|
53
|
+
Error and exception utilities.
|
|
54
|
+
|
|
55
|
+
* ``InternalError`` is a no-arg subclass of ``RuntimeError``.
|
|
56
|
+
|
|
57
|
+
``lockss.pybasic.fileutil``
|
|
58
|
+
File and path utilities.
|
|
59
|
+
|
|
60
|
+
* ``file_lines`` returns the non-empty lines of a file stripped of comments that begin with ``#`` and run to the end of a line.
|
|
61
|
+
|
|
62
|
+
* ``path`` takes a string or ``PurePath`` and returns a ``Path`` for which ``Path.expanduser()`` and ``Path.resolve()`` have been called.
|
|
63
|
+
|
|
64
|
+
``lockss.pybasic.outpututil``
|
|
65
|
+
Utilities to work with `tabulate <https://pypi.org/project/tabulate/>`_.
|
|
66
|
+
|
|
67
|
+
* ``OutputFormat`` is an ``Enum`` of all the output formats from ``tabulate.tabulate_formats``.
|
|
68
|
+
|
|
69
|
+
* ``OutputFormatOptions`` defines a `pydantic-argparse <https://pypi.org/project/pydantic-argparse/>`_ model for setting an output format from ``OutputFormat``.
|
|
70
|
+
|
|
71
|
+
-------------
|
|
72
|
+
Release Notes
|
|
73
|
+
-------------
|
|
74
|
+
|
|
75
|
+
See `<CHANGELOG.rst>`_.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
2
|
+
#
|
|
3
|
+
# Redistribution and use in source and binary forms, with or without
|
|
4
|
+
# modification, are permitted provided that the following conditions are met:
|
|
5
|
+
#
|
|
6
|
+
# 1. Redistributions of source code must retain the above copyright notice,
|
|
7
|
+
# this list of conditions and the following disclaimer.
|
|
8
|
+
#
|
|
9
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
10
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
11
|
+
# and/or other materials provided with the distribution.
|
|
12
|
+
#
|
|
13
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
14
|
+
# may be used to endorse or promote products derived from this software without
|
|
15
|
+
# specific prior written permission.
|
|
16
|
+
#
|
|
17
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
18
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
19
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
20
|
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
21
|
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
22
|
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
23
|
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
24
|
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
25
|
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
26
|
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
27
|
+
# POSSIBILITY OF SUCH DAMAGE.
|
|
28
|
+
|
|
29
|
+
[project]
|
|
30
|
+
name = "lockss-pybasic"
|
|
31
|
+
version = "0.1.0" # Always change in __init__.py, and at release time in README.rst and CHANGELOG.rst
|
|
32
|
+
description = "Basic Python utilities"
|
|
33
|
+
license = { text = "BSD-3-Clause" }
|
|
34
|
+
readme = "README.rst"
|
|
35
|
+
requires-python = ">=3.9,<4.0"
|
|
36
|
+
authors = [
|
|
37
|
+
{ name = "Thib Guicherd-Callin", email = "thib@cs.stanford.edu" },
|
|
38
|
+
]
|
|
39
|
+
maintainers = [
|
|
40
|
+
{ name = "Thib Guicherd-Callin", email = "thib@cs.stanford.edu" },
|
|
41
|
+
]
|
|
42
|
+
dependencies = [
|
|
43
|
+
"pydantic (>=2.11.0,<3.0.0)",
|
|
44
|
+
"pydantic-argparse (>=0.10.0,<0.11.0)",
|
|
45
|
+
"rich-argparse (>=1.7.0,<1.8.0)",
|
|
46
|
+
"tabulate (>=0.9.0,<0.10.0)",
|
|
47
|
+
]
|
|
48
|
+
classifiers = [
|
|
49
|
+
"Development Status :: 4 - Beta",
|
|
50
|
+
"Environment :: Console",
|
|
51
|
+
"Framework :: Pydantic :: 2",
|
|
52
|
+
"Intended Audience :: Developers",
|
|
53
|
+
"License :: OSI Approved :: BSD License",
|
|
54
|
+
"Programming Language :: Python",
|
|
55
|
+
"Topic :: Software Development :: Libraries",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
[project.urls]
|
|
59
|
+
repository = "https://github.com/lockss/lockss-pybasic"
|
|
60
|
+
|
|
61
|
+
[tool.poetry]
|
|
62
|
+
include = [
|
|
63
|
+
"CHANGELOG.rst",
|
|
64
|
+
"LICENSE",
|
|
65
|
+
"README.rst",
|
|
66
|
+
]
|
|
67
|
+
packages = [
|
|
68
|
+
{ include = "lockss", from = "src" }
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
[build-system]
|
|
72
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
73
|
+
build-backend = "poetry.core.masonry.api"
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Basic Python utilities.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__copyright__ = '''
|
|
8
|
+
Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
9
|
+
'''.strip()
|
|
10
|
+
|
|
11
|
+
__license__ = __copyright__ + '\n\n' + '''
|
|
12
|
+
Redistribution and use in source and binary forms, with or without
|
|
13
|
+
modification, are permitted provided that the following conditions are met:
|
|
14
|
+
|
|
15
|
+
1. Redistributions of source code must retain the above copyright notice,
|
|
16
|
+
this list of conditions and the following disclaimer.
|
|
17
|
+
|
|
18
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
19
|
+
this list of conditions and the following disclaimer in the documentation
|
|
20
|
+
and/or other materials provided with the distribution.
|
|
21
|
+
|
|
22
|
+
3. Neither the name of the copyright holder nor the names of its contributors
|
|
23
|
+
may be used to endorse or promote products derived from this software without
|
|
24
|
+
specific prior written permission.
|
|
25
|
+
|
|
26
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
27
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
28
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
29
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
30
|
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
31
|
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
32
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
33
|
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
34
|
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
35
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
36
|
+
POSSIBILITY OF SUCH DAMAGE.
|
|
37
|
+
'''.strip()
|
|
38
|
+
|
|
39
|
+
__version__ = '0.1.0'
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice,
|
|
9
|
+
# this list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
16
|
+
# may be used to endorse or promote products derived from this software without
|
|
17
|
+
# specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
22
|
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
23
|
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
24
|
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
25
|
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
26
|
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
27
|
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
28
|
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
29
|
+
# POSSIBILITY OF SUCH DAMAGE.
|
|
30
|
+
|
|
31
|
+
"""
|
|
32
|
+
Command line utilities.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from collections.abc import Callable
|
|
36
|
+
import sys
|
|
37
|
+
from typing import Any, Dict, Generic, Optional, TypeVar
|
|
38
|
+
|
|
39
|
+
from pydantic.v1 import BaseModel
|
|
40
|
+
from pydantic_argparse import ArgumentParser
|
|
41
|
+
from pydantic_argparse.argparse.actions import SubParsersAction
|
|
42
|
+
from rich_argparse import RichHelpFormatter
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ActionCommand(Callable, BaseModel):
|
|
46
|
+
"""
|
|
47
|
+
Base class for a pydantic-argparse style command.
|
|
48
|
+
"""
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class StringCommand(ActionCommand):
|
|
53
|
+
"""
|
|
54
|
+
A pydantic-argparse style command that prints a string.
|
|
55
|
+
|
|
56
|
+
Example of use:
|
|
57
|
+
|
|
58
|
+
.. code-block:: python
|
|
59
|
+
|
|
60
|
+
class MyCliModel(BaseModel):
|
|
61
|
+
copyright: Optional[StringCommand.type(my_copyright_string)] = Field(description=COPYRIGHT_DESCRIPTION)
|
|
62
|
+
|
|
63
|
+
See also the convenience constants ``COPYRIGHT_DESCRIPTION``,
|
|
64
|
+
``LICENSE_DESCRIPTION``, and ``VERSION_DESCRIPTION``.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def type(display_str: str):
|
|
69
|
+
class _StringCommand(StringCommand):
|
|
70
|
+
def __call__(self, file=sys.stdout, **kwargs):
|
|
71
|
+
print(display_str, file=file)
|
|
72
|
+
return _StringCommand
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
COPYRIGHT_DESCRIPTION = 'print the copyright and exit'
|
|
76
|
+
LICENSE_DESCRIPTION = 'print the software license and exit'
|
|
77
|
+
VERSION_DESCRIPTION = 'print the version number and exit'
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
BaseModelT = TypeVar('BaseModelT', bound=BaseModel)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class BaseCli(Generic[BaseModelT]):
|
|
84
|
+
"""
|
|
85
|
+
Base class for general CLI functionality.
|
|
86
|
+
|
|
87
|
+
``BaseModelT`` represents a Pydantic-Argparse model type deriving from
|
|
88
|
+
``BaseModel``.
|
|
89
|
+
|
|
90
|
+
For each command ``x-y-z`` induced by a Pydantic-Argparse field named
|
|
91
|
+
``x_y_z`` deriving from ``BaseModel`` , the ``dispatch()`` method expects a
|
|
92
|
+
method named ``_x_y_z``.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(self, **kwargs):
|
|
96
|
+
"""
|
|
97
|
+
Constructs a new ``BaseCli`` instance.
|
|
98
|
+
|
|
99
|
+
:param kwargs: Keyword arguments. Must include ``model``, the
|
|
100
|
+
``BaseModel`` type corresponding to ``BaseModelT``. Must
|
|
101
|
+
include ``prog``, the command-line name of the program.
|
|
102
|
+
Must include ``description``, the description string of
|
|
103
|
+
the program.
|
|
104
|
+
:type kwargs: Dict[str, Any]
|
|
105
|
+
"""
|
|
106
|
+
super().__init__()
|
|
107
|
+
self._args: Optional[BaseModelT] = None
|
|
108
|
+
self._parser: Optional[ArgumentParser] = None
|
|
109
|
+
self.extra: Dict[str, Any] = dict(**kwargs)
|
|
110
|
+
|
|
111
|
+
def run(self) -> None:
|
|
112
|
+
"""
|
|
113
|
+
Runs the command line tool:
|
|
114
|
+
|
|
115
|
+
* Creates a Pydantic-Argparse ``ArgumentParser`` with ``model``,
|
|
116
|
+
``prog`` and ``description`` from the constructor keyword
|
|
117
|
+
arguments in ``self.parser``.
|
|
118
|
+
|
|
119
|
+
* Stores the Pydantic-Argparse parsed arguments in ``self.args``.
|
|
120
|
+
|
|
121
|
+
* Calls ``dispatch()``.
|
|
122
|
+
"""
|
|
123
|
+
self._parser: ArgumentParser = ArgumentParser(model=self.extra.get('model'),
|
|
124
|
+
prog=self.extra.get('prog'),
|
|
125
|
+
description=self.extra.get('description'))
|
|
126
|
+
self._initialize_rich_argparse()
|
|
127
|
+
self._args = self._parser.parse_typed_args()
|
|
128
|
+
self.dispatch()
|
|
129
|
+
|
|
130
|
+
def dispatch(self) -> None:
|
|
131
|
+
"""
|
|
132
|
+
Dispatches from the first field ``x_y_z`` in ``self.args`` that is a
|
|
133
|
+
command (i.e. whose value derives from ``BaseModel``) to a method
|
|
134
|
+
called ``_x_y_z``.
|
|
135
|
+
"""
|
|
136
|
+
field_names = self._args.__class__.__fields__.keys()
|
|
137
|
+
for field_name in field_names:
|
|
138
|
+
field_value = getattr(self._args, field_name)
|
|
139
|
+
if issubclass(type(field_value), BaseModel):
|
|
140
|
+
func = getattr(self, f'_{field_name}')
|
|
141
|
+
if callable(func):
|
|
142
|
+
func(field_value)
|
|
143
|
+
else:
|
|
144
|
+
self._parser.exit(1, f'internal error: no _{field_name} callable for the {field_name} command')
|
|
145
|
+
break
|
|
146
|
+
else:
|
|
147
|
+
self._parser.error(f'unknown command; expected one of {', '.join(field_names)}')
|
|
148
|
+
|
|
149
|
+
def _initialize_rich_argparse(self) -> None:
|
|
150
|
+
"""
|
|
151
|
+
Initializes `rich-argparse <https://pypi.org/project/rich-argparse/>`_
|
|
152
|
+
for this instance.
|
|
153
|
+
"""
|
|
154
|
+
self._initialize_rich_argparse_styles()
|
|
155
|
+
def __add_formatter_class(container):
|
|
156
|
+
container.formatter_class = RichHelpFormatter
|
|
157
|
+
if hasattr(container, '_actions'):
|
|
158
|
+
for action in container._actions:
|
|
159
|
+
if issubclass(type(action), SubParsersAction):
|
|
160
|
+
for subaction in action.choices.values():
|
|
161
|
+
__add_formatter_class(subaction)
|
|
162
|
+
__add_formatter_class(self._parser)
|
|
163
|
+
|
|
164
|
+
def _initialize_rich_argparse_styles(self) -> None:
|
|
165
|
+
# See https://github.com/hamdanal/rich-argparse#customize-the-colors
|
|
166
|
+
for cls in [RichHelpFormatter]:
|
|
167
|
+
cls.styles.update({
|
|
168
|
+
'argparse.args': 'bold cyan', # for positional-arguments and --options (e.g "--help")
|
|
169
|
+
'argparse.groups': 'underline dark_orange', # for group names (e.g. "positional arguments")
|
|
170
|
+
'argparse.help': 'default', # for argument's help text (e.g. "show this help message and exit")
|
|
171
|
+
'argparse.metavar': 'italic dark_cyan', # for metavariables (e.g. "FILE" in "--file FILE")
|
|
172
|
+
'argparse.prog': 'bold grey50', # for %(prog)s in the usage (e.g. "foo" in "Usage: foo [options]")
|
|
173
|
+
'argparse.syntax': 'bold', # for highlights of back-tick quoted text (e.g. "`some text`")
|
|
174
|
+
'argparse.text': 'default', # for descriptions, epilog, and --version (e.g. "A program to foo")
|
|
175
|
+
'argparse.default': 'italic', # for %(default)s in the help (e.g. "Value" in "(default: Value)")
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def at_most_one_from_enum(model_cls, values: Dict[str, Any], enum_cls) -> Dict[str, Any]:
|
|
180
|
+
"""
|
|
181
|
+
Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
|
|
182
|
+
tagged with the ``enum`` keyword set to the given ``Enum`` type, ensures
|
|
183
|
+
that at most one of them has a true value in the given Pydantic-Argparse
|
|
184
|
+
validator ``values``, or raises a ``ValueError`` otherwise.
|
|
185
|
+
|
|
186
|
+
:param model_cls: A Pydantic-Argparse model class.
|
|
187
|
+
:param values: The Pydantic-Argparse validator ``values``.
|
|
188
|
+
:param enum_cls: The ``Enum`` class the fields of the Pydantic-Argparse
|
|
189
|
+
model are tagged with (using the ``enum`` keyword).
|
|
190
|
+
:return: The ``values`` argument, if no ``ValueError`` has been raised.
|
|
191
|
+
"""
|
|
192
|
+
enum_names = [field_name for field_name, model_field in model_cls.__fields__.items() if model_field.field_info.extra.get('enum') == enum_cls]
|
|
193
|
+
ret = [field_name for field_name in enum_names if values.get(field_name)]
|
|
194
|
+
if (length := len(ret)) > 1:
|
|
195
|
+
raise ValueError(f'at most one of {', '.join([option_name(enum_name) for enum_name in enum_names])} is allowed, got {length} ({', '.join([option_name(enum_name) for enum_name in ret])})')
|
|
196
|
+
return values
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def get_from_enum(model_inst, enum_cls, default=None):
|
|
200
|
+
"""
|
|
201
|
+
Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
|
|
202
|
+
tagged with the ``enum`` keyword set to the given ``Enum`` type, gets the
|
|
203
|
+
corresponding enum value of the first with a true value in the model, or
|
|
204
|
+
returns the given default value. Assumes the existence of a
|
|
205
|
+
``from_member()`` static method in the ``Enum`` class.
|
|
206
|
+
|
|
207
|
+
:param model_inst:
|
|
208
|
+
:param enum_cls:
|
|
209
|
+
:param default:
|
|
210
|
+
:return:
|
|
211
|
+
"""
|
|
212
|
+
enum_names = [field_name for field_name, model_field in type(model_inst).__fields__.items() if model_field.field_info.extra.get('enum') == enum_cls]
|
|
213
|
+
for field_name in enum_names:
|
|
214
|
+
if getattr(model_inst, field_name):
|
|
215
|
+
return enum_cls[field_name]
|
|
216
|
+
return default
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def at_most_one(values: Dict[str, Any], *names: str):
|
|
220
|
+
if (length := _matchy_length(values, *names)) > 1:
|
|
221
|
+
raise ValueError(f'at most one of {', '.join([option_name(name) for name in names])} is allowed, got {length}')
|
|
222
|
+
return values
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def exactly_one(values: Dict[str, Any], *names: str):
|
|
226
|
+
if (length := _matchy_length(values, *names)) != 1:
|
|
227
|
+
raise ValueError(f'exactly one of {', '.join([option_name(name) for name in names])} is required, got {length}')
|
|
228
|
+
return values
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def one_or_more(values: Dict[str, Any], *names: str):
|
|
232
|
+
if _matchy_length(values, *names) == 0:
|
|
233
|
+
raise ValueError(f'one or more of {', '.join([option_name(name) for name in names])} is required')
|
|
234
|
+
return values
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def option_name(name: str) -> str:
|
|
238
|
+
return f'{('-' if len(name) == 1 else '--')}{name.replace('_', '-')}'
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _matchy_length(values: Dict[str, Any], *names: str) -> int:
|
|
242
|
+
return len([name for name in names if values.get(name)])
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice,
|
|
9
|
+
# this list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
16
|
+
# may be used to endorse or promote products derived from this software without
|
|
17
|
+
# specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
22
|
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
23
|
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
24
|
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
25
|
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
26
|
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
27
|
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
28
|
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
29
|
+
# POSSIBILITY OF SUCH DAMAGE.
|
|
30
|
+
|
|
31
|
+
"""
|
|
32
|
+
Error and exception utilities.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
class InternalError(RuntimeError):
|
|
36
|
+
"""
|
|
37
|
+
A simple no-arg ``RuntimeError`` with the message ``internal error``,
|
|
38
|
+
intended for situations that should never occur.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
"""
|
|
43
|
+
Constructs a new ``InternalError`` instance.
|
|
44
|
+
"""
|
|
45
|
+
super().__init__('internal error')
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice,
|
|
9
|
+
# this list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
16
|
+
# may be used to endorse or promote products derived from this software without
|
|
17
|
+
# specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
22
|
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
23
|
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
24
|
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
25
|
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
26
|
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
27
|
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
28
|
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
29
|
+
# POSSIBILITY OF SUCH DAMAGE.
|
|
30
|
+
|
|
31
|
+
"""
|
|
32
|
+
File and path utilities.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from pathlib import Path, PurePath
|
|
36
|
+
import sys
|
|
37
|
+
from typing import List, Union
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def file_lines(fpath: Path) -> List[str]:
|
|
41
|
+
"""
|
|
42
|
+
Returns a list of lines from the given file, with '#' comments and leading
|
|
43
|
+
and trailing whitespace removed, ignoring empty lines.
|
|
44
|
+
|
|
45
|
+
:param fpath: A ``Path`` to a file, ``-`` for ``sys.stdin``.
|
|
46
|
+
:type fpath: Path
|
|
47
|
+
:return: A list of processed lines.
|
|
48
|
+
:rtype: List[str]
|
|
49
|
+
"""
|
|
50
|
+
f = None
|
|
51
|
+
try:
|
|
52
|
+
f = open(path(fpath), 'r') if fpath != '-' else sys.stdin
|
|
53
|
+
return [line for line in [line.partition('#')[0].strip() for line in f] if len(line) > 0]
|
|
54
|
+
finally:
|
|
55
|
+
if f is not None and path != '-':
|
|
56
|
+
f.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def path(purepath_or_string: Union[PurePath, str]) -> Path:
|
|
60
|
+
"""
|
|
61
|
+
Returns the given ``PurePath`` (or if given a string, the ``Path`` created
|
|
62
|
+
from that string), expanded with ``expanduser()`` and resolved with
|
|
63
|
+
``resolve()``.
|
|
64
|
+
|
|
65
|
+
:param purepath_or_string: A ``PurePath`` (or a ``str`` from which to create
|
|
66
|
+
a ``Path``).
|
|
67
|
+
:type purepath_or_string: Union[PurePath, str]
|
|
68
|
+
:return: An expanded and resolved ``Path``.
|
|
69
|
+
:rtype: Path
|
|
70
|
+
"""
|
|
71
|
+
if not issubclass(type(purepath_or_string), PurePath):
|
|
72
|
+
purepath_or_string = Path(purepath_or_string)
|
|
73
|
+
return purepath_or_string.expanduser().resolve()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2000-2025, Board of Trustees of Leland Stanford Jr. University
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are met:
|
|
7
|
+
#
|
|
8
|
+
# 1. Redistributions of source code must retain the above copyright notice,
|
|
9
|
+
# this list of conditions and the following disclaimer.
|
|
10
|
+
#
|
|
11
|
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
# this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
# and/or other materials provided with the distribution.
|
|
14
|
+
#
|
|
15
|
+
# 3. Neither the name of the copyright holder nor the names of its contributors
|
|
16
|
+
# may be used to endorse or promote products derived from this software without
|
|
17
|
+
# specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
22
|
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
23
|
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
24
|
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
25
|
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
26
|
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
27
|
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
28
|
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
29
|
+
# POSSIBILITY OF SUCH DAMAGE.
|
|
30
|
+
|
|
31
|
+
"""
|
|
32
|
+
Utilities to work with 'tabulate'.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from enum import Enum
|
|
36
|
+
|
|
37
|
+
from pydantic.v1 import BaseModel, Field, validator
|
|
38
|
+
import tabulate
|
|
39
|
+
from typing import Optional
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
OutputFormat = Enum('OutputFormat', tabulate.tabulate_formats)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
DEFAULT_OUTPUT_FORMAT = 'simple' # from tabulate
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class OutputFormatOptions(BaseModel):
|
|
49
|
+
output_format: Optional[str] = Field(DEFAULT_OUTPUT_FORMAT, description=f'[output] set the output format; choices: {', '.join(OutputFormat.__members__.keys())}')
|
|
50
|
+
|
|
51
|
+
@validator('output_format')
|
|
52
|
+
def _validate_output_format(cls, val: str):
|
|
53
|
+
try:
|
|
54
|
+
_ = OutputFormat[val]
|
|
55
|
+
return val
|
|
56
|
+
except KeyError:
|
|
57
|
+
raise ValueError(f'must be one of {', '.join(OutputFormat.__members__.keys())}; got {val}')
|