lockss-pybasic 0.1.0.dev13__py3-none-any.whl → 0.1.0.dev15__py3-none-any.whl
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/__init__.py +1 -1
- lockss/pybasic/cliutil.py +81 -17
- lockss/pybasic/errorutil.py +4 -0
- lockss/pybasic/fileutil.py +19 -3
- lockss/pybasic/outpututil.py +59 -0
- {lockss_pybasic-0.1.0.dev13.dist-info → lockss_pybasic-0.1.0.dev15.dist-info}/METADATA +3 -2
- lockss_pybasic-0.1.0.dev15.dist-info/RECORD +9 -0
- {lockss_pybasic-0.1.0.dev13.dist-info → lockss_pybasic-0.1.0.dev15.dist-info}/WHEEL +1 -1
- lockss_pybasic-0.1.0.dev13.dist-info/RECORD +0 -8
- {lockss_pybasic-0.1.0.dev13.dist-info → lockss_pybasic-0.1.0.dev15.dist-info}/LICENSE +0 -0
lockss/pybasic/__init__.py
CHANGED
lockss/pybasic/cliutil.py
CHANGED
|
@@ -33,6 +33,7 @@ Command line utilities.
|
|
|
33
33
|
"""
|
|
34
34
|
|
|
35
35
|
from abc import ABC, abstractmethod
|
|
36
|
+
from collections.abc import Callable
|
|
36
37
|
import sys
|
|
37
38
|
from typing import Any, Dict, Generic, Optional, TypeVar
|
|
38
39
|
|
|
@@ -40,11 +41,11 @@ from pydantic.v1 import BaseModel, Field
|
|
|
40
41
|
from pydantic_argparse import ArgumentParser
|
|
41
42
|
|
|
42
43
|
|
|
43
|
-
class ActionCommand(
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
44
|
+
class ActionCommand(Callable, BaseModel):
|
|
45
|
+
"""
|
|
46
|
+
Base class for a Pydantic-Argparse command
|
|
47
|
+
"""
|
|
48
|
+
pass
|
|
48
49
|
|
|
49
50
|
|
|
50
51
|
class StringCommand(ActionCommand):
|
|
@@ -52,7 +53,7 @@ class StringCommand(ActionCommand):
|
|
|
52
53
|
@staticmethod
|
|
53
54
|
def type(display_str: str):
|
|
54
55
|
class _StringCommand(StringCommand):
|
|
55
|
-
def
|
|
56
|
+
def __call__(self, file=sys.stdout):
|
|
56
57
|
print(display_str, file=file)
|
|
57
58
|
return _StringCommand
|
|
58
59
|
|
|
@@ -66,48 +67,111 @@ BaseModelT = TypeVar('BaseModelT', bound=BaseModel)
|
|
|
66
67
|
|
|
67
68
|
|
|
68
69
|
class BaseCli(Generic[BaseModelT]):
|
|
70
|
+
"""
|
|
71
|
+
Base class for general CLI functionality.
|
|
72
|
+
|
|
73
|
+
``BaseModelT`` represents a Pydantic-Argparse model type deriving from
|
|
74
|
+
``BaseModel``.
|
|
75
|
+
|
|
76
|
+
For each command ``x-y-z`` induced by a Pydantic-Argparse field named
|
|
77
|
+
``x_y_z`` deriving from ``BaseModel`` , the ``dispatch()`` method expects a
|
|
78
|
+
method named ``_x_y_z``.
|
|
79
|
+
"""
|
|
69
80
|
|
|
70
81
|
def __init__(self, **extra):
|
|
82
|
+
"""
|
|
83
|
+
Makes a new BaseCli instance.
|
|
84
|
+
|
|
85
|
+
:param extra: Keyword arguments. Must include ``model``, the
|
|
86
|
+
``BaseModel`` type corresponding to ``BaseModelT``. Must
|
|
87
|
+
include ``prog``, the command-line name of the program.
|
|
88
|
+
Must include ``description``, the description string of
|
|
89
|
+
the program.
|
|
90
|
+
"""
|
|
71
91
|
super().__init__()
|
|
72
92
|
self.args: Optional[BaseModelT] = None
|
|
73
93
|
self.parser: Optional[ArgumentParser] = None
|
|
74
94
|
self.extra: Dict[str, Any] = dict(**extra)
|
|
75
95
|
|
|
76
|
-
def run(self):
|
|
96
|
+
def run(self) -> None:
|
|
97
|
+
"""
|
|
98
|
+
Runs the command line tool:
|
|
99
|
+
|
|
100
|
+
* Creates a Pydantic-Argparse ``ArgumentParser`` with ``model``,
|
|
101
|
+
``prog`` and ``description`` from the constructor keyword
|
|
102
|
+
arguments in ``self.parser``.
|
|
103
|
+
|
|
104
|
+
* Stores the Pydantic-Argparse parsed arguemnts in ``self.args``.
|
|
105
|
+
|
|
106
|
+
* Calls ``dispatch()``.
|
|
107
|
+
|
|
108
|
+
:return: Nothing.
|
|
109
|
+
"""
|
|
77
110
|
self.parser: ArgumentParser = ArgumentParser(model=self.extra.get('model'),
|
|
78
111
|
prog=self.extra.get('prog'),
|
|
79
112
|
description=self.extra.get('description'))
|
|
80
113
|
self.args = self.parser.parse_typed_args()
|
|
81
114
|
self.dispatch()
|
|
82
115
|
|
|
83
|
-
def dispatch(self):
|
|
116
|
+
def dispatch(self) -> None:
|
|
117
|
+
"""
|
|
118
|
+
Dispatches from the first field ``x_y_z`` in ``self.args`` that is a
|
|
119
|
+
command (i.e. whose value derives from ``BaseModel``) to a method
|
|
120
|
+
called ``_x_y_z``.
|
|
121
|
+
|
|
122
|
+
:return: Nothing.
|
|
123
|
+
"""
|
|
84
124
|
field_names = self.args.__class__.__fields__.keys()
|
|
85
125
|
for field_name in field_names:
|
|
86
126
|
field_value = getattr(self.args, field_name)
|
|
87
127
|
if issubclass(type(field_value), BaseModel):
|
|
88
128
|
func = getattr(self, f'_{field_name}')
|
|
89
|
-
func
|
|
129
|
+
if callable(func):
|
|
130
|
+
func(field_value)
|
|
131
|
+
else:
|
|
132
|
+
self.parser.exit(1, f'internal error: no _{field_name} callable for the {field_name} command')
|
|
90
133
|
break
|
|
91
134
|
else:
|
|
92
135
|
self.parser.error(f'unknown command; expected one of {', '.join(field_names)}')
|
|
93
136
|
|
|
94
137
|
|
|
95
|
-
def at_most_one_from_enum(model_cls, values: Dict[str, Any], enum_cls):
|
|
138
|
+
def at_most_one_from_enum(model_cls, values: Dict[str, Any], enum_cls) -> Dict[str, Any]:
|
|
139
|
+
"""
|
|
140
|
+
Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
|
|
141
|
+
tagged with the ``enum`` keyword set to the given ``Enum`` type, ensures
|
|
142
|
+
that at most one of them has a true value in the given Pydantic-Argparse
|
|
143
|
+
validator ``values``, or raises a ``ValueError`` otherwise.
|
|
144
|
+
|
|
145
|
+
:param model_cls: A Pydantic-Argparse model class.
|
|
146
|
+
:param values: The Pydantic-Argparse validator ``values``.
|
|
147
|
+
:param enum_cls: The ``Enum`` class the fields of the Pydantic-Argparse
|
|
148
|
+
model are tagged with (using the ``enum`` keyword).
|
|
149
|
+
:return: The ``values`` argument, if no ``ValueError`` has been raised.
|
|
150
|
+
"""
|
|
96
151
|
enum_names = [field_name for field_name, model_field in model_cls.__fields__.items() if model_field.field_info.extra.get('enum') == enum_cls]
|
|
97
|
-
ret =
|
|
98
|
-
for field_name in enum_names:
|
|
99
|
-
if values.get(field_name):
|
|
100
|
-
ret.append(field_name)
|
|
152
|
+
ret = [field_name for field_name in enum_names if values.get(field_name)]
|
|
101
153
|
if (length := len(ret)) > 1:
|
|
102
|
-
raise ValueError(f'at most one of {', '.join([option_name(enum_name) for enum_name in enum_names])} is allowed, got {', '.join([option_name(enum_name) for enum_name in ret])}')
|
|
154
|
+
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])})')
|
|
103
155
|
return values
|
|
104
156
|
|
|
105
157
|
|
|
106
158
|
def get_from_enum(model_inst, enum_cls, default=None):
|
|
107
|
-
|
|
159
|
+
"""
|
|
160
|
+
Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
|
|
161
|
+
tagged with the ``enum`` keyword set to the given ``Enum`` type, gets the
|
|
162
|
+
corresponding enum value of the first with a true value in the model, or
|
|
163
|
+
returns the given default value. Assumes the existence of a
|
|
164
|
+
``from_member()`` static method in the ``Enum`` class.
|
|
165
|
+
|
|
166
|
+
:param model_inst:
|
|
167
|
+
:param enum_cls:
|
|
168
|
+
:param default:
|
|
169
|
+
:return:
|
|
170
|
+
"""
|
|
171
|
+
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]
|
|
108
172
|
for field_name in enum_names:
|
|
109
173
|
if getattr(model_inst, field_name):
|
|
110
|
-
return enum_cls
|
|
174
|
+
return enum_cls[field_name]
|
|
111
175
|
return default
|
|
112
176
|
|
|
113
177
|
|
lockss/pybasic/errorutil.py
CHANGED
|
@@ -33,6 +33,10 @@ Error and exception utilities.
|
|
|
33
33
|
"""
|
|
34
34
|
|
|
35
35
|
class InternalError(RuntimeError):
|
|
36
|
+
"""
|
|
37
|
+
A simple ``RuntimeError`` with the message ``internal error``, intended for
|
|
38
|
+
situations that should never occur.
|
|
39
|
+
"""
|
|
36
40
|
|
|
37
41
|
def __init__(self, *args: object) -> None:
|
|
38
42
|
super().__init__('internal error')
|
lockss/pybasic/fileutil.py
CHANGED
|
@@ -34,10 +34,17 @@ File and path utilities.
|
|
|
34
34
|
|
|
35
35
|
from pathlib import Path, PurePath
|
|
36
36
|
import sys
|
|
37
|
-
from typing import Union
|
|
37
|
+
from typing import List, Union
|
|
38
38
|
|
|
39
39
|
|
|
40
|
-
def file_lines(fpath: Path):
|
|
40
|
+
def file_lines(fpath: Path) -> List[str]:
|
|
41
|
+
"""
|
|
42
|
+
Returns a list of lines from the given file, with '#' comments and leading
|
|
43
|
+
trailing whitespace removed, ignoring empty lines.
|
|
44
|
+
|
|
45
|
+
:param fpath: A ``Path`` to a file (``-`` for ``sys.stdin``).
|
|
46
|
+
:return: A list of lines.
|
|
47
|
+
"""
|
|
41
48
|
f = None
|
|
42
49
|
try:
|
|
43
50
|
f = open(path(fpath), 'r') if fpath != '-' else sys.stdin
|
|
@@ -47,7 +54,16 @@ def file_lines(fpath: Path):
|
|
|
47
54
|
f.close()
|
|
48
55
|
|
|
49
56
|
|
|
50
|
-
def path(purepath_or_string: Union[PurePath, str]):
|
|
57
|
+
def path(purepath_or_string: Union[PurePath, str]) -> Path:
|
|
58
|
+
"""
|
|
59
|
+
Returns the given ``PurePath`` (or if given a string, the ``Path`` created
|
|
60
|
+
from that string), expanded with ``expanduser()`` and resolved with
|
|
61
|
+
``resolve()``.
|
|
62
|
+
|
|
63
|
+
:param purepath_or_string: A ``PurePath`` (or a ``str`` from which to create
|
|
64
|
+
a ``Path``).
|
|
65
|
+
:return: An expanded and resolved ``Path``.
|
|
66
|
+
"""
|
|
51
67
|
if not issubclass(type(purepath_or_string), PurePath):
|
|
52
68
|
purepath_or_string = Path(purepath_or_string)
|
|
53
69
|
return purepath_or_string.expanduser().resolve()
|
|
@@ -0,0 +1,59 @@
|
|
|
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
|
+
|
|
36
|
+
from enum import Enum
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
from pydantic.v1 import BaseModel, Field, validator
|
|
40
|
+
import tabulate
|
|
41
|
+
from typing import Optional
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
OutputFormat = Enum('OutputFormat', tabulate.tabulate_formats)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
DEFAULT_OUTPUT_FORMAT = 'simple' # from tabulate
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class OutputFormatOptions(BaseModel):
|
|
51
|
+
output_format: Optional[str] = Field(DEFAULT_OUTPUT_FORMAT, description=f'[output] set the output format; choices: {', '.join(OutputFormat.__members__.keys())}')
|
|
52
|
+
|
|
53
|
+
@validator('output_format')
|
|
54
|
+
def _validate_output_format(cls, val: str):
|
|
55
|
+
try:
|
|
56
|
+
_ = OutputFormat[val]
|
|
57
|
+
return val
|
|
58
|
+
except KeyError:
|
|
59
|
+
raise ValueError(f'must be one of {', '.join(OutputFormat.__members__.keys())}; got {val}')
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: lockss-pybasic
|
|
3
|
-
Version: 0.1.0.
|
|
3
|
+
Version: 0.1.0.dev15
|
|
4
4
|
Summary: Basic Python utilities
|
|
5
5
|
License: BSD-3-Clause
|
|
6
6
|
Author: Thib Guicherd-Callin
|
|
@@ -13,8 +13,9 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.12
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
-
Requires-Dist: pydantic (>=2.11.
|
|
16
|
+
Requires-Dist: pydantic (>=2.11.0,<3.0.0)
|
|
17
17
|
Requires-Dist: pydantic-argparse (>=0.10.0,<0.11.0)
|
|
18
|
+
Requires-Dist: tabulate (>=0.9.0,<0.10.0)
|
|
18
19
|
Description-Content-Type: text/x-rst
|
|
19
20
|
|
|
20
21
|
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
lockss/pybasic/__init__.py,sha256=XExTO4wescY_7hXxgFYf18u69OyEu6ToibH0ZTWSU3A,1679
|
|
2
|
+
lockss/pybasic/cliutil.py,sha256=UK-Z82LWW4t0aJqcqT79E3t6806q0pKREW_Lm_BEdxs,8034
|
|
3
|
+
lockss/pybasic/errorutil.py,sha256=OJqRGOjzKK8_OTJCq77u0_XZ5ti2BoVidk5jSTMB6xg,1882
|
|
4
|
+
lockss/pybasic/fileutil.py,sha256=O_EcxobrHPLeD7lAlvtYOkd0R2NOIvpGK6mZOZTxyG4,2856
|
|
5
|
+
lockss/pybasic/outpututil.py,sha256=S2Jpcj7IctXoA10OFGueNzcd7fMjj6RARpc6s15_xLY,2347
|
|
6
|
+
lockss_pybasic-0.1.0.dev15.dist-info/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
|
|
7
|
+
lockss_pybasic-0.1.0.dev15.dist-info/METADATA,sha256=vRa0BTwoeFeMy8EP1-_cw8T6ZWxMF8yNectGG5ehQug,738
|
|
8
|
+
lockss_pybasic-0.1.0.dev15.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
|
|
9
|
+
lockss_pybasic-0.1.0.dev15.dist-info/RECORD,,
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
lockss/pybasic/__init__.py,sha256=YMxnE1BYFx_4jKjWJqU0JUAYBV_PyFw79GwtM0x51gY,1679
|
|
2
|
-
lockss/pybasic/cliutil.py,sha256=dV1l3jlZy0j49eR1UuOCIYh5nTjvlAUwErXE8ufkxL0,5343
|
|
3
|
-
lockss/pybasic/errorutil.py,sha256=SD0kZtQt_lyVqqlLeo5K6ihkgQ1sm1rtvwI_pST-7ns,1746
|
|
4
|
-
lockss/pybasic/fileutil.py,sha256=hr4RtAaalEKwXx1kjGBReLOcmlbml1cwG9K5zcbreSw,2199
|
|
5
|
-
lockss_pybasic-0.1.0.dev13.dist-info/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
|
|
6
|
-
lockss_pybasic-0.1.0.dev13.dist-info/METADATA,sha256=ts5VSdrLufRNOOn-HueYprKw2owTj8q4N1HY97XQ5eE,696
|
|
7
|
-
lockss_pybasic-0.1.0.dev13.dist-info/WHEEL,sha256=fGIA9gx4Qxk2KDKeNJCbOEwSrmLtjWCwzBz351GyrPQ,88
|
|
8
|
-
lockss_pybasic-0.1.0.dev13.dist-info/RECORD,,
|
|
File without changes
|