Debian Codegraph @

src/asyncclick/decorators.py

raw
1 from __future__ import annotations
2
3 import inspect
4 import typing as t
5 from functools import update_wrapper
6 from gettext import gettext as _
7
8 from .core import Argument
9 from .core import Command
10 from .core import Context
11 from .core import Group
12 from .core import Option
13 from .core import Parameter
14 from .globals import get_current_context
15 from .utils import echo
16
17 if t.TYPE_CHECKING:
18 import typing_extensions as te
19
20 P = te.ParamSpec("P")
21
22 R = t.TypeVar("R")
23 T = t.TypeVar("T")
24 _AnyCallable = t.Callable[..., t.Any]
25 FC = t.TypeVar("FC", bound="_AnyCallable | Command")
26
27
28 def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:
29 """Marks a callback as wanting to receive the current context
30 object as first argument.
31 """
32
33 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
34 return f(get_current_context(), *args, **kwargs)
35
36 return update_wrapper(new_func, f)
37
38
39 def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
40 """Similar to :func:`pass_context`, but only pass the object on the
41 context onwards (:attr:`Context.obj`). This is useful if that object
42 represents the state of a nested system.
43 """
44
45 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
46 return f(get_current_context().obj, *args, **kwargs)
47
48 return update_wrapper(new_func, f)
49
50
51 def make_pass_decorator(
52 object_type: type[T], ensure: bool = False
53 ) -> t.Callable[
54 [t.Callable[te.Concatenate[T, P], R]], t.Callable[P, t.Coroutine[t.Any, t.Any, R]]
55 ]:
56 """Given an object type this creates a decorator that will work
57 similar to :func:`pass_obj` but instead of passing the object of the
58 current context, it will find the innermost context of type
59 :func:`object_type`.
60
61 This generates a decorator that works roughly like this::
62
63 from functools import update_wrapper
64
65 def decorator(f):
66 @pass_context
67 def new_func(ctx, *args, **kwargs):
68 obj = ctx.find_object(object_type)
69 return ctx.invoke(f, obj, *args, **kwargs)
70 return update_wrapper(new_func, f)
71 return decorator
72
73 :param object_type: the type of the object to pass.
74 :param ensure: if set to `True`, a new object will be created and
75 remembered on the context if it's not there yet.
76 """
77
78 def decorator(
79 f: t.Callable[te.Concatenate[T, P], R],
80 ) -> t.Callable[P, t.Coroutine[t.Any, t.Any, R]]:
81 def new_func(*args: P.args, **kwargs: P.kwargs) -> t.Coroutine[t.Any, t.Any, R]:
82 ctx = get_current_context()
83
84 obj: T | None
85 if ensure:
86 obj = ctx.ensure_object(object_type)
87 else:
88 obj = ctx.find_object(object_type)
89
90 if obj is None:
91 raise RuntimeError(
92 "Managed to invoke callback without a context"
93 f" object of type {object_type.__name__!r}"
94 " existing."
95 )
96
97 return ctx.invoke(f, obj, *args, **kwargs)
98
99 return update_wrapper(new_func, f)
100
101 return decorator
102
103
104 def pass_meta_key(
105 key: str, *, doc_description: str | None = None
106 ) -> t.Callable[
107 [t.Callable[te.Concatenate[T, P], R]], t.Callable[P, t.Coroutine[t.Any, t.Any, R]]
108 ]:
109 """Create a decorator that passes a key from
110 :attr:`click.Context.meta` as the first argument to the decorated
111 function.
112
113 :param key: Key in ``Context.meta`` to pass.
114 :param doc_description: Description of the object being passed,
115 inserted into the decorator's docstring. Defaults to "the 'key'
116 key from Context.meta".
117
118 .. versionadded:: 8.0
119 """
120
121 def decorator(
122 f: t.Callable[te.Concatenate[T, P], R],
123 ) -> t.Callable[P, t.Coroutine[t.Any, t.Any, R]]:
124 def new_func(*args: P.args, **kwargs: P.kwargs) -> t.Coroutine[t.Any, t.Any, R]:
125 ctx = get_current_context()
126 obj = ctx.meta[key]
127 return ctx.invoke(f, obj, *args, **kwargs)
128
129 return update_wrapper(new_func, f)
130
131 if doc_description is None:
132 doc_description = f"the {key!r} key from :attr:`click.Context.meta`"
133
134 decorator.__doc__ = (
135 f"Decorator that passes {doc_description} as the first argument"
136 " to the decorated function."
137 )
138 return decorator
139
140
141 CmdType = t.TypeVar("CmdType", bound=Command)
142
143
144 # variant: no call, directly as decorator for a function.
145 @t.overload
146 def command(name: _AnyCallable) -> Command: ...
147
148
149 # variant: with positional name and with positional or keyword cls argument:
150 # @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)
151 @t.overload
152 def command(
153 name: str | None,
154 cls: type[CmdType],
155 **attrs: t.Any,
156 ) -> t.Callable[[_AnyCallable], CmdType]: ...
157
158
159 # variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)
160 @t.overload
161 def command(
162 name: None = None,
163 *,
164 cls: type[CmdType],
165 **attrs: t.Any,
166 ) -> t.Callable[[_AnyCallable], CmdType]: ...
167
168
169 # variant: with optional string name, no cls argument provided.
170 @t.overload
171 def command(
172 name: str | None = ..., cls: None = None, **attrs: t.Any
173 ) -> t.Callable[[_AnyCallable], Command]: ...
174
175
176 def command(
177 name: str | _AnyCallable | None = None,
178 cls: type[CmdType] | None = None,
179 **attrs: t.Any,
180 ) -> Command | t.Callable[[_AnyCallable], Command | CmdType]:
181 r"""Creates a new :class:`Command` and uses the decorated function as
182 callback. This will also automatically attach all decorated
183 :func:`option`\s and :func:`argument`\s as parameters to the command.
184
185 The name of the command defaults to the name of the function, converted to
186 lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes
187 ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example,
188 ``init_data_command`` becomes ``init-data``.
189
190 All keyword arguments are forwarded to the underlying command class.
191 For the ``params`` argument, any decorated params are appended to
192 the end of the list.
193
194 Once decorated the function turns into a :class:`Command` instance
195 that can be invoked as a command line utility or be attached to a
196 command :class:`Group`.
197
198 :param name: The name of the command. Defaults to modifying the function's
199 name as described above.
200 :param cls: The command class to create. Defaults to :class:`Command`.
201
202 .. versionchanged:: 8.2
203 The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are
204 removed when generating the name.
205
206 .. versionchanged:: 8.1
207 This decorator can be applied without parentheses.
208
209 .. versionchanged:: 8.1
210 The ``params`` argument can be used. Decorated params are
211 appended to the end of the list.
212 """
213
214 func: t.Callable[[_AnyCallable], t.Any] | None = None
215
216 if callable(name):
217 func = name
218 name = None
219 assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
220 assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
221
222 if cls is None:
223 cls = t.cast("type[CmdType]", Command)
224
225 def decorator(f: _AnyCallable) -> CmdType:
226 if isinstance(f, Command):
227 raise TypeError("Attempted to convert a callback into a command twice.")
228
229 attr_params = attrs.pop("params", None)
230 params = attr_params if attr_params is not None else []
231
232 try:
233 decorator_params = f.__click_params__ # type: ignore
234 except AttributeError:
235 pass
236 else:
237 del f.__click_params__ # type: ignore
238 params.extend(reversed(decorator_params))
239
240 if attrs.get("help") is None:
241 attrs["help"] = f.__doc__
242
243 if t.TYPE_CHECKING:
244 assert cls is not None
245 assert not callable(name)
246
247 if name is not None:
248 cmd_name = name
249 else:
250 cmd_name = f.__name__.lower().replace("_", "-")
251 cmd_left, sep, suffix = cmd_name.rpartition("-")
252
253 if sep and suffix in {"command", "cmd", "group", "grp"}:
254 cmd_name = cmd_left
255
256 cmd = cls(name=cmd_name, callback=f, params=params, **attrs)
257 cmd.__doc__ = f.__doc__
258 return cmd
259
260 if func is not None:
261 return decorator(func)
262
263 return decorator
264
265
266 GrpType = t.TypeVar("GrpType", bound=Group)
267
268
269 # variant: no call, directly as decorator for a function.
270 @t.overload
271 def group(name: _AnyCallable) -> Group: ...
272
273
274 # variant: with positional name and with positional or keyword cls argument:
275 # @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
276 @t.overload
277 def group(
278 name: str | None,
279 cls: type[GrpType],
280 **attrs: t.Any,
281 ) -> t.Callable[[_AnyCallable], GrpType]: ...
282
283
284 # variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)
285 @t.overload
286 def group(
287 name: None = None,
288 *,
289 cls: type[GrpType],
290 **attrs: t.Any,
291 ) -> t.Callable[[_AnyCallable], GrpType]: ...
292
293
294 # variant: with optional string name, no cls argument provided.
295 @t.overload
296 def group(
297 name: str | None = ..., cls: None = None, **attrs: t.Any
298 ) -> t.Callable[[_AnyCallable], Group]: ...
299
300
301 def group(
302 name: str | _AnyCallable | None = None,
303 cls: type[GrpType] | None = None,
304 **attrs: t.Any,
305 ) -> Group | t.Callable[[_AnyCallable], Group | GrpType]:
306 """Creates a new :class:`Group` with a function as callback. This
307 works otherwise the same as :func:`command` just that the `cls`
308 parameter is set to :class:`Group`.
309
310 .. versionchanged:: 8.1
311 This decorator can be applied without parentheses.
312 """
313 if cls is None:
314 cls = t.cast("type[GrpType]", Group)
315
316 if callable(name):
317 return command(cls=cls, **attrs)(name)
318
319 return command(name, cls, **attrs)
320
321
322 def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:
323 if isinstance(f, Command):
324 f.params.append(param)
325 else:
326 if not hasattr(f, "__click_params__"):
327 f.__click_params__ = [] # type: ignore
328
329 f.__click_params__.append(param) # type: ignore
330
331
332 def argument(
333 *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any
334 ) -> t.Callable[[FC], FC]:
335 """Attaches an argument to the command. All positional arguments are
336 passed as parameter declarations to :class:`Argument`; all keyword
337 arguments are forwarded unchanged (except ``cls``).
338 This is equivalent to creating an :class:`Argument` instance manually
339 and attaching it to the :attr:`Command.params` list.
340
341 For the default argument class, refer to :class:`Argument` and
342 :class:`Parameter` for descriptions of parameters.
343
344 :param cls: the argument class to instantiate. This defaults to
345 :class:`Argument`.
346 :param param_decls: Passed as positional arguments to the constructor of
347 ``cls``.
348 :param attrs: Passed as keyword arguments to the constructor of ``cls``.
349 """
350 if cls is None:
351 cls = Argument
352
353 def decorator(f: FC) -> FC:
354 _param_memo(f, cls(param_decls, **attrs))
355 return f
356
357 return decorator
358
359
360 def option(
361 *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any
362 ) -> t.Callable[[FC], FC]:
363 """Attaches an option to the command. All positional arguments are
364 passed as parameter declarations to :class:`Option`; all keyword
365 arguments are forwarded unchanged (except ``cls``).
366 This is equivalent to creating an :class:`Option` instance manually
367 and attaching it to the :attr:`Command.params` list.
368
369 For the default option class, refer to :class:`Option` and
370 :class:`Parameter` for descriptions of parameters.
371
372 :param cls: the option class to instantiate. This defaults to
373 :class:`Option`.
374 :param param_decls: Passed as positional arguments to the constructor of
375 ``cls``.
376 :param attrs: Passed as keyword arguments to the constructor of ``cls``.
377 """
378 if cls is None:
379 cls = Option
380
381 def decorator(f: FC) -> FC:
382 _param_memo(f, cls(param_decls, **attrs))
383 return f
384
385 return decorator
386
387
388 def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
389 """Add a ``--yes`` option which shows a prompt before continuing if
390 not passed. If the prompt is declined, the program will exit.
391
392 :param param_decls: One or more option names. Defaults to the single
393 value ``"--yes"``.
394 :param kwargs: Extra arguments are passed to :func:`option`.
395 """
396
397 def callback(ctx: Context, param: Parameter, value: bool) -> None:
398 if not value:
399 ctx.abort()
400
401 if not param_decls:
402 param_decls = ("--yes",)
403
404 kwargs.setdefault("is_flag", True)
405 kwargs.setdefault("callback", callback)
406 kwargs.setdefault("expose_value", False)
407 kwargs.setdefault("prompt", "Do you want to continue?")
408 kwargs.setdefault("help", "Confirm the action without prompting.")
409 return option(*param_decls, **kwargs)
410
411
412 def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
413 """Add a ``--password`` option which prompts for a password, hiding
414 input and asking to enter the value again for confirmation.
415
416 :param param_decls: One or more option names. Defaults to the single
417 value ``"--password"``.
418 :param kwargs: Extra arguments are passed to :func:`option`.
419 """
420 if not param_decls:
421 param_decls = ("--password",)
422
423 kwargs.setdefault("prompt", True)
424 kwargs.setdefault("confirmation_prompt", True)
425 kwargs.setdefault("hide_input", True)
426 return option(*param_decls, **kwargs)
427
428
429 def version_option(
430 version: str | None = None,
431 *param_decls: str,
432 package_name: str | None = None,
433 prog_name: str | None = None,
434 message: str | None = None,
435 **kwargs: t.Any,
436 ) -> t.Callable[[FC], FC]:
437 """Add a ``--version`` option which immediately prints the version
438 number and exits the program.
439
440 If ``version`` is not provided, Click will try to detect it using
441 :func:`importlib.metadata.version` to get the version for the
442 ``package_name``.
443
444 If ``package_name`` is not provided, Click will try to detect it by
445 inspecting the stack frames. This will be used to detect the
446 version, so it must match the name of the installed package.
447
448 :param version: The version number to show. If not provided, Click
449 will try to detect it.
450 :param param_decls: One or more option names. Defaults to the single
451 value ``"--version"``.
452 :param package_name: The package name to detect the version from. If
453 not provided, Click will try to detect it.
454 :param prog_name: The name of the CLI to show in the message. If not
455 provided, it will be detected from the command.
456 :param message: The message to show. The values ``%(prog)s``,
457 ``%(package)s``, and ``%(version)s`` are available. Defaults to
458 ``"%(prog)s, version %(version)s"``.
459 :param kwargs: Extra arguments are passed to :func:`option`.
460 :raise RuntimeError: ``version`` could not be detected.
461
462 .. versionchanged:: 8.0
463 Add the ``package_name`` parameter, and the ``%(package)s``
464 value for messages.
465
466 .. versionchanged:: 8.0
467 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The
468 version is detected based on the package name, not the entry
469 point name. The Python package name must match the installed
470 package name, or be passed with ``package_name=``.
471 """
472 if message is None:
473 message = _("%(prog)s, version %(version)s")
474
475 if version is None and package_name is None:
476 frame = inspect.currentframe()
477 f_back = frame.f_back if frame is not None else None
478 f_globals = f_back.f_globals if f_back is not None else None
479 # break reference cycle
480 # https://docs.python.org/3/library/inspect.html#the-interpreter-stack
481 del frame
482
483 if f_globals is not None:
484 package_name = f_globals.get("__name__")
485
486 if package_name == "__main__":
487 package_name = f_globals.get("__package__")
488
489 if package_name:
490 package_name = package_name.partition(".")[0]
491
492 async def callback(ctx: Context, param: Parameter, value: bool) -> None:
493 if not value or ctx.resilient_parsing:
494 return
495
496 nonlocal prog_name
497 nonlocal version
498
499 if prog_name is None:
500 prog_name = ctx.find_root().info_name
501
502 if version is None and package_name is not None:
503 import importlib.metadata
504
505 try:
506 version = importlib.metadata.version(package_name)
507 except importlib.metadata.PackageNotFoundError:
508 raise RuntimeError(
509 f"{package_name!r} is not installed. Try passing"
510 " 'package_name' instead."
511 ) from None
512
513 if version is None:
514 raise RuntimeError(
515 f"Could not determine the version for {package_name!r} automatically."
516 )
517
518 echo(
519 message % {"prog": prog_name, "package": package_name, "version": version},
520 color=ctx.color,
521 )
522 await ctx.aexit()
523
524 if not param_decls:
525 param_decls = ("--version",)
526
527 kwargs.setdefault("is_flag", True)
528 kwargs.setdefault("expose_value", False)
529 kwargs.setdefault("is_eager", True)
530 kwargs.setdefault("help", _("Show the version and exit."))
531 kwargs["callback"] = callback
532 return option(*param_decls, **kwargs)
533
534
535 def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
536 """Pre-configured ``--help`` option which immediately prints the help page
537 and exits the program.
538
539 :param param_decls: One or more option names. Defaults to the single
540 value ``"--help"``.
541 :param kwargs: Extra arguments are passed to :func:`option`.
542 """
543
544 async def show_help(ctx: Context, param: Parameter, value: bool) -> None:
545 """Callback that print the help page on ``<stdout>`` and exits."""
546 if value and not ctx.resilient_parsing:
547 echo(ctx.get_help(), color=ctx.color)
548 await ctx.aexit()
549
550 if not param_decls:
551 param_decls = ("--help",)
552
553 kwargs.setdefault("is_flag", True)
554 kwargs.setdefault("expose_value", False)
555 kwargs.setdefault("is_eager", True)
556 kwargs.setdefault("help", _("Show this message and exit."))
557 kwargs.setdefault("callback", show_help)
558
559 return option(*param_decls, **kwargs)