forked from pulp/pulp-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric.py
More file actions
1880 lines (1579 loc) · 62.7 KB
/
generic.py
File metadata and controls
1880 lines (1579 loc) · 62.7 KB
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 asyncio
import datetime
import json
import re
import sys
import typing as t
from contextlib import closing
from functools import lru_cache, wraps
import click
import schema as s
import yaml
from pulp_glue.common.authentication import AuthProviderBase
from pulp_glue.common.context import (
DATETIME_FORMATS,
DEFAULT_LIMIT,
EntityDefinition,
EntityFieldDefinition,
PluginRequirement,
PulpACSContext,
PulpContentContext,
PulpContentGuardContext,
PulpContext,
PulpDistributionContext,
PulpEntityContext,
PulpRemoteContext,
PulpRepositoryContext,
PulpRepositoryVersionContext,
PulpViewSetContext,
)
from pulp_glue.common.exceptions import PulpException, PulpNoWait
from pulp_glue.common.i18n import get_translation
if sys.version_info >= (3, 13):
from warnings import deprecated
else:
T = t.TypeVar("T")
def deprecated(s: str) -> t.Callable[[T], T]:
def _inner(f: T) -> T:
return f
return _inner
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"
try:
import secretstorage
except ImportError:
SECRET_STORAGE = False
else:
SECRET_STORAGE = True
try:
# Sentinel is introduced in click 8.3.
# We need to use it to identify unset values.
_UNSET = click._utils.Sentinel.UNSET # type: ignore[attr-defined]
def _unset(value: t.Any) -> bool:
return value is _UNSET or value is None or value == () or value == []
except AttributeError:
def _unset(value: t.Any) -> bool:
return value is None or value == () or value == []
translation = get_translation(__package__)
_ = translation.gettext
_AnyCallable = t.Callable[..., t.Any]
FC = t.TypeVar("FC", bound=_AnyCallable | click.Command)
HEADER_REGEX = r"^[-a-zA-Z0-9_]+:.+$"
prn_regex = re.compile(
r"^prn:(?P<app>[a-z][a-z0-9-_]*)\.(?P<model>[a-z][a-z0-9_]*):(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$", # noqa: E501
)
class IncompatibleContext(click.UsageError):
"""Exception to signal that an option or subcommand was used with an incompatible context."""
class ClickNoWait(click.ClickException):
"""Exception raised when a user interrupts waiting for a task/taskgroup."""
exit_code = 0
def show(self, file: t.IO[str] | None = 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: t.Any) -> t.Any:
if isinstance(obj, datetime.datetime):
return obj.isoformat()
else:
return super().default(obj)
def _none_formatter(result: t.Any) -> str:
return ""
def _json_formatter(result: t.Any) -> str:
isatty = sys.stdout.isatty()
output = json.dumps(result, cls=PulpJSONEncoder, indent=(2 if isatty else None))
if PYGMENTS and isatty:
output = highlight(output, JsonLexer(), Terminal256Formatter(style=PYGMENTS_STYLE))
return output
def _yaml_formatter(result: t.Any) -> str:
isatty = sys.stdout.isatty()
output = yaml.dump(result)
if PYGMENTS and isatty:
output = highlight(output, YamlLexer(), Terminal256Formatter(style=PYGMENTS_STYLE))
return output
REGISTERED_OUTPUT_FORMATTERS = {
"none": _none_formatter,
"json": _json_formatter,
"yaml": _yaml_formatter,
}
class PulpCLIContext(PulpContext):
"""
Subclass of the Context that overwrites the CLI specifics.
Parameters:
api_root: The base url (excluding "api/v3/") to the server's api.
api_kwargs: Extra arguments to pass to the wrapped `OpenAPI` object.
background_tasks: Whether to wait for tasks. If `True`, all tasks triggered will
immediately raise `PulpNoWait`.
timeout: Limit of time (in seconds) to wait for unfinished tasks.
format: The format to be used by `output_result`.
domain: Name of the domain to interact with.
"""
def __init__(
self,
api_root: str,
api_kwargs: dict[str, t.Any],
background_tasks: bool,
timeout: int,
format: str,
domain: str = "default",
username: str | None = None,
password: str | None = None,
cert: str | None = None,
key: str | None = None,
oauth2_client_id: str | None = None,
oauth2_client_secret: str | None = None,
chunk_size: int | None = None,
) -> None:
self.username = username
self.password = password
self.oauth2_client_id = oauth2_client_id
self.oauth2_client_secret = oauth2_client_secret
self.cert = cert
self.key = key
api_kwargs["auth_provider"] = PulpCLIAuthProvider(pulp_ctx=self)
verify_ssl: bool | None = api_kwargs.pop("verify_ssl", None)
super().__init__(
api_root=api_root,
api_kwargs=api_kwargs,
verify_ssl=verify_ssl,
background_tasks=background_tasks,
timeout=timeout,
domain=domain,
chunk_size=chunk_size,
)
self.format = format
def echo(self, message: str, nl: bool = True, err: bool = False) -> None:
click.echo(message, nl=nl, err=err)
def output_result(self, result: t.Any) -> None:
"""
Dump the provided result to the console using the selected renderer.
arguments:
result: JSON serializable data to be outputted.
"""
try:
formatter = REGISTERED_OUTPUT_FORMATTERS[self.format]
except KeyError:
raise NotImplementedError(
_("Format '{format}' not implemented.").format(format=self.format)
)
click.echo(formatter(result))
class PulpCLIAuthProvider(AuthProviderBase):
"""
The auth provider using cli promts to ask for missing passwords.
"""
def __init__(self, pulp_ctx: PulpCLIContext):
super().__init__()
self.pulp_ctx = pulp_ctx
self._http_basic: tuple[bytes, bytes] | None = None
self._password_in_secretstorage: bool | None = None
self._oauth2_client_credentials: tuple[bytes, bytes] | None = None
def can_complete_http_basic(self) -> bool:
return self.pulp_ctx.username is not None
def can_complete_oauth2_client_credentials(self, scopes: list[str]) -> bool:
return self.pulp_ctx.oauth2_client_id is not None
def can_complete_mutualTLS(self) -> bool:
return self.pulp_ctx.cert is not None
def _fetch_password(self) -> bytes:
if SECRET_STORAGE:
assert self.pulp_ctx.username is not None
secret_attr: dict[str, str] = {
"service": "pulp-cli",
"base_url": self.pulp_ctx.api.base_url,
"api_path": self.pulp_ctx.api_path,
"username": self.pulp_ctx.username,
}
with closing(secretstorage.dbus_init()) as connection:
collection = secretstorage.get_default_collection(connection)
item = next(collection.search_items(secret_attr), None)
if item:
password = item.get_secret()
self._password_in_secretstorage = True
else:
password = click.prompt("Password", hide_input=True).encode("latin1")
self._password_in_secretstorage = False
else:
password = click.prompt("Password", hide_input=True).encode("latin1")
return password
async def http_basic_credentials(self) -> tuple[bytes, bytes]:
if self._http_basic is None:
assert self.pulp_ctx.username is not None
if self.pulp_ctx.password is not None:
password = self.pulp_ctx.password.encode("latin1")
else:
password = await asyncio.get_running_loop().run_in_executor(
None, self._fetch_password
)
self._http_basic = self.pulp_ctx.username.encode("latin1"), password
return self._http_basic
def _save_password_to_storage(self) -> None:
if click.confirm(_("Add password to password manager?")):
with closing(secretstorage.dbus_init()) as connection:
assert self.pulp_ctx.username is not None
assert self._http_basic is not None
secret_attr: dict[str, str] = {
"service": "pulp-cli",
"base_url": self.pulp_ctx.api.base_url,
"api_path": self.pulp_ctx.api_path,
"username": self.pulp_ctx.username,
}
password = self._http_basic[1]
collection = secretstorage.get_default_collection(connection)
collection.create_item("Pulp CLI", secret_attr, password, replace=True)
async def auth_success_hook(self, **kwargs: t.Any) -> None:
if SECRET_STORAGE and self._password_in_secretstorage is False:
await asyncio.get_running_loop().run_in_executor(None, self._save_password_to_storage)
self._password_in_secretstorage = None
def _remove_password_from_storage(self) -> None:
if click.confirm(_("Remove failed password from password manager?")):
with closing(secretstorage.dbus_init()) as connection:
assert self.pulp_ctx.username is not None
secret_attr: dict[str, str] = {
"service": "pulp-cli",
"base_url": self.pulp_ctx.api.base_url,
"api_path": self.pulp_ctx.api_path,
"username": self.pulp_ctx.username,
}
collection = secretstorage.get_default_collection(connection)
item = next(collection.search_items(secret_attr), None)
if item is not None:
item.delete()
self.password = None
async def auth_failure_hook(self, **kwargs: t.Any) -> None:
if SECRET_STORAGE and self._password_in_secretstorage is True:
await asyncio.get_running_loop().run_in_executor(
None, self._remove_password_from_storage
)
self._password_in_secretstorage = None
self._http_basic = None
self._oauth2_client_credentials = None
def tls_credentials(self) -> tuple[str, str | None]:
assert self.pulp_ctx.cert is not None
return self.pulp_ctx.cert, self.pulp_ctx.key
def _fetch_client_secret(self) -> str:
return self.pulp_ctx.oauth2_client_secret or click.prompt("Client Secret", hide_input=True)
async def oauth2_client_credentials(self) -> tuple[bytes, bytes]:
if self._oauth2_client_credentials is None:
assert self.pulp_ctx.oauth2_client_id is not None
client_secret = await asyncio.get_running_loop().run_in_executor(
None, self._fetch_client_secret
)
self._oauth2_client_credentials = (
self.pulp_ctx.oauth2_client_id.encode("latin1"),
client_secret.encode("latin1"),
)
return self._oauth2_client_credentials
##############################################################################
# Decorator to access certain contexts
pass_pulp_context = click.make_pass_decorator(PulpCLIContext)
"""Decorator to make the Pulp context available to a command."""
pass_view_set_context = click.make_pass_decorator(PulpViewSetContext)
"""Decorator to make the nearest view set context available to a command."""
pass_entity_context = click.make_pass_decorator(PulpEntityContext)
"""Decorator to make the nearest entity context available to a command."""
pass_acs_context = click.make_pass_decorator(PulpACSContext)
"""Decorator to make the nearest ACS context available to a command."""
pass_content_context = click.make_pass_decorator(PulpContentContext)
"""Decorator to make the nearest content context available to a command."""
pass_repository_context = click.make_pass_decorator(PulpRepositoryContext)
"""Decorator to make the nearest repository context available to a command."""
pass_repository_version_context = click.make_pass_decorator(PulpRepositoryVersionContext)
"""Decorator to make the nearest repository version context available to a command."""
##############################################################################
# Custom types for parameters
def int_or_empty(value: str) -> str | int:
"""
Turns a string into an integer or keeps the empty string.
This is meant to be used as a click parameter type.
"""
if value == "":
return ""
else:
return int(value)
int_or_empty.__name__ = "int or empty"
def float_or_empty(value: str) -> str | float:
"""
Turns a string into a float or keeps the empty string.
This is meant to be used as a click parameter type.
"""
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: t.Any,
allowed_with_contexts: tuple[t.Type[PulpEntityContext]] | None = None,
needs_plugins: list[PluginRequirement] | None = None,
**kwargs: t.Any,
):
self.allowed_with_contexts = allowed_with_contexts
self.needs_plugins = needs_plugins
super().__init__(*args, **kwargs)
def invoke(self, ctx: click.Context) -> t.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) -> click.Command | None:
# 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))
and cmd.allowed_with_contexts is not None
and 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))
and cmd.allowed_with_contexts is not None
and not isinstance(ctx.obj, cmd.allowed_with_contexts)
):
continue
commands_filtered_by_context.append(name)
return sorted(commands_filtered_by_context)
def pulp_command(
name: str | None = None, **kwargs: t.Any
) -> t.Callable[[_AnyCallable], PulpCommand]:
"""
Pulp command factory.
Creates a click compatible command that can be modified with `needs_plugins` and
`allowed_with_contexts`. It allows rendering the docstring with the values of `ENTITY` and
`ENTITIES` from the closest entity context.
"""
return click.command(name=name, cls=PulpCommand, **kwargs)
def pulp_group(name: str | None = None, **kwargs: t.Any) -> t.Callable[[_AnyCallable], PulpGroup]:
"""
Pulp command group factory.
Creates a click compatible group command that selects subcommands based on
`allowed_with_contexts` and creates `PulpCommand` subcommands by default.
"""
return click.group(name=name, cls=PulpGroup, **kwargs)
class PulpOption(click.Option):
"""
Pulp-CLI specific subclass of `click.Option`.
The preferred way to use this is through the
[`pulp_option`][pulp_cli.generic.pulp_option] factory.
"""
def __init__(
self,
*args: t.Any,
needs_plugins: list[PluginRequirement] | None = None,
allowed_with_contexts: tuple[t.Type[PulpEntityContext]] | None = None,
**kwargs: t.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: t.Any) -> t.Any:
if self.needs_plugins and not _unset(value):
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,
specifier=plugin_requirement.specifier,
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) -> tuple[str, str] | None:
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: t.Any, **kwargs: t.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: t.Mapping[str, t.Any], args: list[t.Any]
) -> t.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: t.Type[PulpEntityContext] = PulpEntityContext
) -> t.Callable[[click.Context, click.Parameter, str | None], str | None]:
def _callback(ctx: click.Context, param: click.Parameter, value: str | None) -> str | None:
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: t.Type[PulpEntityContext] = PulpEntityContext,
) -> t.Callable[[click.Context, click.Parameter, str | None], str | None]:
def _href_callback(ctx: click.Context, param: click.Parameter, value: str | None) -> str | None:
if value is not None:
entity_ctx = ctx.find_object(context_class)
assert entity_ctx is not None
if value.startswith("prn:"):
entity_ctx.pulp_ctx.needs_plugin(
PluginRequirement(
"core",
specifier=">=3.63.0",
feature=_("PRNs"),
)
)
match = re.match(prn_regex, value)
if match:
# Search-by-single-PRN
entity_ctx.entity = {"prn__in": [value]}
else:
raise click.ClickException(
_("'{value}' is not a valid PRN.").format(
value=value, option_name=param.name
)
)
else:
entity_ctx.pulp_href = value
return value
return _href_callback
def _version_callback(ctx: click.Context, param: click.Parameter, value: int | None) -> int | None:
repository_version_ctx = ctx.find_object(PulpRepositoryVersionContext)
assert repository_version_ctx is not None
repository_version_ctx.entity = {"number": value}
return value
def load_file_wrapper(handler: t.Callable[[click.Context, click.Parameter, str], t.Any]) -> t.Any:
"""
A wrapper that is used for chaining or decorating callbacks that manipulate input data.
When prefixed with `"@"`, content will be read from a file instead of being taken from the
command line.
"""
@wraps(handler)
def _load_file_or_string_wrapper(
ctx: click.Context, param: click.Parameter, value: str | None
) -> t.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)
"""
A reusable callback for text parameters.
It will read data from a file if their value starts with `"@"`, otherwise use it unchanged.
"""
def json_callback(ctx: click.Context, param: click.Parameter, value: str | None) -> t.Any:
"""A reusable callback that will parse its value from json."""
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)
"""
A reusable callback that will parse its value from json.
Will optionally read from a file prefixed with `"@"`.
"""
def load_labels_callback(
ctx: click.Context, param: click.Parameter, value: str | None
) -> dict[str, str] | None:
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: t.Type[PulpContentContext] | None = None,
schema: s.Schema | None = None,
) -> t.Any:
@load_file_wrapper
def _callback(
ctx: click.Context, param: click.Parameter, value: str
) -> list[PulpContentContext] | None:
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(value: str | None) -> int | None:
if value is None:
return None
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 chunk_size_callback(
ctx: click.Context, param: click.Parameter, value: str | None
) -> int | None:
if value == "":
# Actually override the default.
return None
return parse_size(value)
parse_size_callback = deprecated("Use 'chunk_size_callback' instead.")(chunk_size_callback)
def null_callback(ctx: click.Context, param: click.Parameter, value: str | None) -> str | None:
if value == "":
return "null"
return value
def remote_header_callback(
ctx: click.Context, param: click.Parameter, value: t.Iterable[str]
) -> list[dict[str, str]] | None:
click.echo(value, err=True)
if not value:
return None
header_regex = re.compile(HEADER_REGEX)
failed_headers = ", ".join(
(item for item in value if not (item == "" or header_regex.match(item)))
)
if failed_headers:
raise click.BadParameter(f"format must be <header-name>:<value> \n{failed_headers}")
result: list[dict[str, str]] = []
for header in value:
if header == "":
result = []
else:
k, v = header.split(":", maxsplit=1)
result.append({k: v})
return result
##############################################################################
# Decorator common options
def pulp_option(*args: t.Any, **kwargs: t.Any) -> t.Callable[[FC], FC]:
"""
Factory of [`PulpOption`][pulp_cli.generic.PulpOption] objects.
`PulpOption` provides extra features over `click.Option`, namely:
1. Define version constrains.
2. Support for template variables in the help message.
3. Limit the use of options to certain entity contexts.
Examples:
Define version constrains and custom help message:
```
pulp_option(
"--name",
needs_plugins=[PluginRequirement("rpm", specifier=">=3.12.0")],
help=_("Name of {entity}"),
allowed_with_contexts=(PulpRpmRepositoryContext,),
)
```
"""
kwargs["cls"] = PulpOption
return click.option(*args, **kwargs)
domain_pattern = r"(?P<pulp_domain>[-a-zA-Z0-9_]+)"
def resource_lookup_option(*args: t.Any, **kwargs: t.Any) -> t.Callable[[FC], FC]:
"""
A factory to create a lookup option that will pass the lookup to the closest matching Context.
"""
lookup_key: str | None = kwargs.pop("lookup_key", "name")
context_class: t.Type[PulpEntityContext] = kwargs.pop("context_class")
def _option_callback(
ctx: click.Context, param: click.Parameter, value: str | None
) -> 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
)
)
elif value.startswith("prn:"):
entity_ctx.pulp_ctx.needs_plugin(
PluginRequirement(
"core",
feature=_("PRNs"),
specifier=">=3.63.0",
)
)
match = re.match(prn_regex, value)
if match:
# Search-by-single-PRN
entity_ctx.entity = {"prn__in": [value]}
else:
raise click.ClickException(
_("'{value}' is not a valid PRN.").format(value=value, option_name=param.name)
)
elif lookup_key is not None:
# The named identity of a resource was passed
entity_ctx.entity = {lookup_key: value}
else:
raise click.ClickException(
_("'{value}' is not recognised by {option_name}.").format(
value=value, option_name=param.name
)
)
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 <href>.")
if lookup_key is None
else _("A resource to look for identified by <{lookup_key}> or by <href>.").format(
lookup_key=lookup_key
)
)
return click.option(*args, **kwargs)
def resource_option(*args: t.Any, **kwargs: t.Any) -> t.Callable[[FC], FC]:
"""
Factory for an option that passes a preloaded PulpEntityContext to the command.
The resulting option will accept the entity being described in multiple ways, including its
href.
"""
default_plugin: str | None = kwargs.pop("default_plugin", None)
default_type: str | None = kwargs.pop("default_type", None)
lookup_key: str = kwargs.pop("lookup_key", "name")
context_table: dict[str, t.Type[PulpEntityContext]] = kwargs.pop("context_table")
capabilities: list[str] | None = kwargs.pop("capabilities", None)
href_pattern: str | None = kwargs.pop("href_pattern", None)
parent_resource_lookup: tuple[str, t.Type[PulpEntityContext]] | None = kwargs.pop(
"parent_resource_lookup", None
)
def _option_callback(
ctx: click.Context, param: click.Parameter, value: str | None
) -> EntityFieldDefinition:
# Pass None and "" verbatim
if not value:
return value
pulp_href: str | None = None
entity: EntityDefinition | None = 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
elif value.startswith("prn:"):
pulp_ctx.needs_plugin(
PluginRequirement(
"core",
feature=_("PRNs"),
specifier=">=3.63.0",
)
)
match = re.match(prn_regex, value)
if match:
# Search-by-single-PRN
plugin = ""
resource_type = ""
entity = {"prn__in": [value]}
else:
raise click.ClickException(
_("'{value}' is not a valid PRN.").format(value=value, option_name=param.name)
)
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
)