-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_app_core.py
More file actions
1566 lines (1429 loc) · 63 KB
/
Copy path_app_core.py
File metadata and controls
1566 lines (1429 loc) · 63 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
from __future__ import annotations
import functools
import inspect
import logging
import stat
import sys
import time
from collections.abc import Awaitable, Callable, Iterable
from contextvars import ContextVar, Token
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from threading import RLock
from typing import Any, ParamSpec, TypeVar, cast
from ._click_compat import dialect_for_command
from ._lifecycle import (
InvocationOutcome,
RunRecorder,
outcome_from_exception,
outcome_from_exit_code,
)
from ._private_files import write_private_json
from ._runtime import (
RuntimeDirectoryError,
acquire_run_lease,
create_owned_runtime_directory,
create_runtime_directory,
prune_log_files,
prune_run_bundles,
)
from .asyncio_adapter import run_async
from .attachment import AttachmentContract
from .config import ConfigSnapshot
from .context import Context, recover_current_context, reset_current_context, set_current_context
from .errors import ConfigurationError
from .exit_codes import ExitCode
from .history import compact_optional_path, utc_now
from .integrations import TelemetryOptions, TelemetrySession, finish_telemetry, start_telemetry
from .lifecycle_options import (
LifecycleOptions,
LifecycleValues,
)
from .logging import configure_logger, log_invocation
from .paths import (
current_working_dir,
normalize_cli_name,
normalize_explicit_cli_name,
)
from .profile import CliProfile
from .redaction import (
REDACTED,
RedactionPlan,
compile_redaction_plan,
parameter_name_from_decls,
redact_argv,
)
from .runtime import RetentionPolicy
_STANDARD_OPTION_KEYS = ("debug", "quiet", "environment", "config", "keep_temp", "log_file", "json")
_FLAG_LIFECYCLE_OPTION_KEYS = frozenset({"debug", "quiet", "keep_temp", "dry_run", "json"})
_NATIVE_LIFECYCLE_OPTION_ORDER = (
"quiet",
"debug",
"environment",
"config",
"keep_temp",
"log_file",
"dry_run",
"json",
)
_ATTACHED_LIFECYCLE_OPTION_ORDER = (
"log_file",
"keep_temp",
"config",
"environment",
"debug",
"quiet",
"dry_run",
"json",
)
_LIFECYCLE_CAPTURE_META_KEY = object()
_LIFECYCLE_RESOLUTION_META_KEY = object()
DISPLAY_COMMAND_ENV = "BASE_CLI_DISPLAY_COMMAND"
_INVOCATION_ARGV: ContextVar[list[str] | None] = ContextVar("base_cli_invocation_argv", default=None)
_INVOCATION_MAIN_BYPASS: ContextVar[Any | None] = ContextVar(
"base_cli_invocation_main_bypass",
default=None,
)
_COMMAND_APP_ATTRIBUTE = "__base_cli_command_app__"
_COMMAND_APP_LOCK = RLock()
_CLICK_ATTACHMENT_ATTRIBUTE = "__base_cli_attachment__"
_CLICK_INSTRUMENTED_ATTRIBUTE = "__base_cli_lifecycle_instrumented__"
_CLICK_MAIN_INSTRUMENTED_ATTRIBUTE = "__base_cli_main_instrumented__"
_CLICK_ORIGINAL_INVOKE_ATTRIBUTE = "__base_cli_original_invoke__"
_CLICK_ORIGINAL_RESOLVE_ATTRIBUTE = "__base_cli_original_resolve__"
_CLICK_ORIGINAL_MAIN_ATTRIBUTE = "__base_cli_original_main__"
_CLICK_APP_OWNER_ATTRIBUTE = "__base_cli_app_owner__"
_CLICK_LIFECYCLE_BINDINGS_ATTRIBUTE = "__base_cli_lifecycle_bindings__"
_CLICK_INSTRUMENTED_SENTINEL = object()
_CLICK_MAIN_INSTRUMENTED_SENTINEL = object()
_CLICK_ATTACHMENT_LOCK = RLock()
_JSON_DEFAULT_MAX_LOG_FILES = 20
_REGISTRATION_OPEN = "open"
_REGISTRATION_MATERIALIZING = "materializing"
_REGISTRATION_FROZEN = "frozen"
_COMMAND_NAME_SUFFIXES = frozenset({"command", "cmd", "group", "grp"})
_P = ParamSpec("_P")
_R = TypeVar("_R")
_ClickCommandT = TypeVar("_ClickCommandT")
_ASYNC_CALLBACK_ERROR = (
"Native async Click callbacks are not supported by base-cli. "
"Use a synchronous callback or an adapter with an explicit async runner."
)
@dataclass
class _InvocationState:
owner_app: Any = None
run_id: str | None = None
log_file: Path | None = None
debug: bool = False
quiet: bool = False
debug_option: str | None = "--debug"
options_parsed: bool = False
attached_completion: bool = False
json_output: bool = False
@dataclass(frozen=True)
class _SubcommandRegistration:
func: Callable[..., Any]
args: tuple[Any, ...]
kwargs: dict[str, Any]
name: str
@dataclass(frozen=True)
class _LifecycleBinding:
key: str
parameter_name: str
adopted: bool
@dataclass(frozen=True)
class _RawLifecycleValue:
value: Any
source: Any
depth: int
@dataclass(frozen=True)
class _LifecycleResolution:
values: LifecycleValues
raw: dict[str, _RawLifecycleValue]
_ClickAttachment = AttachmentContract
class _AttachedInvocation:
"""One attachment invocation whose schema is completed lazily."""
def __init__(
self,
attachment: _ClickAttachment[Any],
root_click_context: Any,
context: Context[Any, Any, Any],
recorder: RunRecorder,
) -> None:
self.attachment = attachment
self.root_click_context = root_click_context
self.context = context
self.recorder = recorder
self.redaction_plan = RedactionPlan()
self.invocation_argv: list[str] = []
self.started = False
self._resolved_children: dict[int, list[tuple[str, Any, Any]]] = {}
self._resolution_parents: dict[int, Any] = {}
self._has_chain = bool(getattr(attachment.command, "chain", False))
self._selected_boundary_seen = False
def note_resolution(
self,
parent_context: Any,
command_name: str,
child_command: Any,
) -> None:
if getattr(getattr(parent_context, "command", None), "chain", False):
self._has_chain = True
self._resolution_parents[id(parent_context)] = parent_context
self._resolved_children.setdefault(id(parent_context), []).append((command_name, child_command, None))
def note_child_context(self, child_context: Any) -> None:
parent = getattr(child_context, "parent", None)
if parent is None:
return
resolutions = self._resolved_children.get(id(parent), [])
for index in range(len(resolutions) - 1, -1, -1):
name, command, recorded_context = resolutions[index]
if recorded_context is None and command is getattr(child_context, "command", None):
resolutions[index] = (name, command, child_context)
break
def start(
self,
selected_context: Any | None = None,
*,
force: bool = False,
) -> None:
if self.started:
return
if selected_context is not None:
self._selected_boundary_seen = True
if self._has_chain and not force:
# Click resolves all chain members before invoking the first one.
# Wait until root teardown so every selected command can contribute
# its sensitive option names to the conservative chain scan.
return
# Mark first so a schema failure cannot trigger a second logging
# attempt during teardown and mask the original exception.
self.started = True
opaque_teardown = force and not self._selected_boundary_seen
if opaque_teardown:
self.redaction_plan = RedactionPlan()
elif self._has_chain:
self.redaction_plan = compile_redaction_plan(
self.attachment.command,
self.attachment.sensitive_parameters,
selected_paths=_selected_click_paths(
self.root_click_context,
self._resolved_children,
self._resolution_parents,
),
)
else:
selected_path = _selected_click_path(
self.root_click_context,
selected_context,
self._resolved_children,
)
self.redaction_plan = compile_redaction_plan(
self.attachment.command,
self.attachment.sensitive_parameters,
selected_path=selected_path,
)
raw_argv = _current_invocation_argv()
self.invocation_argv = (
[raw_argv[0], *([REDACTED] * (len(raw_argv) - 1))]
if opaque_teardown and raw_argv
else redact_argv(raw_argv, self.redaction_plan)
)
log_invocation(self.context.log, self.invocation_argv, None)
_INVOCATION_STATE: ContextVar[_InvocationState | None] = ContextVar("base_cli_invocation_state", default=None)
_ATTACHED_INVOCATION: ContextVar[_AttachedInvocation | None] = ContextVar(
"base_cli_attached_invocation",
default=None,
)
def _reset_context_var(variable: ContextVar[Any], token: Any) -> None:
try:
variable.reset(token)
except BaseException: # pylint: disable=broad-exception-caught
try:
previous = token.old_value
variable.set(None if previous is Token.MISSING else previous)
except BaseException: # pylint: disable=broad-exception-caught
pass
def _default_log_file(layout: Any, configured_log_file: Path | None) -> Path:
return configured_log_file or layout.log_dir / "primary.log"
def _warn_lifecycle_failure(context: Context[Any, Any, Any], message: str, exc: BaseException) -> None:
"""Report a secondary lifecycle failure without breaking teardown."""
try:
detail = str(exc) or type(exc).__name__
context.log.warning("%s: %s", message, detail)
except BaseException: # pylint: disable=broad-exception-caught
pass
def _capture_invocation_context(context: Context[Any, Any, Any], owner_app: App) -> None:
state = _INVOCATION_STATE.get()
if state is None or state.owner_app is not owner_app:
return
state.run_id = context.run_id
state.log_file = context.log_file
state.debug = context.debug
state.quiet = context.quiet
def _capture_standard_options(standard: dict[str, Any], owner_app: App) -> None:
state = _INVOCATION_STATE.get()
if state is None or state.owner_app is not owner_app:
return
state.debug = bool(standard.get("debug"))
state.quiet = bool(standard.get("quiet"))
state.json_output = bool(standard.get("json"))
state.options_parsed = True
def _capture_effective_output_options(
*,
owner_app: App,
debug: bool,
quiet: bool,
json_output: bool = False,
) -> None:
state = _INVOCATION_STATE.get()
if state is None or state.owner_app is not owner_app:
return
state.debug = debug
state.quiet = quiet
state.json_output = json_output
def _record_lifecycle_diagnostic(context: Context[Any, Any, Any], outcome: InvocationOutcome) -> None:
try:
if outcome.kind == "interrupted":
context.log.warning("Interrupted.")
elif outcome.kind == "unexpected_error":
context.log.debug("Unexpected command exception", exc_info=True)
except BaseException: # pylint: disable=broad-exception-caught
pass
def _start_run_recorder(recorder: RunRecorder) -> None:
try:
recorder.start()
except Exception as exc: # pylint: disable=broad-exception-caught
_warn_lifecycle_failure(recorder.context, "Run metadata start failed", exc)
def _finish_run_recorder(
recorder: RunRecorder,
outcome: InvocationOutcome,
*,
ended_at: datetime,
ended_monotonic_ns: int,
) -> None:
try:
recorder.finish(
outcome,
ended_at=ended_at,
ended_monotonic_ns=ended_monotonic_ns,
)
except BaseException as exc: # pylint: disable=broad-exception-caught
path = recorder.context._run_metadata_path
_warn_lifecycle_failure(
recorder.context,
f"Run metadata finalization failed for '{path}'",
exc,
)
_discard_owned_run_record(recorder)
def _discard_owned_run_record(recorder: RunRecorder) -> None:
try:
recorder.discard_owned_record()
except BaseException as exc: # pylint: disable=broad-exception-caught
_warn_lifecycle_failure(
recorder.context,
f"Run metadata recovery failed for '{recorder.context._run_metadata_path}'",
exc,
)
def _reset_active_context(context: Context[Any, Any, Any], token: Any) -> None:
try:
reset_current_context(token)
except BaseException as exc: # pylint: disable=broad-exception-caught
_warn_lifecycle_failure(context, "Active context reset failed", exc)
try:
recover_current_context(token)
except BaseException: # pylint: disable=broad-exception-caught
pass
def _require_click() -> Any:
try:
import click
except ImportError as exc:
raise RuntimeError("Click is required for base_cli. Install it with 'pip install click'.") from exc
return click
def _explicit_command_name(
command_args: tuple[Any, ...],
command_kwargs: dict[str, Any],
) -> str | None:
if command_args and "name" in command_kwargs:
raise TypeError("Command name cannot be provided both positionally and by keyword.")
name = command_args[0] if command_args else command_kwargs.get("name")
if name is None:
return None
if not isinstance(name, str):
raise TypeError("Command name must be a string or None.")
return name
def _inferred_command_name(func: Callable[..., Any]) -> str:
name = func.__name__.lower().replace("_", "-")
prefix, separator, suffix = name.rpartition("-")
if separator and suffix in _COMMAND_NAME_SUFFIXES:
return prefix
return name
def _resolved_command_name(
func: Callable[..., Any],
command_args: tuple[Any, ...],
command_kwargs: dict[str, Any],
) -> str:
return _explicit_command_name(command_args, command_kwargs) or _inferred_command_name(func)
def _click_command_decorator(
click: Any,
name: str,
command_args: tuple[Any, ...],
command_kwargs: dict[str, Any],
) -> Callable[[Callable[..., Any]], Any]:
# ``name`` is resolved by base-cli so naming and duplicate behavior do not
# drift across supported Click versions. Preserve the optional positional
# command class and all non-name attributes.
args_after_name = command_args[1:] if command_args else ()
attrs = dict(command_kwargs)
attrs.pop("name", None)
return cast(Callable[[Callable[..., Any]], Any], click.command(name, *args_after_name, **attrs))
def _require_materialized_command_name(
command: Any,
expected_name: str,
app_name: str,
) -> None:
actual_name = getattr(command, "name", None)
if actual_name != expected_name:
raise RuntimeError(
f"App '{app_name}' expected Click command name '{expected_name}', "
f"but the configured command class produced {actual_name!r}."
)
# pylint: disable=too-many-statements
class App:
"""Define a Click-backed command with a shared runtime lifecycle."""
# pylint: disable=too-many-arguments,too-many-positional-arguments
def __init__(
self,
name: str | None = None,
version: str | None = None,
help: str | None = None, # pylint: disable=redefined-builtin
log_to_file: bool = True,
max_log_files: int | None = None,
profile: CliProfile | None = None,
lifecycle_options: LifecycleOptions | None = None,
retention: RetentionPolicy | None = None,
max_run_bundles: int | None = None,
max_run_age_seconds: float | None = None,
max_run_total_bytes: int | None = None,
rich: bool = False,
telemetry: TelemetryOptions | None = None,
) -> None:
if max_log_files is not None and max_log_files < 1:
raise ValueError("max_log_files must be greater than 0 when set.")
if retention is not None and not isinstance(retention, RetentionPolicy):
raise TypeError("retention must be a RetentionPolicy instance or None.")
if not isinstance(rich, bool):
raise TypeError("rich must be a bool.")
if telemetry is not None and not isinstance(telemetry, TelemetryOptions):
raise TypeError("telemetry must be a TelemetryOptions instance or None.")
if retention is not None and any(
value is not None for value in (max_run_bundles, max_run_age_seconds, max_run_total_bytes)
):
raise ValueError("pass either retention or individual run retention bounds, not both.")
self._retention_explicit = retention is not None or any(
value is not None for value in (max_run_bundles, max_run_age_seconds, max_run_total_bytes)
)
if retention is not None:
self.retention: RetentionPolicy | None = retention
elif any(value is not None for value in (max_run_bundles, max_run_age_seconds, max_run_total_bytes)):
self.retention = RetentionPolicy(
max_bundles=max_run_bundles,
max_age_seconds=max_run_age_seconds,
max_total_bytes=max_run_total_bytes,
)
elif max_log_files is None:
self.retention = RetentionPolicy.safe_defaults()
else:
# Keep the original per-file option's behavior for explicitly
# opted-in legacy consumers; modern bundles are still handled by
# the compatibility path below.
self.retention = None
self._registration_lock = RLock()
self._registration_state = _REGISTRATION_OPEN
self._name = normalize_explicit_cli_name(name) if name is not None else normalize_cli_name(sys.argv[0])
self.version = version
self.help = help
self.log_to_file = log_to_file
self.max_log_files = max_log_files
self.rich = rich
self.telemetry = telemetry
# Standalone applications must not inherit a consumer's product
# conventions. Consumers with product-specific policies should pass an
# explicit profile.
self.profile = profile or CliProfile.generic()
if lifecycle_options is not None and not isinstance(
lifecycle_options,
LifecycleOptions,
):
raise TypeError("lifecycle_options must be a LifecycleOptions instance or None.")
self._lifecycle_options = lifecycle_options or LifecycleOptions()
self._click_command = None
self._redaction_plan: RedactionPlan | None = None
self._command_func: Callable[..., Any] | None = None
self._command_args: tuple[Any, ...] = ()
self._command_kwargs: dict[str, Any] = {}
self._subcommands: list[_SubcommandRegistration] = []
self._subcommand_names: set[str] = set()
self._attached_command: Any | None = None
@property
def name(self) -> str:
return self._name
@property
def lifecycle_options(self) -> LifecycleOptions:
return self._lifecycle_options
@lifecycle_options.setter
def lifecycle_options(self, value: LifecycleOptions) -> None:
if not isinstance(value, LifecycleOptions):
raise TypeError("lifecycle_options must be a LifecycleOptions instance.")
with self._registration_lock:
self._ensure_registration_open()
self._lifecycle_options = value
def _set_name(self, value: str) -> None:
normalized = normalize_explicit_cli_name(value)
with self._registration_lock:
self._ensure_registration_open()
explicit_name = _explicit_command_name(
self._command_args,
self._command_kwargs,
)
if (
self._command_func is not None
and explicit_name is not None
and normalize_explicit_cli_name(explicit_name) != normalized
):
raise RuntimeError(
f"App '{self.name}' cannot be renamed to '{normalized}' because "
f"its registered command explicitly uses '{explicit_name}'."
)
self._name = normalized
name = name.setter(_set_name) # type: ignore[attr-defined]
def _ensure_registration_open(self) -> None:
if self._registration_state == _REGISTRATION_MATERIALIZING:
raise RuntimeError(
f"App '{self.name}' registration is unavailable while its Click command is being materialized."
)
if self._registration_state == _REGISTRATION_FROZEN:
raise RuntimeError(
f"App '{self.name}' registration is frozen because its Click command has already been materialized."
)
def _validate_single_command_name(
self,
command_args: tuple[Any, ...],
command_kwargs: dict[str, Any],
) -> None:
explicit_name = _explicit_command_name(command_args, command_kwargs)
if explicit_name is not None and normalize_explicit_cli_name(explicit_name) != self.name:
raise RuntimeError(
f"App '{self.name}' is the authoritative command name; "
f"the registered command cannot use '{explicit_name}'."
)
def command(
self,
*command_args: Any,
**command_kwargs: Any,
) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
with self._registration_lock:
self._ensure_registration_open()
self._validate_single_command_name(command_args, command_kwargs)
def decorator(func: Callable[_P, _R]) -> Callable[_P, _R]:
_reject_async_callback(func)
with self._registration_lock:
self._ensure_registration_open()
self._validate_single_command_name(command_args, command_kwargs)
if self._subcommands:
raise RuntimeError(
f"App '{self.name}' already has registered subcommands. "
"Use @app.subcommand() for additional entry points."
)
if self._command_func is not None:
raise RuntimeError(
f"App '{self.name}' already has a registered command. "
"Use subcommands for multiple entry points."
)
self._command_func = func
self._command_args = tuple(command_args)
self._command_kwargs = dict(command_kwargs)
return func
return decorator
def async_command(
self,
*command_args: Any,
**command_kwargs: Any,
) -> Callable[[Callable[_P, Awaitable[_R]]], Callable[_P, _R]]:
"""Register an async callback through the explicit asyncio adapter.
The callback remains an ordinary Click command from the lifecycle's
perspective: ``run_async`` owns one event loop for the invocation,
waits for the callback, and returns its normal synchronous result for
exit-code normalization. Native ``@app.command`` callbacks remain
synchronous and continue to reject unadapted coroutines.
"""
def decorator(func: Callable[_P, Awaitable[_R]]) -> Callable[_P, _R]:
if not inspect.iscoroutinefunction(func):
raise TypeError("@app.async_command() requires an async def callback.")
@functools.wraps(func)
def synchronous_callback(*args: _P.args, **kwargs: _P.kwargs) -> _R:
return run_async(func(*args, **kwargs))
return self.command(*command_args, **command_kwargs)(synchronous_callback)
return decorator
def subcommand(
self,
*command_args: Any,
**command_kwargs: Any,
) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
with self._registration_lock:
self._ensure_registration_open()
_explicit_command_name(command_args, command_kwargs)
def decorator(func: Callable[_P, _R]) -> Callable[_P, _R]:
_reject_async_callback(func)
with self._registration_lock:
self._ensure_registration_open()
if self._command_func is not None:
raise RuntimeError(
f"App '{self.name}' already has a registered command. "
"Use either @app.command() or @app.subcommand(), not both."
)
name = _resolved_command_name(func, command_args, command_kwargs)
if name in self._subcommand_names:
raise RuntimeError(f"App '{self.name}' already has a registered subcommand named '{name}'.")
self._subcommands.append(
_SubcommandRegistration(
func=func,
args=tuple(command_args),
kwargs=dict(command_kwargs),
name=name,
)
)
self._subcommand_names.add(name)
return func
return decorator
def attach(
self,
command: _ClickCommandT,
*,
context_factory: Callable[[Context[Any, Any, Any]], Any] | None = None,
service_factory: Callable[[Context[Any, Any, Any]], Any] | None = None,
sensitive_parameters: Iterable[str] = (),
) -> _ClickCommandT:
"""Attach this app's lifecycle to an existing Click command tree.
The same command object is returned rather than copied. Click continues
to own callbacks, contexts, aliases, and lazy command resolution while
base-cli extends its root parameters and adds one lifecycle boundary.
"""
click = dialect_for_command(command)
if not isinstance(command, click.Command):
raise TypeError("App.attach() requires a click.Command instance.")
_reject_async_callback(getattr(command, "callback", None))
if context_factory is not None and not callable(context_factory):
raise TypeError("context_factory must be callable or None.")
if service_factory is not None and not callable(service_factory):
raise TypeError("service_factory must be callable or None.")
normalized_sensitive_parameters = _normalize_sensitive_parameters(sensitive_parameters)
with _CLICK_ATTACHMENT_LOCK, self._registration_lock:
existing = getattr(command, _CLICK_ATTACHMENT_ATTRIBUTE, None)
if isinstance(existing, _ClickAttachment):
if (
existing.app is self
and existing.command is command
and existing.context_factory is context_factory
and existing.service_factory is service_factory
and existing.sensitive_parameters == normalized_sensitive_parameters
and existing.lifecycle_options == self.lifecycle_options
and self._attached_command is command
and self._click_command is command
and self._registration_state == _REGISTRATION_FROZEN
):
return command
raise RuntimeError(
f"Click command '{getattr(command, 'name', None) or '<unnamed>'}' "
"is already attached to a base_cli.App."
)
native_owner = getattr(command, _CLICK_APP_OWNER_ATTRIBUTE, None)
if isinstance(native_owner, App):
raise RuntimeError(
f"Click command '{getattr(command, 'name', None) or '<unnamed>'}' "
"already belongs to a native base_cli.App and cannot be attached."
)
self._ensure_registration_open()
if self._command_func is not None or self._subcommands:
raise RuntimeError(
f"App '{self.name}' already has registered commands and cannot attach an existing Click tree."
)
if self._attached_command is not None:
raise RuntimeError(f"App '{self.name}' is already attached to a Click command.")
command_name = getattr(command, "name", None)
if not isinstance(command_name, str) or not command_name:
raise RuntimeError("App.attach() requires a named Click command.")
if command_name != self.name:
raise RuntimeError(
f"App '{self.name}' is the authoritative command name; "
f"the attached Click command cannot use '{command_name}'."
)
added_parameters: list[Any] = []
missing_marker = object()
previous_marker = getattr(
command,
_CLICK_ATTACHMENT_ATTRIBUTE,
missing_marker,
)
if previous_marker is not missing_marker and not isinstance(
previous_marker,
_ClickAttachment,
):
raise RuntimeError(
f"Click command '{command_name}' uses base-cli's reserved "
"attachment marker. Remove that attribute before attaching."
)
for marker_name, sentinel, description in (
(
_CLICK_INSTRUMENTED_ATTRIBUTE,
_CLICK_INSTRUMENTED_SENTINEL,
"command instrumentation",
),
(
_CLICK_MAIN_INSTRUMENTED_ATTRIBUTE,
_CLICK_MAIN_INSTRUMENTED_SENTINEL,
"main instrumentation",
),
):
marker = getattr(command, marker_name, missing_marker)
if marker is not missing_marker and marker is not sentinel:
raise RuntimeError(
f"Click command '{command_name}' uses base-cli's reserved "
f"{description} marker. Remove that attribute before attaching."
)
command_was_instrumented = (
getattr(command, _CLICK_INSTRUMENTED_ATTRIBUTE, None) is _CLICK_INSTRUMENTED_SENTINEL
)
main_was_instrumented = (
getattr(command, _CLICK_MAIN_INSTRUMENTED_ATTRIBUTE, None) is _CLICK_MAIN_INSTRUMENTED_SENTINEL
)
previous_redaction_plan = self._redaction_plan
previous_attached_command = self._attached_command
previous_click_command = self._click_command
previous_registration_state = self._registration_state
try:
self._registration_state = _REGISTRATION_MATERIALIZING
standard_bindings = _add_attached_standard_options(
click,
command,
lifecycle_options=self.lifecycle_options,
version=self.version,
added_parameters=added_parameters,
)
redaction_plan = compile_redaction_plan(
command,
normalized_sensitive_parameters,
selected_path=(),
)
attachment = _ClickAttachment(
app=self,
command=command,
context_factory=context_factory,
service_factory=service_factory,
sensitive_parameters=normalized_sensitive_parameters,
lifecycle_options=self.lifecycle_options,
standard_bindings=standard_bindings,
)
_instrument_attached_click_command(click, command)
_instrument_attached_click_main(command)
self._redaction_plan = redaction_plan
self._attached_command = command
self._click_command = command
self._registration_state = _REGISTRATION_FROZEN
# Publish ownership last. Invoke wrappers synchronize on this
# lock, so neither the marker nor partial App state can become
# observable before every attachment invariant is established.
setattr(command, _CLICK_ATTACHMENT_ATTRIBUTE, attachment)
except BaseException:
if previous_marker is missing_marker:
try:
delattr(command, _CLICK_ATTACHMENT_ATTRIBUTE)
except (AttributeError, TypeError):
pass
else:
try:
setattr(command, _CLICK_ATTACHMENT_ATTRIBUTE, previous_marker)
except (AttributeError, TypeError):
pass
if not main_was_instrumented:
_restore_attached_click_main(command)
if not command_was_instrumented:
_restore_attached_click_command(command)
for parameter in added_parameters:
try:
command.params.remove(parameter)
except (AttributeError, ValueError):
pass
object.__setattr__(self, "_redaction_plan", previous_redaction_plan)
object.__setattr__(self, "_attached_command", previous_attached_command)
object.__setattr__(self, "_click_command", previous_click_command)
object.__setattr__(
self,
"_registration_state",
previous_registration_state,
)
raise
return command
def __call__(self, *args: Any, **kwargs: Any) -> Any:
if len(args) < 2 and "prog_name" not in kwargs:
kwargs["prog_name"] = self.profile.display_command() or self.name
return self.click_command(*args, **kwargs)
@property
def click_command(self) -> Any:
with self._registration_lock:
command = self._click_command
if command is not None:
return command
if self._registration_state == _REGISTRATION_MATERIALIZING:
raise RuntimeError(f"App '{self.name}' Click command materialization is already in progress.")
self._registration_state = _REGISTRATION_MATERIALIZING
try:
command = self._build_click_command()
redaction_plan = compile_redaction_plan(command)
except BaseException:
# A missing dependency, invalid custom Click class, or plan
# compilation failure must not strand an otherwise repairable
# application in a half-materialized state.
self._registration_state = _REGISTRATION_OPEN
raise
else:
# Publish the command last so another thread can never invoke
# its wrapper before the corresponding plan is available.
self._redaction_plan = redaction_plan
self._registration_state = _REGISTRATION_FROZEN
self._click_command = command
return command
def _build_click_command(self) -> Any:
if self._command_func is None and not self._subcommands:
raise RuntimeError("No command has been registered on this base_cli.App.")
click = _require_click()
if self._command_func is not None:
wrapper = self._build_command_wrapper(click, self._command_func)
command_kwargs = dict(self._command_kwargs)
if self.help is not None:
command_kwargs.setdefault("help", self.help)
command = _click_command_decorator(
click,
self.name,
self._command_args,
command_kwargs,
)(wrapper)
_require_materialized_command_name(command, self.name, self.name)
_install_native_lifecycle_options(
click,
command,
self.lifecycle_options,
version=self.version,
)
setattr(command, _CLICK_APP_OWNER_ATTRIBUTE, self)
return command
group_wrapper = _build_group_wrapper(click)
group = click.group(name=self.name, help=self.help)(group_wrapper)
_install_native_lifecycle_options(
click,
group,
self.lifecycle_options,
version=self.version,
)
setattr(group, _CLICK_APP_OWNER_ATTRIBUTE, self)
for registration in self._subcommands:
wrapper = self._build_command_wrapper(click, registration.func)
command = _click_command_decorator(
click,
registration.name,
registration.args,
registration.kwargs,
)(wrapper)
_require_materialized_command_name(command, registration.name, self.name)
_install_native_lifecycle_options(
click,
command,
self.lifecycle_options,
version=None,
)
setattr(command, _CLICK_APP_OWNER_ATTRIBUTE, self)
# Supplying the canonical name explicitly also prevents a custom
# Command implementation from changing the group key between the
# validation above and Click's registration step.
group.add_command(
command,
name=registration.name,
)
return group
def _build_command_wrapper(
self,
click: Any,
func: Callable[..., Any],
) -> Callable[..., Any]:
explicit_dry_run_parameter = getattr(
func,
"__base_cli_dry_run_parameter__",
None,
)
conventional_dry_run_parameter = any(
parameter_name_from_decls(param_decls) == "dry_run"
for _kind, param_decls, _attrs, *_metadata in getattr(
func,
"__base_cli_param_specs__",
(),
)
)
if self.lifecycle_options.dry_run is not None and (
explicit_dry_run_parameter is not None or conventional_dry_run_parameter
):
conflicting_parameter = explicit_dry_run_parameter or "dry_run"
raise RuntimeError(
f"{func.__name__} designates '{conflicting_parameter}' as dry-run, "
"but LifecycleOptions.dry_run is also enabled. Use only one dry-run source."
)
dry_run_parameter = explicit_dry_run_parameter or "dry_run"
@functools.wraps(func)
def wrapper(**kwargs: Any) -> Any:
if _ATTACHED_INVOCATION.get() is not None:
raise RuntimeError(
f"base_cli command '{self.name}' cannot run inside an attached "
"Click tree because that would create a second lifecycle."
)
click_context = click.get_current_context()
bindings = getattr(
click_context.command,
_CLICK_LIFECYCLE_BINDINGS_ATTRIBUTE,
{},
)
extra_values: dict[str, _RawLifecycleValue] = {}
if self.lifecycle_options.dry_run is None and dry_run_parameter in kwargs:
extra_values["dry_run"] = _RawLifecycleValue(
value=kwargs.get(dry_run_parameter),
source=click_context.get_parameter_source(dry_run_parameter),
depth=_context_depth(click_context),
)
resolution = _resolve_lifecycle_values(
click,
click_context,
bindings,
extra_values=extra_values,
)
standard = _standard_options_from_values(resolution.values)
_validate_standard_options(click, standard, self.lifecycle_options)