lockss-pybasic 0.2.0.dev9__py3-none-any.whl → 0.2.0.dev11__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.
@@ -36,4 +36,4 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36
36
  POSSIBILITY OF SUCH DAMAGE.
37
37
  '''.strip()
38
38
 
39
- __version__ = '0.2.0-dev9'
39
+ __version__ = '0.2.0-dev11'
lockss/pybasic/cliutil.py CHANGED
@@ -31,225 +31,10 @@
31
31
  """
32
32
  Command line utilities.
33
33
  """
34
- import pathlib
35
- from collections.abc import Callable
36
- import sys
37
- from typing import Any, Dict, Generic, Optional, TypeVar
38
34
 
39
- import click
40
- from pydantic.v1 import BaseModel as BaseModel1
41
- from pydantic_argparse import ArgumentParser
42
- from pydantic_argparse.argparse.actions import SubParsersAction
43
- from rich_argparse import RichHelpFormatter
44
-
45
- from .fileutil import path
46
-
47
-
48
- class ActionCommand(Callable, BaseModel1):
49
- """
50
- Base class for a pydantic-argparse style command.
51
- """
52
- pass
53
-
54
-
55
- class StringCommand(ActionCommand):
56
- """
57
- A pydantic-argparse style command that prints a string.
58
-
59
- Example of use:
60
-
61
- .. code-block:: python
62
-
63
- class MyCliModel(BaseModel):
64
- copyright: Optional[StringCommand.type(my_copyright_string)] = Field(description=COPYRIGHT_DESCRIPTION)
65
-
66
- See also the convenience constants ``COPYRIGHT_DESCRIPTION``,
67
- ``LICENSE_DESCRIPTION``, and ``VERSION_DESCRIPTION``.
68
- """
69
-
70
- @staticmethod
71
- def type(display_str: str):
72
- class _StringCommand(StringCommand):
73
- def __call__(self, file=sys.stdout, **kwargs):
74
- print(display_str, file=file)
75
- return _StringCommand
76
-
77
-
78
- COPYRIGHT_DESCRIPTION = 'print the copyright and exit'
79
- LICENSE_DESCRIPTION = 'print the software license and exit'
80
- VERSION_DESCRIPTION = 'print the version number and exit'
81
-
82
-
83
- BaseModelT = TypeVar('BaseModelT', bound=BaseModel1)
84
-
85
-
86
- class BaseCli(Generic[BaseModelT]):
87
- """
88
- Base class for general CLI functionality.
89
-
90
- ``BaseModelT`` represents a Pydantic-Argparse model type deriving from
91
- ``BaseModel``.
92
-
93
- For each command ``x-y-z`` induced by a Pydantic-Argparse field named
94
- ``x_y_z`` deriving from ``BaseModel`` , the ``dispatch()`` method expects a
95
- method named ``_x_y_z``.
96
- """
97
-
98
- def __init__(self, **kwargs):
99
- """
100
- Constructs a new ``BaseCli`` instance.
101
-
102
- :param kwargs: Keyword arguments. Must include ``model``, the
103
- ``BaseModel`` type corresponding to ``BaseModelT``. Must
104
- include ``prog``, the command-line name of the program.
105
- Must include ``description``, the description string of
106
- the program.
107
- :type kwargs: Dict[str, Any]
108
- """
109
- super().__init__()
110
- self._args: Optional[BaseModelT] = None
111
- self._parser: Optional[ArgumentParser] = None
112
- self.extra: Dict[str, Any] = dict(**kwargs)
113
-
114
- def run(self) -> None:
115
- """
116
- Runs the command line tool:
117
-
118
- * Creates a Pydantic-Argparse ``ArgumentParser`` with ``model``,
119
- ``prog`` and ``description`` from the constructor keyword
120
- arguments in ``self.parser``.
121
-
122
- * Stores the Pydantic-Argparse parsed arguments in ``self.args``.
35
+ from typing import Optional
123
36
 
124
- * Calls ``dispatch()``.
125
- """
126
- self._parser: ArgumentParser = ArgumentParser(model=self.extra.get('model'),
127
- prog=self.extra.get('prog'),
128
- description=self.extra.get('description'))
129
- self._initialize_rich_argparse()
130
- self._args = self._parser.parse_typed_args()
131
- self.dispatch()
132
-
133
- def dispatch(self) -> None:
134
- """
135
- Dispatches from the first field ``x_y_z`` in ``self._args`` that is a
136
- command (i.e. whose value derives from ``BaseModel``) to a method
137
- called ``_x_y_z``.
138
- """
139
- self._dispatch_recursive(self._args, [])
140
-
141
- def _dispatch_recursive(self, base_model: BaseModel1, subcommands: list[str]) -> None:
142
- field_names = base_model.__class__.__fields__.keys()
143
- for field_name in field_names:
144
- field_value = getattr(base_model, field_name)
145
- if issubclass(type(field_value), BaseModel1):
146
- self._dispatch_recursive(field_value, [*subcommands, field_name])
147
- return
148
- func_name = ''.join(f'_{sub}' for sub in subcommands)
149
- func = getattr(self, func_name)
150
- if callable(func):
151
- func(base_model) # FIXME?
152
- else:
153
- self._parser.exit(1, f'internal error: no {func_name} callable for the {" ".join(sub for sub in subcommands)} command')
154
-
155
- def _initialize_rich_argparse(self) -> None:
156
- """
157
- Initializes `rich-argparse <https://pypi.org/project/rich-argparse/>`_
158
- for this instance.
159
- """
160
- self._initialize_rich_argparse_styles()
161
- def __add_formatter_class(container):
162
- container.formatter_class = RichHelpFormatter
163
- if hasattr(container, '_actions'):
164
- for action in container._actions:
165
- if issubclass(type(action), SubParsersAction):
166
- for subaction in action.choices.values():
167
- __add_formatter_class(subaction)
168
- __add_formatter_class(self._parser)
169
-
170
- def _initialize_rich_argparse_styles(self) -> None:
171
- # See https://github.com/hamdanal/rich-argparse#customize-the-colors
172
- for cls in [RichHelpFormatter]:
173
- cls.styles.update({
174
- 'argparse.args': 'bold cyan', # for positional-arguments and --options (e.g "--help")
175
- 'argparse.groups': 'underline dark_orange', # for group names (e.g. "positional arguments")
176
- 'argparse.help': 'default', # for argument's help text (e.g. "show this help message and exit")
177
- 'argparse.metavar': 'italic dark_cyan', # for metavariables (e.g. "FILE" in "--file FILE")
178
- 'argparse.prog': 'bold grey50', # for %(prog)s in the usage (e.g. "foo" in "Usage: foo [options]")
179
- 'argparse.syntax': 'bold', # for highlights of back-tick quoted text (e.g. "`some text`")
180
- 'argparse.text': 'default', # for descriptions, epilog, and --version (e.g. "A program to foo")
181
- 'argparse.default': 'italic', # for %(default)s in the help (e.g. "Value" in "(default: Value)")
182
- })
183
-
184
-
185
- def at_most_one_from_enum(model_cls, values: Dict[str, Any], enum_cls) -> Dict[str, Any]:
186
- """
187
- Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
188
- tagged with the ``enum`` keyword set to the given ``Enum`` type, ensures
189
- that at most one of them has a true value in the given Pydantic-Argparse
190
- validator ``values``, or raises a ``ValueError`` otherwise.
191
-
192
- :param model_cls: A Pydantic-Argparse model class.
193
- :param values: The Pydantic-Argparse validator ``values``.
194
- :param enum_cls: The ``Enum`` class the fields of the Pydantic-Argparse
195
- model are tagged with (using the ``enum`` keyword).
196
- :return: The ``values`` argument, if no ``ValueError`` has been raised.
197
- """
198
- enum_names = [field_name for field_name, model_field in model_cls.__fields__.items() if model_field.field_info.extra.get('enum') == enum_cls]
199
- ret = [field_name for field_name in enum_names if values.get(field_name)]
200
- if (length := len(ret)) > 1:
201
- 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])})')
202
- return values
203
-
204
-
205
- def get_from_enum(model_inst, enum_cls, default=None):
206
- """
207
- Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
208
- tagged with the ``enum`` keyword set to the given ``Enum`` type, gets the
209
- corresponding enum value of the first with a true value in the model, or
210
- returns the given default value. Assumes the existence of a
211
- ``from_member()`` static method in the ``Enum`` class.
212
-
213
- :param model_inst:
214
- :param enum_cls:
215
- :param default:
216
- :return:
217
- """
218
- 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]
219
- for field_name in enum_names:
220
- if getattr(model_inst, field_name):
221
- return enum_cls[field_name]
222
- return default
223
-
224
-
225
- def at_most_one(values: Dict[str, Any], *names: str):
226
- if (length := _matchy_length(values, *names)) > 1:
227
- raise ValueError(f'at most one of {", ".join([option_name(name) for name in names])} is allowed, got {length}')
228
- return values
229
-
230
-
231
- def exactly_one(values: Dict[str, Any], *names: str):
232
- if (length := _matchy_length(values, *names)) != 1:
233
- raise ValueError(f'exactly one of {", ".join([option_name(name) for name in names])} is required, got {length}')
234
- return values
235
-
236
-
237
- def one_or_more(values: Dict[str, Any], *names: str):
238
- if _matchy_length(values, *names) == 0:
239
- raise ValueError(f'one or more of {", ".join([option_name(name) for name in names])} is required')
240
- return values
241
-
242
-
243
- def option_name(model_cls: type[BaseModel1], name: str) -> str:
244
- if (info := model_cls.__fields__.get(name)) is None:
245
- raise RuntimeError(f'invalid name: {name}')
246
- if alias := info.alias:
247
- name = alias
248
- return f'{("-" if len(name) == 1 else "--")}{name.replace("_", "-")}'
249
-
250
-
251
- def _matchy_length(values: Dict[str, Any], *names: str) -> int:
252
- return len([name for name in names if values.get(name)])
37
+ import click
253
38
 
254
39
 
255
40
  def click_path(spec: Optional[str]) -> click.Path:
@@ -271,25 +56,27 @@ def click_path(spec: Optional[str]) -> click.Path:
271
56
  dir_okay = True
272
57
  file_okay = False
273
58
  elif char == 'e':
59
+ if 'E' in spec:
60
+ raise ValueError(f'"e" and "E" are mutually exclusive: {spec}')
61
+ exists = True
62
+ elif char == 'E':
63
+ if 'e' in spec:
64
+ raise ValueError(f'"E" and "e" are mutually exclusive: {spec}')
274
65
  exists = True
275
66
  elif char == 'f':
276
67
  if 'd' in spec:
277
68
  raise ValueError(f'"f" and "d" are mutually exclusive: {spec}')
278
69
  dir_okay = False
279
70
  file_okay = True
280
- # elif char == 'p':
281
- # if 'P' in spec or 's' in spec:
282
- # raise ValueError(f'"p", "P", and "s" are mutually exclusive: {spec}')
283
- # path_type = path
284
- elif char == 'P':
285
- if 'p' in spec or 's' in spec:
286
- raise ValueError(f'"P", "p", and "s" are mutually exclusive: {spec}')
71
+ elif char == 'p':
72
+ if 's' in spec:
73
+ raise ValueError(f'"p" and "s" are mutually exclusive: {spec}')
287
74
  path_type = pathlib.Path
288
75
  elif char == 'r':
289
76
  readable = True
290
77
  elif char == 's':
291
- if 'p' in spec or 'P' in spec:
292
- raise ValueError(f'"s", "p", and "P" are mutually exclusive: {spec}')
78
+ if 'p' in spec:
79
+ raise ValueError(f'"s" and "p" are mutually exclusive: {spec}')
293
80
  path_type = str
294
81
  elif char == 'w':
295
82
  writable = True
@@ -301,12 +88,12 @@ def click_path(spec: Optional[str]) -> click.Path:
301
88
  allow_dash = True
302
89
  else:
303
90
  raise ValueError(f'unknown specification character "{char}": {spec}')
304
- return click.Path(allow_dash=allow_dash,
305
- dir_okay=dir_okay,
306
- executable=executable,
307
- exists=exists,
308
- file_okay=file_okay,
309
- path_type=path_type,
310
- readable=readable,
311
- resolve_path=resolve_path,
312
- writable=writable)
91
+ return click.Path(allow_dash=allow_dash,
92
+ dir_okay=dir_okay,
93
+ executable=executable,
94
+ exists=exists,
95
+ file_okay=file_okay,
96
+ path_type=path_type,
97
+ readable=readable,
98
+ resolve_path=resolve_path,
99
+ writable=writable)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lockss-pybasic
3
- Version: 0.2.0.dev9
3
+ Version: 0.2.0.dev11
4
4
  Summary: Basic Python utilities
5
5
  License: BSD-3-Clause
6
6
  License-File: LICENSE
@@ -17,10 +17,6 @@ Classifier: License :: OSI Approved :: BSD License
17
17
  Classifier: Programming Language :: Python
18
18
  Classifier: Topic :: Software Development :: Libraries
19
19
  Requires-Dist: click-extra (>=7.5.0,<7.6.0)
20
- Requires-Dist: pydantic (>=2.11.0,<2.12.0)
21
- Requires-Dist: pydantic-argparse (>=0.10.0,<0.11.0)
22
- Requires-Dist: rich-argparse (>=1.7.0,<1.8.0)
23
- Requires-Dist: tabulate (>=0.9.0,<0.10.0)
24
20
  Project-URL: Repository, https://github.com/lockss/lockss-pybasic
25
21
  Description-Content-Type: text/x-rst
26
22
 
@@ -28,7 +24,7 @@ Description-Content-Type: text/x-rst
28
24
  lockss-pybasic
29
25
  ==============
30
26
 
31
- .. |RELEASE| replace:: 0.2.0-dev9
27
+ .. |RELEASE| replace:: 0.2.0-dev11
32
28
  .. |RELEASE_DATE| replace:: NOT YET RELEASED
33
29
 
34
30
  **Latest release:** |RELEASE| (|RELEASE_DATE|)
@@ -0,0 +1,9 @@
1
+ lockss/pybasic/__init__.py,sha256=v88nAXWCPkYyXSKwoJyGBE9un55PDsUvOjDsQyFGl4k,1679
2
+ lockss/pybasic/auidutil.py,sha256=o5IsRLEYROXRVS6oTO1VFtdzw7SImYSR5VcqAMHY4To,13921
3
+ lockss/pybasic/cliutil.py,sha256=7WjxKy97kZYLzWv6rvLeBisR1AxV2SdlJ1dkxM7lneg,3764
4
+ lockss/pybasic/errorutil.py,sha256=XI84PScZ851_-gfoazivJ8ceieMYWaxQr7qih5ltga0,1951
5
+ lockss/pybasic/fileutil.py,sha256=BpdoPWL70xYTuhyQRBEurScRVnPQg0mX-XW8yyKPGjw,2958
6
+ lockss_pybasic-0.2.0.dev11.dist-info/METADATA,sha256=kbpWDzqZQxTirLvtlQIub64AIIY9_Q7iFDlUMm45MOU,4145
7
+ lockss_pybasic-0.2.0.dev11.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
8
+ lockss_pybasic-0.2.0.dev11.dist-info/licenses/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
9
+ lockss_pybasic-0.2.0.dev11.dist-info/RECORD,,
@@ -1,57 +0,0 @@
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}')
@@ -1,10 +0,0 @@
1
- lockss/pybasic/__init__.py,sha256=w19js6dIeUAH99jh-rFzKKjiv0Jsex8m3GD2WU-cDwA,1678
2
- lockss/pybasic/auidutil.py,sha256=o5IsRLEYROXRVS6oTO1VFtdzw7SImYSR5VcqAMHY4To,13921
3
- lockss/pybasic/cliutil.py,sha256=Mstw3CqDMlFX2HoWmoD7pnjS-VDfcNEsdjb3XSFWKFw,12882
4
- lockss/pybasic/errorutil.py,sha256=XI84PScZ851_-gfoazivJ8ceieMYWaxQr7qih5ltga0,1951
5
- lockss/pybasic/fileutil.py,sha256=BpdoPWL70xYTuhyQRBEurScRVnPQg0mX-XW8yyKPGjw,2958
6
- lockss/pybasic/outpututil.py,sha256=8naQEZ1rM6vOFNL-9mWoK4dMBWokHmzQ0FkHaz8dyuM,2345
7
- lockss_pybasic-0.2.0.dev9.dist-info/METADATA,sha256=RMTTw6WSWW6q9Kl-ayqnuMWVbzt--UlP_Wg-Cxgfmpo,4326
8
- lockss_pybasic-0.2.0.dev9.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
9
- lockss_pybasic-0.2.0.dev9.dist-info/licenses/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
10
- lockss_pybasic-0.2.0.dev9.dist-info/RECORD,,