lockss-pybasic 0.1.0.dev13__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 +81 -17
- lockss/pybasic/errorutil.py +4 -0
- lockss/pybasic/fileutil.py +19 -3
- {lockss_pybasic-0.1.0.dev13.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.dev13.dist-info/RECORD +0 -8
- {lockss_pybasic-0.1.0.dev13.dist-info → lockss_pybasic-0.1.0.dev14.dist-info}/LICENSE +0 -0
- {lockss_pybasic-0.1.0.dev13.dist-info → lockss_pybasic-0.1.0.dev14.dist-info}/WHEEL +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()
|
|
@@ -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=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
|
|
File without changes
|