decorators.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. from __future__ import annotations
  2. import inspect
  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="_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, 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: 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 | None
  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: str | None = None
  75. ) -> t.Callable[[t.Callable[te.Concatenate[T, 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, 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: str | None,
  107. cls: 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: 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: str | None = ..., cls: None = None, **attrs: t.Any
  122. ) -> t.Callable[[_AnyCallable], Command]: ...
  123. def command(
  124. name: str | _AnyCallable | None = None,
  125. cls: type[CmdType] | None = None,
  126. **attrs: t.Any,
  127. ) -> Command | t.Callable[[_AnyCallable], 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, converted to
  132. lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes
  133. ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example,
  134. ``init_data_command`` becomes ``init-data``.
  135. All keyword arguments are forwarded to the underlying command class.
  136. For the ``params`` argument, any decorated params are appended to
  137. the end of the list.
  138. Once decorated the function turns into a :class:`Command` instance
  139. that can be invoked as a command line utility or be attached to a
  140. command :class:`Group`.
  141. :param name: The name of the command. Defaults to modifying the function's
  142. name as described above.
  143. :param cls: The command class to create. Defaults to :class:`Command`.
  144. .. versionchanged:: 8.2
  145. The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are
  146. removed when generating the name.
  147. .. versionchanged:: 8.1
  148. This decorator can be applied without parentheses.
  149. .. versionchanged:: 8.1
  150. The ``params`` argument can be used. Decorated params are
  151. appended to the end of the list.
  152. """
  153. func: t.Callable[[_AnyCallable], t.Any] | None = None
  154. if callable(name):
  155. func = name
  156. name = None
  157. assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
  158. assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
  159. if cls is None:
  160. cls = t.cast("type[CmdType]", Command)
  161. def decorator(f: _AnyCallable) -> CmdType:
  162. if isinstance(f, Command):
  163. raise TypeError("Attempted to convert a callback into a command twice.")
  164. attr_params = attrs.pop("params", None)
  165. params = attr_params if attr_params is not None else []
  166. try:
  167. decorator_params = f.__click_params__ # type: ignore
  168. except AttributeError:
  169. pass
  170. else:
  171. del f.__click_params__ # type: ignore
  172. params.extend(reversed(decorator_params))
  173. if attrs.get("help") is None:
  174. attrs["help"] = f.__doc__
  175. if t.TYPE_CHECKING:
  176. assert cls is not None
  177. assert not callable(name)
  178. if name is not None:
  179. cmd_name = name
  180. else:
  181. cmd_name = f.__name__.lower().replace("_", "-")
  182. cmd_left, sep, suffix = cmd_name.rpartition("-")
  183. if sep and suffix in {"command", "cmd", "group", "grp"}:
  184. cmd_name = cmd_left
  185. cmd = cls(name=cmd_name, callback=f, params=params, **attrs)
  186. cmd.__doc__ = f.__doc__
  187. return cmd
  188. if func is not None:
  189. return decorator(func)
  190. return decorator
  191. GrpType = t.TypeVar("GrpType", bound=Group)
  192. # variant: no call, directly as decorator for a function.
  193. @t.overload
  194. def group(name: _AnyCallable) -> Group: ...
  195. # variant: with positional name and with positional or keyword cls argument:
  196. # @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
  197. @t.overload
  198. def group(
  199. name: str | None,
  200. cls: type[GrpType],
  201. **attrs: t.Any,
  202. ) -> t.Callable[[_AnyCallable], GrpType]: ...
  203. # variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)
  204. @t.overload
  205. def group(
  206. name: None = None,
  207. *,
  208. cls: type[GrpType],
  209. **attrs: t.Any,
  210. ) -> t.Callable[[_AnyCallable], GrpType]: ...
  211. # variant: with optional string name, no cls argument provided.
  212. @t.overload
  213. def group(
  214. name: str | None = ..., cls: None = None, **attrs: t.Any
  215. ) -> t.Callable[[_AnyCallable], Group]: ...
  216. def group(
  217. name: str | _AnyCallable | None = None,
  218. cls: type[GrpType] | None = None,
  219. **attrs: t.Any,
  220. ) -> Group | t.Callable[[_AnyCallable], Group | GrpType]:
  221. """Creates a new :class:`Group` with a function as callback. This
  222. works otherwise the same as :func:`command` just that the `cls`
  223. parameter is set to :class:`Group`.
  224. .. versionchanged:: 8.1
  225. This decorator can be applied without parentheses.
  226. """
  227. if cls is None:
  228. cls = t.cast("type[GrpType]", Group)
  229. if callable(name):
  230. return command(cls=cls, **attrs)(name)
  231. return command(name, cls, **attrs)
  232. def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:
  233. if isinstance(f, Command):
  234. f.params.append(param)
  235. else:
  236. if not hasattr(f, "__click_params__"):
  237. f.__click_params__ = [] # type: ignore
  238. f.__click_params__.append(param) # type: ignore
  239. def argument(
  240. *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any
  241. ) -> t.Callable[[FC], FC]:
  242. """Attaches an argument to the command. All positional arguments are
  243. passed as parameter declarations to :class:`Argument`; all keyword
  244. arguments are forwarded unchanged (except ``cls``).
  245. This is equivalent to creating an :class:`Argument` instance manually
  246. and attaching it to the :attr:`Command.params` list.
  247. For the default argument class, refer to :class:`Argument` and
  248. :class:`Parameter` for descriptions of parameters.
  249. :param cls: the argument class to instantiate. This defaults to
  250. :class:`Argument`.
  251. :param param_decls: Passed as positional arguments to the constructor of
  252. ``cls``.
  253. :param attrs: Passed as keyword arguments to the constructor of ``cls``.
  254. """
  255. if cls is None:
  256. cls = Argument
  257. def decorator(f: FC) -> FC:
  258. _param_memo(f, cls(param_decls, **attrs))
  259. return f
  260. return decorator
  261. def option(
  262. *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any
  263. ) -> t.Callable[[FC], FC]:
  264. """Attaches an option to the command. All positional arguments are
  265. passed as parameter declarations to :class:`Option`; all keyword
  266. arguments are forwarded unchanged (except ``cls``).
  267. This is equivalent to creating an :class:`Option` instance manually
  268. and attaching it to the :attr:`Command.params` list.
  269. For the default option class, refer to :class:`Option` and
  270. :class:`Parameter` for descriptions of parameters.
  271. :param cls: the option class to instantiate. This defaults to
  272. :class:`Option`.
  273. :param param_decls: Passed as positional arguments to the constructor of
  274. ``cls``.
  275. :param attrs: Passed as keyword arguments to the constructor of ``cls``.
  276. """
  277. if cls is None:
  278. cls = Option
  279. def decorator(f: FC) -> FC:
  280. _param_memo(f, cls(param_decls, **attrs))
  281. return f
  282. return decorator
  283. def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  284. """Add a ``--yes`` option which shows a prompt before continuing if
  285. not passed. If the prompt is declined, the program will exit.
  286. :param param_decls: One or more option names. Defaults to the single
  287. value ``"--yes"``.
  288. :param kwargs: Extra arguments are passed to :func:`option`.
  289. """
  290. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  291. if not value:
  292. ctx.abort()
  293. if not param_decls:
  294. param_decls = ("--yes",)
  295. kwargs.setdefault("is_flag", True)
  296. kwargs.setdefault("callback", callback)
  297. kwargs.setdefault("expose_value", False)
  298. kwargs.setdefault("prompt", "Do you want to continue?")
  299. kwargs.setdefault("help", "Confirm the action without prompting.")
  300. return option(*param_decls, **kwargs)
  301. def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  302. """Add a ``--password`` option which prompts for a password, hiding
  303. input and asking to enter the value again for confirmation.
  304. :param param_decls: One or more option names. Defaults to the single
  305. value ``"--password"``.
  306. :param kwargs: Extra arguments are passed to :func:`option`.
  307. """
  308. if not param_decls:
  309. param_decls = ("--password",)
  310. kwargs.setdefault("prompt", True)
  311. kwargs.setdefault("confirmation_prompt", True)
  312. kwargs.setdefault("hide_input", True)
  313. return option(*param_decls, **kwargs)
  314. def version_option(
  315. version: str | None = None,
  316. *param_decls: str,
  317. package_name: str | None = None,
  318. prog_name: str | None = None,
  319. message: str | None = None,
  320. **kwargs: t.Any,
  321. ) -> t.Callable[[FC], FC]:
  322. """Add a ``--version`` option which immediately prints the version
  323. number and exits the program.
  324. If ``version`` is not provided, Click will try to detect it using
  325. :func:`importlib.metadata.version` to get the version for the
  326. ``package_name``.
  327. If ``package_name`` is not provided, Click will try to detect it by
  328. inspecting the stack frames. This will be used to detect the
  329. version, so it must match the name of the installed package.
  330. :param version: The version number to show. If not provided, Click
  331. will try to detect it.
  332. :param param_decls: One or more option names. Defaults to the single
  333. value ``"--version"``.
  334. :param package_name: The package name to detect the version from. If
  335. not provided, Click will try to detect it.
  336. :param prog_name: The name of the CLI to show in the message. If not
  337. provided, it will be detected from the command.
  338. :param message: The message to show. The values ``%(prog)s``,
  339. ``%(package)s``, and ``%(version)s`` are available. Defaults to
  340. ``"%(prog)s, version %(version)s"``.
  341. :param kwargs: Extra arguments are passed to :func:`option`.
  342. :raise RuntimeError: ``version`` could not be detected.
  343. .. versionchanged:: 8.0
  344. Add the ``package_name`` parameter, and the ``%(package)s``
  345. value for messages.
  346. .. versionchanged:: 8.0
  347. Use :mod:`importlib.metadata` instead of ``pkg_resources``. The
  348. version is detected based on the package name, not the entry
  349. point name. The Python package name must match the installed
  350. package name, or be passed with ``package_name=``.
  351. """
  352. if message is None:
  353. message = _("%(prog)s, version %(version)s")
  354. if version is None and package_name is None:
  355. frame = inspect.currentframe()
  356. f_back = frame.f_back if frame is not None else None
  357. f_globals = f_back.f_globals if f_back is not None else None
  358. # break reference cycle
  359. # https://docs.python.org/3/library/inspect.html#the-interpreter-stack
  360. del frame
  361. if f_globals is not None:
  362. package_name = f_globals.get("__name__")
  363. if package_name == "__main__":
  364. package_name = f_globals.get("__package__")
  365. if package_name:
  366. package_name = package_name.partition(".")[0]
  367. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  368. if not value or ctx.resilient_parsing:
  369. return
  370. nonlocal prog_name
  371. nonlocal version
  372. if prog_name is None:
  373. prog_name = ctx.find_root().info_name
  374. if version is None and package_name is not None:
  375. import importlib.metadata
  376. try:
  377. version = importlib.metadata.version(package_name)
  378. except importlib.metadata.PackageNotFoundError:
  379. raise RuntimeError(
  380. f"{package_name!r} is not installed. Try passing"
  381. " 'package_name' instead."
  382. ) from None
  383. if version is None:
  384. raise RuntimeError(
  385. f"Could not determine the version for {package_name!r} automatically."
  386. )
  387. echo(
  388. message % {"prog": prog_name, "package": package_name, "version": version},
  389. color=ctx.color,
  390. )
  391. ctx.exit()
  392. if not param_decls:
  393. param_decls = ("--version",)
  394. kwargs.setdefault("is_flag", True)
  395. kwargs.setdefault("expose_value", False)
  396. kwargs.setdefault("is_eager", True)
  397. kwargs.setdefault("help", _("Show the version and exit."))
  398. kwargs["callback"] = callback
  399. return option(*param_decls, **kwargs)
  400. def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  401. """Pre-configured ``--help`` option which immediately prints the help page
  402. and exits the program.
  403. :param param_decls: One or more option names. Defaults to the single
  404. value ``"--help"``.
  405. :param kwargs: Extra arguments are passed to :func:`option`.
  406. """
  407. def show_help(ctx: Context, param: Parameter, value: bool) -> None:
  408. """Callback that print the help page on ``<stdout>`` and exits."""
  409. if value and not ctx.resilient_parsing:
  410. echo(ctx.get_help(), color=ctx.color)
  411. ctx.exit()
  412. if not param_decls:
  413. param_decls = ("--help",)
  414. kwargs.setdefault("is_flag", True)
  415. kwargs.setdefault("expose_value", False)
  416. kwargs.setdefault("is_eager", True)
  417. kwargs.setdefault("help", _("Show this message and exit."))
  418. kwargs.setdefault("callback", show_help)
  419. return option(*param_decls, **kwargs)