decorators.py 18 KB

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