decorators.py 11 KB

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