cli3 1.0.2__tar.gz → 1.1.1__tar.gz

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.
cli3-1.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 IHaxYou
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
cli3-1.1.1/PKG-INFO ADDED
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.1
2
+ Name: cli3
3
+ Version: 1.1.1
4
+ Summary: A highly configurable, dynamic, fast, and easy solution to managing a command-line application.
5
+ Home-page: https://github.com/imgurbot12/cli
6
+ Author: Andrew Scott
7
+ Author-email: imgurbot12@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.7
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+
16
+ cli
17
+ ===
18
+
19
+ [![forthebadge](https://forthebadge.com/images/badges/you-didnt-ask-for-this.svg)](https://forthebadge.com)
20
+ [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)
21
+ [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com)
22
+
23
+ A highly configurable, dynamic, fast, and easy solution to managing
24
+ a command-line application. The goal is to make cli development as simple
25
+ and effective as possible for any configuration enabling the developer to
26
+ focus on function over form.
27
+
28
+ Supports Python >= 3.7 and can run asynchronously or synchronously.
29
+
30
+ This library took heavy initial inspiration by [urfave/cli](https://github.com/urfave/cli)
31
+ so credit to them for their work as well.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ $ pip install cli3
37
+ ```
38
+
39
+ ## Documentation
40
+
41
+ More documentation is available in [`./docs`](https://github.com/imgurbot12/cli/tree/master/docs) or the hosted
42
+ documentation site at <https://cli3.readthedocs.org>.
43
+
44
+ ## License
45
+
46
+ See [`LICENSE`](./LICENSE)
@@ -4,15 +4,16 @@ CLI exposed components for quick import/access
4
4
 
5
5
  #** Variables **#
6
6
  __all__ = [
7
- 'UsageErrorFunc',
8
- 'ExitErrorFunc',
9
- 'NotFoundFunc',
10
- 'App',
11
-
7
+ 'NO_ACTION',
8
+ 'Result',
9
+ 'SyncAction',
10
+ 'AsyncAction',
12
11
  'Action',
12
+ 'Flags',
13
+ 'FlagDict',
13
14
  'Commands',
14
- 'Command',
15
-
15
+ 'AppFunc',
16
+ 'CommandFunc',
16
17
  'CliError',
17
18
  'UsageError',
18
19
  'ExitError',
@@ -20,8 +21,28 @@ __all__ = [
20
21
  'ConfigError',
21
22
  'Args',
22
23
  'Context',
24
+ 'AbsFlag',
25
+ 'AbsCommand',
26
+ 'AbsApplication',
27
+
28
+ 'UsageErrorFunc',
29
+ 'ExitErrorFunc',
30
+ 'NotFoundFunc',
31
+ 'App',
32
+
33
+ 'ArgumentError',
34
+ 'parse_bool',
35
+ 'parse_decimal',
36
+ 'parse_duration',
37
+ 'parse_new_file',
38
+ 'parse_existing_file',
39
+ 'parse_list_function',
40
+ 'range_args',
41
+ 'exact_args',
42
+ 'no_args',
43
+
44
+ 'Command',
23
45
 
24
- 'Flags',
25
46
  'Flag',
26
47
  'BoolFlag',
27
48
  'IntFlag',
@@ -33,30 +54,31 @@ __all__ = [
33
54
  'EnumFlag',
34
55
  'FilePathFlag',
35
56
 
36
- 'run_app',
37
-
38
57
  'help_app_template',
39
58
  'help_cmd_template',
40
59
 
41
- 'range_args',
42
- 'exact_args',
43
- 'no_args',
60
+ 'validate_cmd',
61
+ 'exec_app',
62
+ 'run_app',
63
+ 'EX_USAGE',
64
+ 'EX_UNAVAILABLE',
65
+ 'EX_CONFIG',
44
66
 
45
67
  'Decimal',
46
68
  'Duration',
47
69
  'NewFile',
48
70
  'ExistingFile',
49
-
50
71
  'app',
51
72
  'action',
73
+ 'command',
52
74
  ]
53
75
 
54
76
  #** Imports **#
77
+ from .abc import *
55
78
  from .app import *
56
- from .flag import *
57
- from .context import *
79
+ from .argument import *
58
80
  from .command import *
59
- from .parser import *
81
+ from .flag import *
60
82
  from .help import *
83
+ from .parser import *
61
84
  from .wraps import *
62
- from .argument import *
cli3-1.1.1/cli/abc.py ADDED
@@ -0,0 +1,458 @@
1
+ """
2
+ Abstract/BaseClass Instances/Protocols
3
+ """
4
+ from abc import abstractmethod
5
+ from collections import UserList
6
+ from dataclasses import dataclass, field
7
+ from functools import cached_property
8
+ from typing import *
9
+ from typing_extensions import Self
10
+
11
+ #** Variables **#
12
+ __all__ = [
13
+ 'T',
14
+ 'NO_ACTION',
15
+ 'Result',
16
+ 'SyncAction',
17
+ 'AsyncAction',
18
+ 'Action',
19
+ 'OptAction',
20
+ 'Flags',
21
+ 'FlagDict',
22
+ 'Commands',
23
+ 'AppFunc',
24
+ 'CommandFunc',
25
+ 'OptCoroutine',
26
+ 'OptStrList',
27
+
28
+ 'CliError',
29
+ 'UsageError',
30
+ 'ExitError',
31
+ 'NotFoundError',
32
+ 'ConfigError',
33
+
34
+ 'Args',
35
+ 'Context',
36
+ 'AbsFlag',
37
+ 'AbsCommand',
38
+ 'AbsApplication',
39
+ ]
40
+
41
+ #: generic typevar for flag definitions
42
+ T = TypeVar('T')
43
+
44
+ #: tracker for parser to know if a command has taken no action
45
+ class NO_ACTION:
46
+ pass
47
+
48
+ #: typehint definition for action return-type
49
+ Result = Optional[Type[NO_ACTION]]
50
+
51
+ #: definition for sync action type
52
+ SyncAction = Callable[['Context'], Result]
53
+
54
+ #: definition for async action type
55
+ AsyncAction = Callable[['Context'], Coroutine[Any, Any, Result]]
56
+
57
+ #: defintion for any action called in commands
58
+ Action = Union[SyncAction, AsyncAction]
59
+
60
+ #: definition for optional action
61
+ OptAction = Optional[Action]
62
+
63
+ #: definition for list of flags
64
+ Flags = List['AbsFlag']
65
+
66
+ #: definition for flags organized into a dictionary
67
+ FlagDict = Dict[str, Any]
68
+
69
+ #: defintion for list of commands
70
+ Commands = List['AbsCommand']
71
+
72
+ #: type definition app function
73
+ AppFunc = Callable[[Callable], 'AbsApplication']
74
+
75
+ #: type definition command function
76
+ CommandFunc = Callable[[Callable], 'AbsCommand']
77
+
78
+ #: type definition for optional empty coroutine
79
+ OptCoroutine = Optional[Coroutine[None, None, None]]
80
+
81
+ #: type definition for optional list of strings
82
+ OptStrList = Optional[List[str]]
83
+
84
+ #** Functions **#
85
+
86
+ def ctx_fix_key(flags: Flags, fdict: FlagDict, key: str) -> Optional[str]:
87
+ """translate key into long flag-name if it matches any existing flags"""
88
+ if key not in fdict:
89
+ for flag in flags:
90
+ if key in flag.names:
91
+ key = flag.long
92
+ break
93
+ if key in fdict:
94
+ return key
95
+
96
+ def ctx_get(flags: Flags, fdict: FlagDict, key: str, default: Any) -> Any:
97
+ """get value in flag-dictionary with the specified key"""
98
+ realkey = ctx_fix_key(flags, fdict, key)
99
+ return default if realkey is None else fdict[realkey]
100
+
101
+ def ctx_set(flags: Flags, fdict: FlagDict, key: str, value: Any):
102
+ """set value in flag-dictionary with the specified key"""
103
+ key = ctx_fix_key(flags, fdict, key) or key
104
+ fdict[key] = value
105
+
106
+ def ctx_default(flags: Flags, fdict: FlagDict, key: str, default: Any) -> Any:
107
+ """`setdefault` implementation w/ ctx-key-translation"""
108
+ key = ctx_fix_key(flags, fdict, key) or key
109
+ fdict.setdefault(key, default)
110
+
111
+ #** Classes **#
112
+
113
+ class CliError(Exception):
114
+ """baseclass for all cli internal exceptions"""
115
+
116
+ def __init__(self, msg: str, ctx: 'Context', cmd: 'AbsCommand'):
117
+ self.message = msg
118
+ self.context = ctx
119
+ self.command = cmd
120
+
121
+ def __str__(self):
122
+ return f'cmd={self.command.name!r} error={self.message!r}'
123
+
124
+ class UsageError(CliError):
125
+ """raise error during usage issue"""
126
+
127
+ class ExitError(CliError):
128
+ """raise error when app must exit"""
129
+
130
+ def __init__(self, msg: str, code: int, ctx: 'Context', cmd: 'AbsCommand'):
131
+ self.message = msg
132
+ self.code = code
133
+ self.context = ctx
134
+ self.command = cmd
135
+
136
+ class NotFoundError(CliError):
137
+ """raise error when app gets flag it doesnt recognize"""
138
+
139
+ def __init__(self, msg: str, path: List[str], ctx: 'Context', cmd: 'AbsCommand'):
140
+ self.message = msg
141
+ self.path = path
142
+ self.context = ctx
143
+ self.command = cmd
144
+ if not path:
145
+ path.append(cmd.name)
146
+ while ctx.ctx_parent:
147
+ if ctx.command.name not in path:
148
+ path.insert(0, ctx.command.name)
149
+ ctx = ctx.ctx_parent
150
+
151
+ class ConfigError(CliError):
152
+ """raise error when app is improperly configured"""
153
+
154
+ def __init__(self, msg: str, cmd: 'AbsCommand'):
155
+ self.message = msg
156
+ self.command = cmd
157
+ self.context = None
158
+
159
+ class Args(UserList):
160
+ """extended list object intended to add ease-of-use functions for context"""
161
+
162
+ def get(self, index: int) -> Optional[str]:
163
+ """
164
+ retrieve value from arguments at given index
165
+
166
+ :param index: index of arg to collect
167
+ :return: value from index if exists
168
+ """
169
+ return self[index] if len(self) > index else None
170
+
171
+ def first(self) -> Optional[str]:
172
+ """return 1st argument in args"""
173
+ return self.get(0)
174
+
175
+ def tail(self) -> Self:
176
+ """return all arguments but first"""
177
+ return self[1:] if len(self) >= 2 else self
178
+
179
+ def present(self) -> bool:
180
+ """return true if there are any arguments"""
181
+ return len(self) != 0
182
+
183
+ def swap(self, fromidx: int, toidx: int):
184
+ """swap from and to index in list"""
185
+ if fromidx >= len(self) or toidx >= len(self):
186
+ raise ValueError("index out of range")
187
+ self[fromidx], self[toidx] = self[toidx], self[fromidx]
188
+
189
+ @dataclass
190
+ class Context:
191
+ """Context-Object to Pass Information into/from Various Command Actions"""
192
+ app: 'AbsApplication' = field(repr=False)
193
+ command: 'AbsCommand' = field(repr=False)
194
+ ctx_parent: Optional['Context'] = field(default=None, repr=False)
195
+ global_flags: FlagDict = field(default_factory=dict)
196
+ local_flags: FlagDict = field(default_factory=dict)
197
+ args: Args = field(default_factory=Args)
198
+
199
+ @property
200
+ def parent(self) -> Self:
201
+ """retrieve parent or raise execution error"""
202
+ if self.ctx_parent is None:
203
+ raise CliError(
204
+ 'Unable to retrieve Context Parent', self, self.command)
205
+ return self.ctx_parent
206
+
207
+ def get(self, name: str, default: Any = None) -> Any:
208
+ """
209
+ collect a localized command flag value or return default
210
+
211
+ :param name: name of flag to retrieve
212
+ :param default: default value to return if not found
213
+ :return: flag value or default when not found
214
+ """
215
+ return ctx_get(self.command.flags, self.local_flags, name, default)
216
+
217
+ def set(self, name: str, value: Any):
218
+ """
219
+ set a new localized command flag value
220
+
221
+ :param name: name of flag to set
222
+ :param value: value of flag to set
223
+ """
224
+ return ctx_set(self.command.flags, self.global_flags, name, value)
225
+
226
+ @abstractmethod
227
+ def get_global(self, name: str, default: Any = None) -> Any:
228
+ """
229
+ collect a globalized command flag value or return default
230
+
231
+ :param name: name of flag to retrieve
232
+ :param default: default value to return if not found
233
+ :return: flag value or default when not found
234
+ """
235
+ return ctx_get(self.app.flags, self.global_flags, name, default)
236
+
237
+ @abstractmethod
238
+ def set_global(self, name: str, value: Any):
239
+ """
240
+ set a new globalized command flag value
241
+
242
+ :param name: name of flag to set
243
+ :param value: value of flag to set
244
+ """
245
+ return ctx_set(self.app.flags, self.global_flags, name, value)
246
+
247
+ def setdefault(self, name: str, value: Any, isglobal: bool = False):
248
+ """
249
+ set default value for localized flag if specified name is not present
250
+
251
+ :param name: name of flag to set default for
252
+ :param value: value to set default as
253
+ :param isglobal: modify global variables if true
254
+ """
255
+ flags = self.app.flags if isglobal else self.command.flags
256
+ fdict = self.global_flags if isglobal else self.local_flags
257
+ return ctx_default(flags, fdict, name, value)
258
+
259
+ def not_found_error(self, error: str, path: List[str]):
260
+ """
261
+ handle not-found error with the current action
262
+
263
+ :param error: error-message to pass to handlers
264
+ """
265
+ raise NotFoundError(error, path, self, self.command)
266
+
267
+ def on_usage_error(self, error: str):
268
+ """
269
+ handle a usage error with the current action
270
+
271
+ :param error: error-message to pass to handlers
272
+ """
273
+ raise UsageError(error, self, self.command)
274
+
275
+ def exit_with_error(self, error: str, exit_code: int = 1):
276
+ """
277
+ exit with the following error and exit-code for some unrecoverable error
278
+
279
+ :param error: error-message to pass to handlers
280
+ :param exit_code: exit-code to exit program with
281
+ """
282
+ raise ExitError(error, exit_code, self, self.command)
283
+
284
+ class AbsFlag(Protocol[T]):
285
+ """Abstract Flag Object Definition"""
286
+ name: str
287
+ usage: Optional[str]
288
+ default: Optional[T]
289
+ hidden: bool
290
+ required: bool
291
+ type: Type[T]
292
+ has_value: bool
293
+
294
+ @abstractmethod
295
+ def parse(self, value: str) -> T:
296
+ raise NotImplementedError
297
+
298
+ @cached_property
299
+ def names(self) -> List[str]:
300
+ return [n for n in (n.strip() for n in self.name.split(',', 1)) if n]
301
+
302
+ @property
303
+ def display(self) -> str:
304
+ return ', '.join(self.names)
305
+
306
+ @property
307
+ def long(self) -> str:
308
+ return self.names[0]
309
+
310
+ @property
311
+ def short(self) -> str:
312
+ return self.names[-1]
313
+
314
+ def index(self, values: Iterable[str]) -> Optional[int]:
315
+ """
316
+ return index of flag in values if found
317
+
318
+ :param values: list of values to search
319
+ :return: index-num (if found)
320
+ """
321
+ names = self.names
322
+ for n, value in enumerate(values, 0):
323
+ if value.lstrip('-') in names and value.startswith('-'):
324
+ return n
325
+
326
+ class AbsCommand(Protocol):
327
+ """Abstract Command Object Definition"""
328
+ name: str
329
+ aliases: List[str]
330
+ flags: Flags
331
+ commands: Commands
332
+ category: Optional[str]
333
+ hidden: bool
334
+ allow_parent: bool
335
+
336
+ @overload
337
+ @abstractmethod
338
+ def command(self, func: Callable) -> 'AbsCommand':
339
+ ...
340
+
341
+ @overload
342
+ @abstractmethod
343
+ def command(self, *args, **kwargs) -> CommandFunc:
344
+ ...
345
+
346
+ @abstractmethod
347
+ def command(self, *args, **kwargs) -> Union['AbsCommand', CommandFunc]:
348
+ raise NotImplementedError
349
+
350
+ async def run_before(self, ctx: Context):
351
+ pass
352
+
353
+ async def run_action(self, ctx: Context) -> Result:
354
+ return NO_ACTION
355
+
356
+ async def run_after(self, ctx: Context):
357
+ pass
358
+
359
+ def categories(self) -> Dict[str, 'AbsCommand']:
360
+ """
361
+ organize sub-commands into categories
362
+
363
+ :return: dictionary of category names associated w/ sub-commands
364
+ """
365
+ categories = {}
366
+ for cmd in self.commands:
367
+ categories.setdefault(cmd.category, [])
368
+ categories[cmd.category].append(cmd)
369
+ return categories
370
+
371
+ def visible_flags(self) -> Flags:
372
+ """
373
+ retrieve visable flags
374
+
375
+ :return: all non hidden flags attached to this command
376
+ """
377
+ return [f for f in self.flags if not f.hidden]
378
+
379
+ def visible_commands(self, category: Optional[str] = None) -> Commands:
380
+ """
381
+ retrieve visable commands (of given category if specified)
382
+
383
+ :param category: only return commands of the given category if specified
384
+ :return: commands not hidden
385
+ """
386
+ commands = [c for c in self.commands if not c.hidden]
387
+ if category is not None:
388
+ commands = [c for c in commands if c.category == category]
389
+ return commands
390
+
391
+ def visible_categories(self) -> List[str]:
392
+ """
393
+ retrieve category names
394
+
395
+ :return: list of visible category names
396
+ """
397
+ return [category for category in self.categories.keys()]
398
+
399
+ @cached_property
400
+ def display(self):
401
+ """convert command names/alises to string for help formatting"""
402
+ return ', '.join([self.name, *self.aliases])
403
+
404
+ def has_name(self, name: str) -> bool:
405
+ """
406
+ return true if command has the given name
407
+
408
+ :param name: name being compared to command
409
+ :return: true if any names/aliases match
410
+ """
411
+ return name == self.name or name in self.aliases
412
+
413
+ def index(self, values: Iterable[str]) -> Optional[int]:
414
+ """
415
+ return earliest index of where a command name/alias was found
416
+
417
+ :param values: list of strings to be searched
418
+ :return: index-num (if found)
419
+ """
420
+ for n, value in enumerate(values, 0):
421
+ if value == self.name or value in self.aliases:
422
+ return n
423
+
424
+ class AbsApplication(AbsCommand, Protocol):
425
+ writer: TextIO
426
+ err_writer: TextIO
427
+ help_app_template: Optional[str]
428
+ help_cmd_template: Optional[str]
429
+
430
+ @abstractmethod
431
+ def on_usage_error(self, err: UsageError):
432
+ raise NotImplementedError
433
+
434
+ @abstractmethod
435
+ def exit_with_error(self, err: ExitError):
436
+ raise NotImplementedError
437
+
438
+ @abstractmethod
439
+ def not_found_error(self, err: NotFoundError):
440
+ raise NotImplementedError
441
+
442
+ @abstractmethod
443
+ def config_error(self, err: ConfigError):
444
+ raise NotImplementedError
445
+
446
+ @overload
447
+ @abstractmethod
448
+ def run(self, args: OptStrList = None, run_async: Literal[False] = False):
449
+ ...
450
+
451
+ @overload
452
+ @abstractmethod
453
+ def run(self, args: OptStrList = None, run_async: Literal[True] = True) -> Coroutine[None, None, None]:
454
+ ...
455
+
456
+ @abstractmethod
457
+ def run(self, args: OptStrList = None, run_async: bool = False) -> OptCoroutine:
458
+ raise NotImplementedError