|
1 | 1 | import inspect |
| 2 | +import typing as t |
2 | 3 | from functools import update_wrapper |
3 | 4 |
|
4 | 5 | from .core import Argument |
|
8 | 9 | from .globals import get_current_context |
9 | 10 | from .utils import echo |
10 | 11 |
|
| 12 | +if t.TYPE_CHECKING: |
| 13 | + F = t.TypeVar("F", bound=t.Callable[..., t.Any]) |
11 | 14 |
|
12 | 15 | def pass_context(f): |
13 | 16 | """Marks a callback as wanting to receive the current context |
@@ -75,6 +78,39 @@ def new_func(*args, **kwargs): |
75 | 78 | return decorator |
76 | 79 |
|
77 | 80 |
|
| 81 | +def pass_meta_key( |
| 82 | + key: str, *, doc_description: t.Optional[str] = None |
| 83 | +) -> "t.Callable[[F], F]": |
| 84 | + """Create a decorator that passes a key from |
| 85 | + :attr:`click.Context.meta` as the first argument to the decorated |
| 86 | + function. |
| 87 | +
|
| 88 | + :param key: Key in ``Context.meta`` to pass. |
| 89 | + :param doc_description: Description of the object being passed, |
| 90 | + inserted into the decorator's docstring. Defaults to "the 'key' |
| 91 | + key from Context.meta". |
| 92 | +
|
| 93 | + .. versionadded:: 8.0 |
| 94 | + """ |
| 95 | + |
| 96 | + def decorator(f: "F") -> "F": |
| 97 | + def new_func(*args, **kwargs): |
| 98 | + ctx = get_current_context() |
| 99 | + obj = ctx.meta[key] |
| 100 | + return ctx.invoke(f, obj, *args, **kwargs) |
| 101 | + |
| 102 | + return update_wrapper(t.cast("F", new_func), f) |
| 103 | + |
| 104 | + if doc_description is None: |
| 105 | + doc_description = f"the {key!r} key from :attr:`click.Context.meta`" |
| 106 | + |
| 107 | + decorator.__doc__ = ( |
| 108 | + f"Decorator that passes {doc_description} as the first argument" |
| 109 | + " to the decorated function." |
| 110 | + ) |
| 111 | + return decorator |
| 112 | + |
| 113 | + |
78 | 114 | def _make_command(f, name, attrs, cls): |
79 | 115 | if isinstance(f, Command): |
80 | 116 | raise TypeError("Attempted to convert a callback into a command twice.") |
|
0 commit comments