decorators.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import inspect
  2. import sys
  3. from functools import update_wrapper
  4. from ._compat import iteritems
  5. from ._unicodefun import _check_for_unicode_literals
  6. from .core import Argument
  7. from .core import Command
  8. from .core import Group
  9. from .core import Option
  10. from .globals import get_current_context
  11. from .utils import echo
  12. def pass_context(f):
  13. """Marks a callback as wanting to receive the current context
  14. object as first argument.
  15. """
  16. def new_func(*args, **kwargs):
  17. return f(get_current_context(), *args, **kwargs)
  18. return update_wrapper(new_func, f)
  19. def pass_obj(f):
  20. """Similar to :func:`pass_context`, but only pass the object on the
  21. context onwards (:attr:`Context.obj`). This is useful if that object
  22. represents the state of a nested system.
  23. """
  24. def new_func(*args, **kwargs):
  25. return f(get_current_context().obj, *args, **kwargs)
  26. return update_wrapper(new_func, f)
  27. def make_pass_decorator(object_type, ensure=False):
  28. """Given an object type this creates a decorator that will work
  29. similar to :func:`pass_obj` but instead of passing the object of the
  30. current context, it will find the innermost context of type
  31. :func:`object_type`.
  32. This generates a decorator that works roughly like this::
  33. from functools import update_wrapper
  34. def decorator(f):
  35. @pass_context
  36. def new_func(ctx, *args, **kwargs):
  37. obj = ctx.find_object(object_type)
  38. return ctx.invoke(f, obj, *args, **kwargs)
  39. return update_wrapper(new_func, f)
  40. return decorator
  41. :param object_type: the type of the object to pass.
  42. :param ensure: if set to `True`, a new object will be created and
  43. remembered on the context if it's not there yet.
  44. """
  45. def decorator(f):
  46. def new_func(*args, **kwargs):
  47. ctx = get_current_context()
  48. if ensure:
  49. obj = ctx.ensure_object(object_type)
  50. else:
  51. obj = ctx.find_object(object_type)
  52. if obj is None:
  53. raise RuntimeError(
  54. "Managed to invoke callback without a context"
  55. " object of type '{}' existing".format(object_type.__name__)
  56. )
  57. return ctx.invoke(f, obj, *args, **kwargs)
  58. return update_wrapper(new_func, f)
  59. return decorator
  60. def _make_command(f, name, attrs, cls):
  61. if isinstance(f, Command):
  62. raise TypeError("Attempted to convert a callback into a command twice.")
  63. try:
  64. params = f.__click_params__
  65. params.reverse()
  66. del f.__click_params__
  67. except AttributeError:
  68. params = []
  69. help = attrs.get("help")
  70. if help is None:
  71. help = inspect.getdoc(f)
  72. if isinstance(help, bytes):
  73. help = help.decode("utf-8")
  74. else:
  75. help = inspect.cleandoc(help)
  76. attrs["help"] = help
  77. _check_for_unicode_literals()
  78. return cls(
  79. name=name or f.__name__.lower().replace("_", "-"),
  80. callback=f,
  81. params=params,
  82. **attrs
  83. )
  84. def command(name=None, cls=None, **attrs):
  85. r"""Creates a new :class:`Command` and uses the decorated function as
  86. callback. This will also automatically attach all decorated
  87. :func:`option`\s and :func:`argument`\s as parameters to the command.
  88. The name of the command defaults to the name of the function with
  89. underscores replaced by dashes. If you want to change that, you can
  90. pass the intended name as the first argument.
  91. All keyword arguments are forwarded to the underlying command class.
  92. Once decorated the function turns into a :class:`Command` instance
  93. that can be invoked as a command line utility or be attached to a
  94. command :class:`Group`.
  95. :param name: the name of the command. This defaults to the function
  96. name with underscores replaced by dashes.
  97. :param cls: the command class to instantiate. This defaults to
  98. :class:`Command`.
  99. """
  100. if cls is None:
  101. cls = Command
  102. def decorator(f):
  103. cmd = _make_command(f, name, attrs, cls)
  104. cmd.__doc__ = f.__doc__
  105. return cmd
  106. return decorator
  107. def group(name=None, **attrs):
  108. """Creates a new :class:`Group` with a function as callback. This
  109. works otherwise the same as :func:`command` just that the `cls`
  110. parameter is set to :class:`Group`.
  111. """
  112. attrs.setdefault("cls", Group)
  113. return command(name, **attrs)
  114. def _param_memo(f, param):
  115. if isinstance(f, Command):
  116. f.params.append(param)
  117. else:
  118. if not hasattr(f, "__click_params__"):
  119. f.__click_params__ = []
  120. f.__click_params__.append(param)
  121. def argument(*param_decls, **attrs):
  122. """Attaches an argument to the command. All positional arguments are
  123. passed as parameter declarations to :class:`Argument`; all keyword
  124. arguments are forwarded unchanged (except ``cls``).
  125. This is equivalent to creating an :class:`Argument` instance manually
  126. and attaching it to the :attr:`Command.params` list.
  127. :param cls: the argument class to instantiate. This defaults to
  128. :class:`Argument`.
  129. """
  130. def decorator(f):
  131. ArgumentClass = attrs.pop("cls", Argument)
  132. _param_memo(f, ArgumentClass(param_decls, **attrs))
  133. return f
  134. return decorator
  135. def option(*param_decls, **attrs):
  136. """Attaches an option to the command. All positional arguments are
  137. passed as parameter declarations to :class:`Option`; all keyword
  138. arguments are forwarded unchanged (except ``cls``).
  139. This is equivalent to creating an :class:`Option` instance manually
  140. and attaching it to the :attr:`Command.params` list.
  141. :param cls: the option class to instantiate. This defaults to
  142. :class:`Option`.
  143. """
  144. def decorator(f):
  145. # Issue 926, copy attrs, so pre-defined options can re-use the same cls=
  146. option_attrs = attrs.copy()
  147. if "help" in option_attrs:
  148. option_attrs["help"] = inspect.cleandoc(option_attrs["help"])
  149. OptionClass = option_attrs.pop("cls", Option)
  150. _param_memo(f, OptionClass(param_decls, **option_attrs))
  151. return f
  152. return decorator
  153. def confirmation_option(*param_decls, **attrs):
  154. """Shortcut for confirmation prompts that can be ignored by passing
  155. ``--yes`` as parameter.
  156. This is equivalent to decorating a function with :func:`option` with
  157. the following parameters::
  158. def callback(ctx, param, value):
  159. if not value:
  160. ctx.abort()
  161. @click.command()
  162. @click.option('--yes', is_flag=True, callback=callback,
  163. expose_value=False, prompt='Do you want to continue?')
  164. def dropdb():
  165. pass
  166. """
  167. def decorator(f):
  168. def callback(ctx, param, value):
  169. if not value:
  170. ctx.abort()
  171. attrs.setdefault("is_flag", True)
  172. attrs.setdefault("callback", callback)
  173. attrs.setdefault("expose_value", False)
  174. attrs.setdefault("prompt", "Do you want to continue?")
  175. attrs.setdefault("help", "Confirm the action without prompting.")
  176. return option(*(param_decls or ("--yes",)), **attrs)(f)
  177. return decorator
  178. def password_option(*param_decls, **attrs):
  179. """Shortcut for password prompts.
  180. This is equivalent to decorating a function with :func:`option` with
  181. the following parameters::
  182. @click.command()
  183. @click.option('--password', prompt=True, confirmation_prompt=True,
  184. hide_input=True)
  185. def changeadmin(password):
  186. pass
  187. """
  188. def decorator(f):
  189. attrs.setdefault("prompt", True)
  190. attrs.setdefault("confirmation_prompt", True)
  191. attrs.setdefault("hide_input", True)
  192. return option(*(param_decls or ("--password",)), **attrs)(f)
  193. return decorator
  194. def version_option(version=None, *param_decls, **attrs):
  195. """Adds a ``--version`` option which immediately ends the program
  196. printing out the version number. This is implemented as an eager
  197. option that prints the version and exits the program in the callback.
  198. :param version: the version number to show. If not provided Click
  199. attempts an auto discovery via setuptools.
  200. :param prog_name: the name of the program (defaults to autodetection)
  201. :param message: custom message to show instead of the default
  202. (``'%(prog)s, version %(version)s'``)
  203. :param others: everything else is forwarded to :func:`option`.
  204. """
  205. if version is None:
  206. if hasattr(sys, "_getframe"):
  207. module = sys._getframe(1).f_globals.get("__name__")
  208. else:
  209. module = ""
  210. def decorator(f):
  211. prog_name = attrs.pop("prog_name", None)
  212. message = attrs.pop("message", "%(prog)s, version %(version)s")
  213. def callback(ctx, param, value):
  214. if not value or ctx.resilient_parsing:
  215. return
  216. prog = prog_name
  217. if prog is None:
  218. prog = ctx.find_root().info_name
  219. ver = version
  220. if ver is None:
  221. try:
  222. import pkg_resources
  223. except ImportError:
  224. pass
  225. else:
  226. for dist in pkg_resources.working_set:
  227. scripts = dist.get_entry_map().get("console_scripts") or {}
  228. for _, entry_point in iteritems(scripts):
  229. if entry_point.module_name == module:
  230. ver = dist.version
  231. break
  232. if ver is None:
  233. raise RuntimeError("Could not determine version")
  234. echo(message % {"prog": prog, "version": ver}, color=ctx.color)
  235. ctx.exit()
  236. attrs.setdefault("is_flag", True)
  237. attrs.setdefault("expose_value", False)
  238. attrs.setdefault("is_eager", True)
  239. attrs.setdefault("help", "Show the version and exit.")
  240. attrs["callback"] = callback
  241. return option(*(param_decls or ("--version",)), **attrs)(f)
  242. return decorator
  243. def help_option(*param_decls, **attrs):
  244. """Adds a ``--help`` option which immediately ends the program
  245. printing out the help page. This is usually unnecessary to add as
  246. this is added by default to all commands unless suppressed.
  247. Like :func:`version_option`, this is implemented as eager option that
  248. prints in the callback and exits.
  249. All arguments are forwarded to :func:`option`.
  250. """
  251. def decorator(f):
  252. def callback(ctx, param, value):
  253. if value and not ctx.resilient_parsing:
  254. echo(ctx.get_help(), color=ctx.color)
  255. ctx.exit()
  256. attrs.setdefault("is_flag", True)
  257. attrs.setdefault("expose_value", False)
  258. attrs.setdefault("help", "Show this message and exit.")
  259. attrs.setdefault("is_eager", True)
  260. attrs["callback"] = callback
  261. return option(*(param_decls or ("--help",)), **attrs)(f)
  262. return decorator