decorators.py 18 KB

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