-
Notifications
You must be signed in to change notification settings - Fork 41
/
generic.py
1424 lines (1196 loc) · 46.1 KB
/
generic.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
import datetime
import json
import re
from functools import lru_cache, wraps
from typing import IO, Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union
import click
import schema as s
import yaml
from click.decorators import FC, F
from pulp_glue.common.context import (
DATETIME_FORMATS,
DEFAULT_LIMIT,
EntityDefinition,
EntityFieldDefinition,
PluginRequirement,
PulpACSContext,
PulpContentContext,
PulpContext,
PulpDistributionContext,
PulpEntityContext,
PulpException,
PulpNoWait,
PulpRemoteContext,
PulpRepositoryContext,
PulpRepositoryVersionContext,
)
from pulp_glue.common.i18n import get_translation
try:
from pygments import highlight
from pygments.formatters import Terminal256Formatter
from pygments.lexers import JsonLexer, YamlLexer
except ImportError:
PYGMENTS = False
else:
PYGMENTS = True
PYGMENTS_STYLE = "solarized-dark"
translation = get_translation(__name__)
_ = translation.gettext
class IncompatibleContext(click.UsageError):
pass
class ClickNoWait(click.ClickException):
exit_code = 0
def show(self, file: Optional[IO[str]] = None) -> None:
"""
Format the message into file or STDERR.
Overwritten from base class to not print "Error: ".
"""
if file is None:
file = click.get_text_stream("stderr")
click.echo(self.format_message(), file=file)
class PulpJSONEncoder(json.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, datetime.datetime):
return obj.isoformat()
else:
return super().default(obj)
class PulpCLIContext(PulpContext):
"""
Subclass of the Context that overwrites the CLI specifics.
"""
def __init__(
self,
api_root: str,
api_kwargs: Dict[str, Any],
background_tasks: bool,
timeout: int,
format: str,
domain: str = "default",
) -> None:
super().__init__(
api_root=api_root,
api_kwargs=api_kwargs,
background_tasks=background_tasks,
timeout=timeout,
domain=domain,
)
self.format = format
def echo(self, message: str, nl: bool = True, err: bool = False) -> None:
click.echo(message, nl=nl, err=err)
def prompt(self, text: str, hide_input: bool = False) -> Any:
return click.prompt(text, hide_input=hide_input)
def output_result(self, result: Any) -> None:
"""
Dump the provided result to the console using the selected renderer
"""
if self.format == "json":
output = json.dumps(result, cls=PulpJSONEncoder, indent=(2 if self.isatty else None))
if PYGMENTS and self.isatty:
output = highlight(output, JsonLexer(), Terminal256Formatter(style=PYGMENTS_STYLE))
self.echo(output)
elif self.format == "yaml":
output = yaml.dump(result)
if PYGMENTS and self.isatty:
output = highlight(output, YamlLexer(), Terminal256Formatter(style=PYGMENTS_STYLE))
self.echo(output)
elif self.format == "none":
pass
else:
raise NotImplementedError(
_("Format '{format}' not implemented.").format(format=self.format)
)
##############################################################################
# Decorator to access certain contexts
pass_pulp_context = click.make_pass_decorator(PulpCLIContext)
pass_entity_context = click.make_pass_decorator(PulpEntityContext)
pass_repository_context = click.make_pass_decorator(PulpRepositoryContext)
pass_repository_version_context = click.make_pass_decorator(PulpRepositoryVersionContext)
pass_content_context = click.make_pass_decorator(PulpContentContext)
##############################################################################
# Custom types for parameters
def int_or_empty(value: str) -> Union[str, int]:
if value == "":
return ""
else:
return int(value)
int_or_empty.__name__ = "int or empty"
def float_or_empty(value: str) -> Union[str, float]:
if value == "":
return ""
else:
return float(value)
float_or_empty.__name__ = "float or empty"
##############################################################################
# Custom classes for commands and parameters
class PulpCommand(click.Command):
def __init__(
self,
*args: Any,
allowed_with_contexts: Optional[Tuple[Type[PulpEntityContext]]] = None,
needs_plugins: Optional[List[PluginRequirement]] = None,
**kwargs: Any,
):
self.allowed_with_contexts = allowed_with_contexts
self.needs_plugins = needs_plugins
super().__init__(*args, **kwargs)
def invoke(self, ctx: click.Context) -> Any:
try:
if self.needs_plugins:
pulp_ctx = ctx.find_object(PulpCLIContext)
assert pulp_ctx is not None
for plugin_requirement in self.needs_plugins:
pulp_ctx.needs_plugin(plugin_requirement)
return super().invoke(ctx)
except PulpException as e:
raise click.ClickException(str(e))
except PulpNoWait as e:
raise ClickNoWait(str(e))
def get_short_help_str(self, limit: int = 45) -> str:
return self.short_help or ""
def format_help_text(
self, ctx: click.Context, formatter: click.formatting.HelpFormatter
) -> None:
if self.help is not None:
entity_ctx = ctx.find_object(PulpEntityContext)
if entity_ctx is not None:
self.help = self.help.format(entity=entity_ctx.ENTITY, entities=entity_ctx.ENTITIES)
super().format_help_text(ctx, formatter)
def get_params(self, ctx: click.Context) -> List[click.Parameter]:
params = super().get_params(ctx)
new_params: List[click.Parameter] = []
for param in params:
if isinstance(param, PulpOption):
if param.allowed_with_contexts is not None:
if not isinstance(ctx.obj, param.allowed_with_contexts):
continue
new_params.append(param)
return new_params
class PulpGroup(PulpCommand, click.Group):
command_class = PulpCommand
group_class = type
def get_command(self, ctx: click.Context, cmd_name: str) -> Optional[click.Command]:
# Overwriting this removes the command from the help message and from being callable
cmd = super().get_command(ctx, cmd_name)
if isinstance(cmd, (PulpCommand, PulpGroup)):
if cmd.allowed_with_contexts is not None:
if not isinstance(ctx.obj, cmd.allowed_with_contexts):
raise IncompatibleContext(
_("The subcommand '{name}' is not available in this context.").format(
name=cmd.name
)
)
return cmd
def list_commands(self, ctx: click.Context) -> List[str]:
commands_filtered_by_context = []
for name, cmd in self.commands.items():
if isinstance(cmd, (PulpCommand, PulpGroup)):
if cmd.allowed_with_contexts is None or isinstance(
ctx.obj, cmd.allowed_with_contexts
):
commands_filtered_by_context.append(name)
return sorted(commands_filtered_by_context)
def pulp_command(name: Optional[str] = None, **kwargs: Any) -> Callable[[F], click.Command]:
return click.command(name=name, cls=PulpCommand, **kwargs)
def pulp_group(name: Optional[str] = None, **kwargs: Any) -> Callable[[F], click.Group]:
return click.group(name=name, cls=PulpGroup, **kwargs)
class PulpOption(click.Option):
def __init__(
self,
*args: Any,
needs_plugins: Optional[List[PluginRequirement]] = None,
allowed_with_contexts: Optional[Tuple[Type[PulpEntityContext]]] = None,
**kwargs: Any,
):
self.needs_plugins = needs_plugins
self.allowed_with_contexts = allowed_with_contexts
super().__init__(*args, **kwargs)
def process_value(self, ctx: click.Context, value: Any) -> Any:
if value is not None and self.needs_plugins:
pulp_ctx = ctx.find_object(PulpCLIContext)
assert pulp_ctx is not None
for plugin_requirement in self.needs_plugins:
if not plugin_requirement.feature:
plugin_requirement = PluginRequirement(
plugin_requirement.name,
plugin_requirement.min,
plugin_requirement.max,
feature=_("the {name} option").format(name=self.name),
inverted=plugin_requirement.inverted,
)
pulp_ctx.needs_plugin(plugin_requirement)
return super().process_value(ctx, value)
def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
tmp = super().get_help_record(ctx)
if tmp is None:
return None
synopsis, help_text = tmp
entity_ctx = ctx.find_object(PulpEntityContext)
if entity_ctx is not None:
help_text = help_text.format(entity=entity_ctx.ENTITY, entities=entity_ctx.ENTITIES)
return synopsis, help_text
class GroupOption(PulpOption):
def __init__(self, *args: Any, **kwargs: Any) -> None:
self.group: List[str] = kwargs.pop("group")
assert self.group, "'group' parameter required"
kwargs["help"] = (
kwargs.get("help", "")
+ " "
+ _("Option is grouped with {option_list}.").format(option_list=", ".join(self.group))
).strip()
super().__init__(*args, **kwargs)
def handle_parse_result(
self, ctx: click.Context, opts: Mapping[str, Any], args: List[Any]
) -> Any:
assert self.name is not None
all_options = self.group + [self.name]
options_present = [x for x in all_options if x in opts]
num_options = len(options_present)
if num_options != len(all_options) and (num_options != 0 or self.required):
raise click.UsageError(
_("Illegal usage, please specify all options in the group: {option_list}").format(
option_list=", ".join(all_options)
)
)
self.prompt = None
value = opts.get(self.name)
if self.callback is not None and num_options != 0:
value = self.callback(ctx, self, {o: opts[o] for o in options_present})
if self.expose_value:
ctx.params[self.name] = value
return value, args
##############################################################################
# Option callbacks
@lru_cache(typed=True)
def lookup_callback(
attribute: str, context_class: Type[PulpEntityContext] = PulpEntityContext
) -> Callable[[click.Context, click.Parameter, Optional[str]], Optional[str]]:
def _callback(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Optional[str]:
if value is not None:
if value == "":
value = "null"
entity_ctx = ctx.find_object(context_class)
assert entity_ctx is not None
entity_ctx.entity = {attribute: value}
return value
return _callback
def href_callback(
context_class: Type[PulpEntityContext] = PulpEntityContext,
) -> Callable[[click.Context, click.Parameter, Optional[str]], Optional[str]]:
def _href_callback(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Optional[str]:
if value is not None:
entity_ctx = ctx.find_object(context_class)
assert entity_ctx is not None
entity_ctx.pulp_href = value
return value
return _href_callback
def _version_callback(
ctx: click.Context, param: click.Parameter, value: Optional[int]
) -> Optional[int]:
entity_ctx = ctx.find_object(PulpEntityContext)
assert entity_ctx is not None
repository_ctx = ctx.find_object(PulpRepositoryContext)
assert repository_ctx is not None
if value is not None:
entity_ctx.pulp_href = f"{repository_ctx.entity['versions_href']}{value}/"
else:
entity_ctx.pulp_href = repository_ctx.entity["latest_version_href"]
return value
def load_file_wrapper(handler: Callable[[click.Context, click.Parameter, str], Any]) -> Any:
"""A wrapper that used for chaining or decorating callbacks that manipulate with input data."""
@wraps(handler)
def _load_file_or_string_wrapper(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Any:
"""Load the string from input, or from file if the value starts with @."""
if not value:
return value
if value.startswith("@"):
the_file = value[1:]
try:
with click.open_file(the_file, "r") as fp:
the_content = fp.read()
except OSError:
raise click.ClickException(
_("Failed to load content from {file}").format(file=the_file)
)
else:
the_content = value
return handler(ctx, param, the_content)
return _load_file_or_string_wrapper
load_string_callback = load_file_wrapper(lambda c, p, x: x)
def json_callback(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> Any:
if value is None:
return None
try:
json_object = json.loads(value)
except json.decoder.JSONDecodeError:
raise click.ClickException(_("Failed to decode JSON"))
else:
return json_object
load_json_callback = load_file_wrapper(json_callback)
def load_labels_callback(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Optional[Dict[str, str]]:
if value is None:
return value
value = load_json_callback(ctx, param, value)
if isinstance(value, dict) and all(
(isinstance(key, str) and isinstance(val, str) for key, val in value.items())
):
return value
raise click.ClickException(_("Labels must be provided as a dictionary of strings."))
def create_content_json_callback(
context_class: Optional[Type[PulpContentContext]] = None, schema: s.Schema = None
) -> Any:
@load_file_wrapper
def _callback(
ctx: click.Context, param: click.Parameter, value: str
) -> Optional[List[PulpContentContext]]:
ctx_class = context_class
new_value = json_callback(ctx, param, value)
if new_value is not None:
if schema is not None:
try:
schema.validate(new_value)
except s.SchemaError as e:
raise click.ClickException(
_("Validation of '{parameter}' failed: {error}").format(
parameter=param.name, error=str(e)
)
)
pulp_ctx = ctx.find_object(PulpCLIContext)
assert pulp_ctx is not None
if ctx_class is None:
context = ctx.find_object(PulpContentContext)
assert context is not None
ctx_class = type(context)
return [ctx_class(pulp_ctx, entity=unit) for unit in new_value]
return new_value
return _callback
# based on https://stackoverflow.com/a/42865957/2002471
units = {"B": 1, "KB": 10**3, "MB": 10**6, "GB": 10**9, "TB": 10**12}
def parse_size_callback(ctx: click.Context, param: click.Parameter, value: str) -> int:
size = value.strip().upper()
match = re.match(r"^([0-9]+)\s*([KMGT]?B)?$", size)
if not match:
raise click.ClickException("Please pass in a valid size of form: [0-9] [K/M/G/T]B")
number, unit = match.groups(default="B")
return int(float(number) * units[unit])
def null_callback(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Optional[str]:
if value == "":
return "null"
return value
##############################################################################
# Decorator common options
def pulp_option(*args: Any, **kwargs: Any) -> Callable[[FC], FC]:
kwargs["cls"] = PulpOption
return click.option(*args, **kwargs)
domain_pattern = r"(?P<pulp_domain>[-a-zA-Z0-9_]+)"
def resource_lookup_option(*args: Any, **kwargs: Any) -> Callable[[FC], FC]:
lookup_key: str = kwargs.pop("lookup_key", "name")
context_class: Type[PulpEntityContext] = kwargs.pop("context_class")
def _option_callback(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> EntityFieldDefinition:
# Pass None and "" verbatim
if not value:
return value
pulp_ctx = ctx.find_object(PulpCLIContext)
assert pulp_ctx is not None
entity_ctx = ctx.find_object(context_class)
assert entity_ctx is not None
if value.startswith("/"):
# The HREF of a resource was passed
href_pattern = entity_ctx.HREF_PATTERN
if pulp_ctx.domain_enabled:
pattern = rf"^{pulp_ctx._api_root}{domain_pattern}/api/v3/{href_pattern}"
else:
pattern = rf"^{pulp_ctx.api_path}{href_pattern}"
match = re.match(pattern, value)
if match:
entity_ctx.pulp_href = value
else:
raise click.ClickException(
_("'{value}' is not a valid href for {option_name}.").format(
value=value, option_name=param.name
)
)
else:
# The named identity of a resource was passed
entity_ctx.entity = {lookup_key: value}
return entity_ctx
if "cls" not in kwargs:
kwargs["cls"] = PulpOption
kwargs["callback"] = _option_callback
kwargs["expose_value"] = False
if "help" not in kwargs:
kwargs["help"] = _("A resource to look for identified by <name> or by <href>.")
return click.option(*args, **kwargs)
def resource_option(*args: Any, **kwargs: Any) -> Callable[[FC], FC]:
default_plugin: Optional[str] = kwargs.pop("default_plugin", None)
default_type: Optional[str] = kwargs.pop("default_type", None)
lookup_key: str = kwargs.pop("lookup_key", "name")
context_table: Dict[str, Type[PulpEntityContext]] = kwargs.pop("context_table")
capabilities: Optional[List[str]] = kwargs.pop("capabilities", None)
href_pattern: Optional[str] = kwargs.pop("href_pattern", None)
parent_resource_lookup: Optional[Tuple[str, Type[PulpEntityContext]]] = kwargs.pop(
"parent_resource_lookup", None
)
def _option_callback(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> EntityFieldDefinition:
# Pass None and "" verbatim
if not value:
return value
pulp_href: Optional[str] = None
entity: Optional[EntityDefinition] = None
pulp_ctx = ctx.find_object(PulpCLIContext)
assert pulp_ctx is not None
if value.startswith("/"):
# An href was passed
if href_pattern is None:
raise click.ClickException(
_("The option {option_name} does not support href.").format(
option_name=param.name
)
)
if pulp_ctx.domain_enabled:
pattern = rf"^{pulp_ctx._api_root}{domain_pattern}/api/v3/{href_pattern}"
else:
pattern = rf"^{pulp_ctx.api_path}{href_pattern}"
match = re.match(pattern, value)
if match is None:
raise click.ClickException(
_("'{value}' is not a valid href for {option_name}.").format(
value=value, option_name=param.name
)
)
match_groups = match.groupdict(default="")
plugin = match_groups.get("plugin", "")
resource_type = match_groups.get("resource_type", "")
pulp_href = value
else:
# A natural key identifier was passed
split_value = value.split(":", maxsplit=2)
while len(split_value) < 3:
split_value.insert(0, "")
plugin, resource_type, identifier = split_value
entity = {lookup_key: identifier}
if resource_type == "":
if default_type is None:
raise click.ClickException(
_("A resource type must be specified with the {option_name} option.").format(
option_name=param.name
)
)
resource_type = default_type
if plugin == "":
if default_plugin is None:
raise click.ClickException(
_("A plugin must be specified with the {option_name} option.").format(
option_name=param.name
)
)
plugin = default_plugin
context_class = context_table.get(plugin + ":" + resource_type)
if context_class is None:
raise click.ClickException(
_(
"The type '{plugin}:{resource_type}' "
"is not valid for the {option_name} option."
).format(plugin=plugin, resource_type=resource_type, option_name=param.name)
)
entity_ctx: PulpEntityContext = context_class(pulp_ctx, pulp_href=pulp_href, entity=entity)
if capabilities is not None:
for capability in capabilities:
if not entity_ctx.capable(capability):
raise click.ClickException(
_(
"The type '{plugin}:{resource_type}' "
"does not support the '{capability}' capability."
).format(plugin=plugin, resource_type=resource_type, capability=capability)
)
if parent_resource_lookup:
parent_lookup_key, parent_context_type = parent_resource_lookup
parent_ctx = ctx.find_object(parent_context_type)
assert parent_ctx is not None
parent_ctx.entity = {parent_lookup_key: entity_ctx}
return entity_ctx
def _multi_option_callback(
ctx: click.Context, param: click.Parameter, value: Iterable[Optional[str]]
) -> Iterable[EntityFieldDefinition]:
if value:
return (_option_callback(ctx, param, item) for item in value)
return tuple()
if "cls" not in kwargs:
kwargs["cls"] = PulpOption
if kwargs.get("multiple"):
kwargs["callback"] = _multi_option_callback
else:
kwargs["callback"] = _option_callback
if "help" not in kwargs:
kwargs["help"] = _(
"Referenced resource, in the form {plugin_form}{type_form}<name> or by href. "
"{plugin_default}{type_default}"
).format(
plugin_form=_("[<plugin>:]") if default_plugin else _("<plugin>:"),
type_form=_("[<resource_type>:]") if default_type else _("<resource_type>:"),
plugin_default=_("'<plugin>' defaults to {plugin}. ").format(plugin=default_plugin)
if default_plugin
else "",
type_default=_("'<resource_type>' defaults to {type}. ").format(type=default_type)
if default_type
else "",
)
return click.option(*args, **kwargs)
def type_option(*args: Any, **kwargs: Any) -> Callable[[FC], FC]:
choices: Dict[str, Type[PulpEntityContext]] = kwargs.pop("choices")
assert choices and isinstance(choices, dict)
type_names = list(choices.keys())
case_sensitive = kwargs.pop("case_sensitive", False)
defaults = {
"cls": PulpOption,
"default": type_names[0],
"is_eager": True,
"expose_value": False,
}
def _type_callback(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> str:
pulp_ctx = ctx.find_object(PulpCLIContext)
assert pulp_ctx
if value is not None:
cls = choices[value]
assert issubclass(cls, PulpEntityContext)
ctx.obj = cls(pulp_ctx)
return value
raise NotImplementedError()
for k, v in defaults.items():
if k not in kwargs:
kwargs[k] = v
if not args:
args = ("-t", "--type", "entity_type")
kwargs["callback"] = _type_callback
kwargs["type"] = click.types.Choice(type_names, case_sensitive=case_sensitive)
return click.option(*args, **kwargs)
limit_option = pulp_option(
"--limit",
default=DEFAULT_LIMIT,
type=click.IntRange(1),
help=_("Limit the number of {entities} to show."),
)
offset_option = pulp_option(
"--offset",
default=0,
type=int,
help=_("Skip a number of {entities} to show."),
)
ordering_option = pulp_option(
"--ordering",
multiple=True,
required=False,
help=_("A field that will be used to order the results. Can be specified multiple times."),
)
field_option = pulp_option(
"--field",
"fields",
multiple=True,
required=False,
help=_("A field that is to be selected from a result. Can be specified multiple times."),
)
exclude_field_option = pulp_option(
"--exclude-field",
"exclude_fields",
multiple=True,
required=False,
help=_("A field that is to be excluded from a result. Can be specified multiple times."),
)
href_option = pulp_option(
"--href",
help=_("HREF of the {entity}"),
callback=href_callback(),
expose_value=False,
)
name_option = pulp_option(
"--name",
help=_("Name of the {entity}"),
callback=lookup_callback("name"),
expose_value=False,
)
name_filter_option = pulp_option(
"--name",
help=_("Filter {entity} by exact name"),
)
name_contains_option = pulp_option(
"--name-contains",
"name__contains",
help=_("Filter {entity} results where name contains value"),
)
name_icontains_option = pulp_option(
"--name-icontains",
"name__icontains",
help=_("Filter {entity} results where name contains value, case insensitive"),
)
name_in_option = pulp_option(
"--name-in",
"name__in",
multiple=True,
help=_("Filter {entity} by name. Can be specified multiple times"),
)
repository_href_option = click.option(
"--repository-href",
help=_("HREF of the repository"),
callback=href_callback(PulpRepositoryContext),
expose_value=False,
)
repository_option = click.option(
"--repository",
help=_("Name of the repository"),
callback=lookup_callback("name", PulpRepositoryContext),
expose_value=False,
)
repository_lookup_option = resource_lookup_option(
"--repository",
context_class=PulpRepositoryContext,
)
remote_lookup_option = resource_lookup_option(
"--remote",
context_class=PulpRemoteContext,
)
distribution_lookup_option = resource_lookup_option(
"--distribution",
context_class=PulpDistributionContext,
)
acs_lookup_option = resource_lookup_option(
"--acs",
context_class=PulpACSContext,
)
version_option = click.option(
"--version",
help=_("Repository version number"),
type=int,
callback=_version_callback,
expose_value=False,
)
label_select_option = pulp_option(
"--label-select",
"pulp_label_select",
help=_("Filter {entities} by a label search query."),
type=str,
)
base_path_option = pulp_option(
"--base-path",
help=_("Base-path of the {entity}"),
type=str,
)
base_path_contains_option = pulp_option(
"--base-path-contains",
"base_path__icontains",
help=_("{entity} base-path contains search"),
type=str,
)
content_in_option = pulp_option(
"--content",
"content__in",
help=_(
"Search for {entities} with these content hrefs in them (JSON list or "
"@file containing a JSON list)"
),
callback=load_json_callback,
)
chunk_size_option = pulp_option(
"--chunk-size",
help=_("Chunk size to break up {entity} into. Defaults to 1MB"),
default="1MB",
callback=parse_size_callback,
)
pulp_created_gte_option = pulp_option(
"--created-after",
"pulp_created__gte",
help=_("Search for {entities} created at or after this date"),
type=click.DateTime(formats=DATETIME_FORMATS),
)
pulp_created_lte_option = pulp_option(
"--created-before",
"pulp_created__lte",
help=_("Search for {entities} created at or before this date"),
type=click.DateTime(formats=DATETIME_FORMATS),
)
pulp_last_updated_gte_option = pulp_option(
"--updated-after",
"pulp_last_updated__gte",
help=_("Search for {entities} last updated at or after this date"),
type=click.DateTime(formats=DATETIME_FORMATS),
)
pulp_last_updated_lte_option = pulp_option(
"--updated-before",
"pulp_last_updated__lte",
help=_("Search for {entities} last updated at or before this date"),
type=click.DateTime(formats=DATETIME_FORMATS),
)
retained_versions_option = pulp_option(
"--retain-repo-versions",
needs_plugins=[PluginRequirement("core", min="3.13.0")],
help=_("Number of repository versions to keep."),
type=int,
)
pulp_labels_option = pulp_option(
"--labels",
"pulp_labels",
help=_(
"JSON dictionary of labels to set on {entity} (or " "@file containing a JSON dictionary)"
),
callback=load_labels_callback,
)
name_filter_options = [
name_filter_option,
name_contains_option,
name_icontains_option,
name_in_option,
]
remote_filter_options = name_filter_options + [
label_select_option,
pulp_last_updated_gte_option,
pulp_last_updated_lte_option,
]
distribution_filter_options = name_filter_options + [
label_select_option,
base_path_option,
base_path_contains_option,
]
common_distribution_create_options = [
click.option("--name", required=True),
click.option("--base-path", required=True),
]
publication_filter_options = [
content_in_option,
pulp_created_gte_option,
pulp_created_lte_option,
pulp_option("--repository-version", help=_("Search {entities} by repository version HREF")),
]
common_remote_create_options = [
click.option("--name", required=True),
click.option("--url", required=True),
click.option(
"--ca-cert",
help=_("a PEM encoded CA certificate or @file containing same"),
callback=load_string_callback,
),
click.option(
"--client-cert",
help=_("a PEM encoded client certificate or @file containing same"),
callback=load_string_callback,
),
click.option(
"--client-key",
help=_("a PEM encode private key or @file containing same"),
callback=load_string_callback,
),
click.option("--connect-timeout", type=float),
click.option(
"--download-concurrency", type=int, help=_("total number of simultaneous connections")
),
click.option(
"--password",
help=_(
"The password to authenticate to the remote (can contain leading and trailing spaces)."
),
),
click.option("--proxy-url"),
click.option("--proxy-username"),
click.option(
"--proxy-password",
help=_(
"The password to authenticate to the proxy (can contain leading and trailing spaces)."
),
),
click.option("--rate-limit", type=int, help=_("limit download rate in requests per second")),
click.option("--sock-connect-timeout", type=float),
click.option("--sock-read-timeout", type=float),
click.option("--tls-validation", type=bool),
click.option("--total-timeout", type=float),
click.option("--username"),
click.option(
"--max-retries",
type=int,
help=_("maximum number of retry attemts after a download failure"),
),
pulp_labels_option,
]
common_remote_update_options = [
click.option("--url"),
click.option(
"--ca-cert",
help=_("a PEM encoded CA certificate or @file containing same"),
callback=load_string_callback,
),
click.option(
"--client-cert",
help=_("a PEM encoded client certificate or @file containing same"),
callback=load_string_callback,
),
click.option(
"--client-key",