48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369 | @define
class BrokenTyper:
"""Yet another Typer wrapper, with goodies"""
description: str = ""
"""The default 'help' message of the CLI"""
app: typer.Typer = None
"""The main managed typer.Typer instance"""
chain: bool = False
"""Same as Typer.chain"""
commands: set[str] = Factory(set)
"""List of known commands"""
default: str = None
"""Default command to run if none is provided"""
prehook: Callable = lambda: None
"""Function to run before any command"""
posthook: Callable = lambda: None
"""Function to run after any command"""
shell: bool = False
"""If True, will run a REPL when no arguments are provided"""
naih: bool = True
"""No args is help"""
help: bool = True
"""Add an --help option to the CLI"""
credits: str = (
f"• Made by [green][link=https://github.com/Tremeschin]Tremeschin[/link][/] [yellow]{Runtime.Method} v{Runtime.Version}[/]\n\n"
"[italic grey53]→ Consider [blue][link=https://brokensrc.dev/about/sponsors/]Supporting[/link][/blue] my work [red]:heart:[/]"
)
@staticmethod
def exclude() -> typer.Option:
return typer.Option(
parser=(lambda type: type),
expose_value=False,
hidden=True,
)
def __attrs_post_init__(self):
self.app = typer.Typer(
add_help_option=self.help,
pretty_exceptions_enable=False,
no_args_is_help=self.naih,
add_completion=False,
rich_markup_mode="rich",
chain=self.chain,
epilog=self.credits,
)
_panel: str = None
@contextlib.contextmanager
def panel(self, name: str) -> Generator:
try:
previous = self._panel
self._panel = name
yield None
finally:
self._panel = previous
def command(self,
target: Union[Callable, BaseModel],
description: str=None,
help: bool=True,
naih: bool=False,
name: str=None,
context: bool=False,
default: bool=False,
panel: str=None,
post: Callable=None,
hidden: bool=False,
**kwargs,
) -> None:
# Method must be implemented, ignore and fail ok else
if getattr(target, "__isabstractmethod__", False):
return None
cls = (target if isinstance(target, type) else type(target))
# Convert pydantic to a wrapper with same signature
if issubclass(cls, BaseModel):
target = BrokenTyper.pydantic2typer(cls=target, post=post)
name = (name or cls.__name__)
naih = True # (Complex command)
else:
name = (name or target.__name__)
# Add to known or default commands, create it
name = name.replace("_", "-").lower()
self.default = (name if default else self.default)
self.commands.add(name)
self.app.command(
name=(name),
help=(description or target.__doc__),
add_help_option=(help),
no_args_is_help=(naih),
rich_help_panel=(panel or self._panel),
context_settings=dict(
allow_extra_args=True,
ignore_unknown_options=True,
) if context else None,
hidden=(hidden),
**kwargs,
)(target)
@staticmethod
def pydantic2typer(
cls: Union[BaseModel, type[BaseModel]],
post: Callable=None
) -> Callable:
"""Makes a Pydantic BaseModel class signature Typer compatible, creating a class and sending
it to the 'post' method for back-communication/catching the new object instance"""
# Assert object derives from BaseModel
if isinstance(cls, type):
if (not issubclass(cls, BaseModel)):
raise TypeError(f"Class type {cls} is not a pydantic BaseModel")
signature = cls
else:
if (not isinstance(cls, BaseModel)):
raise TypeError(f"Class instance {cls} is not a pydantic BaseModel")
signature = type(cls)
def wrapper(**kwargs):
nonlocal cls, post
# Instantiate if type
if isinstance(cls, type):
cls = cls()
# Copy new values to the instance
for name, value in kwargs.items():
field = cls.model_fields[name]
# Idea: Deal with nested models?
# Skip factory fields, not our business
if (field.default_factory is not None):
continue
setattr(cls, name, value)
# Call the post method if provided
if post: post(cls)
# Copy the signatures to the wrapper function (the new initializer)
wrapper.__signature__ = inspect.signature(signature)
wrapper.__doc__ = cls.__doc__
# Note: Requires ConfigDict(use_attribute_docstrings=True)
# Inject docstring into typer's help
for value in cls.model_fields.values():
for metadata in value.metadata:
if isinstance(metadata, OptionInfo):
metadata.help = (metadata.help or value.description)
return wrapper
@property
def _shell(self) -> bool:
return (self.shell and Environment.flag("REPL", 1))
def should_shell(self) -> Self:
self.shell = all((
(Runtime.Binary),
(not BrokenPlatform.OnLinux),
(not arguments()),
))
return self
@staticmethod
def simple(*commands: Callable) -> None:
app = BrokenTyper()
apply(app.command, commands)
return app(*sys.argv[1:])
@staticmethod
def proxy(callable: Callable) -> Callable:
"""Redirects a ctx to sys.argv and calls the method"""
def wrapper(ctx: typer.Context):
sys.argv[1:] = ctx.args
return callable()
return wrapper
@staticmethod
def complex(
main: Callable,
nested: Optional[Iterable[Callable]]=None,
simple: Optional[Iterable[Callable]]=None,
) -> None:
app = BrokenTyper(description=(
"[bold orange3]Note:[/] The default command is implicit when only arguments are provided\n\n"
"[bold grey58]→ This means [orange3]'entry (default) (args)'[/] is the same as [orange3]'entry (args)'[/]\n"
), help=False).should_shell()
# Preprocess arguments
nested = flatten(nested)
simple = flatten(simple)
for target in flatten(main, nested, simple):
method: bool = (target in simple)
default: bool = (target is main)
# Mark the default command
description = ' '.join((
(target.__doc__ or "No help provided"),
(default*"[bold indian_red](default)[/]"),
))
# Nested typer apps must be used with sys.argv
_target = (target if method else BrokenTyper.proxy(target))
app.command(
target=_target,
name=target.__name__,
description=description,
default=default,
context=True,
help=method,
)
return app(*sys.argv[1:])
def shell_welcome(self) -> None:
console.print(Panel(
title="⭐️ Tips",
title_align="left",
border_style="bold grey42",
expand=False,
padding=(1, 1),
renderable=Text.from_markup(
"• Press [spring_green1]'Ctrl+C'[/] to exit [bold bright_black](or close this window)[/]\n"
"• Run any [spring_green1]'{command} --help'[/] for more info\n"
"• Press [royal_blue1]Enter[/] for a command list [bold bright_black](above)[/]",
)
))
console.print(Text.from_markup(
"\n[bold grey58]→ Write a command from the list above and run it![/]"
))
def shell_prompt(self) -> bool:
try:
sys.argv[1:] = shlex.split(typer.prompt(
text="", prompt_suffix="\n❯",
show_default=False,
default=""
))
return True
except (click.exceptions.Abort, KeyboardInterrupt):
log.trace("BrokenTyper Repl exit KeyboardInterrupt")
return False
def __call__(self, *args: Any) -> None:
"""
Run the Typer app with the provided arguments
Warn:
Send sys.argv[1:] if running directly from user input
"""
if (not self.commands):
log.warning("No commands were added to the Typer app")
return None
# Minor pre-processing
self.app.info.help = (self.description or "No help provided for this CLI")
sys.argv[1:] = apply(str, flatten(args))
for index in itertools.count(0):
# On subsequent runs, prompt for command
if (self._shell) and (index > 0):
if not self.shell_prompt():
return
# Allow repl users to use the same commands as python entry point scripts,
# like 'depthflow gradio' where 'depthflow' isn't the package __main__.py
if (list_get(sys.argv, 1, "") == self.default):
sys.argv.pop(1)
# Defines a default, arguments are present, and no known commands were provided
if (self.default and arguments()) and all((x not in sys.argv for x in self.commands)):
sys.argv.insert(1, self.default)
try:
self.prehook()
self.app(sys.argv[1:])
self.posthook()
except SystemExit:
log.trace("Skipping SystemExit on BrokenTyper")
except KeyboardInterrupt:
log.success("BrokenTyper exit KeyboardInterrupt")
except Exception as error:
if (not self.shell):
raise error
console.print_exception(); print() # noqa
log.error(f"BrokenTyper exited with error: {repr(error)}")
input("\nPress Enter to continue..")
# Exit out non-repl mode
if (not self._shell):
return
# Some action was taken, like 'depthflow main -o ./video.mp4'
if (index == 0) and arguments():
return
# Pretty welcome message on the first 'empty' run
if (index == 0):
self.shell_welcome()
# The args were "consumed"
sys.argv = [sys.argv[0]]
|