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/style.py ADDED
@@ -0,0 +1,180 @@
1
+ """
2
+ CLI UI Coloring/Styling Utilities
3
+ """
4
+ import re
5
+ from abc import abstractmethod
6
+ from typing import Dict, Literal, Protocol, Tuple, Union
7
+
8
+ #** Variables **#
9
+ __all__ = [
10
+ 'Rgb',
11
+ 'SimpleColor',
12
+ 'Color',
13
+
14
+ 'Styling',
15
+ 'AnsiTermStyle',
16
+ ]
17
+
18
+ Rgb = Tuple[int, int, int]
19
+ SimpleColor = Literal['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan',
20
+ 'white', 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
21
+ 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white']
22
+
23
+ Color = Union[SimpleColor, Rgb]
24
+ Style = Literal['bold', 'dim', 'underline', 'overline',
25
+ 'italic', 'blink', 'reverse', 'strike']
26
+
27
+ _re_ansi = re.compile(r'\033\[[0-?]*[ -/]*[@-~]')
28
+
29
+ #** Classes **#
30
+
31
+ class Styling(Protocol):
32
+ """
33
+ Output Styling Abstraction (Primarily for ANSI Terminal Codes)
34
+ """
35
+ BLACK: str
36
+ RED: str
37
+ GREEN: str
38
+ YELLOW: str
39
+ BLUE: str
40
+ MAGENTA: str
41
+ CYAN: str
42
+ WHITE: str
43
+ BRIGHT_BLACK: str
44
+ BRIGHT_RED: str
45
+ BRIGHT_GREEN: str
46
+ BRIGHT_YELLOW: str
47
+ BRIGHT_BLUE: str
48
+ BRIGHT_MAGENTA: str
49
+ BRIGHT_CYAN: str
50
+ BRIGHT_WHITE: str
51
+
52
+ @abstractmethod
53
+ def format_rgba(self, r: int, g: int, b: int):
54
+ """
55
+ format rgb color in the relevant style
56
+ """
57
+ raise NotImplementedError
58
+
59
+ @abstractmethod
60
+ def reset_color(self, color: Color) -> str:
61
+ """
62
+ reset the styling of the specified color
63
+ """
64
+ raise NotImplementedError
65
+
66
+ @abstractmethod
67
+ def format_style(self, style: Style) -> str:
68
+ """
69
+ return format for the specific text styling
70
+ """
71
+ raise NotImplementedError
72
+
73
+ @abstractmethod
74
+ def reset_style(self, style: Style) -> str:
75
+ """
76
+ return reset for the specific text styling
77
+ """
78
+ raise NotImplementedError
79
+
80
+ @abstractmethod
81
+ def strip(self, text: str) -> str:
82
+ """
83
+ strip styling elements from the given text
84
+ """
85
+ raise NotImplementedError()
86
+
87
+ def format_simple(self, color: SimpleColor) -> str:
88
+ """
89
+ format a simple color with its relevant prefix
90
+ """
91
+ return getattr(self, color.upper())
92
+
93
+ def format_color(self, color: Color) -> str:
94
+ """
95
+ return formating for a color (both simple/rgb)
96
+ """
97
+ if isinstance(color, tuple):
98
+ return self.format_rgba(*color)
99
+ return self.format_simple(color)
100
+
101
+ def wrap_color(self, color: Color, text: str):
102
+ """
103
+ wrap the given text with the specified color formatting
104
+ """
105
+ return f'{self.format_color(color)}{text}{self.reset_color(color)}'
106
+
107
+ def wrap_style(self, style: Style, text: str):
108
+ """
109
+ wrap the given text with the specified style formatting
110
+ """
111
+ return f'{self.format_style(style)}{text}{self.reset_style(style)}'
112
+
113
+ def toggle_color(self, color: Color, apply: bool):
114
+ """
115
+ toggle color as either format or reset
116
+ """
117
+ return self.format_color(color) if apply else self.reset_color(color)
118
+
119
+ def toggle_style(self, style: Style, apply: bool):
120
+ """
121
+ toggle style as either format or reset
122
+ """
123
+ return self.format_style(style) if apply else self.reset_style(style)
124
+
125
+ class AnsiTermStyle(Styling):
126
+ """
127
+ Terminal ANSI Escape Codes for Styling
128
+ """
129
+ ANSI_ADD: Dict[Style, int] = {
130
+ 'bold': 1,
131
+ 'dim': 2,
132
+ 'underline': 4,
133
+ 'overline': 53,
134
+ 'italic': 3,
135
+ 'blink': 5,
136
+ 'reverse': 7,
137
+ 'strike': 9,
138
+ }
139
+ ANSI_CLEAR: Dict[Style, int] = {
140
+ 'bold': 22,
141
+ 'dim': 22,
142
+ 'underline': 24,
143
+ 'overline': 55,
144
+ 'italic': 23,
145
+ 'blink': 25,
146
+ 'reverse': 27,
147
+ 'strike': 29,
148
+ }
149
+
150
+ BLACK = '\033[30m'
151
+ RED = '\033[31m'
152
+ GREEN = '\033[32m'
153
+ YELLOW = '\033[33m'
154
+ BLUE = '\033[34m'
155
+ MAGENTA = '\033[35m'
156
+ CYAN = '\033[36m'
157
+ WHITE = '\033[37m'
158
+ BRIGHT_BLACK = '\033[90m'
159
+ BRIGHT_RED = '\033[91m'
160
+ BRIGHT_GREEN = '\033[92m'
161
+ BRIGHT_YELLOW = '\033[93m'
162
+ BRIGHT_BLUE = '\033[94m'
163
+ BRIGHT_MAGENTA = '\033[95m'
164
+ BRIGHT_CYAN = '\033[96m'
165
+ BRIGHT_WHITE = '\033[97m'
166
+
167
+ def format_rgba(self, r: int, g: int, b: int):
168
+ return f'\033[38;2;{r:d};{g:d};{b:d}m'
169
+
170
+ def reset_color(self, color: Color) -> str:
171
+ return '\033[39m'
172
+
173
+ def format_style(self, style: Style) -> str:
174
+ return f'\033[{self.ANSI_ADD[style]}m'
175
+
176
+ def reset_style(self, style: Style) -> str:
177
+ return f'\033[{self.ANSI_CLEAR[style]}m'
178
+
179
+ def strip(self, text: str) -> str:
180
+ return _re_ansi.sub("", text)
cli/suggest.py ADDED
@@ -0,0 +1,256 @@
1
+ """
2
+ CLI Autocomplete Suggestion Implementation
3
+ """
4
+ import functools
5
+ from typing import (
6
+ Any, Dict, Iterator, List, Mapping, Optional, Sequence, Set,
7
+ Tuple, Type, Union)
8
+
9
+ from . import SuggestFunc
10
+ from .arg import Arg
11
+ from .context import Context
12
+ from .cmd import Command
13
+ from .flag import Flag
14
+ from .parser import index_commands, index_flags
15
+ from .utils import echo
16
+ from .wraps import wrap_suggestor
17
+
18
+ #** Variables **#
19
+ __all__ = ['SuggestorCLS', 'SuggestFunc', 'Suggest', 'Suggestor', 'suggest_static']
20
+
21
+ Hints = Iterator[str]
22
+ Static = Union[Sequence[str], Set[str], Mapping[str, Any]]
23
+
24
+ SuggestorCLS = Type['Suggestor']
25
+
26
+ #** Functions **#
27
+
28
+ def empty():
29
+ yield from ()
30
+
31
+ def _action(ctx: Context):
32
+ """
33
+ default auto-complete command action
34
+ """
35
+ suggestor = ctx.suggestor()
36
+ pos = ctx.get_arg('pos', int)
37
+ args = ctx.get_arg('args', List[str])
38
+ partial = len(args) > pos
39
+ for suggest in suggestor.suggest(args, partial):
40
+ echo(suggest)
41
+ ctx.exit()
42
+
43
+ @functools.lru_cache()
44
+ def autocomplete_cmd() -> Command:
45
+ """
46
+ default auto-complete hidden command definition
47
+ """
48
+ return Command(
49
+ name='__autocomplete',
50
+ about='Hidden autocompletion command',
51
+ args=[Arg[int]('pos'), Arg[str]('args', repeat=True)],
52
+ hidden=True,
53
+ action=_action,
54
+ )
55
+
56
+ def suggest_options(options: List[str], value: str) -> Hints:
57
+ """
58
+ helper function to suggest items from a list based on the value
59
+
60
+ :param options: options to recommend against
61
+ :param value: current value used to generate suggestions
62
+ """
63
+ if not value:
64
+ yield from options
65
+ return
66
+ for option in options:
67
+ if option.startswith(value) and value != option:
68
+ hint = option[len(value):]
69
+ yield hint
70
+
71
+ def suggest_static(s: Static) -> SuggestFunc:
72
+ """
73
+ generate suggestor based on a static list of items
74
+
75
+ :param s: list of static items to suggest against
76
+ :return: static suggestion function
77
+ """
78
+ vals = list(s.keys()) if isinstance(s, Mapping) else list(s)
79
+ options = [str(v) for v in vals]
80
+ def static_suggestor(value: str) -> Hints:
81
+ return suggest_options(options, value)
82
+ return static_suggestor
83
+
84
+ #** Classes **#
85
+
86
+ class Suggest:
87
+ """
88
+ Suggestion Annotation-Helper Type
89
+
90
+ ```python
91
+ Test = Annotated[str, Suggest[my_suggest_function]]
92
+ ```
93
+ """
94
+ __slots__ = ('suggestor', )
95
+
96
+ def __init__(self, suggestor: SuggestFunc):
97
+ self.suggestor = suggestor
98
+
99
+ @classmethod
100
+ def __class_getitem__(cls, suggestor: Union[SuggestFunc, Static]):
101
+ return cls(suggestor) \
102
+ if callable(suggestor) else cls(suggest_static(suggestor))
103
+
104
+ class Suggestor:
105
+ """
106
+ Auto-Complete Suggestion Generator Implementation
107
+ """
108
+ __slots__ = ('command', 'extra')
109
+
110
+ def __init__(self, command: Command, extra: Optional[Dict[str, Any]] = None):
111
+ self.command = command
112
+ self.extra = extra or {}
113
+
114
+ def split_commands(self, args: List[str]) -> Command:
115
+ """
116
+ find last valid command in raw arguments
117
+ """
118
+ command = self.command
119
+ while args:
120
+ indexes = index_commands(command.visible_commands(), args)
121
+ if not indexes:
122
+ break
123
+ index, command = indexes[-1]
124
+ args[:index] = []
125
+ return command
126
+
127
+ def split_flags(self, flags: List[Flag],
128
+ args: List[str]) -> Tuple[Optional[Flag], List[Flag]]:
129
+ """
130
+ find last valid flag in raw arguments (if present)
131
+
132
+ :param flags: list of flags to compare against
133
+ :param args: raw arguments to parse
134
+ :return: (last matched-flag, list of all matched-flags)
135
+ """
136
+ indexes = index_flags(flags, args)
137
+ if not indexes:
138
+ return None, []
139
+ index, flag = indexes[-1]
140
+ if flag.suggestor is False:
141
+ return None, []
142
+ args[:index] = []
143
+ return flag, [f for _,f in indexes]
144
+
145
+ def split_args(self,
146
+ cmdargs: List[Arg], args: List[str], partial: bool) -> Optional[Arg]:
147
+ """
148
+ find last valid argument in raw arguments (if present)
149
+
150
+ :param cmdargs: list of command arguments to compare against
151
+ :param args: raw arguments to parse
152
+ :param partial: status of cursor (either partial string or new)
153
+ """
154
+ limit = 1 if partial else 0
155
+ cmdargs = cmdargs.copy()
156
+ while cmdargs and len(args) > limit:
157
+ value = args.pop(0)
158
+ if value == '--':
159
+ continue
160
+ cmdarg = cmdargs[0]
161
+ if not cmdarg.repeat:
162
+ cmdargs.pop(0)
163
+
164
+ if not cmdargs:
165
+ return None
166
+ cmd = cmdargs[0]
167
+ return None if cmd.suggestor is False else cmd
168
+
169
+ def suggest_options(self, options: List[str], value: str) -> Hints:
170
+ """
171
+ helper function to suggest items from a list based on the value
172
+
173
+ :param options: options to recommend against
174
+ :param value: current value used to generate suggestions
175
+ """
176
+ return suggest_options(options, value)
177
+
178
+ def suggest_source(self, source: Union[Arg, Flag], value: str) -> Hints:
179
+ """
180
+ generate suggestions from the given source argument/flag
181
+
182
+ :param source: source of suggestions
183
+ :param value: value used to generate suggestions from
184
+ """
185
+ results = []
186
+ raw_suggestor = source.suggestor
187
+ if callable(raw_suggestor):
188
+ suggestor = wrap_suggestor(raw_suggestor)
189
+ for item in suggestor(self.extra, value):
190
+ if item not in results:
191
+ results.append(item)
192
+
193
+ default = str(source.default) if source.default is not None else None
194
+ if default:
195
+ for item in self.suggest_options([default], value):
196
+ if item not in results:
197
+ results.append(item)
198
+ yield from results
199
+
200
+ def suggest(self, args: List[str], partial: bool = False) -> Hints:
201
+ """
202
+ Build suggestions based on latest relevant argument in args
203
+
204
+ :param args: list of arguments from command-line
205
+ :param partial: declaration if last argument was partial or complete
206
+ :return: yielded suggestion results
207
+ """
208
+ command = self.split_commands(args)
209
+ if command is not self.command:
210
+ args.pop(0)
211
+ if not args and partial:
212
+ return empty()
213
+
214
+ flag, fmatched = self.split_flags(command.visible_flags(), args)
215
+ if flag is not None:
216
+ args.pop(0)
217
+ if len(args) == 0 and flag._requires_value():
218
+ if not partial:
219
+ return self.suggest_source(flag, '')
220
+ return empty()
221
+ if len(args) == 1 and flag._requires_value():
222
+ if partial:
223
+ return self.suggest_source(flag, args[0])
224
+ args.pop(0)
225
+
226
+ arg = self.split_args(command.args, args, partial)
227
+ if arg is not None:
228
+ if len(args) == 1 and partial:
229
+ return self.suggest_source(arg, args[0])
230
+ return self.suggest_source(arg, '')
231
+
232
+ value = args[-1] if args and partial else ''
233
+ all_flags = command.visible_flags()
234
+ flags = [f for f in all_flags if f not in fmatched or f.repeat]
235
+ flags = [f for f in flags if f.suggestor is not False]
236
+ f_required = [f for f in flags if f.required]
237
+ if f_required:
238
+ options = [v for flag in f_required for v in flag.variants()]
239
+ return self.suggest_options(options, value)
240
+
241
+ options = [c.name for c in command.visible_commands() if c.suggest]
242
+ if options and not command.invoke_without_command:
243
+ return self.suggest_options(options, value)
244
+
245
+ options += [v for flag in flags for v in flag.variants()]
246
+ return self.suggest_options(options, value)
247
+
248
+ def suggest_list(self, args: List[str], partial: bool = False) -> List[str]:
249
+ """
250
+ Build suggestions based on latest relevant argument in args
251
+
252
+ :param args: list of arguments from command-line
253
+ :param partial: declaration if last argument was partial or complete
254
+ :return: list of complete suggestions
255
+ """
256
+ return list(self.suggest(args, partial))
cli/tests/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """
2
+ CLI Implementation UnitTests
3
+ """
4
+
5
+ #** Variables **#
6
+ __all__ = [
7
+ 'ParserTestsV1',
8
+ 'ParserTestsV2',
9
+ 'SuggestTestsV1',
10
+ 'SuggestTestsV2'
11
+ ]
12
+
13
+ #** Imports **#
14
+ from .parser import ParserTestsV1, ParserTestsV2
15
+ from .suggest import SuggestTestsV1, SuggestTestsV2
@@ -0,0 +1,19 @@
1
+ """
2
+ Application Implementations for UnitTests
3
+ """
4
+ from typing_extensions import Annotated
5
+
6
+ from ...suggest import Suggest
7
+
8
+ #** Variables **#
9
+ __all__ = ['APP_V1', 'APP_V2']
10
+
11
+ USERS = ['bob', 'jeff', 'jerry', 'aiden', 'admin', 'root']
12
+ REPEAT = [1, 2, 3, 11]
13
+
14
+ User = Annotated[str, Suggest[USERS]]
15
+ Repeat = Annotated[int, Suggest[REPEAT]]
16
+
17
+ #** Imports **#
18
+ from .v1 import APP_V1
19
+ from .v2 import APP_V2
cli/tests/_apps/v1.py ADDED
@@ -0,0 +1,61 @@
1
+ """
2
+ Simple Application Command Description for UnitTesting
3
+ """
4
+ import logging
5
+ from pathlib import Path
6
+
7
+ from . import User, Repeat
8
+ from ... import Arg, Command, Flag
9
+ from ...validate import LogLevel
10
+
11
+ #** Variables **#
12
+ __all__ = ['APP_V1']
13
+
14
+ APP_V1 = Command(
15
+ name='v1',
16
+ about='example application v1',
17
+ args=[],
18
+ flags=[
19
+ Flag[User]('user, u', 'user to run application as', 'root'),
20
+ Flag[LogLevel]('log, l', 'specify loglevel for whole application', logging.DEBUG),
21
+ Flag[bool]('debug, d', 'same as --log debug'),
22
+ Flag[Repeat]('repeat, r', 'repeatable flag', repeat=True),
23
+ ],
24
+ invoke_without_command=True,
25
+ commands=[
26
+ Command(
27
+ name='echo',
28
+ about='repeat something back to the user',
29
+ args=[Arg[str]('test', repeat=True)],
30
+ flags=[
31
+ Flag[bool]('dry, d', 'run dry run'),
32
+ Flag[Path]('file, f', 'file to echo content to'),
33
+ ]
34
+ ),
35
+ Command(
36
+ name='do',
37
+ about='do a specific action',
38
+ flags=[
39
+ Flag[bool]('kill, k', 'end action with "and dies..."'),
40
+ ],
41
+ commands=[
42
+ Command(
43
+ name='run',
44
+ about='run a given number of miles',
45
+ args=[Arg[Repeat]('dist1'), Arg[int]('dist2', default=42)],
46
+ flags=[
47
+ Flag[bool]('km', 'use kilometers rather than miles')
48
+ ]
49
+ ),
50
+ Command(
51
+ name='fly',
52
+ about='fly a given number of miles',
53
+ args=[Arg[int]('dist2')],
54
+ flags=[
55
+ Flag[bool]('km', 'use kilometers rather than miles'),
56
+ ]
57
+ )
58
+ ],
59
+ )
60
+ ],
61
+ )
cli/tests/_apps/v2.py ADDED
@@ -0,0 +1,76 @@
1
+ """
2
+ Action Based Application Command Description for UnitTesting
3
+ """
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import List, Optional
7
+
8
+ from . import User, Repeat
9
+ from ... import Context, command, extra, option
10
+ from ...validate import LogLevel
11
+
12
+ #** Variables **#
13
+ __all__ = ['APP_V2']
14
+
15
+ @command(invoke_without_command=True)
16
+ @option('user', short='u')
17
+ @option('log', short='l')
18
+ @option('debug', short='d')
19
+ @option('repeat', short='r')
20
+ def v1(ctx: Context, *,
21
+ user: User = 'root',
22
+ log: LogLevel = logging.DEBUG,
23
+ debug: bool = False,
24
+ repeat: Optional[List[Repeat]] = None,
25
+ ):
26
+ """
27
+ example application v1
28
+
29
+ :param user: user to run application as
30
+ :param log: specify loglevel for whole application
31
+ :param debug: same as --log debug
32
+ :param repeat: repeatable flag
33
+ """
34
+ pass
35
+
36
+ @v1.command
37
+ @option('dry', short='d')
38
+ @option('file', short='f')
39
+ def echo(*test: str, dry: bool = False, file: Optional[Path] = None):
40
+ """
41
+ repeat something back to the user
42
+
43
+ :param dry: run dry run
44
+ :param file: file to echo content to
45
+ """
46
+ print('echo', test, dry, file)
47
+
48
+ @v1.command
49
+ @option('kill', short='k')
50
+ def do(ctx: Context, *, kill: bool = False):
51
+ """
52
+ do a specific action
53
+
54
+ :param kill: end action with "and dies..."
55
+ """
56
+ ctx.extra['extra'] = 'ayylmao'
57
+ print('do!', kill)
58
+
59
+ @do.command
60
+ @extra('extra')
61
+ def run(dist1: Repeat, dist2: int = 42, *, km: bool = False, extra: str):
62
+ """
63
+ run a given number of miles
64
+
65
+ :param km: use kilometers rather than miles
66
+ """
67
+ print('run', dist1, dist2, km, extra)
68
+
69
+ @do.command
70
+ def fly(dist2: int, *, km: bool = False):
71
+ """
72
+ :param km: use kilometers rather than miles
73
+ """
74
+ print('fly', dist2, km)
75
+
76
+ APP_V2 = v1