lockss-pybasic 0.2.0.dev5__py3-none-any.whl → 0.2.0.dev7__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/auidutil.py +417 -0
- lockss/pybasic/cliutil.py +34 -42
- lockss/pybasic/outpututil.py +2 -2
- {lockss_pybasic-0.2.0.dev5.dist-info → lockss_pybasic-0.2.0.dev7.dist-info}/METADATA +5 -4
- lockss_pybasic-0.2.0.dev7.dist-info/RECORD +10 -0
- {lockss_pybasic-0.2.0.dev5.dist-info → lockss_pybasic-0.2.0.dev7.dist-info}/WHEEL +1 -1
- lockss_pybasic-0.2.0.dev5.dist-info/RECORD +0 -9
- {lockss_pybasic-0.2.0.dev5.dist-info → lockss_pybasic-0.2.0.dev7.dist-info/licenses}/LICENSE +0 -0
lockss/pybasic/__init__.py
CHANGED
|
@@ -0,0 +1,417 @@
|
|
|
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
|
+
LOCKSS AUID Generator
|
|
33
|
+
|
|
34
|
+
Port of the AUID generation logic from org.lockss.plugin.PluginManager
|
|
35
|
+
and related utility classes in the LOCKSS lockss-core library.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
import urllib.parse
|
|
39
|
+
from typing import Dict
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class InvalidAuidError(ValueError):
|
|
43
|
+
"""Raised when an AUID string is malformed or invalid."""
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AuidGenerator:
|
|
48
|
+
"""
|
|
49
|
+
Generator for LOCKSS Archival Unit Identifiers (AUIDs).
|
|
50
|
+
|
|
51
|
+
This class provides static methods for generating and parsing AUIDs,
|
|
52
|
+
which uniquely identify archival units in the LOCKSS system.
|
|
53
|
+
|
|
54
|
+
AUID Format: pluginKey&auKey
|
|
55
|
+
- pluginKey: Plugin class name with dots replaced by pipes
|
|
56
|
+
- auKey: Canonically encoded definitional parameters
|
|
57
|
+
|
|
58
|
+
Example:
|
|
59
|
+
>>> plugin_id = "org.lockss.plugin.simulated.SimulatedPlugin"
|
|
60
|
+
>>> params = {"base_url": "http://example.com/", "year": "2023"}
|
|
61
|
+
>>> auid = AuidGenerator.generate_auid(plugin_id, params)
|
|
62
|
+
>>> print(auid)
|
|
63
|
+
org|lockss|plugin|simulated|SimulatedPlugin&base_url~http%3A%2F%2Fexample%2Ecom%2F&year~2023
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def plugin_key_from_id(plugin_id: str) -> str:
|
|
68
|
+
"""
|
|
69
|
+
Convert plugin ID to plugin key by replacing dots with pipes.
|
|
70
|
+
|
|
71
|
+
Port of PluginManager.pluginKeyFromId()
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
plugin_id: Plugin class name (e.g., "org.lockss.plugin.simulated.SimulatedPlugin")
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
Plugin key (e.g., "org|lockss|plugin|simulated|SimulatedPlugin")
|
|
78
|
+
|
|
79
|
+
Example:
|
|
80
|
+
>>> AuidGenerator.plugin_key_from_id("org.lockss.plugin.TestPlugin")
|
|
81
|
+
'org|lockss|plugin|TestPlugin'
|
|
82
|
+
"""
|
|
83
|
+
if not plugin_id:
|
|
84
|
+
raise ValueError("plugin_id cannot be empty")
|
|
85
|
+
return plugin_id.replace(".", "|")
|
|
86
|
+
|
|
87
|
+
@staticmethod
|
|
88
|
+
def plugin_id_from_key(plugin_key: str) -> str:
|
|
89
|
+
"""
|
|
90
|
+
Convert plugin key back to plugin ID by replacing pipes with dots.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
plugin_key: Plugin key (e.g., "org|lockss|plugin|simulated|SimulatedPlugin")
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
Plugin ID (e.g., "org.lockss.plugin.simulated.SimulatedPlugin")
|
|
97
|
+
|
|
98
|
+
Example:
|
|
99
|
+
>>> AuidGenerator.plugin_id_from_key("org|lockss|plugin|TestPlugin")
|
|
100
|
+
'org.lockss.plugin.TestPlugin'
|
|
101
|
+
"""
|
|
102
|
+
if not plugin_key:
|
|
103
|
+
raise ValueError("plugin_key cannot be empty")
|
|
104
|
+
return plugin_key.replace("|", ".")
|
|
105
|
+
|
|
106
|
+
# Characters that don't need encoding - matches Java PropKeyEncoder exactly
|
|
107
|
+
# See lockss-core PropKeyEncoder.java lines 46-62
|
|
108
|
+
_DONT_NEED_ENCODING = set(
|
|
109
|
+
'abcdefghijklmnopqrstuvwxyz'
|
|
110
|
+
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
111
|
+
'0123456789'
|
|
112
|
+
' ' # Space is converted to '+' in encode()
|
|
113
|
+
'-'
|
|
114
|
+
'_'
|
|
115
|
+
'*'
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def encode_component(s: str) -> str:
|
|
120
|
+
"""
|
|
121
|
+
URL-encode a string component for use in AUID.
|
|
122
|
+
|
|
123
|
+
Port of PropKeyEncoder.encode() from lockss-core.
|
|
124
|
+
|
|
125
|
+
This method encodes strings using URL encoding with the following rules:
|
|
126
|
+
- Alphanumeric characters (a-z, A-Z, 0-9) are not encoded
|
|
127
|
+
- Hyphens (-), underscores (_), and asterisks (*) are not encoded
|
|
128
|
+
- Spaces are encoded as '+'
|
|
129
|
+
- All other characters (including periods) are percent-encoded with uppercase hex digits
|
|
130
|
+
|
|
131
|
+
Note: This differs from standard URL encoding (RFC 3986) which treats
|
|
132
|
+
periods (.) as unreserved. Java's PropKeyEncoder encodes periods.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
s: String to encode
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
URL-encoded string with spaces as '+' and uppercase hex digits
|
|
139
|
+
|
|
140
|
+
Example:
|
|
141
|
+
>>> AuidGenerator.encode_component("http://example.com/")
|
|
142
|
+
'http%3A%2F%2Fexample%2Ecom%2F'
|
|
143
|
+
"""
|
|
144
|
+
if not s:
|
|
145
|
+
return ""
|
|
146
|
+
|
|
147
|
+
result = []
|
|
148
|
+
# Encode string to UTF-8 bytes, matching Java's OutputStreamWriter behavior
|
|
149
|
+
for char in s:
|
|
150
|
+
if char in AuidGenerator._DONT_NEED_ENCODING:
|
|
151
|
+
if char == ' ':
|
|
152
|
+
result.append('+')
|
|
153
|
+
else:
|
|
154
|
+
result.append(char)
|
|
155
|
+
else:
|
|
156
|
+
# Encode character to UTF-8 bytes and percent-encode each byte
|
|
157
|
+
char_bytes = char.encode('utf-8')
|
|
158
|
+
for byte in char_bytes:
|
|
159
|
+
result.append('%')
|
|
160
|
+
result.append(format(byte, '02X'))
|
|
161
|
+
|
|
162
|
+
return ''.join(result)
|
|
163
|
+
|
|
164
|
+
@staticmethod
|
|
165
|
+
def decode_component(s: str) -> str:
|
|
166
|
+
"""
|
|
167
|
+
URL-decode a string component from an AUID.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
s: URL-encoded string
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
Decoded string
|
|
174
|
+
|
|
175
|
+
Example:
|
|
176
|
+
>>> AuidGenerator.decode_component('http%3A%2F%2Fexample.com%2F')
|
|
177
|
+
'http://example.com/'
|
|
178
|
+
"""
|
|
179
|
+
if not s:
|
|
180
|
+
return ""
|
|
181
|
+
return urllib.parse.unquote_plus(s, errors="strict")
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def props_to_canonical_encoded_string(props: Dict[str, str]) -> str:
|
|
185
|
+
"""
|
|
186
|
+
Convert properties dictionary to canonical encoded string.
|
|
187
|
+
|
|
188
|
+
Port of PropUtil.propsToCanonicalEncodedString() from lockss-core.
|
|
189
|
+
|
|
190
|
+
The canonical form is created by:
|
|
191
|
+
1. Sorting keys alphabetically
|
|
192
|
+
2. Encoding each key and value
|
|
193
|
+
3. Joining with '~' between key and value, '&' between pairs
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
props: Dictionary of AU definitional parameters
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
Canonical encoded string (e.g., "key1~val1&key2~val2")
|
|
200
|
+
|
|
201
|
+
Example:
|
|
202
|
+
>>> props = {"year": "2023", "base_url": "http://example.com/"}
|
|
203
|
+
>>> AuidGenerator.props_to_canonical_encoded_string(props)
|
|
204
|
+
'base_url~http%3A%2F%2Fexample.com%2F&year~2023'
|
|
205
|
+
"""
|
|
206
|
+
if not props:
|
|
207
|
+
return ""
|
|
208
|
+
|
|
209
|
+
# Sort keys for canonical ordering (case-sensitive, like Java TreeSet)
|
|
210
|
+
sorted_keys = sorted(props.keys())
|
|
211
|
+
|
|
212
|
+
parts = []
|
|
213
|
+
for key in sorted_keys:
|
|
214
|
+
val = props[key]
|
|
215
|
+
if val is None:
|
|
216
|
+
val = ""
|
|
217
|
+
encoded_key = AuidGenerator.encode_component(str(key))
|
|
218
|
+
encoded_val = AuidGenerator.encode_component(str(val))
|
|
219
|
+
parts.append(f"{encoded_key}~{encoded_val}")
|
|
220
|
+
|
|
221
|
+
return "&".join(parts)
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def canonical_encoded_string_to_props(encoded: str) -> Dict[str, str]:
|
|
225
|
+
"""
|
|
226
|
+
Decode a canonical encoded string back to properties dictionary.
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
encoded: Canonical encoded string (e.g., "key1~val1&key2~val2")
|
|
230
|
+
|
|
231
|
+
Returns:
|
|
232
|
+
Dictionary of decoded parameters
|
|
233
|
+
|
|
234
|
+
Example:
|
|
235
|
+
>>> encoded = 'base_url~http%3A%2F%2Fexample.com%2F&year~2023'
|
|
236
|
+
>>> AuidGenerator.canonical_encoded_string_to_props(encoded)
|
|
237
|
+
{'base_url': 'http://example.com/', 'year': '2023'}
|
|
238
|
+
"""
|
|
239
|
+
if not encoded:
|
|
240
|
+
return {}
|
|
241
|
+
|
|
242
|
+
props = {}
|
|
243
|
+
pairs = encoded.split("&")
|
|
244
|
+
|
|
245
|
+
for pair in pairs:
|
|
246
|
+
if "~" not in pair:
|
|
247
|
+
raise ValueError("Missing tilde in key-value pair")
|
|
248
|
+
key_encoded, val_encoded = pair.split("~", 1)
|
|
249
|
+
if "~" in val_encoded:
|
|
250
|
+
raise ValueError("Additional tilde in key-value pair")
|
|
251
|
+
key = AuidGenerator.decode_component(key_encoded)
|
|
252
|
+
val = AuidGenerator.decode_component(val_encoded)
|
|
253
|
+
props[key] = val
|
|
254
|
+
|
|
255
|
+
return props
|
|
256
|
+
|
|
257
|
+
@staticmethod
|
|
258
|
+
def generate_auid(plugin_id: str, au_def_props: Dict[str, str]) -> str:
|
|
259
|
+
"""
|
|
260
|
+
Generate an AUID from plugin ID and definitional properties.
|
|
261
|
+
|
|
262
|
+
Port of PluginManager.generateAuId() from lockss-core.
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
plugin_id: Plugin class name (e.g., "org.lockss.plugin.simulated.SimulatedPlugin")
|
|
266
|
+
au_def_props: Dictionary of AU definitional parameters
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
AUID string (e.g., "org|lockss|plugin|simulated|SimulatedPlugin&base_url~...")
|
|
270
|
+
|
|
271
|
+
Raises:
|
|
272
|
+
ValueError: If plugin_id is empty
|
|
273
|
+
|
|
274
|
+
Example:
|
|
275
|
+
>>> plugin_id = "org.lockss.plugin.simulated.SimulatedPlugin"
|
|
276
|
+
>>> params = {"base_url": "http://example.com/", "year": "2023"}
|
|
277
|
+
>>> AuidGenerator.generate_auid(plugin_id, params)
|
|
278
|
+
'org|lockss|plugin|simulated|SimulatedPlugin&base_url~http%3A%2F%2Fexample.com%2F&year~2023'
|
|
279
|
+
"""
|
|
280
|
+
if not plugin_id:
|
|
281
|
+
raise ValueError("plugin_id cannot be empty")
|
|
282
|
+
|
|
283
|
+
plugin_key = AuidGenerator.plugin_key_from_id(plugin_id)
|
|
284
|
+
au_key = AuidGenerator.props_to_canonical_encoded_string(au_def_props)
|
|
285
|
+
return f"{plugin_key}&{au_key}"
|
|
286
|
+
|
|
287
|
+
@staticmethod
|
|
288
|
+
def plugin_key_from_auid(auid: str) -> str:
|
|
289
|
+
"""
|
|
290
|
+
Extract plugin key from AUID.
|
|
291
|
+
|
|
292
|
+
Port of PluginManager.pluginKeyFromAuId() from lockss-core.
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
auid: AUID string
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
Plugin key portion
|
|
299
|
+
|
|
300
|
+
Raises:
|
|
301
|
+
InvalidAuidError: If AUID format is invalid
|
|
302
|
+
|
|
303
|
+
Example:
|
|
304
|
+
>>> auid = "org|lockss|plugin|TestPlugin&base_url~http%3A%2F%2Fexample.com%2F"
|
|
305
|
+
>>> AuidGenerator.plugin_key_from_auid(auid)
|
|
306
|
+
'org|lockss|plugin|TestPlugin'
|
|
307
|
+
"""
|
|
308
|
+
if not auid:
|
|
309
|
+
raise InvalidAuidError("AUID cannot be empty")
|
|
310
|
+
|
|
311
|
+
idx = auid.find("&")
|
|
312
|
+
if idx < 0:
|
|
313
|
+
raise InvalidAuidError(f"AUID missing '&' separator: {auid}")
|
|
314
|
+
|
|
315
|
+
return auid[:idx]
|
|
316
|
+
|
|
317
|
+
@staticmethod
|
|
318
|
+
def au_key_from_auid(auid: str) -> str:
|
|
319
|
+
"""
|
|
320
|
+
Extract AU key from AUID.
|
|
321
|
+
|
|
322
|
+
Port of PluginManager.auKeyFromAuId() from lockss-core.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
auid: AUID string
|
|
326
|
+
|
|
327
|
+
Returns:
|
|
328
|
+
AU key portion (may be empty string)
|
|
329
|
+
|
|
330
|
+
Raises:
|
|
331
|
+
InvalidAuidError: If AUID format is invalid
|
|
332
|
+
|
|
333
|
+
Example:
|
|
334
|
+
>>> auid = "org|lockss|plugin|TestPlugin&base_url~http%3A%2F%2Fexample.com%2F"
|
|
335
|
+
>>> AuidGenerator.au_key_from_auid(auid)
|
|
336
|
+
'base_url~http%3A%2F%2Fexample.com%2F'
|
|
337
|
+
"""
|
|
338
|
+
if not auid:
|
|
339
|
+
raise InvalidAuidError("AUID cannot be empty")
|
|
340
|
+
|
|
341
|
+
idx = auid.find("&")
|
|
342
|
+
if idx < 0:
|
|
343
|
+
raise InvalidAuidError(f"AUID missing '&' separator: {auid}")
|
|
344
|
+
|
|
345
|
+
return auid[idx + 1:]
|
|
346
|
+
|
|
347
|
+
@staticmethod
|
|
348
|
+
def plugin_id_from_auid(auid: str) -> str:
|
|
349
|
+
"""
|
|
350
|
+
Extract plugin ID from AUID.
|
|
351
|
+
|
|
352
|
+
Port of PluginManager.pluginIdFromAuId() from lockss-core.
|
|
353
|
+
|
|
354
|
+
Args:
|
|
355
|
+
auid: AUID string
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
Plugin ID (with dots restored)
|
|
359
|
+
|
|
360
|
+
Raises:
|
|
361
|
+
InvalidAuidError: If AUID format is invalid
|
|
362
|
+
|
|
363
|
+
Example:
|
|
364
|
+
>>> auid = "org|lockss|plugin|TestPlugin&base_url~http%3A%2F%2Fexample.com%2F"
|
|
365
|
+
>>> AuidGenerator.plugin_id_from_auid(auid)
|
|
366
|
+
'org.lockss.plugin.TestPlugin'
|
|
367
|
+
"""
|
|
368
|
+
plugin_key = AuidGenerator.plugin_key_from_auid(auid)
|
|
369
|
+
return AuidGenerator.plugin_id_from_key(plugin_key)
|
|
370
|
+
|
|
371
|
+
@staticmethod
|
|
372
|
+
def decode_auid(auid: str) -> Dict[str, str]:
|
|
373
|
+
"""
|
|
374
|
+
Decode an AUID into its definitional parameters.
|
|
375
|
+
|
|
376
|
+
This is a convenience method that extracts the AU key and decodes it.
|
|
377
|
+
|
|
378
|
+
Args:
|
|
379
|
+
auid: AUID string
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
Dictionary of decoded AU parameters
|
|
383
|
+
|
|
384
|
+
Raises:
|
|
385
|
+
InvalidAuidError: If AUID format is invalid
|
|
386
|
+
|
|
387
|
+
Example:
|
|
388
|
+
>>> auid = "org|lockss|plugin|TestPlugin&base_url~http%3A%2F%2Fexample.com%2F&year~2023"
|
|
389
|
+
>>> AuidGenerator.decode_auid(auid)
|
|
390
|
+
{'base_url': 'http://example.com/', 'year': '2023'}
|
|
391
|
+
"""
|
|
392
|
+
au_key = AuidGenerator.au_key_from_auid(auid)
|
|
393
|
+
return AuidGenerator.canonical_encoded_string_to_props(au_key)
|
|
394
|
+
|
|
395
|
+
@staticmethod
|
|
396
|
+
def validate_auid(auid: str) -> bool:
|
|
397
|
+
"""
|
|
398
|
+
Check if an AUID string is valid.
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
auid: AUID string to validate
|
|
402
|
+
|
|
403
|
+
Returns:
|
|
404
|
+
True if valid, False otherwise
|
|
405
|
+
|
|
406
|
+
Example:
|
|
407
|
+
>>> AuidGenerator.validate_auid("org|lockss|plugin|TestPlugin&base_url~http%3A%2F%2Fexample.com%2F")
|
|
408
|
+
True
|
|
409
|
+
>>> AuidGenerator.validate_auid("invalid-auid")
|
|
410
|
+
False
|
|
411
|
+
"""
|
|
412
|
+
try:
|
|
413
|
+
AuidGenerator.plugin_key_from_auid(auid)
|
|
414
|
+
AuidGenerator.au_key_from_auid(auid)
|
|
415
|
+
return True
|
|
416
|
+
except (InvalidAuidError, ValueError):
|
|
417
|
+
return False
|
lockss/pybasic/cliutil.py
CHANGED
|
@@ -34,55 +34,47 @@ Command line utilities.
|
|
|
34
34
|
|
|
35
35
|
from collections.abc import Callable
|
|
36
36
|
import sys
|
|
37
|
-
from typing import Any,
|
|
38
|
-
import warnings
|
|
37
|
+
from typing import Any, Dict, Generic, Optional, TypeVar
|
|
39
38
|
|
|
40
|
-
from pydantic.v1 import BaseModel
|
|
41
|
-
from pydantic.v1.fields import FieldInfo
|
|
39
|
+
from pydantic.v1 import BaseModel
|
|
42
40
|
from pydantic_argparse import ArgumentParser
|
|
43
41
|
from pydantic_argparse.argparse.actions import SubParsersAction
|
|
44
42
|
from rich_argparse import RichHelpFormatter
|
|
45
43
|
|
|
46
|
-
if TYPE_CHECKING:
|
|
47
|
-
from _typeshed import SupportsWrite as SupportsWriteStr
|
|
48
|
-
else:
|
|
49
|
-
SupportsWriteStr = Any
|
|
50
44
|
|
|
45
|
+
class ActionCommand(Callable, BaseModel):
|
|
46
|
+
"""
|
|
47
|
+
Base class for a pydantic-argparse style command.
|
|
48
|
+
"""
|
|
49
|
+
pass
|
|
51
50
|
|
|
52
|
-
class StringCommand(BaseModel):
|
|
53
|
-
|
|
54
|
-
def display(self, file: SupportsWriteStr=sys.stdout) -> None:
|
|
55
|
-
print(getattr(self, '_display_string'), file=file)
|
|
56
|
-
|
|
57
|
-
@staticmethod
|
|
58
|
-
def make(model_name: str, option_name: str, description: str, display_string: str):
|
|
59
|
-
with warnings.catch_warnings():
|
|
60
|
-
warnings.simplefilter("ignore") # Pydantic v1 demands that PrivateAttr begins with a hyphen but raises a warning that such names are for private attributes
|
|
61
|
-
return create_model(model_name,
|
|
62
|
-
__base__=StringCommand,
|
|
63
|
-
_display_string=PrivateAttr(display_string),
|
|
64
|
-
**{option_name: (Optional[bool], FieldInfo(False, description=description))})
|
|
65
51
|
|
|
52
|
+
class StringCommand(ActionCommand):
|
|
53
|
+
"""
|
|
54
|
+
A pydantic-argparse style command that prints a string.
|
|
66
55
|
|
|
67
|
-
|
|
56
|
+
Example of use:
|
|
68
57
|
|
|
69
|
-
|
|
70
|
-
def make(display_string: str):
|
|
71
|
-
return StringCommand.make('CopyrightCommand', 'copyright', 'print the copyright and exit', display_string)
|
|
58
|
+
.. code-block:: python
|
|
72
59
|
|
|
60
|
+
class MyCliModel(BaseModel):
|
|
61
|
+
copyright: Optional[StringCommand.type(my_copyright_string)] = Field(description=COPYRIGHT_DESCRIPTION)
|
|
73
62
|
|
|
74
|
-
|
|
63
|
+
See also the convenience constants ``COPYRIGHT_DESCRIPTION``,
|
|
64
|
+
``LICENSE_DESCRIPTION``, and ``VERSION_DESCRIPTION``.
|
|
65
|
+
"""
|
|
75
66
|
|
|
76
67
|
@staticmethod
|
|
77
|
-
def
|
|
78
|
-
|
|
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
|
|
79
73
|
|
|
80
74
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def make(display_string: str):
|
|
85
|
-
return StringCommand.make('VersionCommand', 'version', 'print the version number and exit', display_string)
|
|
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'
|
|
86
78
|
|
|
87
79
|
|
|
88
80
|
BaseModelT = TypeVar('BaseModelT', bound=BaseModel)
|
|
@@ -187,7 +179,7 @@ class BaseCli(Generic[BaseModelT]):
|
|
|
187
179
|
})
|
|
188
180
|
|
|
189
181
|
|
|
190
|
-
def at_most_one_from_enum(model_cls
|
|
182
|
+
def at_most_one_from_enum(model_cls, values: Dict[str, Any], enum_cls) -> Dict[str, Any]:
|
|
191
183
|
"""
|
|
192
184
|
Among the fields of a Pydantic-Argparse model whose ``Field`` definition is
|
|
193
185
|
tagged with the ``enum`` keyword set to the given ``Enum`` type, ensures
|
|
@@ -203,7 +195,7 @@ def at_most_one_from_enum(model_cls: type[BaseModel], values: Dict[str, Any], en
|
|
|
203
195
|
enum_names = [field_name for field_name, model_field in model_cls.__fields__.items() if model_field.field_info.extra.get('enum') == enum_cls]
|
|
204
196
|
ret = [field_name for field_name in enum_names if values.get(field_name)]
|
|
205
197
|
if (length := len(ret)) > 1:
|
|
206
|
-
raise ValueError(f'at most one of {
|
|
198
|
+
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])})')
|
|
207
199
|
return values
|
|
208
200
|
|
|
209
201
|
|
|
@@ -227,21 +219,21 @@ def get_from_enum(model_inst, enum_cls, default=None):
|
|
|
227
219
|
return default
|
|
228
220
|
|
|
229
221
|
|
|
230
|
-
def at_most_one(
|
|
222
|
+
def at_most_one(values: Dict[str, Any], *names: str):
|
|
231
223
|
if (length := _matchy_length(values, *names)) > 1:
|
|
232
|
-
raise ValueError(f'at most one of {
|
|
224
|
+
raise ValueError(f'at most one of {", ".join([option_name(name) for name in names])} is allowed, got {length}')
|
|
233
225
|
return values
|
|
234
226
|
|
|
235
227
|
|
|
236
|
-
def exactly_one(
|
|
228
|
+
def exactly_one(values: Dict[str, Any], *names: str):
|
|
237
229
|
if (length := _matchy_length(values, *names)) != 1:
|
|
238
|
-
raise ValueError(f'exactly one of {
|
|
230
|
+
raise ValueError(f'exactly one of {", ".join([option_name(name) for name in names])} is required, got {length}')
|
|
239
231
|
return values
|
|
240
232
|
|
|
241
233
|
|
|
242
|
-
def one_or_more(
|
|
234
|
+
def one_or_more(values: Dict[str, Any], *names: str):
|
|
243
235
|
if _matchy_length(values, *names) == 0:
|
|
244
|
-
raise ValueError(f'one or more of {
|
|
236
|
+
raise ValueError(f'one or more of {", ".join([option_name(name) for name in names])} is required')
|
|
245
237
|
return values
|
|
246
238
|
|
|
247
239
|
|
|
@@ -250,7 +242,7 @@ def option_name(model_cls: type[BaseModel], name: str) -> str:
|
|
|
250
242
|
raise RuntimeError(f'invalid name: {name}')
|
|
251
243
|
if alias := info.alias:
|
|
252
244
|
name = alias
|
|
253
|
-
return f'{(
|
|
245
|
+
return f'{("-" if len(name) == 1 else "--")}{name.replace("_", "-")}'
|
|
254
246
|
|
|
255
247
|
|
|
256
248
|
def _matchy_length(values: Dict[str, Any], *names: str) -> int:
|
lockss/pybasic/outpututil.py
CHANGED
|
@@ -46,7 +46,7 @@ DEFAULT_OUTPUT_FORMAT = 'simple' # from tabulate
|
|
|
46
46
|
|
|
47
47
|
|
|
48
48
|
class OutputFormatOptions(BaseModel):
|
|
49
|
-
output_format: Optional[str] = Field(DEFAULT_OUTPUT_FORMAT, description=f'[output] set the output format; choices: {
|
|
49
|
+
output_format: Optional[str] = Field(DEFAULT_OUTPUT_FORMAT, description=f'[output] set the output format; choices: {", ".join(OutputFormat.__members__.keys())}')
|
|
50
50
|
|
|
51
51
|
@validator('output_format')
|
|
52
52
|
def _validate_output_format(cls, val: str):
|
|
@@ -54,4 +54,4 @@ class OutputFormatOptions(BaseModel):
|
|
|
54
54
|
_ = OutputFormat[val]
|
|
55
55
|
return val
|
|
56
56
|
except KeyError:
|
|
57
|
-
raise ValueError(f'must be one of {
|
|
57
|
+
raise ValueError(f'must be one of {", ".join(OutputFormat.__members__.keys())}; got {val}')
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: lockss-pybasic
|
|
3
|
-
Version: 0.2.0.
|
|
3
|
+
Version: 0.2.0.dev7
|
|
4
4
|
Summary: Basic Python utilities
|
|
5
5
|
License: BSD-3-Clause
|
|
6
|
+
License-File: LICENSE
|
|
6
7
|
Author: Thib Guicherd-Callin
|
|
7
8
|
Author-email: thib@cs.stanford.edu
|
|
8
9
|
Maintainer: Thib Guicherd-Callin
|
|
@@ -26,8 +27,8 @@ Description-Content-Type: text/x-rst
|
|
|
26
27
|
lockss-pybasic
|
|
27
28
|
==============
|
|
28
29
|
|
|
29
|
-
.. |RELEASE| replace:: 0.1.
|
|
30
|
-
.. |RELEASE_DATE| replace:: 2025-
|
|
30
|
+
.. |RELEASE| replace:: 0.1.1
|
|
31
|
+
.. |RELEASE_DATE| replace:: 2025-10-02
|
|
31
32
|
|
|
32
33
|
**Latest release:** |RELEASE| (|RELEASE_DATE|)
|
|
33
34
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
lockss/pybasic/__init__.py,sha256=zBCFbOy0mzMxX4ofmKT5pq7i2s5bTNX5ECUCi02W2M4,1678
|
|
2
|
+
lockss/pybasic/auidutil.py,sha256=o5IsRLEYROXRVS6oTO1VFtdzw7SImYSR5VcqAMHY4To,13921
|
|
3
|
+
lockss/pybasic/cliutil.py,sha256=BFOijSrTByMHno3bbDmtICLQfREJpD7lVGUAuzvrHBY,10697
|
|
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.dev7.dist-info/METADATA,sha256=ReyRdrU3vbGjOcdjkz4r2nqNCHXHWLK0tsN7g_2b2_s,4269
|
|
8
|
+
lockss_pybasic-0.2.0.dev7.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
|
|
9
|
+
lockss_pybasic-0.2.0.dev7.dist-info/licenses/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
|
|
10
|
+
lockss_pybasic-0.2.0.dev7.dist-info/RECORD,,
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
lockss/pybasic/__init__.py,sha256=-Q8lj5dmHarJid06shaGAk79FNGd3QUDDyFCPMVOeAY,1678
|
|
2
|
-
lockss/pybasic/cliutil.py,sha256=PaMrDg2eGMx_h1JEybvgLlXnvxV09CYlEFBIHS1urgA,11475
|
|
3
|
-
lockss/pybasic/errorutil.py,sha256=XI84PScZ851_-gfoazivJ8ceieMYWaxQr7qih5ltga0,1951
|
|
4
|
-
lockss/pybasic/fileutil.py,sha256=BpdoPWL70xYTuhyQRBEurScRVnPQg0mX-XW8yyKPGjw,2958
|
|
5
|
-
lockss/pybasic/outpututil.py,sha256=JyXKXlkaCcCGvonUvmDGRdI6PxwN5t7DPVIk64S8-2g,2345
|
|
6
|
-
lockss_pybasic-0.2.0.dev5.dist-info/LICENSE,sha256=O9ONND4uDxY_jucI4jZDf2liAk05ScEJaYu-Al7EOdQ,1506
|
|
7
|
-
lockss_pybasic-0.2.0.dev5.dist-info/METADATA,sha256=QhQmvLDES42rAOQTuNcbd_8J7IEX8hKut4uK2L5gmrQ,4247
|
|
8
|
-
lockss_pybasic-0.2.0.dev5.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
|
|
9
|
-
lockss_pybasic-0.2.0.dev5.dist-info/RECORD,,
|
{lockss_pybasic-0.2.0.dev5.dist-info → lockss_pybasic-0.2.0.dev7.dist-info/licenses}/LICENSE
RENAMED
|
File without changes
|