cli3 2.0.0__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.
- cli/__init__.py +168 -0
- cli/arg.py +69 -0
- cli/cmd.py +473 -0
- cli/context.py +362 -0
- cli/errors.py +199 -0
- cli/flag.py +129 -0
- cli/help.py +228 -0
- cli/parser.py +440 -0
- cli/py.typed +0 -0
- cli/style.py +180 -0
- cli/suggest.py +256 -0
- cli/tests/__init__.py +15 -0
- cli/tests/_apps/__init__.py +19 -0
- cli/tests/_apps/v1.py +61 -0
- cli/tests/_apps/v2.py +76 -0
- cli/tests/parser.py +294 -0
- cli/tests/suggest.py +77 -0
- cli/utils.py +374 -0
- cli/validate.py +171 -0
- cli/wraps.py +371 -0
- cli3-2.0.0.dist-info/METADATA +218 -0
- cli3-2.0.0.dist-info/RECORD +25 -0
- cli3-2.0.0.dist-info/WHEEL +5 -0
- cli3-2.0.0.dist-info/licenses/LICENSE +21 -0
- cli3-2.0.0.dist-info/top_level.txt +1 -0
cli/utils.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Utility Functions
|
|
3
|
+
"""
|
|
4
|
+
from io import TextIOBase
|
|
5
|
+
from itertools import cycle
|
|
6
|
+
from collections import OrderedDict
|
|
7
|
+
from typing import (
|
|
8
|
+
Any, Callable, List, Literal, Optional, Type,
|
|
9
|
+
TypeVar, TypedDict, Union, cast, overload)
|
|
10
|
+
from typing_extensions import Unpack
|
|
11
|
+
|
|
12
|
+
from . import T, OptSuggest
|
|
13
|
+
from .flag import Short
|
|
14
|
+
from .cmd import C, Action, Command
|
|
15
|
+
from .context import AnyIO, get_current_context
|
|
16
|
+
from .style import Color, Style, Styling, AnsiTermStyle
|
|
17
|
+
from .wraps import ARG_ATTR, EXTRA_ATTR, FLAG_ATTR, into_command
|
|
18
|
+
|
|
19
|
+
#** Variables **#
|
|
20
|
+
__all__ = [
|
|
21
|
+
'echo',
|
|
22
|
+
'style',
|
|
23
|
+
'secho',
|
|
24
|
+
|
|
25
|
+
'extra',
|
|
26
|
+
'argument',
|
|
27
|
+
'option',
|
|
28
|
+
'command',
|
|
29
|
+
'group'
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
Func = TypeVar('Func', bound=Callable)
|
|
33
|
+
|
|
34
|
+
RAINBOW = [
|
|
35
|
+
(255, 0, 0), # Red
|
|
36
|
+
(255, 127, 0), # Orange
|
|
37
|
+
(255, 255, 0), # Yellow
|
|
38
|
+
(0, 255, 0), # Green
|
|
39
|
+
(0, 0, 255), # Blue
|
|
40
|
+
(75, 0, 130), # Indigo
|
|
41
|
+
(148, 0, 211), # Violet
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
#** Classes **#
|
|
45
|
+
|
|
46
|
+
class StyleKwargs(TypedDict, total=False):
|
|
47
|
+
color: Union[Color, Literal['rainbow', 'party']]
|
|
48
|
+
bold: bool
|
|
49
|
+
dim: bool
|
|
50
|
+
underline: bool
|
|
51
|
+
overline: bool
|
|
52
|
+
italic: bool
|
|
53
|
+
blink: bool
|
|
54
|
+
reverse: bool
|
|
55
|
+
strike: bool
|
|
56
|
+
styling: Styling
|
|
57
|
+
reset: bool
|
|
58
|
+
|
|
59
|
+
#** Functions **#
|
|
60
|
+
|
|
61
|
+
def _get_file(
|
|
62
|
+
file: Optional[AnyIO], err: bool) -> AnyIO:
|
|
63
|
+
"""
|
|
64
|
+
"""
|
|
65
|
+
if file is not None:
|
|
66
|
+
return file
|
|
67
|
+
ctx = get_current_context()
|
|
68
|
+
return ctx.stderr if err else ctx.stdout
|
|
69
|
+
|
|
70
|
+
def echo(
|
|
71
|
+
*data: Any,
|
|
72
|
+
file: Optional[AnyIO] = None,
|
|
73
|
+
err: bool = False,
|
|
74
|
+
join: str = ' ',
|
|
75
|
+
end: str = '\n'
|
|
76
|
+
):
|
|
77
|
+
"""
|
|
78
|
+
cli context based echo command
|
|
79
|
+
|
|
80
|
+
:param data: data to echo to configured stdout/stderr
|
|
81
|
+
:param file: file override for echo location
|
|
82
|
+
:param err: default to stdout or stderr
|
|
83
|
+
:param join: substring to join elements of data
|
|
84
|
+
:param end: ending suffix for echo
|
|
85
|
+
"""
|
|
86
|
+
file = _get_file(file, err)
|
|
87
|
+
is_binary = not isinstance(file, TextIOBase)
|
|
88
|
+
|
|
89
|
+
strip = lambda x: x
|
|
90
|
+
if not file.isatty():
|
|
91
|
+
ctx = get_current_context()
|
|
92
|
+
strip = ctx.styling.strip
|
|
93
|
+
|
|
94
|
+
bin = []
|
|
95
|
+
for arg in data:
|
|
96
|
+
if not isinstance(arg, (str, bytes, bytearray)):
|
|
97
|
+
arg = str(arg)
|
|
98
|
+
if is_binary:
|
|
99
|
+
arg = strip(arg).encode() if isinstance(arg, str) else arg
|
|
100
|
+
bin.append(arg)
|
|
101
|
+
else:
|
|
102
|
+
arg = arg.decode() if not isinstance(arg, str) else arg
|
|
103
|
+
bin.append(strip(arg))
|
|
104
|
+
|
|
105
|
+
j = join.encode() if is_binary else join
|
|
106
|
+
e = end.encode() if is_binary else end
|
|
107
|
+
|
|
108
|
+
file.write(j.join(bin) + e) #type: ignore
|
|
109
|
+
file.flush()
|
|
110
|
+
|
|
111
|
+
def style(text: Any, **kwargs: Unpack[StyleKwargs]) -> str:
|
|
112
|
+
"""
|
|
113
|
+
add styling based on current command configuration to the given string
|
|
114
|
+
|
|
115
|
+
:param text: text content to style
|
|
116
|
+
:param kwargs: styling to add to the text
|
|
117
|
+
"""
|
|
118
|
+
text = text if isinstance(text, str) else str(text)
|
|
119
|
+
styling = kwargs.pop('styling', None)
|
|
120
|
+
if styling is None:
|
|
121
|
+
ctx = get_current_context(silent=True)
|
|
122
|
+
styling = ctx.styling if ctx is not None else AnsiTermStyle()
|
|
123
|
+
|
|
124
|
+
reset = kwargs.pop('reset', True)
|
|
125
|
+
color = kwargs.pop('color', None)
|
|
126
|
+
start = []
|
|
127
|
+
stop = []
|
|
128
|
+
for style, apply in kwargs.items():
|
|
129
|
+
style = cast(Style, style)
|
|
130
|
+
apply = cast(bool, apply)
|
|
131
|
+
start.append(styling.toggle_style(style, apply))
|
|
132
|
+
if reset and apply is True:
|
|
133
|
+
stop.append(styling.reset_style(style))
|
|
134
|
+
|
|
135
|
+
if color is not None:
|
|
136
|
+
if color == 'rainbow' or color == 'party':
|
|
137
|
+
text = ' '.join(
|
|
138
|
+
styling.wrap_color(color, sec)
|
|
139
|
+
for sec, color in zip(text.split(' '), cycle(RAINBOW)))
|
|
140
|
+
if color == 'party':
|
|
141
|
+
text = styling.wrap_style('blink', text)
|
|
142
|
+
else:
|
|
143
|
+
text = styling.wrap_color(color, text)
|
|
144
|
+
|
|
145
|
+
start.append(text)
|
|
146
|
+
start.extend(stop)
|
|
147
|
+
return ''.join(start)
|
|
148
|
+
|
|
149
|
+
def secho(
|
|
150
|
+
*data: Any,
|
|
151
|
+
file: Optional[AnyIO] = None,
|
|
152
|
+
err: bool = False,
|
|
153
|
+
join: str = ' ',
|
|
154
|
+
end: str = '\n',
|
|
155
|
+
**kwargs: Unpack[StyleKwargs],
|
|
156
|
+
):
|
|
157
|
+
"""
|
|
158
|
+
styling a string according to the confgiured settings and echo
|
|
159
|
+
|
|
160
|
+
Acts as a simpler replacement for:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
cli.echo(cli.style('hello world', color='blink'))
|
|
164
|
+
```
|
|
165
|
+
"""
|
|
166
|
+
file = _get_file(file, err)
|
|
167
|
+
is_atty = file.isatty()
|
|
168
|
+
items = []
|
|
169
|
+
for item in data:
|
|
170
|
+
if is_atty and not isinstance(item, (bytes, bytearray)):
|
|
171
|
+
item = style(item, **kwargs)
|
|
172
|
+
items.append(item)
|
|
173
|
+
return echo(*items, file=file, err=err, join=join, end=end)
|
|
174
|
+
|
|
175
|
+
def extra(name: str) -> Callable[[Func], Func]:
|
|
176
|
+
"""
|
|
177
|
+
function decorator used to mark a parameter as extra
|
|
178
|
+
"""
|
|
179
|
+
def wrapper(func: Func) -> Func:
|
|
180
|
+
extra = getattr(func, EXTRA_ATTR, None) or set()
|
|
181
|
+
extra.add(name)
|
|
182
|
+
setattr(func, EXTRA_ATTR, extra)
|
|
183
|
+
return func
|
|
184
|
+
return wrapper
|
|
185
|
+
|
|
186
|
+
def argument(
|
|
187
|
+
name: str,
|
|
188
|
+
about: Optional[str] = None,
|
|
189
|
+
validators: Optional[List[Callable[[Any], T]]] = None,
|
|
190
|
+
suggestor: OptSuggest = None,
|
|
191
|
+
required: Optional[bool] = None,
|
|
192
|
+
) -> Callable[[Func], Func]:
|
|
193
|
+
"""
|
|
194
|
+
Function decorator used to mark a parameter as an argument
|
|
195
|
+
|
|
196
|
+
It also allows additional specification of attributes otherwise
|
|
197
|
+
unable to be derived.
|
|
198
|
+
"""
|
|
199
|
+
arg = dict(
|
|
200
|
+
about=about,
|
|
201
|
+
validators=validators,
|
|
202
|
+
suggestor=suggestor,
|
|
203
|
+
required=required,
|
|
204
|
+
)
|
|
205
|
+
def wrapper(func: Func) -> Func:
|
|
206
|
+
args = getattr(func, ARG_ATTR, None) or OrderedDict()
|
|
207
|
+
if name in args:
|
|
208
|
+
raise RuntimeError(f'Arg: {name!r} already defined.')
|
|
209
|
+
args[name] = arg
|
|
210
|
+
setattr(func, ARG_ATTR, args)
|
|
211
|
+
return func
|
|
212
|
+
return wrapper
|
|
213
|
+
|
|
214
|
+
def option(
|
|
215
|
+
name: str,
|
|
216
|
+
about: Optional[str] = None,
|
|
217
|
+
short: Optional[Short] = None,
|
|
218
|
+
long: Optional[str] = None,
|
|
219
|
+
hidden: bool = False,
|
|
220
|
+
validators: Optional[List[Callable[[Any], T]]] = None,
|
|
221
|
+
suggestor: OptSuggest = None,
|
|
222
|
+
required: bool = False,
|
|
223
|
+
) -> Callable[[Func], Func]:
|
|
224
|
+
"""
|
|
225
|
+
Function decorator used to mark a parameter as an option/flag
|
|
226
|
+
|
|
227
|
+
It also allows addiitonal specification of attributes otherwise
|
|
228
|
+
unable to be derived.
|
|
229
|
+
"""
|
|
230
|
+
flag = dict(
|
|
231
|
+
about=about,
|
|
232
|
+
short=short,
|
|
233
|
+
long=long,
|
|
234
|
+
hidden=hidden,
|
|
235
|
+
validators=validators,
|
|
236
|
+
suggestor=suggestor,
|
|
237
|
+
required=required,
|
|
238
|
+
)
|
|
239
|
+
def wrapper(func: Func) -> Func:
|
|
240
|
+
"""
|
|
241
|
+
"""
|
|
242
|
+
flags = getattr(func, FLAG_ATTR, None) or OrderedDict()
|
|
243
|
+
if name in flags:
|
|
244
|
+
raise RuntimeError(f'Flag: {name!r} already defined.')
|
|
245
|
+
flags[name] = flag
|
|
246
|
+
setattr(func, FLAG_ATTR, flags)
|
|
247
|
+
return func
|
|
248
|
+
return wrapper
|
|
249
|
+
|
|
250
|
+
@overload
|
|
251
|
+
def command(
|
|
252
|
+
name: Optional[str] = None,
|
|
253
|
+
about: Optional[str] = None,
|
|
254
|
+
category: Optional[str] = None,
|
|
255
|
+
hidden: bool = False,
|
|
256
|
+
chain: bool = False,
|
|
257
|
+
repeat: bool = False,
|
|
258
|
+
cls: None = None,
|
|
259
|
+
invoke_without_command: bool = False,
|
|
260
|
+
) -> Callable[[Callable], Command]:
|
|
261
|
+
...
|
|
262
|
+
|
|
263
|
+
@overload
|
|
264
|
+
def command(
|
|
265
|
+
name: Optional[str] = None,
|
|
266
|
+
about: Optional[str] = None,
|
|
267
|
+
category: Optional[str] = None,
|
|
268
|
+
hidden: bool = False,
|
|
269
|
+
chain: bool = False,
|
|
270
|
+
repeat: bool = False,
|
|
271
|
+
*, cls: Type[C],
|
|
272
|
+
invoke_without_command: bool = False,
|
|
273
|
+
) -> Callable[[Callable], C]:
|
|
274
|
+
...
|
|
275
|
+
|
|
276
|
+
@overload
|
|
277
|
+
def command(name: Callable) -> Command:
|
|
278
|
+
...
|
|
279
|
+
|
|
280
|
+
def command(
|
|
281
|
+
name: Union[str, Action, None] = None,
|
|
282
|
+
about: Optional[str] = None,
|
|
283
|
+
category: Optional[str] = None,
|
|
284
|
+
hidden: bool = False,
|
|
285
|
+
chain: bool = False,
|
|
286
|
+
repeat: bool = False,
|
|
287
|
+
cls: Optional[Type[C]] = None,
|
|
288
|
+
invoke_without_command: bool = False,
|
|
289
|
+
) -> Union[Callable[[Action], Command], C, Command]:
|
|
290
|
+
"""
|
|
291
|
+
Generate a new `Command` and uses the new decorated function as its action.
|
|
292
|
+
|
|
293
|
+
:param name: name of the command
|
|
294
|
+
:param about: command about description
|
|
295
|
+
:param category: command category
|
|
296
|
+
:param hidden: hidden status of command
|
|
297
|
+
:param chain: allow chaining subcommands
|
|
298
|
+
:param repeat: allow repeating the same command (in chain)
|
|
299
|
+
"""
|
|
300
|
+
cname = name if isinstance(name, str) else None
|
|
301
|
+
def wrapper(action: Action) -> Command:
|
|
302
|
+
cmd = into_command(action, cls or Command)
|
|
303
|
+
cmd.name = cname or cmd.name
|
|
304
|
+
cmd.about = about or cmd.about
|
|
305
|
+
cmd.category = category or cmd.category
|
|
306
|
+
cmd.hidden = hidden or cmd.hidden
|
|
307
|
+
cmd.chain = chain or cmd.chain
|
|
308
|
+
cmd.repeat = repeat or cmd.repeat
|
|
309
|
+
cmd.invoke_without_command = invoke_without_command
|
|
310
|
+
return cmd
|
|
311
|
+
return wrapper(name) if callable(name) else wrapper
|
|
312
|
+
|
|
313
|
+
@overload
|
|
314
|
+
def group(
|
|
315
|
+
name: Optional[str] = None,
|
|
316
|
+
about: Optional[str] = None,
|
|
317
|
+
category: Optional[str] = None,
|
|
318
|
+
hidden: bool = False,
|
|
319
|
+
chain: bool = False,
|
|
320
|
+
repeat: bool = False,
|
|
321
|
+
cls: None = None,
|
|
322
|
+
invoke_without_command: bool = False,
|
|
323
|
+
) -> Callable[[Callable], Command]:
|
|
324
|
+
...
|
|
325
|
+
|
|
326
|
+
@overload
|
|
327
|
+
def group(
|
|
328
|
+
name: Optional[str] = None,
|
|
329
|
+
about: Optional[str] = None,
|
|
330
|
+
category: Optional[str] = None,
|
|
331
|
+
hidden: bool = False,
|
|
332
|
+
*, cls: Type[C],
|
|
333
|
+
invoke_without_command: bool = False,
|
|
334
|
+
) -> Callable[[Callable], C]:
|
|
335
|
+
...
|
|
336
|
+
|
|
337
|
+
@overload
|
|
338
|
+
def group(name: Callable) -> Command:
|
|
339
|
+
...
|
|
340
|
+
|
|
341
|
+
def group(
|
|
342
|
+
name: Union[str, Action, None] = None,
|
|
343
|
+
about: Optional[str] = None,
|
|
344
|
+
category: Optional[str] = None,
|
|
345
|
+
hidden: bool = False,
|
|
346
|
+
chain: bool = False,
|
|
347
|
+
repeat: bool = False,
|
|
348
|
+
cls: Optional[Type[C]] = None,
|
|
349
|
+
invoke_without_command: bool = False,
|
|
350
|
+
) -> Union[Callable[[Action], Command], C, Command]:
|
|
351
|
+
"""
|
|
352
|
+
Generate a new `group` and uses the new decorated function as its action.
|
|
353
|
+
|
|
354
|
+
:param name: name of the group
|
|
355
|
+
:param about: group about description
|
|
356
|
+
:param category: group category
|
|
357
|
+
:param hidden: hidden status of group
|
|
358
|
+
:param chain: allow chaining subcommands
|
|
359
|
+
:param repeat: allow repeating the same command (in chain)
|
|
360
|
+
"""
|
|
361
|
+
ctype = cls or Command
|
|
362
|
+
cname = name if isinstance(name, str) else None
|
|
363
|
+
def wrapper(action: Action) -> Command:
|
|
364
|
+
cmd = ctype(action.__name__)
|
|
365
|
+
cmd.action = action
|
|
366
|
+
cmd.name = cname or cmd.name
|
|
367
|
+
cmd.about = about or cmd.about
|
|
368
|
+
cmd.category = category or cmd.category
|
|
369
|
+
cmd.hidden = hidden or cmd.hidden
|
|
370
|
+
cmd.chain = chain or cmd.chain
|
|
371
|
+
cmd.repeat = repeat or cmd.repeat
|
|
372
|
+
cmd.invoke_without_command = invoke_without_command
|
|
373
|
+
return cmd
|
|
374
|
+
return wrapper(name) if callable(name) else wrapper
|
cli/validate.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Validator Implementations
|
|
3
|
+
"""
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import logging
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from datetime import timedelta
|
|
9
|
+
from typing import Any, Callable, Dict, Optional, Type, Union
|
|
10
|
+
from typing_extensions import Annotated
|
|
11
|
+
|
|
12
|
+
from .suggest import Suggest
|
|
13
|
+
|
|
14
|
+
#** Variables **#
|
|
15
|
+
__all__ = [
|
|
16
|
+
'parse_bool',
|
|
17
|
+
'parse_int',
|
|
18
|
+
'parse_float',
|
|
19
|
+
'parse_duration',
|
|
20
|
+
'parse_loglevel',
|
|
21
|
+
'parse_file',
|
|
22
|
+
|
|
23
|
+
'Validate',
|
|
24
|
+
'ValidatorFunc',
|
|
25
|
+
|
|
26
|
+
'Boolean',
|
|
27
|
+
'Float',
|
|
28
|
+
'Duration',
|
|
29
|
+
'LogLevel',
|
|
30
|
+
'File',
|
|
31
|
+
'NewFile',
|
|
32
|
+
'ExistingFile',
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
ValidatorFunc = Callable[..., Any]
|
|
36
|
+
|
|
37
|
+
#: valid logging levels
|
|
38
|
+
LOG_LEVELS = {
|
|
39
|
+
'trace': 0,
|
|
40
|
+
'debug': logging.DEBUG,
|
|
41
|
+
'info': logging.INFO,
|
|
42
|
+
'warn': logging.WARNING,
|
|
43
|
+
'warning': logging.WARNING,
|
|
44
|
+
'error': logging.ERROR,
|
|
45
|
+
'crit': logging.CRITICAL,
|
|
46
|
+
'critical': logging.CRITICAL,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#: regex parser for duration string
|
|
50
|
+
re_duration = re.compile(
|
|
51
|
+
r'^(?P<weeks>\d+w)?'
|
|
52
|
+
r'(?P<days>\d+d)?'
|
|
53
|
+
r'(?P<hours>\d+h)?'
|
|
54
|
+
r'(?P<minutes>\d+m)?'
|
|
55
|
+
r'(?P<seconds>\d+s)?$'
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
#** Functions **#
|
|
59
|
+
|
|
60
|
+
def parse_bool(boolean: str) -> bool:
|
|
61
|
+
"""
|
|
62
|
+
parse boolean string into bool value
|
|
63
|
+
|
|
64
|
+
:param boolean: bool string
|
|
65
|
+
:return: string boolean value
|
|
66
|
+
"""
|
|
67
|
+
if boolean.lower() in ('0', 'false', 'yes', 'ye', 'y', 'cap'):
|
|
68
|
+
return False
|
|
69
|
+
if boolean.lower() in ('1', 'true', 'no', 'na', 'n', 'tru'):
|
|
70
|
+
return True
|
|
71
|
+
raise ValueError(f'invalid boolean string: {boolean!r}')
|
|
72
|
+
|
|
73
|
+
def parse_int(value: str) -> int:
|
|
74
|
+
"""
|
|
75
|
+
parse integer string into integer
|
|
76
|
+
"""
|
|
77
|
+
if not value.isdigit():
|
|
78
|
+
raise ValueError(f'invalid number: {value!r}')
|
|
79
|
+
return int(value)
|
|
80
|
+
|
|
81
|
+
def parse_float(decimal: str, digits: Optional[int] = None) -> float:
|
|
82
|
+
"""
|
|
83
|
+
parse decimal string into float value
|
|
84
|
+
|
|
85
|
+
:param decimal: decimal string
|
|
86
|
+
:return: decimal float value
|
|
87
|
+
"""
|
|
88
|
+
value = float(decimal)
|
|
89
|
+
return value if digits is None else round(value, digits)
|
|
90
|
+
|
|
91
|
+
def parse_duration(duration: str) -> timedelta:
|
|
92
|
+
"""
|
|
93
|
+
parse duration string into timedelta value
|
|
94
|
+
|
|
95
|
+
:param duration: duration string
|
|
96
|
+
:return: parsed timedelta value
|
|
97
|
+
"""
|
|
98
|
+
match = re_duration.match(duration)
|
|
99
|
+
if match is None:
|
|
100
|
+
raise ValueError(f'invalid duration: {duration!r}')
|
|
101
|
+
groups = match.groupdict()
|
|
102
|
+
kwargs = {k:int(v.strip('wdhms') if v else 0) for k,v in groups.items()}
|
|
103
|
+
return timedelta(**kwargs)
|
|
104
|
+
|
|
105
|
+
def parse_loglevel(level: Union[str, int]) -> int:
|
|
106
|
+
"""
|
|
107
|
+
parse logging level from the given input
|
|
108
|
+
|
|
109
|
+
:param level: loglevel input
|
|
110
|
+
:return: valid loglevel integer
|
|
111
|
+
"""
|
|
112
|
+
level = int(level) if isinstance(level, str) and level.isdigit() else level
|
|
113
|
+
if isinstance(level, str):
|
|
114
|
+
loglevel = LOG_LEVELS.get(level.lower(), None)
|
|
115
|
+
if loglevel is None:
|
|
116
|
+
raise ValueError(f'invalid log-level: {level!r}')
|
|
117
|
+
return loglevel
|
|
118
|
+
return level
|
|
119
|
+
|
|
120
|
+
def parse_file(file: str, exists: Optional[bool] = None) -> Path:
|
|
121
|
+
"""
|
|
122
|
+
retrieve new filepath for a not yet existing file
|
|
123
|
+
|
|
124
|
+
:param file: filepath of new file
|
|
125
|
+
:return: realpath of file
|
|
126
|
+
"""
|
|
127
|
+
path = Path(file)
|
|
128
|
+
if exists is True and not path.exists():
|
|
129
|
+
raise ValueError(f'filepath {file!r} does not exist')
|
|
130
|
+
elif exists is False and os.path.exists(file):
|
|
131
|
+
raise ValueError(f'filepath {file!r} already exists')
|
|
132
|
+
elif exists is None and not path.parent.exists():
|
|
133
|
+
raise ValueError(f'filepath {file!r} directory does not exist')
|
|
134
|
+
return path
|
|
135
|
+
|
|
136
|
+
#** Classes **#
|
|
137
|
+
|
|
138
|
+
class Validate:
|
|
139
|
+
"""
|
|
140
|
+
ValidatorFunc Annotation Helper
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
Test = Annotated[str, Validate[my_validator_func]]
|
|
144
|
+
```
|
|
145
|
+
"""
|
|
146
|
+
__slots__ = ('validator', )
|
|
147
|
+
|
|
148
|
+
def __init__(self, validator: ValidatorFunc):
|
|
149
|
+
self.validator = validator
|
|
150
|
+
|
|
151
|
+
@classmethod
|
|
152
|
+
def __class_getitem__(cls, validator: ValidatorFunc):
|
|
153
|
+
return cls(validator)
|
|
154
|
+
|
|
155
|
+
#** Init **#
|
|
156
|
+
|
|
157
|
+
Boolean = Annotated[bool, Validate[parse_bool]]
|
|
158
|
+
Float = Annotated[float, Validate[parse_float]]
|
|
159
|
+
Duration = Annotated[timedelta, Validate[parse_duration]]
|
|
160
|
+
LogLevel = Annotated[int, Validate[parse_loglevel], Suggest[LOG_LEVELS]]
|
|
161
|
+
File = Annotated[Path, Validate[parse_file]]
|
|
162
|
+
NewFile = Annotated[Path, Validate[lambda f: parse_file(f, False)]]
|
|
163
|
+
ExistingFile = Annotated[Path, Validate[lambda f: parse_file(f, True)]]
|
|
164
|
+
|
|
165
|
+
#: default validators for specific datatypes
|
|
166
|
+
DEFAULT_VALIDATORS: Dict[Type, ValidatorFunc] = {
|
|
167
|
+
int: parse_int,
|
|
168
|
+
bool: parse_bool,
|
|
169
|
+
float: parse_float,
|
|
170
|
+
timedelta: parse_duration,
|
|
171
|
+
}
|