decorators.py 16 KB

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