You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

438 lines
15KB

  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. assert frame is not None
  266. assert frame.f_back is not None
  267. f_globals = frame.f_back.f_globals if frame is not None else None
  268. # break reference cycle
  269. # https://docs.python.org/3/library/inspect.html#the-interpreter-stack
  270. del frame
  271. if f_globals is not None:
  272. package_name = f_globals.get("__name__")
  273. if package_name == "__main__":
  274. package_name = f_globals.get("__package__")
  275. if package_name:
  276. package_name = package_name.partition(".")[0]
  277. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  278. if not value or ctx.resilient_parsing:
  279. return
  280. nonlocal prog_name
  281. nonlocal version
  282. if prog_name is None:
  283. prog_name = ctx.find_root().info_name
  284. if version is None and package_name is not None:
  285. metadata: t.Optional[types.ModuleType]
  286. try:
  287. from importlib import metadata # type: ignore
  288. except ImportError:
  289. # Python < 3.8
  290. import importlib_metadata as metadata # type: ignore
  291. try:
  292. version = metadata.version(package_name) # type: ignore
  293. except metadata.PackageNotFoundError: # type: ignore
  294. raise RuntimeError(
  295. f"{package_name!r} is not installed. Try passing"
  296. " 'package_name' instead."
  297. )
  298. if version is None:
  299. raise RuntimeError(
  300. f"Could not determine the version for {package_name!r} automatically."
  301. )
  302. echo(
  303. t.cast(str, message)
  304. % {"prog": prog_name, "package": package_name, "version": version},
  305. color=ctx.color,
  306. )
  307. ctx.exit()
  308. if not param_decls:
  309. param_decls = ("--version",)
  310. kwargs.setdefault("is_flag", True)
  311. kwargs.setdefault("expose_value", False)
  312. kwargs.setdefault("is_eager", True)
  313. kwargs.setdefault("help", _("Show the version and exit."))
  314. kwargs["callback"] = callback
  315. return option(*param_decls, **kwargs)
  316. def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
  317. """Add a ``--help`` option which immediately prints the help page
  318. and exits the program.
  319. This is usually unnecessary, as the ``--help`` option is added to
  320. each command automatically unless ``add_help_option=False`` is
  321. passed.
  322. :param param_decls: One or more option names. Defaults to the single
  323. value ``"--help"``.
  324. :param kwargs: Extra arguments are passed to :func:`option`.
  325. """
  326. def callback(ctx: Context, param: Parameter, value: bool) -> None:
  327. if not value or ctx.resilient_parsing:
  328. return
  329. echo(ctx.get_help(), color=ctx.color)
  330. ctx.exit()
  331. if not param_decls:
  332. param_decls = ("--help",)
  333. kwargs.setdefault("is_flag", True)
  334. kwargs.setdefault("expose_value", False)
  335. kwargs.setdefault("is_eager", True)
  336. kwargs.setdefault("help", _("Show this message and exit."))
  337. kwargs["callback"] = callback
  338. return option(*param_decls, **kwargs)