decorators.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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", 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. def _make_command(
  93. f: F,
  94. name: t.Optional[str],
  95. attrs: t.MutableMapping[str, t.Any],
  96. cls: t.Type[Command],
  97. ) -> Command:
  98. if isinstance(f, Command):
  99. raise TypeError("Attempted to convert a callback into a command twice.")
  100. try:
  101. params = f.__click_params__ # type: ignore
  102. params.reverse()
  103. del f.__click_params__ # type: ignore
  104. except AttributeError:
  105. params = []
  106. help = attrs.get("help")
  107. if help is None:
  108. help = inspect.getdoc(f)
  109. else:
  110. help = inspect.cleandoc(help)
  111. attrs["help"] = help
  112. return cls(
  113. name=name or f.__name__.lower().replace("_", "-"),
  114. callback=f,
  115. params=params,
  116. **attrs,
  117. )
  118. def command(
  119. name: t.Optional[str] = None,
  120. cls: t.Optional[t.Type[Command]] = None,
  121. **attrs: t.Any,
  122. ) -> t.Callable[[F], Command]:
  123. r"""Creates a new :class:`Command` and uses the decorated function as
  124. callback. This will also automatically attach all decorated
  125. :func:`option`\s and :func:`argument`\s as parameters to the command.
  126. The name of the command defaults to the name of the function with
  127. underscores replaced by dashes. If you want to change that, you can
  128. pass the intended name as the first argument.
  129. All keyword arguments are forwarded to the underlying command class.
  130. Once decorated the function turns into a :class:`Command` instance
  131. that can be invoked as a command line utility or be attached to a
  132. command :class:`Group`.
  133. :param name: the name of the command. This defaults to the function
  134. name with underscores replaced by dashes.
  135. :param cls: the command class to instantiate. This defaults to
  136. :class:`Command`.
  137. """
  138. if cls is None:
  139. cls = Command
  140. def decorator(f: t.Callable[..., t.Any]) -> Command:
  141. cmd = _make_command(f, name, attrs, cls) # type: ignore
  142. cmd.__doc__ = f.__doc__
  143. return cmd
  144. return decorator
  145. def group(name: t.Optional[str] = None, **attrs: t.Any) -> t.Callable[[F], Group]:
  146. """Creates a new :class:`Group` with a function as callback. This
  147. works otherwise the same as :func:`command` just that the `cls`
  148. parameter is set to :class:`Group`.
  149. """
  150. attrs.setdefault("cls", Group)
  151. return t.cast(Group, command(name, **attrs))
  152. def _param_memo(f: FC, param: Parameter) -> None:
  153. if isinstance(f, Command):
  154. f.params.append(param)
  155. else:
  156. if not hasattr(f, "__click_params__"):
  157. f.__click_params__ = [] # type: ignore
  158. f.__click_params__.append(param) # type: ignore
  159. def argument(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:
  160. """Attaches an argument to the command. All positional arguments are
  161. passed as parameter declarations to :class:`Argument`; all keyword
  162. arguments are forwarded unchanged (except ``cls``).
  163. This is equivalent to creating an :class:`Argument` instance manually
  164. and attaching it to the :attr:`Command.params` list.
  165. :param cls: the argument class to instantiate. This defaults to
  166. :class:`Argument`.
  167. """
  168. def decorator(f: FC) -> FC:
  169. ArgumentClass = attrs.pop("cls", Argument)
  170. _param_memo(f, ArgumentClass(param_decls, **attrs))
  171. return f
  172. return decorator
  173. def option(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:
  174. """Attaches an option to the command. All positional arguments are
  175. passed as parameter declarations to :class:`Option`; all keyword
  176. arguments are forwarded unchanged (except ``cls``).
  177. This is equivalent to creating an :class:`Option` instance manually
  178. and attaching it to the :attr:`Command.params` list.
  179. :param cls: the option class to instantiate. This defaults to
  180. :class:`Option`.
  181. """
  182. def decorator(f: FC) -> FC:
  183. # Issue 926, copy attrs, so pre-defined options can re-use the same cls=
  184. option_attrs = attrs.copy()
  185. if "help" in option_attrs:
  186. option_attrs["help"] = inspect.cleandoc(option_attrs["help"])
  187. OptionClass = option_attrs.pop("cls", Option)
  188. _param_memo(f, OptionClass(param_decls, **option_attrs))
  189. return f
  190. return decorator
  191. def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  192. """Add a ``--yes`` option which shows a prompt before continuing if
  193. not passed. If the prompt is declined, the program will exit.
  194. :param param_decls: One or more option names. Defaults to the single
  195. value ``"--yes"``.
  196. :param kwargs: Extra arguments are passed to :func:`option`.
  197. """
  198. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  199. if not value:
  200. ctx.abort()
  201. if not param_decls:
  202. param_decls = ("--yes",)
  203. kwargs.setdefault("is_flag", True)
  204. kwargs.setdefault("callback", callback)
  205. kwargs.setdefault("expose_value", False)
  206. kwargs.setdefault("prompt", "Do you want to continue?")
  207. kwargs.setdefault("help", "Confirm the action without prompting.")
  208. return option(*param_decls, **kwargs)
  209. def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  210. """Add a ``--password`` option which prompts for a password, hiding
  211. input and asking to enter the value again for confirmation.
  212. :param param_decls: One or more option names. Defaults to the single
  213. value ``"--password"``.
  214. :param kwargs: Extra arguments are passed to :func:`option`.
  215. """
  216. if not param_decls:
  217. param_decls = ("--password",)
  218. kwargs.setdefault("prompt", True)
  219. kwargs.setdefault("confirmation_prompt", True)
  220. kwargs.setdefault("hide_input", True)
  221. return option(*param_decls, **kwargs)
  222. def version_option(
  223. version: t.Optional[str] = None,
  224. *param_decls: str,
  225. package_name: t.Optional[str] = None,
  226. prog_name: t.Optional[str] = None,
  227. message: t.Optional[str] = None,
  228. **kwargs: t.Any,
  229. ) -> t.Callable[[FC], FC]:
  230. """Add a ``--version`` option which immediately prints the version
  231. number and exits the program.
  232. If ``version`` is not provided, Click will try to detect it using
  233. :func:`importlib.metadata.version` to get the version for the
  234. ``package_name``. On Python < 3.8, the ``importlib_metadata``
  235. backport must be installed.
  236. If ``package_name`` is not provided, Click will try to detect it by
  237. inspecting the stack frames. This will be used to detect the
  238. version, so it must match the name of the installed package.
  239. :param version: The version number to show. If not provided, Click
  240. will try to detect it.
  241. :param param_decls: One or more option names. Defaults to the single
  242. value ``"--version"``.
  243. :param package_name: The package name to detect the version from. If
  244. not provided, Click will try to detect it.
  245. :param prog_name: The name of the CLI to show in the message. If not
  246. provided, it will be detected from the command.
  247. :param message: The message to show. The values ``%(prog)s``,
  248. ``%(package)s``, and ``%(version)s`` are available. Defaults to
  249. ``"%(prog)s, version %(version)s"``.
  250. :param kwargs: Extra arguments are passed to :func:`option`.
  251. :raise RuntimeError: ``version`` could not be detected.
  252. .. versionchanged:: 8.0
  253. Add the ``package_name`` parameter, and the ``%(package)s``
  254. value for messages.
  255. .. versionchanged:: 8.0
  256. Use :mod:`importlib.metadata` instead of ``pkg_resources``. The
  257. version is detected based on the package name, not the entry
  258. point name. The Python package name must match the installed
  259. package name, or be passed with ``package_name=``.
  260. """
  261. if message is None:
  262. message = _("%(prog)s, version %(version)s")
  263. if version is None and package_name is None:
  264. frame = inspect.currentframe()
  265. f_back = frame.f_back if frame is not None else None
  266. f_globals = f_back.f_globals if f_back is not None else None
  267. # break reference cycle
  268. # https://docs.python.org/3/library/inspect.html#the-interpreter-stack
  269. del frame
  270. if f_globals is not None:
  271. package_name = f_globals.get("__name__")
  272. if package_name == "__main__":
  273. package_name = f_globals.get("__package__")
  274. if package_name:
  275. package_name = package_name.partition(".")[0]
  276. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  277. if not value or ctx.resilient_parsing:
  278. return
  279. nonlocal prog_name
  280. nonlocal version
  281. if prog_name is None:
  282. prog_name = ctx.find_root().info_name
  283. if version is None and package_name is not None:
  284. metadata: t.Optional[types.ModuleType]
  285. try:
  286. from importlib import metadata # type: ignore
  287. except ImportError:
  288. # Python < 3.8
  289. import importlib_metadata as metadata # type: ignore
  290. try:
  291. version = metadata.version(package_name) # type: ignore
  292. except metadata.PackageNotFoundError: # type: ignore
  293. raise RuntimeError(
  294. f"{package_name!r} is not installed. Try passing"
  295. " 'package_name' instead."
  296. ) from None
  297. if version is None:
  298. raise RuntimeError(
  299. f"Could not determine the version for {package_name!r} automatically."
  300. )
  301. echo(
  302. t.cast(str, message)
  303. % {"prog": prog_name, "package": package_name, "version": version},
  304. color=ctx.color,
  305. )
  306. ctx.exit()
  307. if not param_decls:
  308. param_decls = ("--version",)
  309. kwargs.setdefault("is_flag", True)
  310. kwargs.setdefault("expose_value", False)
  311. kwargs.setdefault("is_eager", True)
  312. kwargs.setdefault("help", _("Show the version and exit."))
  313. kwargs["callback"] = callback
  314. return option(*param_decls, **kwargs)
  315. def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  316. """Add a ``--help`` option which immediately prints the help page
  317. and exits the program.
  318. This is usually unnecessary, as the ``--help`` option is added to
  319. each command automatically unless ``add_help_option=False`` is
  320. passed.
  321. :param param_decls: One or more option names. Defaults to the single
  322. value ``"--help"``.
  323. :param kwargs: Extra arguments are passed to :func:`option`.
  324. """
  325. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  326. if not value or ctx.resilient_parsing:
  327. return
  328. echo(ctx.get_help(), color=ctx.color)
  329. ctx.exit()
  330. if not param_decls:
  331. param_decls = ("--help",)
  332. kwargs.setdefault("is_flag", True)
  333. kwargs.setdefault("expose_value", False)
  334. kwargs.setdefault("is_eager", True)
  335. kwargs.setdefault("help", _("Show this message and exit."))
  336. kwargs["callback"] = callback
  337. return option(*param_decls, **kwargs)