-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcli.py
2349 lines (2089 loc) · 90.6 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import datetime
import enum
import functools
import json
import os
import pathlib
import re
import shlex
import subprocess
import sys
import textwrap
from typing import Any, Awaitable, Callable, Dict, Iterable, List, Optional, Pattern, Set, Tuple, Type, Union
import bullet
import click
import devtools
import kubernetes_asyncio
import loguru
import pydantic
import pygments
import pygments.formatters
import typer
import yaml
# Expose helpers
from tabulate import tabulate
from timeago import format as timeago
import servo
import servo.runner
import servo.utilities.yaml
class Section(str, enum.Enum):
assembly = "Assembly Commands"
ops = "Operational Commands"
config = "Configuration Commands"
connectors = "Connector Commands"
commands = "Commands"
other = "Other Commands"
class LogLevel(str, enum.Enum):
trace = "TRACE"
debug = "DEBUG"
info = "INFO"
success = "SUCCESS"
warning = "WARNING"
error = "ERROR"
critical = "CRITICAL"
class ConfigOutputFormat(servo.AbstractOutputFormat):
yaml = servo.YAML_FORMAT
json = servo.JSON_FORMAT
dict = servo.DICT_FORMAT
text = servo.TEXT_FORMAT
configmap = servo.CONFIGMAP_FORMAT
class SchemaOutputFormat(servo.AbstractOutputFormat):
json = servo.JSON_FORMAT
text = servo.TEXT_FORMAT
dict = servo.DICT_FORMAT
html = servo.HTML_FORMAT
class VersionOutputFormat(servo.AbstractOutputFormat):
text = servo.TEXT_FORMAT
json = servo.JSON_FORMAT
# FIXME: Eliminate the mixin and put our context object onto the Click.obj instance
class Context(typer.Context):
"""
Context models state required by different CLI invocations.
Hydration of the state if handled by callbacks on the `CLI` class.
"""
# Basic configuration
config_file: Optional[pathlib.Path] = None
optimizer: Optional[servo.Optimizer] = None
name: Optional[str] = None
token: Optional[str] = None
token_file: Optional[pathlib.Path] = None
base_url: Optional[str] = None
url: Optional[str] = None
limit: Optional[int] = None
# Assembled servo
assembly: Optional[servo.Assembly] = None
servo_: Optional[servo.Servo] = None
# Active connector
connector: Optional[servo.BaseConnector] = None
# NOTE: Section defaults generally only apply to Groups (see notes below)
section: Section = Section.commands
@classmethod
def attributes(cls) -> Set[str]:
"""Returns the names of the attributes to be hydrated by ContextMixin"""
return {
"config_file",
"name",
"optimizer",
"assembly",
"servo_",
"connector",
"section",
"token",
"token_file",
"base_url",
"url",
"limit",
}
@property
def servo(self) -> servo.Servo:
return self.servo_
def __init__(
self,
command: "Command",
*args,
config_file: Optional[pathlib.Path] = None,
name: Optional[str] = None,
optimizer: Optional[servo.Optimizer] = None,
assembly: Optional[servo.Assembly] = None,
servo_: Optional[servo.Servo] = None,
connector: Optional[servo.BaseConnector] = None,
section: Section = Section.commands,
token: Optional[str] = None,
token_file: Optional[pathlib.Path] = None,
base_url: Optional[str] = None,
url: Optional[str] = None,
limit: Optional[int] = None,
**kwargs,
) -> None: # noqa: D107
self.config_file = config_file
self.name = name
self.optimizer = optimizer
self.assembly = assembly
self.servo_ = servo_
self.connector = connector
self.section = section
self.token = token
self.token_file = token_file
self.base_url = base_url
self.limit = limit
return super().__init__(command, *args, **kwargs)
class ContextMixin:
# NOTE: Override the Click `make_context` base method to inject our class
def make_context(self, info_name, args, parent=None, **extra):
if parent and not issubclass(parent.__class__, Context):
raise ValueError(
f"Encountered an unexpected parent subclass type '{parent.__class__}' while attempting to create a context"
)
for key, value in self.context_settings.items():
if key not in extra:
extra[key] = value
if isinstance(parent, Context):
for attribute in Context.attributes():
if attribute not in extra:
extra[attribute] = getattr(parent, attribute)
ctx = Context(self, info_name=info_name, parent=parent, **extra)
with ctx.scope(cleanup=False):
self.parse_args(ctx, args)
return ctx
class Command(click.Command, ContextMixin):
@property
def section(self) -> Optional[Section]:
# NOTE: The `callback` property is the decorated function. See `command()` on CLI
return getattr(self.callback, "section", None)
def make_context(self, info_name, args, parent=None, **extra):
return ContextMixin.make_context(self, info_name, args, parent, **extra)
class Group(click.Group, ContextMixin):
@property
def section(self) -> Optional[Section]:
# NOTE: For Groups, Typer doesn't give us a great way to pass the state (can't decorate callback fn)
# so instead we hang it on the context and rely on the command() to override it
if self.context_settings:
return self.context_settings.get("section", None)
else:
return None
def make_context(self, info_name, args, parent=None, **extra):
return ContextMixin.make_context(self, info_name, args, parent, **extra)
def format_commands(self, ctx, formatter):
"""
Formats all commands into sections
"""
sections_of_commands: Dict[Section, List[Tuple[str, Command]]] = {}
for section in Section:
sections_of_commands[section] = []
for command_name in self.list_commands(ctx):
command = self.get_command(ctx, command_name)
if command.hidden:
continue
# Determine the command section
# NOTE: We may have non-CLI instances so we guard attribute access
section = getattr(command, "section", Section.commands)
commands = sections_of_commands.get(section, [])
commands.append(
(
command_name,
command,
)
)
sections_of_commands[section] = commands
for section, commands in sections_of_commands.items():
if len(commands) == 0:
continue
limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
# Sort the connector and other commands as ordering isn't explicit
if section in (
Section.connectors,
Section.other,
):
commands = sorted(commands)
rows = []
for name, command in commands:
help = command.get_short_help_str(limit)
rows.append((name, help))
with formatter.section(section):
formatter.write_dl(rows)
class OrderedGroup(Group):
# NOTE: Rely on ordering of modern Python dicts
def list_commands(self, ctx):
return self.commands
class CLI(typer.Typer, servo.logging.Mixin):
section: Section = Section.commands
def __init__(
self,
*args,
name: Optional[str] = None,
help: Optional[str] = None,
command_type: Optional[Type[click.Command]] = None,
callback: Optional[Callable] = typer.models.Default(None),
section: Section = Section.commands,
**kwargs,
) -> None: # noqa: D107
# NOTE: Set default command class to get custom context
if command_type is None:
command_type = Group
if isinstance(callback, typer.models.DefaultPlaceholder):
callback = self.root_callback
self.section = section
super().__init__(
*args, name=name, help=help, cls=command_type, callback=callback, **kwargs
)
def command(
self,
*args,
cls: Optional[Type[click.Command]] = None,
section: Section = None,
**kwargs,
) -> Callable[[typer.models.CommandFunctionType], typer.models.CommandFunctionType]:
# NOTE: Set default command class to get custom context & section support
if cls is None:
cls = Command
# NOTE: This is a little fancy. We are decorating the function with the
# section metadata and then returning the Typer decorator implementation
parent_decorator = super().command(*args, cls=cls, **kwargs)
def decorator(
f: typer.models.CommandFunctionType,
) -> typer.models.CommandFunctionType:
f.section = section if section else self.section
return parent_decorator(f)
return decorator
def callback(
self,
*args,
cls: Optional[Type[click.Command]] = None,
**kwargs,
) -> Callable[[typer.models.CommandFunctionType], typer.models.CommandFunctionType]:
# NOTE: Override the default to inject our Command class
if cls is None:
cls = Group
return super().callback(*args, cls=cls, **kwargs)
def add_cli(
self,
cli: "CLI",
*args,
cls: Optional[Type[click.Command]] = None,
section: Optional[Section] = None,
context_settings: Optional[Dict[Any, Any]] = None,
**kwargs,
) -> None:
if not isinstance(cli, CLI):
raise ValueError(
f"Cannot add cli of type '{cli.__class__}: not a servo.cli.CLI"
)
if cls is None:
cls = Group
if context_settings is None:
context_settings = {}
section = section if section else cli.section
# NOTE: Hang section state on the context for `Group` to pick up later
context_settings["section"] = section
return self.add_typer(
cli, *args, cls=cls, context_settings=context_settings, **kwargs
)
@staticmethod
def root_callback(
ctx: Context,
optimizer: str = typer.Option(
None,
envvar="OPSANI_OPTIMIZER",
show_envvar=True,
metavar="OPTIMIZER",
help="Opsani optimizer to connect to (format is example.com/app)",
),
token: str = typer.Option(
None,
envvar="OPSANI_TOKEN",
show_envvar=True,
metavar="TOKEN",
help="Opsani API access token",
),
token_file: pathlib.Path = typer.Option(
None,
envvar="OPSANI_TOKEN_FILE",
show_envvar=True,
exists=True,
file_okay=True,
dir_okay=False,
writable=False,
readable=True,
resolve_path=True,
help="File to load the access token from",
),
base_url: str = typer.Option(
"https://api.opsani.com/",
"--base-url",
envvar="OPSANI_BASE_URL",
show_envvar=True,
show_default=True,
metavar="URL",
help="Base URL for connecting to Opsani API",
),
url: str = typer.Option(
None,
hidden=True,
envvar="OPSANI_URL",
metavar="URL",
help="Complete URL to reach the Opsani API, overriding the URL computed from the base URL",
),
config_file: pathlib.Path = typer.Option(
"servo.yaml",
"--config-file",
"-c",
envvar="SERVO_CONFIG_FILE",
show_envvar=True,
exists=False,
file_okay=True,
dir_okay=False,
writable=False,
readable=True,
resolve_path=True,
help="Servo configuration file",
),
name: Optional[str] = typer.Option(
None,
"--name",
"-n",
envvar="SERVO_NAME",
show_envvar=True,
help="Name of the servo to use",
),
limit: Optional[int] = typer.Option(
None,
"--limit",
help="Limit multi-servo concurrency",
),
log_level: LogLevel = typer.Option(
LogLevel.info,
"--log-level",
"-l",
envvar="SERVO_LOG_LEVEL",
show_envvar=True,
help="Set the log level",
),
no_color: Optional[bool] = typer.Option(
None,
"--no-color",
envvar=["SERVO_NO_COLOR", "NO_COLOR"],
help="Disable colored output",
),
):
ctx.config_file = config_file
ctx.name = name
ctx.optimizer = optimizer
ctx.token = token
ctx.token_file = token_file
ctx.base_url = base_url
ctx.url = url
ctx.limit = limit
servo.logging.set_level(log_level)
servo.logging.set_colors(not no_color)
# TODO: This should be pluggable. Base it off of the section?
if ctx.invoked_subcommand not in {
"init",
"connectors",
"schema",
"generate",
"validate",
"version",
}:
try:
CLI.assemble_from_context(ctx)
except (ValueError, pydantic.ValidationError) as error:
typer.echo(f"fatal: invalid configuration: {error}", err=True)
raise typer.Exit(2)
@staticmethod
def assemble_from_context(ctx: Context):
if ctx.config_file is None:
raise typer.BadParameter("Config file must be specified")
if not ctx.config_file.exists():
raise typer.BadParameter(f"Config file '{ctx.config_file}' does not exist")
# Conditionalize based on multi-servo options
optimizer = None
configs = list(yaml.full_load_all(open(ctx.config_file)))
if not isinstance(configs, list):
raise TypeError(
f'error: config file "{ctx.config_file}" parsed to an unexpected value of type "{configs.__class__}"'
)
if len(configs) == 0:
configs.append({})
if len(configs) == 1:
config = configs[0]
if not isinstance(config, dict):
raise TypeError(
f'error: config file "{ctx.config_file}" parsed to an unexpected value of type "{config.__class__}"'
)
if config.get("optimizer", None) == None:
if ctx.optimizer is None:
raise typer.BadParameter("An optimizer must be specified")
# Resolve token
if ctx.token is None and ctx.token_file is None:
raise typer.BadParameter(
"API token must be provided via --token (ENV['OPSANI_TOKEN']) or --token-file (ENV['OPSANI_TOKEN_FILE'])"
)
if ctx.token is not None and ctx.token_file is not None:
raise typer.BadParameter("--token and --token-file cannot both be given")
if ctx.token_file is not None and ctx.token_file.exists():
ctx.token = ctx.token_file.read_text().strip()
if len(ctx.token) == 0 or ctx.token.isspace():
raise typer.BadParameter("token cannot be blank")
optimizer = servo.Optimizer(
id=ctx.optimizer, token=ctx.token, base_url=ctx.base_url, __url__=ctx.url
)
else:
if ctx.optimizer:
raise typer.BadParameter(f"An optimizer cannot be specified in a multi-servo configuration (found {ctx.optimizer})")
if ctx.token or ctx.token_file:
raise typer.BadParameter("A token cannot be specified in a multi-servo configuration")
if ctx.limit:
if len(configs) > ctx.limit:
servo.logger.warning(f"concurrent servo execution limited to {ctx.limit}: declining to run {len(configs) - ctx.limit} configured servos")
configs = configs[0:ctx.limit]
# Assemble the Servo
try:
assembly = run_async(servo.Assembly.assemble(
config_file=ctx.config_file,
configs=configs,
optimizer=optimizer
))
except pydantic.ValidationError as error:
typer.echo(error, err=True)
raise typer.Exit(2) from error
# Target a specific servo if possible
ctx.assembly = assembly
if assembly.servos:
if len(assembly.servos) == 1:
ctx.servo_ = assembly.servos[0]
if ctx.name and ctx.servo_.name != ctx.name:
raise typer.BadParameter(f"No servo was found named \"{ctx.name}\"")
elif ctx.name:
for servo_ in assembly.servos:
if servo_.name == ctx.name:
ctx.servo_ = servo_
break
if ctx.servo_ is None:
raise typer.BadParameter(f"No servo was found named \"{ctx.name}\"")
@staticmethod
def connectors_named(names: List[str], servo_: servo.Servo) -> List[servo.BaseConnector]:
connectors: List[servo.BaseConnector] = []
for name in names:
size = len(connectors)
for connector in servo_.all_connectors:
if connector.name == name:
connectors.append(connector)
break
if len(connectors) == size:
raise typer.BadParameter(f"no connector found named '{name}'")
return connectors
@staticmethod
def connectors_type_callback(
context: typer.Context, value: Optional[Union[str, List[str]]]
) -> Optional[Union[Type[servo.BaseConnector], List[Type[servo.BaseConnector]]]]:
"""
Transforms a one or more connector key-paths into Connector types
"""
if value:
if isinstance(value, str):
if connector := servo.connector._connector_class_from_string(value):
return connector
else:
raise typer.BadParameter(
f"no Connector type found for key '{value}'"
)
else:
connectors: List[servo.BaseConnector] = []
for key in value:
if connector := servo.connector._connector_class_from_string(key):
connectors.append(connector)
else:
raise typer.BadParameter(
f"no Connector type found for key '{key}'"
)
return connectors
else:
return None
@staticmethod
def connector_routes_callback(
context: typer.Context, value: Optional[List[str]]
) -> Optional[Dict[str, Type[servo.BaseConnector]]]:
"""
Transforms a one or more connector descriptors into a dict of names to Connectors
"""
if not value:
return None
routes: Dict[str, Type[servo.BaseConnector]] = {}
for key in value:
if ":" in key:
# We have an alias descriptor
name, identifier = key.split(":", 2)
else:
# Vanilla key-path or class name
name = None
identifier = key
if connector_class := servo.connector._connector_class_from_string(
identifier
):
if name is None:
name = connector_class.__default_name__
routes[name] = connector_class
else:
raise typer.BadParameter(
f"no connector found for identifier '{identifier}'"
)
return routes
@staticmethod
def duration_callback(
context: typer.Context, value: Optional[str]
) -> Optional[Union[servo.BaseConnector, List[servo.BaseConnector]]]:
"""
Transform a string into a Duration object.
Parses duration strings.
"""
if not value:
return None
try:
return servo.Duration(value)
except ValueError as e:
raise typer.BadParameter(f"invalid duration parameter: {e}") from e
class ConnectorCLI(CLI):
connector_type: Type[servo.BaseConnector]
# CLI registry
__clis__: Set["CLI"] = set()
def __init__(
self,
connector_type: Type[servo.BaseConnector],
*args,
name: Optional[str] = None,
help: Optional[str] = None,
command_type: Optional[Type[click.Command]] = None,
callback: Optional[Callable] = typer.models.Default(None),
section: Section = Section.commands,
**kwargs,
) -> None: # noqa: D107
# Register for automated inclusion in the ServoCLI
ConnectorCLI.__clis__.add(self)
def connector_callback(
context: Context,
connector: Optional[str] = typer.Option(
None,
"--connector",
"-c",
metavar="CONNECTOR",
help="Connector to activate",
),
) -> None:
if context.servo is None:
raise typer.BadParameter(f"A servo must be selected")
instances = list(filter(lambda c: isinstance(c, connector_type), context.servo.connectors))
instance_count = len(instances)
if instance_count == 0:
raise typer.BadParameter(f"no instances of \"{connector_type.__name__}\" are active the in servo \"{context.servo.name}\"")
elif instance_count == 1:
context.connector = instances[0]
else:
names = []
for instance in instances:
if instance.name == connector:
context.connector = instance
break
names.append(instance.name)
if context.connector is None:
if connector is None:
raise typer.BadParameter(f"multiple instances of \"{connector_type.__name__}\" found in servo \"{context.servo.name}\": select one of {repr(names)}")
else:
raise typer.BadParameter(f"no connector named \"{connector}\" of type \"{connector_type.__name__}\" found in servo \"{context.servo.name}\": select one of {repr(names)}")
if name is None:
name = servo.utilities.strings.commandify(connector_type.__default_name__)
if help is None:
help = connector_type.description
if isinstance(callback, typer.models.DefaultPlaceholder):
callback = connector_callback
super().__init__(
*args,
name=name,
help=help,
command_type=command_type,
callback=callback,
section=section,
**kwargs,
)
class ServoCLI(CLI):
"""
Provides the top-level commandline interface for interacting with the servo.
"""
def __init__(
self,
*args,
name: Optional[str] = "servo",
command_type: Optional[Type[click.Command]] = None,
add_completion: bool = True,
no_args_is_help: bool = True,
**kwargs,
) -> None: # noqa: D107
# NOTE: We pass OrderedGroup to suppress sorting of commands alphabetically
if command_type is None:
command_type = OrderedGroup
super().__init__(
*args,
command_type=command_type,
name=name,
add_completion=add_completion,
no_args_is_help=no_args_is_help,
**kwargs,
)
self.add_commands()
def add_commands(self) -> None:
self.add_ops_commands()
self.add_config_commands()
self.add_assembly_commands()
self.add_connector_commands()
@property
def logger(self) -> loguru.Logger:
return servo.logger
def add_assembly_commands(self) -> None:
@self.command(section=Section.assembly)
def init(
context: Context,
dotenv: bool = typer.Option(
True,
help="Generate .env file",
),
) -> None:
"""
Initialize a servo assembly
"""
if dotenv:
dotenv_file = pathlib.Path(".env")
write_dotenv = True
if dotenv_file.exists():
write_dotenv = typer.confirm(
f"File '{dotenv_file}' already exists. Overwrite it?"
)
if write_dotenv:
optimizer = typer.prompt(
"Opsani optimizer? (format: dev.opsani.com/app-name)",
default=context.optimizer,
)
optimizer != context.optimizer or typer.echo()
token = typer.prompt("API token?", default=context.token)
token != context.token or typer.echo()
dotenv_file.write_text(
f"OPSANI_OPTIMIZER={optimizer}\nOPSANI_TOKEN={token}\nSERVO_LOG_LEVEL=DEBUG\n"
)
typer.echo(".env file initialized")
customize = typer.confirm(
f"Generating servo.yaml. Do you want to select the connectors?"
)
if customize:
types = servo.Assembly.all_connector_types()
types.remove(servo.Servo)
check = bullet.Check(
"\nWhich connectors do you want to activate? [space to (de)select]",
choices=list(map(lambda c: c.name, types)),
check=" √",
indent=0,
margin=4,
align=4,
pad_right=4,
check_color=bullet.colors.bright(bullet.colors.foreground["green"]),
check_on_switch=bullet.colors.bright(
bullet.colors.foreground["black"]
),
background_color=bullet.colors.background["black"],
background_on_switch=bullet.colors.background["white"],
word_color=bullet.colors.foreground["white"],
word_on_switch=bullet.colors.foreground["black"],
)
result = check.launch()
connectors = list(
filter(
None,
map(
lambda c: c.__default_name__ if c.name in result else None,
servo.Assembly.all_connector_types(),
),
)
)
else:
connectors = None
typer_click_object = typer.main.get_group(self)
context.invoke(
typer_click_object.commands["generate"], connectors=connectors
)
show_cli = CLI(name="show", help="Display one or more resources")
@show_cli.command()
def connectors(
context: Context,
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Display verbose info"
),
) -> None:
"""Manage connectors"""
headers = ["NAME", "TYPE", "VERSION", "DESCRIPTION"]
if verbose:
headers += ["HOMEPAGE", "MATURITY", "LICENSE"]
for servo_ in context.assembly.servos:
if context.servo_ and context.servo_ != servo_:
continue
connectors = servo_.all_connectors
table = []
connectors_by_type = {}
for c in connectors:
c_type = c.__class__ if isinstance(c, servo.BaseConnector) else c
c_list = connectors_by_type.get(c_type, [])
c_list.append(c)
connectors_by_type[c_type] = c_list
for connector_type in connectors_by_type.keys():
names = list(
map(lambda c: c.name, connectors_by_type[connector_type])
)
row = [
"\n".join(names),
connector_type.name,
connector_type.version,
connector_type.description,
]
if verbose:
row += [
connector_type.homepage,
connector_type.maturity,
connector_type.license,
]
table.append(row)
if len(context.assembly.servos) > 1:
typer.echo(f"{servo_.name}")
typer.echo(tabulate(table, headers, tablefmt="plain") + "\n")
@show_cli.command()
def components(context: Context) -> None:
"""Display adjustable components"""
for servo_ in context.assembly.servos:
if context.servo_ and context.servo_ != servo_:
continue
results = run_async(servo_.dispatch_event(servo.Events.components))
headers = ["COMPONENT", "SETTINGS", "CONNECTOR"]
table = []
for result in results:
for component in result.value:
settings_list = sorted(
list(
map(
lambda s: f"{s.name}={s.human_readable_value} {s.summary()}",
component.settings,
)
)
)
row = [
component.name,
"\n".join(settings_list),
result.connector.name,
]
table.append(row)
if len(context.assembly.servos) > 1:
typer.echo(f"{servo_.name}")
typer.echo(tabulate(table, headers, tablefmt="plain") + "\n")
@show_cli.command()
def events(
context: Context,
all: bool = typer.Option(
None,
"--all",
"-a",
help="Include models from all available connectors",
),
by_connector: bool = typer.Option(
None,
"--by-connector",
"-c",
help="Display output by connector instead of event",
),
before: bool = typer.Option(
None,
help="Display before event handlers",
),
on: bool = typer.Option(
None,
help="Display on event handlers",
),
after: bool = typer.Option(
None,
help="Display after event handlers",
),
) -> None:
"""
Display event handler info
"""
for servo_ in context.assembly.servos:
if context.servo and context.servo != servo_:
continue
event_handlers: List[servo.EventHandler] = []
connectors = (
context.assembly.all_connector_types()
if all
else servo_.all_connectors
)
for connector in connectors:
event_handlers.extend(connector.__event_handlers__)
# If we have switched any on the preposition only include explicitly flagged
preposition_switched = list(
filter(lambda s: s is not None, (before, on, after))
)
if preposition_switched:
if False in preposition_switched:
# Handle explicit exclusions
prepositions = [
servo.Preposition.before,
servo.Preposition.on,
servo.Preposition.after,
]
if before == False:
prepositions.remove(servo.Preposition.before)
if on == False:
prepositions.remove(servo.Preposition.on)
if after == False:
prepositions.remove(servo.Preposition.after)
else:
# Add explicit inclusions
prepositions = []
if before:
prepositions.append(servo.Preposition.before)
if on:
prepositions.append(servo.Preposition.on)
if after:
prepositions.append(servo.Preposition.after)
else:
prepositions = [
servo.Preposition.before,
servo.Preposition.on,
servo.Preposition.after,
]
sorted_event_names = sorted(
list(set(map(lambda handler: handler.event.name, event_handlers)))
)
table = []
if by_connector:
headers = ["CONNECTOR", "EVENTS"]
connector_types_by_name = dict(
map(
lambda handler: (
handler.connector_type.name,
connector,
),
event_handlers,
)
)
sorted_connector_names = sorted(connector_types_by_name.keys())