lockss-pybasic 0.1.0.dev12__py3-none-any.whl → 0.1.0.dev14__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 +115 -55
- lockss/pybasic/errorutil.py +4 -0
- lockss/pybasic/fileutil.py +19 -3
- {lockss_pybasic-0.1.0.dev12.dist-info → lockss_pybasic-0.1.0.dev14.dist-info}/METADATA +2 -2
- lockss_pybasic-0.1.0.dev14.dist-info/RECORD +8 -0
- lockss_pybasic-0.1.0.dev12.dist-info/RECORD +0 -8
- {lockss_pybasic-0.1.0.dev12.dist-info → lockss_pybasic-0.1.0.dev14.dist-info}/LICENSE +0 -0
- {lockss_pybasic-0.1.0.dev12.dist-info → lockss_pybasic-0.1.0.dev14.dist-info}/WHEEL +0 -0
lockss/pybasic/__init__.py
CHANGED
lockss/pybasic/cliutil.py
CHANGED
|
@@ -33,109 +33,169 @@ 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
|
-
from typing import Any, Dict, Generic,
|
|
38
|
+
from typing import Any, Dict, Generic, Optional, TypeVar
|
|
38
39
|
|
|
39
40
|
from pydantic.v1 import BaseModel, Field
|
|
40
41
|
from pydantic_argparse import ArgumentParser
|
|
41
42
|
|
|
42
43
|
|
|
43
|
-
class
|
|
44
|
+
class ActionCommand(Callable, BaseModel):
|
|
45
|
+
"""
|
|
46
|
+
Base class for a Pydantic-Argparse command
|
|
47
|
+
"""
|
|
48
|
+
pass
|
|
44
49
|
|
|
45
|
-
def print(self, file=sys.stdout):
|
|
46
|
-
print(self.get_display(), file=file)
|
|
47
50
|
|
|
48
|
-
|
|
49
|
-
def get_display(self):
|
|
50
|
-
pass
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
class CopyrightCommand:
|
|
51
|
+
class StringCommand(ActionCommand):
|
|
54
52
|
|
|
55
53
|
@staticmethod
|
|
56
|
-
def
|
|
57
|
-
class
|
|
58
|
-
def
|
|
59
|
-
|
|
60
|
-
return
|
|
54
|
+
def type(display_str: str):
|
|
55
|
+
class _StringCommand(StringCommand):
|
|
56
|
+
def __call__(self, file=sys.stdout):
|
|
57
|
+
print(display_str, file=file)
|
|
58
|
+
return _StringCommand
|
|
61
59
|
|
|
62
|
-
@staticmethod
|
|
63
|
-
def field():
|
|
64
|
-
return Field(description='print the copyright and exit')
|
|
65
60
|
|
|
61
|
+
COPYRIGHT_DESCRIPTION = 'print the copyright and exit'
|
|
62
|
+
LICENSE_DESCRIPTION = 'print the software license and exit'
|
|
63
|
+
VERSION_DESCRIPTION = 'print the version number and exit'
|
|
66
64
|
|
|
67
|
-
class LicenseCommand:
|
|
68
65
|
|
|
69
|
-
|
|
70
|
-
def make(license):
|
|
71
|
-
class LicenseModel(Printable, BaseModel):
|
|
72
|
-
def get_display(self):
|
|
73
|
-
return license
|
|
74
|
-
return LicenseModel
|
|
66
|
+
BaseModelT = TypeVar('BaseModelT', bound=BaseModel)
|
|
75
67
|
|
|
76
|
-
@staticmethod
|
|
77
|
-
def field():
|
|
78
|
-
return Field(description='print the software license and exit')
|
|
79
68
|
|
|
69
|
+
class BaseCli(Generic[BaseModelT]):
|
|
70
|
+
"""
|
|
71
|
+
Base class for general CLI functionality.
|
|
80
72
|
|
|
81
|
-
|
|
73
|
+
``BaseModelT`` represents a Pydantic-Argparse model type deriving from
|
|
74
|
+
``BaseModel``.
|
|
82
75
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return version
|
|
88
|
-
return VersionModel
|
|
89
|
-
|
|
90
|
-
@staticmethod
|
|
91
|
-
def field():
|
|
92
|
-
return Field(description='print the version number and exit')
|
|
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
|
+
"""
|
|
93
80
|
|
|
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
|
+
"""
|
|
91
|
+
super().__init__()
|
|
92
|
+
self.args: Optional[BaseModelT] = None
|
|
93
|
+
self.parser: Optional[ArgumentParser] = None
|
|
94
|
+
self.extra: Dict[str, Any] = dict(**extra)
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
def run(self) -> None:
|
|
97
|
+
"""
|
|
98
|
+
Runs the command line tool:
|
|
96
99
|
|
|
100
|
+
* Creates a Pydantic-Argparse ``ArgumentParser`` with ``model``,
|
|
101
|
+
``prog`` and ``description`` from the constructor keyword
|
|
102
|
+
arguments in ``self.parser``.
|
|
97
103
|
|
|
98
|
-
|
|
104
|
+
* Stores the Pydantic-Argparse parsed arguemnts in ``self.args``.
|
|
99
105
|
|
|
100
|
-
|
|
101
|
-
super().__init__()
|
|
102
|
-
self.args: ModelT = None
|
|
103
|
-
self.parser: ArgumentParser = None
|
|
104
|
-
self.extra: Dict[str, Any] = dict(**extra)
|
|
106
|
+
* Calls ``dispatch()``.
|
|
105
107
|
|
|
106
|
-
|
|
108
|
+
:return: Nothing.
|
|
109
|
+
"""
|
|
107
110
|
self.parser: ArgumentParser = ArgumentParser(model=self.extra.get('model'),
|
|
108
111
|
prog=self.extra.get('prog'),
|
|
109
112
|
description=self.extra.get('description'))
|
|
110
113
|
self.args = self.parser.parse_typed_args()
|
|
111
114
|
self.dispatch()
|
|
112
115
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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
|
+
"""
|
|
124
|
+
field_names = self.args.__class__.__fields__.keys()
|
|
125
|
+
for field_name in field_names:
|
|
126
|
+
field_value = getattr(self.args, field_name)
|
|
127
|
+
if issubclass(type(field_value), BaseModel):
|
|
128
|
+
func = getattr(self, f'_{field_name}')
|
|
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')
|
|
133
|
+
break
|
|
134
|
+
else:
|
|
135
|
+
self.parser.error(f'unknown command; expected one of {', '.join(field_names)}')
|
|
136
|
+
|
|
137
|
+
|
|
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
|
+
"""
|
|
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]
|
|
152
|
+
ret = [field_name for field_name in enum_names if values.get(field_name)]
|
|
153
|
+
if (length := len(ret)) > 1:
|
|
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])})')
|
|
155
|
+
return values
|
|
116
156
|
|
|
117
157
|
|
|
118
|
-
def
|
|
119
|
-
|
|
158
|
+
def get_from_enum(model_inst, enum_cls, default=None):
|
|
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]
|
|
172
|
+
for field_name in enum_names:
|
|
173
|
+
if getattr(model_inst, field_name):
|
|
174
|
+
return enum_cls[field_name]
|
|
175
|
+
return default
|
|
120
176
|
|
|
121
177
|
|
|
122
178
|
def at_most_one(values: Dict[str, Any], *names: str):
|
|
123
|
-
if (length := _matchy_length(values, names)) > 1:
|
|
179
|
+
if (length := _matchy_length(values, *names)) > 1:
|
|
124
180
|
raise ValueError(f'at most one of {', '.join([option_name(name) for name in names])} is allowed, got {length}')
|
|
125
181
|
return values
|
|
126
182
|
|
|
127
183
|
|
|
128
184
|
def exactly_one(values: Dict[str, Any], *names: str):
|
|
129
|
-
if (length := _matchy_length(values, names)) != 1:
|
|
185
|
+
if (length := _matchy_length(values, *names)) != 1:
|
|
130
186
|
raise ValueError(f'exactly one of {', '.join([option_name(name) for name in names])} is required, got {length}')
|
|
131
187
|
return values
|
|
132
188
|
|
|
133
189
|
|
|
134
190
|
def one_or_more(values: Dict[str, Any], *names: str):
|
|
135
|
-
if _matchy_length(values, names) == 0:
|
|
191
|
+
if _matchy_length(values, *names) == 0:
|
|
136
192
|
raise ValueError(f'one or more of {', '.join([option_name(name) for name in names])} is required')
|
|
137
193
|
return values
|
|
138
194
|
|
|
139
195
|
|
|
140
196
|
def option_name(name: str):
|
|
141
197
|
return f'{('-' if len(name) == 1 else '--')}{name.replace('_', '-')}'
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _matchy_length(values: Dict[str, Any], *names: str) -> int:
|
|
201
|
+
return len([name for name in names if values.get(name)])
|
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()
|
|
@@ -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.dev14
|
|
4
4
|
Summary: Basic Python utilities
|
|
5
5
|
License: BSD-3-Clause
|
|
6
6
|
Author: Thib Guicherd-Callin
|
|
@@ -13,7 +13,7 @@ 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
18
|
Description-Content-Type: text/x-rst
|
|
19
19
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
lockss/pybasic/__init__.py,sha256=oNqF2XvMGruAJn3JJJHni3MX72Hwmv9pW9C1YHf2g9A,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-0.1.0.dev14.dist-info/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
|
|
6
|
+
lockss_pybasic-0.1.0.dev14.dist-info/METADATA,sha256=JjYlda28TysulP8Mu-rAAIvKqDpjqEtWaNw7yYyppJs,696
|
|
7
|
+
lockss_pybasic-0.1.0.dev14.dist-info/WHEEL,sha256=fGIA9gx4Qxk2KDKeNJCbOEwSrmLtjWCwzBz351GyrPQ,88
|
|
8
|
+
lockss_pybasic-0.1.0.dev14.dist-info/RECORD,,
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
lockss/pybasic/__init__.py,sha256=YSnY4g1QwuL_AhsQgTVfznUy6uTQ1uwlFxsgU14IIMA,1679
|
|
2
|
-
lockss/pybasic/cliutil.py,sha256=sPaQ5gZ2Xj6Ld5Ol5AYH5Uh8ahXhvbOjEAbnWPRH7nI,4558
|
|
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.dev12.dist-info/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
|
|
6
|
-
lockss_pybasic-0.1.0.dev12.dist-info/METADATA,sha256=-_J0Ua6w6bnUqs88DHBOoV7fqnx4UD_nGxHNrQJ5xX8,696
|
|
7
|
-
lockss_pybasic-0.1.0.dev12.dist-info/WHEEL,sha256=fGIA9gx4Qxk2KDKeNJCbOEwSrmLtjWCwzBz351GyrPQ,88
|
|
8
|
-
lockss_pybasic-0.1.0.dev12.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|