Skip to content
Myr

click.py

This file

Path

click.py

1,656 lines · 57.9 KiB · Python

Last changed by

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

History of this file

Take it

Initial commitArmin Ronacherbefore adoption4101de3

lines 1–24
1# -*- coding: utf-8 -*-
2"""3 click4 ~~~~~56 click is a simple Python module that wraps the stdlib's optparse to make7 writing command line scripts fun. Unlike other modules it's based around8 a simple API that does not come with too much magic and is composable.910 In case optparse ever goes away from the stdlib it will be shipped by11 this module.1213 :copyright: (c) 2014 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16import os17import sys18import codecs19import inspect20import getpass21import optparse22import textwrap23import struct24from itertools import chain

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 25why, one step back
25from functools import update_wrapper

Initial commitArmin Ronacherbefore adoption4101de3

lines 26–76
26
2728PY2 = sys.version_info[0] == 229if PY2:30 text_type = unicode31 bytes = str3233 def open_stream(filename, mode='r', encoding=None, errors='strict'):34 if filename != '-':35 if encoding is not None:36 return codecs.open(filename, mode, encoding, errors), True37 return open(filename, mode), True38 if 'w' in mode:39 f = sys.stdout40 if encoding is not None:41 f = _wrap_stream_for_codec(f, encoding, errors)42 else:43 f = sys.stdin44 if 'b' not in mode:45 if encoding is None:46 encoding = sys.stdin.encoding47 f = _wrap_stream_for_codec(f, encoding, errors)48 return f, False49else:50 text_type = str51 raw_input = input5253 def open_stream(filename, mode='r', encoding=None, errors='strict'):54 if filename != '-':55 return open(filename, mode, encoding=encoding, errors=errors), True56 if 'w' in mode:57 f = sys.stdout58 if encoding is not None or 'b' in mode:59 f = f.buffer.raw60 if encoding is not None:61 f = _wrap_stream_for_codec(f, encoding, errors)62 else:63 f = sys.stdin64 if 'b' in mode:65 f = f.buffer.raw66 if encoding is not None:67 f = _wrap_stream_for_codec(f, encoding, errors)68 return f, False697071def get_terminal_size():72 """Returns the current size of the terminal as tuple in the form73 ``(width, height)`` in columns and rows.74 """75 def ioctl_gwinsz(fd):76 try:

Merge pull request #9 from ikkebr/patch-3Armin Ronacherbefore adoption3755db7

lines 77–78why, one step back
77 import fcntl
78 import termios

Initial commitArmin Ronacherbefore adoption4101de3

lines 79–99
79 cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
80 except Exception:81 return82 return cr8384 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)85 if not cr:86 try:87 fd = os.open(os.ctermid(), os.O_RDONLY)88 try:89 cr = ioctl_gwinsz(fd)90 finally:91 os.close(fd)92 except Exception:93 pass94 if not cr:95 cr = (os.environ.get('LINES', 25),96 os.environ.get('COLUMNS', 80))97 return int(cr[1]), int(cr[0])9899

Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf

lines 100–109why, one step back
100def safecall(func):
101 """Wraps a function so that it swallows exceptions."""102 def wrapper(*args, **kwargs):103 try:104 return func(*args, **kwargs)105 except Exception:106 pass107 return wrapper108109

Initial commitArmin Ronacherbefore adoption4101de3

lines 110–170
110class TextWrapper(textwrap.TextWrapper):
111112 def _cutdown(self, ucstr, space_left):113 l = 0114 for i in xrange(len(ucstr)):115 l += len(ucstr[i])116 if space_left < l:117 return (ucstr[:i], ucstr[i:])118 return ucstr, ''119120 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):121 space_left = max(width - cur_len, 1)122123 if self.break_long_words:124 cut, res = self._cutdown(reversed_chunks[-1], space_left)125 cur_line.append(cut)126 reversed_chunks[-1] = res127 elif not cur_line:128 cur_line.append(reversed_chunks.pop())129130 def fill_paragraphs(self, text):131 # Remove unnecessary newlines so that we can fill properly132 p = []133 buf = []134 for line in text.splitlines():135 if not line:136 p.append(' '.join(buf))137 buf = []138 else:139 buf.append(line)140 if buf:141 p.append(' '.join(buf))142143 rv = []144 for text in p:145 rv.append(self.fill(text))146 return '\n\n'.join(rv)147148149def _wrap_stream_for_codec(f, encoding=None, errors='strict'):150 if encoding is None:151 encoding = 'utf-8'152 info = codecs.lookup(encoding)153 f = codecs.StreamReaderWriter(f, info.streamreader,154 info.streamwriter,155 errors)156 f.encoding = encoding157 return f158159160def echo(message=None, file=None):161 if file is None:162 file = sys.stdout163 if message:164 if PY2 and isinstance(message, text_type):165 message = message.encode(file.encoding)166 file.write(message)167 file.write('\n')168 file.flush()169170

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 171–222why, one step back
171def pass_context(f):
172 """Marks a callback that it wants to receive the current context173 object as first argument.174 """175 f.__click_pass_context__ = True176 return f177178179def pass_obj(f):180 """Similar to :func:`pass_context` but only pass the object on the181 context onwards (:attr:`Context.obj`). This is useful if that object182 represents the state of a nested system.183 """184 @pass_context185 def new_func(*args, **kwargs):186 ctx = args[0]187 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)188 return update_wrapper(new_func, f)189190191def make_pass_decorator(object_type):192 """Given an object type this creates a decorator that will work193 similar to :func:`pass_obj` but instead of passing the object of the194 current context, it will find the innermost context of type195 :func:`object_type`.196197 This generates a decorator that works roughly like this::198199 from functools import update_wrapper200201 def decorator(f):202 @pass_context203 def new_func(ctx, *args, **kwargs):204 obj = ctx.find_object(object_type)205 return ctx.invoke(f, obj, *args, **kwargs)206 return update_wrapper(new_func, f)207 return decorator208 """209 def decorator(f):210 @pass_context211 def new_func(*args, **kwargs):212 ctx = args[0]213 obj = ctx.find_object(object_type)214 if obj is None:215 raise RuntimeError('Managed to invoke callback without a '216 'context object of type %r existing'217 % object_type.__name__)218 return ctx.invoke(f, obj, *args[1:], **kwargs)219 return update_wrapper(new_func, f)220 return decorator221222

Initial commitArmin Ronacherbefore adoption4101de3

lines 223–333
223class Context(object):
224 """The context is a special internal object that holds state relevant225 for the script execution at every single level. It's normally invisible226 to commands unless they opt-in to getting access to it.227228 The context is useful as it can pass internal objects around and can229 control special execution features such as reading data from230 environment variables.231232 A context can be used as context manager in which case it will call233 :meth:`close` on teardown.234235 :param command: the command class for this context.236 :param parent: the parent context.237 :param info_name: the info name for this invokation. Generally this238 is the most descriptive name for the script or239 command. For the toplevel script is is usually240 the name of the script, for commands below it it's241 the name of the script.242 :param obj: an arbitrary object of user data.243 :param auto_envvar_prefix: the prefix to use for automatic environment244 variables. If this is `None` then reading245 from environment variables is disabled. This246 does not affect manually set environment247 variables which are always read.248 """249250 def __init__(self, command, parent=None, info_name=None, obj=None,251 auto_envvar_prefix=None):252 #: the parent context or `None` if none exists.253 self.parent = parent254 #: the :class:`Command` for this context.255 self.command = command256 #: the descriptive information name257 self.info_name = info_name258 #: the parsed parameters except if the value is hidden in which259 #: case it's not remembered.260 self.params = {}261 #: the leftover arguments.262 self.args = []263 #: this flag indicates if a subcommand is going to be executed.264 #: a group callback can use this information to figure out if it's265 #: being executed directly or because the execution flow passes266 #: onwards to a subcommand. By default it's `None` but it can be267 #: the name of the subcommand to execute.268 self.invoked_subcommand = None269 if obj is None and parent is not None:270 obj = parent.obj271 #: the user object stored.272 self.obj = obj273274 # If there is no envvar prefix yet, but the parent has one and275 # the command on this level has a name, we can expand the envvar276 # prefix automatically.277 if auto_envvar_prefix is None:278 if parent is not None \279 and parent.auto_envvar_prefix is not None and \280 self.info_name is not None:281 auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,282 self.info_name.upper())283 else:284 self.auto_envvar_prefix = auto_envvar_prefix.upper()285 self.auto_envvar_prefix = auto_envvar_prefix286287 self._parser = command._make_parser(self)288 self._close_callbacks = []289290 def __enter__(self):291 return self292293 def __exit__(self, exc_type, exc_value, tb):294 self.close()295296 def call_on_close(self, f):297 """This decorator remembers a function as callback that should be298 executed when the context tears down. This is most useful to bind299 resource handling to the script execution. For instance file objects300 opened by the :class:`File` type will register their close callbacks301 here.302303 :param f: the function to execute on teardown.304 """305 self._close_callbacks.append(f)306 return f307308 def close(self):309 """Invokes all close callbacks."""310 for cb in self._close_callbacks:311 cb()312 self._close_callbacks = []313314 @property315 def command_path(self):316 """The computed command path. This is used for the ``usage``317 information on the help page. It's automatically created by318 combining the info names of the chain of contexts to the root.319 """320 rv = ''321 if self.info_name is not None:322 rv = self.info_name323 if self.parent is not None:324 rv = self.parent.command_path + ' ' + rv325 return rv.lstrip()326327 def find_root(self):328 """Finds the outermost context."""329 node = self330 while node.parent is not None:331 node = node.parent332 return node333

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 334–341why, one step back
334 def find_object(self, object_type):
335 """Finds the closest object of a given type."""336 node = self337 while node.parent is not None:338 if isinstance(node.obj, object_type):339 return node.obj340 node = node.parent341

Initial commitArmin Ronacherbefore adoption4101de3

lines 342–369
342 def fail(self, message):
343 """Aborts the execution of the program with a specific error344 message.345346 :param message: the error message to fail with.347 """348 raise UsageError(message, self)349350 def abort(self):351 """Aborts the script."""352 raise Abort()353354 def exit(self, code=0):355 """Exits the application with a given exit code."""356 sys.exit(code)357358 def format_usage(self):359 """Helper method to get formatted usage string for the current360 context and command.361 """362 return self._parser.get_usage()363364 def format_help(self):365 """Helper method to get formatted help page for the current366 context and command.367 """368 return self._parser.format_help().rstrip()369

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 370–377why, one step back
370 def invoke(*args, **kwargs):
371 """Invokes a command callback in exactly the way it expects.372 """373 self, callback = args[:2]374 args = args[2:]375 if getattr(callback, '__click_pass_context__', False):376 args = (self,) + args377 return callback(*args, **kwargs)

Initial commitArmin Ronacherbefore adoption4101de3

line 378
378

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 379why, one step back
379

Initial commitArmin Ronacherbefore adoption4101de3

lines 380–473
380class UsageError(Exception):
381 """An internal exception that signals a usage error. This typically382 aborts any further handling.383 """384385 def __init__(self, message, ctx=None):386 if PY2:387 Exception.__init__(self, message.encode('utf-8'))388 else:389 Exception.__init__(self, message)390 self.message = message391 self.ctx = ctx392393394class Abort(Exception):395 """An internal signalling exception that signals click to abort."""396397398class _SimplifiedFormatter(optparse.IndentedHelpFormatter):399400 def __init__(self):401 optparse.IndentedHelpFormatter.__init__(self,402 width=min(get_terminal_size()[0], 80) - 2)403 self.default_tag = ''404405 def format_usage(self, usage):406 prefix = 'Usage: '407 indent = len(prefix)408 text_width = self.width - indent409 return '%s%s\n' % (prefix, TextWrapper(410 text_width, initial_indent='',411 subsequent_indent=' ' * indent,412 replace_whitespace=False).fill(usage))413414 def _format_text(self, text):415 text_width = self.width - self.current_indent416 indent = ' ' * self.current_indent417418 return TextWrapper(text_width,419 initial_indent=indent,420 subsequent_indent=indent,421 replace_whitespace=False).fill_paragraphs(text)422423 def format_description(self, description):424 if not description:425 return ''426 self.indent()427 rv = self._format_text(description) + '\n'428 self.dedent()429 return rv430431 def format_option_strings(self, option):432 rv = optparse.IndentedHelpFormatter.format_option_strings(self, option)433 if hasattr(option, '_negative_version'):434 rv += ' / ' + optparse.IndentedHelpFormatter.format_option_strings(435 self, option._negative_version)436 return rv437438439class _SimplifiedOptionParser(optparse.OptionParser):440441 def __init__(self, ctx, **extra):442 usage = ctx.command_path + ' ' + ctx.command.options_metavar443 optparse.OptionParser.__init__(self, prog=ctx.command_path,444 usage=usage,445 add_help_option=False,446 formatter=_SimplifiedFormatter(),447 **extra)448 self.__ctx = ctx449450 def expand_prog_name(self, s):451 return s452453 def format_option_help(self, formatter):454 rv = optparse.OptionParser.format_option_help(self, formatter)455 extra_help = self.__ctx.command._format_extra_help(self.__ctx)456 if extra_help:457 rv = '%s\n\n%s' % (extra_help, rv)458 return rv459460 def error(self, msg):461 raise UsageError(msg, self.__ctx)462463464class Command(object):465 """Commands are the basic building block of command line interfaces in466 click. A basic command handles command line parsing and might dispatch467 more parsing to commands nested blow it.468469 :param name: the name of the command to use unless a group overrides it.470 :param callback: the callback to invoke. This is optional.471 :param params: the parameters to register with this command. This can472 be either :class:`Option` or :class:`Argument` objects.473 :param help: the help string to use for this command.

Added epilog support.Armin Ronacherbefore adoption9d027aa

lines 474–475why, one step back
474 :param epilog: like the help string but it's printed at the end of the
475 help page after everything else.

Initial commitArmin Ronacherbefore adoption4101de3

lines 476–482
476 :param short_help: the short help to use for this command. This is
477 shown on the command listing of the parent command.478 :param add_help_option: by default each command registers a ``--help``479 option. This can be disabled by this parameter.480 """481 allow_extra_args = False482

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 483why, one step back
483 def __init__(self, name, callback=None, params=None, help=None,

Added epilog support.Armin Ronacherbefore adoption9d027aa

lines 484–485why, one step back
484 epilog=None, short_help=None,
485 options_metavar='[OPTIONS]', add_help_option=True):

Initial commitArmin Ronacherbefore adoption4101de3

lines 486–498
486 #: the name the command things it has. Upon registering a command
487 #: on a :class:`Group` the group will default the command name488 #: with this information. You should instead use the489 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.490 self.name = name491 #: the callback to execute when the command fires. This might be492 #: `None` in which case nothing happens.493 self.callback = callback494 #: the list of parameters for this command in the order they495 #: should show up in the help page and execute. Eager parameters496 #: will automatically be handled before non eager ones.497 self.params = params or []498 self.help = help

Added epilog support.Armin Ronacherbefore adoption9d027aa

line 499why, one step back
499 self.epilog = epilog

Initial commitArmin Ronacherbefore adoption4101de3

lines 500–523
500 self.options_metavar = options_metavar
501 if short_help is None and help:502 short_help = help.split('.')[0].strip()503 if len(short_help) > 45:504 short_help = None505 elif short_help:506 short_help = short_help[0].lower() + short_help[1:] + '.'507 self.short_help = short_help508 if add_help_option:509 help_option()(self)510511 def iter_params_for_processing(self):512 """This returns an iterator over all attached parameters in the513 order of processing. This iterator returns all eager parameters514 first, followed by all non-eager parameters.515 """516 for param in self.params:517 if param.is_eager:518 yield param519 for param in self.params:520 if not param.is_eager:521 yield param522523 def _make_parser(self, ctx):

Added epilog support.Armin Ronacherbefore adoption9d027aa

lines 524–525why, one step back
524 parser = _SimplifiedOptionParser(ctx, description=self.help,
525 epilog=self.epilog)

Initial commitArmin Ronacherbefore adoption4101de3

lines 526–567
526 for param in self.params:
527 param._add_to_parser(parser, ctx)528 return parser529530 def _format_extra_help(self, ctx):531 pass532533 def make_context(self, info_name, args, parent=None, **extra):534 """This function when given an info name and arguments will kick535 off the parsing and create a new :class:`Context`. It does not536 invoke the actual command callback though.537538 :param info_name: the info name for this invokation. Generally this539 is the most descriptive name for the script or540 command. For the toplevel script is is usually541 the name of the script, for commands below it it's542 the name of the script.543 :param args: the arguments to parse as list of strings.544 :param parent: the parent context if available.545 :param extra: extra keyword arguments forwarded to the context546 constructor.547 """548 ctx = Context(self, info_name=info_name, parent=parent, **extra)549 opts, args = ctx._parser.parse_args(args=args)550 opts = opts.__dict__551552 for param in ctx.command.iter_params_for_processing():553 value, args = param.handle_parse_result(ctx, opts, args)554555 if args and not self.allow_extra_args:556 ctx.fail('Got unexpected extra argument%s (%s)'557 % (len(args) != 1 and 's' or '', ' '.join(args)))558559 ctx.args = args560561 return ctx562563 def invoke(self, ctx):564 """Given a context, this invokes the attached callback (if it exists)565 in the right way.566 """567 if self.callback is not None:

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 568why, one step back
568 ctx.invoke(self.callback, **ctx.params)

Initial commitArmin Ronacherbefore adoption4101de3

lines 569–634
569
570 def main(self, args=None, prog_name=None, **extra):571 """This is the way to invoke a script with all the bells and572 whistles as command line application. This will always terminate573 the application after calling. If this is not wanted, ``SystemExit``574 needs to be caught.575576 This method is also available by directly calling the instance of577 a :class:`Command`.578579 :param args: the arguments that should be used for parsing. If not580 provided, ``sys.argv[1:]`` is used.581 :param prog_name: the program name that should be used. By default582 the progam name is constructed by taking the file583 name from ``sys.argv[0]``.584 :param extra: extra keyword arguments are forwarded to the context585 constructor.586 """587 if args is None:588 args = sys.argv[1:]589 else:590 args = list(args)591 if prog_name is None:592 prog_name = os.path.basename(sys.argv and sys.argv[0] or __file__)593 try:594 try:595 with self.make_context(prog_name, args, **extra) as ctx:596 self.invoke(ctx)597 ctx.exit()598 except (EOFError, KeyboardInterrupt):599 echo(file=sys.stderr)600 raise Abort()601 except UsageError as e:602 if e.ctx is not None:603 echo(e.ctx.format_usage(), file=sys.stderr)604 echo('Error: %s' % e.message, file=sys.stderr)605 sys.exit(2)606 except Abort:607 echo('Aborted!', file=sys.stderr)608 sys.exit(1)609610 def __call__(self, *args, **kwargs):611 """Alias for :meth:`main`."""612 return self.main(*args, **kwargs)613614615class MultiCommand(Command):616 """A multi command is the basic implementation of a command that617 dispatches to subcommands. The most common version is the618 :class:`Command`.619620 :param invoke_without_command: this controls how the multi command itself621 is invoked. By default it's only invoked622 if a subcommand is provided.623 :param no_args_is_help: this controls what happens if no arguments are624 provided. This option is enabled by default if625 `invoke_without_command` is disabled or disabled626 if it's enabled. If enabled this will add627 ``--help`` as argument if no arguments are628 passed.629 :param subcommand_metavar: the string that is used in the documentation630 to indicate the subcommand place.631 """632 allow_extra_args = True633634 def __init__(self, name=None, invoke_without_command=False,

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 635–636why, one step back
635 no_args_is_help=None, subcommand_metavar='COMMAND [ARGS]...',
636 **attrs):

Initial commitArmin Ronacherbefore adoption4101de3

lines 637–764
637 Command.__init__(self, name, **attrs)
638 if no_args_is_help is None:639 no_args_is_help = not invoke_without_command640 self.no_args_is_help = no_args_is_help641 self.invoke_without_command = invoke_without_command642 self.subcommand_metavar = subcommand_metavar643644 def _make_parser(self, ctx):645 parser = Command._make_parser(self, ctx)646 parser.usage += ' ' + self.subcommand_metavar647 parser.disable_interspersed_args()648 return parser649650 def _format_extra_help(self, ctx):651 commands = self.list_commands()652 if not commands:653 return654655 longest = len(sorted(commands, key=len)[-1])656657 subcommand_info = []658 for subcommand in self.list_commands():659 cmd = self.get_command(ctx, subcommand)660 help = cmd.short_help or ''661 subcommand_info.append(' %-*s %s' % (longest, subcommand, help))662663 return 'Commands:\n%s' % '\n'.join(subcommand_info)664665 def make_context(self, info_name, args, parent=None, **extra):666 # Multi-commands invoked without any arguments is a shortcut to667 # invoking it with --help unless supresssed.668 if not args and self.no_args_is_help:669 args = ['--help']670 return Command.make_context(self, info_name, args, parent, **extra)671672 def invoke(self, ctx):673 if not ctx.args:674 if self.invoke_without_command:675 return Command.invoke(self, ctx)676 ctx.fail('Missing command')677 cmd_name = ctx.args[0]678679 cmd = self.get_command(ctx, cmd_name)680 if cmd is None:681 ctx.fail('No such command "%s"' % cmd_name)682683 # Whenever we dispatch to a subcommand we also invoke the regular684 # callback. This is done so that parameters can be handled.685 ctx.invoked_subcommand = cmd_name686 Command.invoke(self, ctx)687688 with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:689 return cmd.invoke(cmd_ctx)690691 def get_command(self, ctx, cmd_name):692 """Given a context and a command name, this returns a693 :class:`Command` object if it exists or returns `None`.694 """695 raise NotImplementedError()696697 def list_commands(self):698 """Returns a list of subcommand names in the order they should699 appear.700 """701 return []702703704class Group(MultiCommand):705 """A group allows a command to have subcommands attached. This is the706 most common way to implement nesting in click.707708 :param commands: a dictionary of commands.709 """710711 def __init__(self, name=None, commands=None, **attrs):712 MultiCommand.__init__(self, name, **attrs)713 #: the registered subcommands by their exported names.714 self.commands = commands or {}715716 def add_command(self, cmd, name=None):717 """Registers another :class:`Command` with this group. If the name718 is not provided, the name of the command is used.719 """720 name = name or cmd.name721 if name is None:722 raise TypeError('Command has no name.')723 self.commands[name] = cmd724725 def command(self, *args, **kwargs):726 """A shortcut decorator for declaring and attaching a command to727 the group. This takes the same arguments as :func:`command` but728 immediately registers the created command with this instance by729 calling into :meth:`add_command`.730 """731 def decorator(f):732 cmd = command(*args, **kwargs)(f)733 self.add_command(cmd)734 return cmd735 return decorator736737 def get_command(self, ctx, cmd_name):738 return self.commands.get(cmd_name)739740 def list_commands(self):741 return sorted(self.commands)742743744class ParamType(object):745 """Helper for converting values through types. The following is746 necessary for a valid type:747748 * it needs a name749 * it needs to pass through None unchanged750 * it needs to convert from a string751 * it needs to convert its result type through unchanged752 (eg: needs to be idempotent)753 * it needs to be able to deal with param and context being none.754 This can be the case when the object is used with prompt755 inputs.756 """757758 #: the descriptive name of this type759 name = None760761 def __call__(self, value, param=None, ctx=None):762 if value is not None:763 return self.convert(value, param, ctx)764

Added choice supportArmin Ronacherbefore adoption9eacc90

lines 765–767why, one step back
765 def get_metavar(self, param):
766 """Returns the metavar default for this param if it provides one."""767

Initial commitArmin Ronacherbefore adoption4101de3

lines 768–819
768 def convert(self, param, ctx, value):
769 """Converts the value. This is not invoked for values that are770 `None` (the missing value).771 """772 return value773774 def fail(self, message, param=None, ctx=None):775 """Helper method to fail with an invalid value message."""776 if param is None:777 message = 'Invalid value: %s' % message778 else:779 message = 'Invalid value for %s: %s' % (param.name, message)780 raise UsageError(message, ctx=ctx)781782783class FuncParamType(ParamType):784785 def __init__(self, func):786 self.name = func.__name__787 self.func = func788789 def convert(self, value, param, ctx):790 try:791 return self.func(value)792 except ValueError:793 try:794 value = unicode(value)795 except UnicodeError:796 value = str(value).decode('utf-8', 'replace')797 self.fail(value, param, ctx)798799800class StringParamType(ParamType):801 name = 'string'802803 def convert(self, value, param, ctx):804 if isinstance(value, bytes):805 try:806 if sys.stdin.encoding is not None:807 value = value.decode(sys.stdin.encoding)808 except UnicodeError:809 try:810 value = value.decode(sys.getfilesystemencoding())811 except UnicodeError:812 value = value.decode('utf-8', 'replace')813 return value814 return value815816 def __repr__(self):817 return 'STRING'818819

Added choice supportArmin Ronacherbefore adoption9eacc90

lines 820–838why, one step back
820class Choice(ParamType):
821 name = 'choice'822823 def __init__(self, choices):824 self.choices = choices825826 def get_metavar(self, param):827 return '[%s]' % '|'.join(self.choices)828829 def convert(self, value, param, ctx):830 if value in self.choices:831 return value832 self.fail('invalid choice: %s. (chose from %s)' %833 (value, ', '.join(self.choices)), param, ctx)834835 def __repr__(self):836 return 'Choice(%r)' % list(self.choices)837838

Initial commitArmin Ronacherbefore adoption4101de3

lines 839–903
839class IntParamType(ParamType):
840 name = 'integer'841842 def convert(self, value, param, ctx):843 try:844 return int(value)845 except ValueError:846 self.fail('%s is not a valid integer' % value, param, ctx)847848 def __repr__(self):849 return 'INT'850851852class BoolParamType(ParamType):853 name = 'boolean'854855 def convert(self, value, param, ctx):856 if isinstance(value, bool):857 return bool(value)858 value = value.lower()859 if value in ('true', '1', 'yes', 'y'):860 return True861 elif value in ('false', '0', 'no', 'n'):862 return False863 self.fail('%s is not a valid boolean' % value, param, ctx)864865 def __repr__(self):866 return 'BOOL'867868869class FloatParamType(ParamType):870 name = 'float'871872 def convert(self, value, param, ctx):873 try:874 return float(value)875 except ValueError:876 self.fail('%s is not a valid floating point value' %877 value, param, ctx)878879 def __repr__(self):880 return 'FLOAT'881882883class File(ParamType):884 """Declares a parameter to be a file for reading or writing. The file885 is automatically closed once the context tears down (after the command886 finished working).887888 Files can be opened for reading or writing. The special value ``-``889 indicates stdin or stdout depending on the mode.890891 By default the file is opened for reading text data but it can also be892 opened in binary mode or for writing. The encoding parameter can be used893 to force a specific encoding.894 """895 name = 'filename'896897 def __init__(self, mode='r', encoding=None, errors='strict'):898 self.mode = mode899 self.encoding = encoding900 self.errors = errors901902 def convert(self, value, param, ctx):903 try:

Pass default values through the type system.Armin Ronacherbefore adoption7783631

lines 904–905why, one step back
904 if hasattr(value, 'read') or hasattr(value, 'write'):
905 return value

Initial commitArmin Ronacherbefore adoption4101de3

lines 906–914
906 f, was_opened = open_stream(value, self.mode, self.encoding,
907 self.errors)908 # If a context is provided we automatically close the file909 # at the end of the context execution (or flush out). If a910 # context does not exist it's the caller's responsibility to911 # properly close the file. This for instance happens when the912 # type is used with prompts.913 if ctx is not None:914 if was_opened:

Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf

line 915why, one step back
915 ctx.call_on_close(safecall(f.close))

Initial commitArmin Ronacherbefore adoption4101de3

line 916
916 else:

Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf

line 917why, one step back
917 ctx.call_on_close(safecall(f.flush))

Initial commitArmin Ronacherbefore adoption4101de3

lines 918–921
918 return f
919 except (IOError, OSError) as e:920 if isinstance(value, bytes):921 value = value.decode(sys.getfilesystemencoding(), 'replace')

Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf

lines 922–928why, one step back
922 if hasattr(e, 'strerror'):
923 msg = e.strerror924 else:925 msg = str(e)926 if isinstance(msg, bytes):927 msg = msg.decode('utf-8', 'replace')928 self.fail('Could not open file %s: %s' % (value, msg),

Initial commitArmin Ronacherbefore adoption4101de3

lines 929–1005
929 param, ctx)
930931932def convert_type(ty, default=None):933 """Converts a callable or python ty into the most appropriate param934 ty.935 """936 if isinstance(ty, ParamType):937 return ty938 guessed_type = False939 if ty is None and default is not None:940 ty = type(default)941 guessed_type = True942 if ty is text_type or ty is str or ty is None:943 return STRING944 if ty is int:945 return INT946 # Booleans are only okay if not guessed. This is done because for947 # flags the default value is actually a bit of a lie in that it948 # indicates which of the flags is the one we want. See get_default()949 # for more information.950 if ty is bool and not guessed_type:951 return BOOL952 if ty is float:953 return FLOAT954 if guessed_type:955 return STRING956 return FuncParamType(ty)957958959class Parameter(object):960 """A parameter to a command comes in two versions: they are either961 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently962 not supported by design as some of the internals for parsing are963 intentionally not finalized.964965 Some settings are supported by both options and arguments.966967 :param param_decls: the parameter declarations for this option or968 argument. This is a list of flags or argument969 names.970 :param type: the type that should be used. Either a :class:`ParamType`971 or a python type. The latter is converted into the former972 automatically if supported.973 :param required: controls if this is optional or not.974 :param default: the default value if omitted. This can also be a callable975 in which case it's invoked when the default is needed976 without any arguments.977 :param help: the help string.978 :param callback: a callback that should be executed after the parameter979 was matched. This is called as ``fn(ctx, value)`` and980 needs to return the value.981 :param nargs: the number of arguments to match. If not ``1`` the return982 value is a tuple instead of single value.983 :param metavar: how the value is represented in the help page.984 :param expose_value: if this is `True` then the value is passed onwards985 to the command callback and stored on the context,986 otherwise it's skipped.987 :param is_eager: eager values are processed before non eager ones. This988 should not be set for arguments or it will inverse the989 order of processing.990 :param envvar: a string or list of strings that are environment variables991 that should be checked.992 """993 param_type_name = 'parameter'994995 def __init__(self, param_decls=None, type=None, required=False,996 default=None, help=None, callback=None, nargs=1,997 metavar=None, expose_value=True, is_eager=False,998 envvar=None):999 self.name, self.opts, self.secondary_opts = \1000 self._parse_decls(param_decls or ())1001 self.type = convert_type(type, default)1002 self.required = required1003 self.help = help1004 self.callback = callback1005 self.nargs = nargs

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

line 1006why, one step back
1006 self.multiple = False

Initial commitArmin Ronacherbefore adoption4101de3

lines 1007–1015
1007 self.expose_value = expose_value
1008 self.default = default1009 self.is_eager = is_eager1010 self.metavar = metavar1011 self.envvar = envvar10121013 def make_metavar(self):1014 if self.metavar is not None:1015 return self.metavar

Added choice supportArmin Ronacherbefore adoption9eacc90

lines 1016–1018why, one step back
1016 metavar = self.type.get_metavar(self)
1017 if metavar is not None:1018 return metavar

Initial commitArmin Ronacherbefore adoption4101de3

lines 1019–1027
1019 metavar = self.name.upper()
1020 if self.nargs != 1:1021 metavar += '...'1022 return metavar10231024 def get_default(self, ctx):1025 """Given a context variable this calculates the default value."""1026 # Otherwise go with the regular default.1027 if callable(self.default):

Pass default values through the type system.Armin Ronacherbefore adoption7783631

lines 1028–1031why, one step back
1028 rv = self.default()
1029 else:1030 rv = self.default1031 return self.type(rv, self, ctx)

Initial commitArmin Ronacherbefore adoption4101de3

lines 1032–1039
1032
1033 def _add_to_parser(self, parser, ctx):1034 raise NotImplementedError()10351036 def process_value(self, ctx, value):1037 """Given a value and context this runs the logic to convert the1038 value as necessary.1039 """

Added support for mixing nargs and multipleArmin Ronacherbefore adoption24efee0

lines 1040–1042why, one step back
1040 def _convert(value, level):
1041 if level == 0:1042 return self.type(value, self, ctx)

Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2

line 1043why, one step back
1043 return tuple(_convert(x, level - 1) for x in value or ())

Added support for mixing nargs and multipleArmin Ronacherbefore adoption24efee0

line 1044why, one step back
1044 return _convert(value, (self.nargs != 1) + bool(self.multiple))

Initial commitArmin Ronacherbefore adoption4101de3

lines 1045–1107
1045
1046 def full_process_value(self, ctx, value):1047 value = self.process_value(ctx, value)10481049 if value is None:1050 value = self.get_default(ctx)10511052 if value is None and self.required:1053 ctx.fail(self.get_missing_message(ctx))10541055 return value10561057 def get_missing_message(self, ctx):1058 return 'Missing %s "%s".' % (1059 self.param_type_name,1060 ' / '.join(chain(self.opts, self.secondary_opts)),1061 )10621063 def value_from_envvar(self, ctx):1064 if self.envvar is None:1065 return1066 if isinstance(self.envvar, (tuple, list)):1067 for envvar in self.envvar:1068 rv = os.environ.get(envvar)1069 if rv is not None:1070 return rv1071 else:1072 return os.environ.get(self.envvar)10731074 def consume_value(self, ctx, opts, args):1075 return None, args10761077 def handle_parse_result(self, ctx, opts, args):1078 value, args = self.consume_value(ctx, opts, args)1079 value = self.full_process_value(ctx, value)1080 if self.callback is not None:1081 value = self.callback(ctx, value)1082 if self.expose_value:1083 ctx.params[self.name] = value1084 return value, args108510861087class Option(Parameter):1088 """Options are usually optionaly values on the command line and1089 have some extra features that arguments don't have.10901091 All other parameters are passed onwards to the parameter constructor.10921093 :param show_default: controls if the default value should be shown on the1094 help page. The default is auto detection.1095 :param prompt: if set to `True` or a non empty string then the user will1096 be prompted for input if not set. If set to `True` the1097 prompt will be the option name capitalized.1098 :param confirmation_prompt: if set then the value will need to be confirmed1099 if it was prompted for.1100 :param hide_input: if this is `True` then the input on the prompt will be1101 hidden from the user. This is useful for password1102 input.1103 :param is_flag: forces this option to act as a flag. The default is1104 auto detection.1105 :param flag_value: which value should be used for this flag if it's1106 enabled. This is set to a boolean automatically if1107 the option string contains a slash to mark two options.

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 1108–1111why, one step back
1108 :param multiple: if this is set to True then the argument is accepted
1109 multiple times and recorded. This is similar to nargs1110 in how it works but supports arbitrary number of1111 arguments.

Initial commitArmin Ronacherbefore adoption4101de3

lines 1112–1121
1112 :param allow_from_autoenv: if this is enabled then the value of this
1113 parameter will be pulled from an environment1114 variable in case a prefix is defined on the1115 context.1116 """1117 param_type_name = 'option'11181119 def __init__(self, param_decls=None, show_default=None,1120 prompt=False, confirmation_prompt=False,1121 hide_input=False, is_flag=None, flag_value=None,

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

lines 1122–1123why, one step back
1122 multiple=False, allow_from_autoenv=True, type=None,
1123 **attrs):

Initial commitArmin Ronacherbefore adoption4101de3

lines 1124–1149
1124 Parameter.__init__(self, param_decls, type=type, **attrs)
1125 if prompt is True:1126 prompt = self.name.replace('_', ' ').capitalize()1127 elif prompt is False:1128 prompt = None1129 self.prompt = prompt1130 self.confirmation_prompt = confirmation_prompt1131 self.hide_input = hide_input11321133 if is_flag is None:1134 if flag_value is not None:1135 is_flag = True1136 else:1137 is_flag = bool(self.secondary_opts)11381139 if is_flag and self.default is None:1140 self.default = False1141 if show_default is None:1142 show_default = False11431144 if flag_value is None:1145 flag_value = not self.default11461147 self.show_default = show_default1148 self.is_flag = is_flag1149 self.flag_value = flag_value

Added support for multiple arguments.Armin Ronacherbefore adoption18fff34

line 1150why, one step back
1150 self.multiple = multiple

Initial commitArmin Ronacherbefore adoption4101de3

lines 1151–1220
1151
1152 if self.is_flag and isinstance(self.flag_value, bool) \1153 and type is None:1154 self.type = BoolParamType()1155 self.is_bool_flag = True1156 else:1157 self.is_bool_flag = False11581159 self.allow_from_autoenv = allow_from_autoenv11601161 # Sanity check for stuff we don't support1162 if __debug__:1163 if self.prompt and self.is_flag and not self.is_bool_flag:1164 raise TypeError('Cannot prompt for flags that are not bools.')1165 if not self.is_bool_flag and self.secondary_opts:1166 raise TypeError('Got secondary option for non boolean flag.')1167 if self.is_bool_flag and self.hide_input \1168 and self.prompt is not None:1169 raise TypeError('Hidden input does not work with boolean '1170 'flag prompts.')11711172 def _parse_decls(self, decls):1173 opts = []1174 secondary_opts = []1175 name = None1176 possible_names = []11771178 for decl in decls:1179 if not decl.startswith('-'):1180 if name is not None:1181 raise TypeError('Name defined twice')1182 name = decl1183 else:1184 if '/' in decl:1185 first, second = decl.split('/', 1)1186 possible_names.append(first.lstrip('-'))1187 opts.append(first)1188 secondary_opts.append(second)1189 else:1190 possible_names.append(decl.lstrip('-'))1191 opts.append(decl)11921193 if name is None and possible_names:1194 possible_names.sort(key=len)1195 name = possible_names[-1]11961197 if name is None:1198 raise TypeError('Could not determine name for option')11991200 return name.replace('-', '_'), opts, secondary_opts12011202 def _add_to_parser(self, parser, ctx):1203 help = self.help1204 extra = []1205 if self.default is not None and self.show_default:1206 extra.append('default: %s' % self.default)1207 if self.required:1208 extra.append('required')1209 if self.nargs != 1:1210 extra.append('%d arguments' % self.nargs)1211 if extra:1212 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))12131214 kwargs = {1215 'help': help,1216 'dest': self.name,1217 'nargs': self.nargs,1218 'metavar': self.make_metavar(),1219 }1220

Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2

lines 1221–1222why, one step back
1221 action = self.multiple and 'append' or 'store'
1222

Initial commitArmin Ronacherbefore adoption4101de3

lines 1223–1225
1223 if self.is_flag:
1224 kwargs.pop('nargs', None)1225 if self.is_bool_flag and self.secondary_opts:

Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2

line 1226why, one step back
1226 pos_opt = optparse.Option(*self.opts, action=action + '_true',

Initial commitArmin Ronacherbefore adoption4101de3

lines 1227–1230
1227 **kwargs)
1228 kwargs.pop('default', None)1229 kwargs.pop('help', None)1230 neg_opt = optparse.Option(*self.secondary_opts,

Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2

line 1231why, one step back
1231 action=action + '_false',

Initial commitArmin Ronacherbefore adoption4101de3

lines 1232–1237
1232 help=optparse.SUPPRESS_HELP,
1233 **kwargs)1234 pos_opt._negative_version = neg_opt1235 parser.add_option(pos_opt)1236 parser.add_option(neg_opt)1237 else:

Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2

line 1238why, one step back
1238 parser.add_option(*self.opts, action=action + '_const',

Initial commitArmin Ronacherbefore adoption4101de3

lines 1239–1241
1239 const=self.flag_value,
1240 **kwargs)1241 else:

Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2

line 1242why, one step back
1242 kwargs['action'] = action

Initial commitArmin Ronacherbefore adoption4101de3

lines 1243–1335
1243 parser.add_option(*self.opts, **kwargs)
12441245 def get_default(self, ctx):1246 # If we're a non boolean flag out default is more complex because1247 # we need to look at all flags in the same group to figure out1248 # if we're the the default one in which case we return the flag1249 # value as default.1250 if self.is_flag and not self.is_bool_flag:1251 for param in ctx.command.params:1252 if param.name == self.name and param.default:1253 return param.flag_value1254 return None1255 return Parameter.get_default(self, ctx)12561257 def prompt_for_value(self, ctx):1258 """This is an alternative flow that can be activated in the full1259 value processing if a value does not exist. It will prompt the1260 user until a valid value exists and then returns the processed1261 value as result.1262 """1263 # Calculate the default before prompting anything to be stable.1264 default = self.get_default(ctx)12651266 # If this is a prompt for a flag we need to handle this1267 # differently.1268 if self.is_bool_flag:1269 return confirm(self.prompt, default)12701271 return prompt(self.prompt, default=default,1272 hide_input=self.hide_input,1273 confirmation_prompt=self.confirmation_prompt,1274 value_proc=lambda x: self.process_value(ctx, x))12751276 def value_from_envvar(self, ctx):1277 rv = Parameter.value_from_envvar(self, ctx)1278 if rv is not None:1279 return rv1280 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1281 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1282 return os.environ.get(envvar)12831284 def full_process_value(self, ctx, value):1285 if value is None and self.prompt is not None:1286 return self.prompt_for_value(ctx)1287 return Parameter.full_process_value(self, ctx, value)12881289 def consume_value(self, ctx, opts, args):1290 value = opts.get(self.name)1291 if value is None:1292 value = self.value_from_envvar(ctx)1293 return value, args129412951296class Argument(Parameter):1297 param_type_name = 'argument'12981299 def __init__(self, param_decls, required=True, **attrs):1300 Parameter.__init__(self, param_decls, required=required, **attrs)13011302 def make_metavar(self):1303 if self.metavar is not None:1304 return self.metavar1305 var = self.name.upper()1306 if not self.required:1307 var = '[%s]' % var1308 if self.nargs != 1:1309 var += '...'1310 return var13111312 def _parse_decls(self, decls):1313 if not decls:1314 raise TypeError('Could not determine name for argument')1315 if len(decls) == 1:1316 name = arg = decls[0]1317 elif len(decls) == 2:1318 name, arg = decls1319 else:1320 raise TypeError('Arguments take exactly one or two '1321 'parameter declarations, got %d' % len(decls))1322 return name.replace('-', '_'), [arg], []13231324 def _add_to_parser(self, parser, ctx):1325 parser.usage += ' ' + self.make_metavar()13261327 def consume_value(self, ctx, opts, args):1328 found = True1329 if self.nargs == 1:1330 try:1331 value = args.pop(0)1332 except IndexError:1333 found = False1334 elif self.nargs < 0:1335 value = tuple(args)

Correct fix for #20Armin Ronacherbefore adoption8ca33a9

line 1336why, one step back
1336 found = value

Initial commitArmin Ronacherbefore adoption4101de3

lines 1337–1341
1337 args = []
1338 else:1339 values = args[:self.nargs]1340 args = args[self.nargs:]1341 value = tuple(values)

Correct fix for #20Armin Ronacherbefore adoption8ca33a9

line 1342why, one step back
1342 found = value

Initial commitArmin Ronacherbefore adoption4101de3

lines 1343–1345
1343 if not found:
1344 value = self.value_from_envvar(ctx)1345 if self.nargs != 1:

Correct fix for #20Armin Ronacherbefore adoption8ca33a9

line 1346why, one step back
1346 value = value and (value,) or ()

Initial commitArmin Ronacherbefore adoption4101de3

lines 1347–1367
1347 return value, args
134813491350def _make_command(f, name, attrs, cls):1351 if isinstance(f, Command):1352 raise TypeError('Attempted to convert a callback into a '1353 'command twice.')1354 try:1355 params = f.__click_params__1356 params.reverse()1357 del f.__click_params__1358 except AttributeError:1359 params = []1360 help = inspect.getdoc(f)1361 if isinstance(help, bytes):1362 help = help.decode('utf-8')1363 attrs.setdefault('help', help)1364 return cls(name=name or f.__name__.lower(),1365 callback=f, params=params, **attrs)13661367

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

line 1368why, one step back
1368def command(name=None, cls=None, **attrs):

Initial commitArmin Ronacherbefore adoption4101de3

lines 1369–1381
1369 """Creates a new :class:`Command` and uses the decorated function as
1370 callback. This will also automatically attach all decorated1371 :func:`option`\s and :func:`argument`\s as paramters to the command.13721373 The name of the command defaults to the name of the function. If you1374 want to change that, you can pass the intended name as the first1375 argument.13761377 All keyword arguments are forwarded to the underlying command class.13781379 Once decorated the function turns into a :class:`Command` instance1380 that can be invoked as a command line utility or be attached to a1381 command :class:`Group`.

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 1382–1386why, one step back
1382
1383 :param name: the name of the command. This defaults to the function1384 name.1385 :param cls: the command class to instanciate. This defaults to1386 :class:`Command`.

Initial commitArmin Ronacherbefore adoption4101de3

line 1387
1387 """

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 1388–1389why, one step back
1388 if cls is None:
1389 cls = Command

Initial commitArmin Ronacherbefore adoption4101de3

line 1390
1390 def decorator(f):

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

line 1391why, one step back
1391 return _make_command(f, name, attrs, cls)

Initial commitArmin Ronacherbefore adoption4101de3

lines 1392–1396
1392 return decorator
139313941395def group(name=None, **attrs):1396 """Creates a new :class:`Group` with a function as callback. This

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 1397–1398why, one step back
1397 works otherwise the same as :func:`command` just that the `cls`
1398 parameter is set to :class:`Group`.

Initial commitArmin Ronacherbefore adoption4101de3

line 1399
1399 """

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

line 1400why, one step back
1400 return command(name, cls=Group, **attrs)

Initial commitArmin Ronacherbefore adoption4101de3

lines 1401–1656
1401
14021403def _param_memo(f, param):1404 if isinstance(f, Command):1405 f.params.append(param)1406 else:1407 if not hasattr(f, '__click_params__'):1408 f.__click_params__ = []1409 f.__click_params__.append(param)141014111412def argument(*param_decls, **attrs):1413 """Attaches an option to the command. All positional arguments are1414 passed as parameter declarations to :class:`Argment`, all keyword1415 arguments are forwarded unchanged. This is equivalent to creating an1416 :class:`Option` instance manually and attaching it to the1417 :attr:`Command.params` list.1418 """1419 def decorator(f):1420 _param_memo(f, Argument(param_decls, **attrs))1421 return f1422 return decorator142314241425def option(*param_decls, **attrs):1426 """Attaches an option to the command. All positional arguments are1427 passed as parameter declarations to :class:`Option`, all keyword1428 arguments are forwarded unchanged. This is equivalent to creating an1429 :class:`Option` instance manually and attaching it to the1430 :attr:`Command.params` list.1431 """1432 def decorator(f):1433 _param_memo(f, Option(param_decls, **attrs))1434 return f1435 return decorator143614371438def confirmation_option(*param_decls, **attrs):1439 """Shortcut for confirmation prompts that can be ignored by bypassed1440 ``--yes`` as parameter.14411442 This is equivalent to decorating a function with :func:`option` with1443 the following parameters::14441445 def callback(ctx, value):1446 if not value:1447 ctx.abort()14481449 @click.command()1450 @click.option('--yes', is_flag=True, callback=callback,1451 expose_value=False, prompt='Do you want to continue?')1452 def dropdb():1453 pass1454 """1455 def decorator(f):1456 def callback(ctx, value):1457 if not value:1458 ctx.abort()1459 attrs.setdefault('is_flag', True)1460 attrs.setdefault('callback', callback)1461 attrs.setdefault('expose_value', False)1462 attrs.setdefault('prompt', 'Do you want to continue?')1463 return option(*(param_decls or ('--yes',)), **attrs)(f)1464 return decorator146514661467def password_option(*param_decls, **attrs):1468 """Shortcut for password prompts.14691470 This is equivalent to decorating a function with :func:`option` with1471 the following parameters::14721473 @click.command()1474 @click.option('--password', prompt=True, confirmation_prompt=True,1475 hide_input=True)1476 def changeadmin(password):1477 pass1478 """1479 def decorator(f):1480 attrs.setdefault('prompt', True)1481 attrs.setdefault('confirmation_prompt', True)1482 attrs.setdefault('hide_input', True)1483 return option(*(param_decls or ('--password',)), **attrs)(f)1484 return decorator148514861487def version_option(version, *param_decls, **attrs):1488 """Adds a ``--version`` option which immediately ends the program1489 printing out the version number. This is implemented as an eager1490 option that prints the version and exits the program in the callback.14911492 :param version: the version number to show1493 :param prog_name: the name of the program (defaults to autodetection)1494 :param message: custom message to show instead of the default1495 (``'%(prog)s, version %(version)s'``)1496 :param others: everything else is forwarded to :func:`option`.1497 """1498 def decorator(f):1499 prog_name = attrs.pop('prog_name', None)1500 message = attrs.pop('message', '%(prog)s, version %(version)s')15011502 def callback(ctx, value):1503 if not value:1504 return1505 prog = prog_name1506 if prog is None:1507 prog = ctx.find_root().info_name1508 echo(message % {1509 'prog': prog,1510 'version': version,1511 })1512 ctx.exit()15131514 attrs.setdefault('is_flag', True)1515 attrs.setdefault('expose_value', False)1516 attrs.setdefault('is_eager', True)1517 attrs.setdefault('help', 'Show the version and exit.')1518 attrs['callback'] = callback1519 return option(*(param_decls or ('--version',)), **attrs)(f)1520 return decorator152115221523def help_option(*param_decls, **attrs):1524 """Adds a ``--help`` option which immediately ends the program1525 printing out the help page. This is usually unnecessary to add as1526 this is added by default to all commands unless supressed.15271528 Like :func:`version_option` this is implemented as eager option that1529 prints in the callback and exits.15301531 All arguments are forwarded to :func:`option`.1532 """1533 def decorator(f):1534 def callback(ctx, value):1535 if value:1536 echo(ctx.format_help())1537 ctx.exit()1538 attrs.setdefault('is_flag', True)1539 attrs.setdefault('expose_value', False)1540 attrs.setdefault('help', 'Show this message and exit.')1541 attrs.setdefault('is_eager', True)1542 attrs['callback'] = callback1543 return option(*(param_decls or ('--help',)), **attrs)(f)1544 return decorator154515461547def confirm(text, default=False, abort=False):1548 """Prompts for confirmation (yes/no question).15491550 If the user aborts the input by sending a interrupt signal this1551 function will catch it and raise a :exc:`Abort` exception.15521553 :param text: the question to ask.1554 :param default: the default for the prompt.1555 :param abort: if this is set to `True` a negative answer aborts the1556 exception by raising :exc:`Abort`.1557 """1558 prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')1559 while 1:1560 try:1561 value = raw_input(prompt).lower().strip()1562 except (KeyboardInterrupt, EOFError):1563 raise Abort()1564 if value in ('y', 'yes'):1565 rv = True1566 elif value in ('n', 'no'):1567 rv = False1568 elif value == '':1569 rv = default1570 else:1571 echo('Error: invalid input')1572 continue1573 break1574 if abort and not rv:1575 raise Abort()1576 return rv157715781579def prompt(text, default=None, hide_input=False,1580 confirmation_prompt=False, type=None,1581 value_proc=None):1582 """Prompts a user for input. This is a convenience function that can1583 be used to prompt a user for input later.15841585 If the user aborts the input by sending a interrupt signal this1586 function will catch it and raise a :exc:`Abort` exception.15871588 :param text: the text to show for the prompt.1589 :param default: the default value to use if no input happens. If this1590 is not given it will prompt until it's aborted.1591 :param hide_input: if this is set to true then the input value will1592 be hidden.1593 :param confirmation_prompt: asks for confirmation for the value.1594 :param type: the type to use to check the value against.1595 :param value_proc: if this parameter is provided it's a function that1596 is invoked instead of the type conversion to1597 convert a value.1598 """1599 result = None16001601 def prompt_func(text):1602 f = hide_input and getpass.getpass or raw_input1603 try:1604 return f(text)1605 except (KeyboardInterrupt, EOFError):1606 raise Abort()16071608 if value_proc is None:1609 value_proc = convert_type(type, default)16101611 prompt = text1612 if default is not None:1613 prompt = '%s [%s]' % (prompt, default)1614 prompt += ': '16151616 while 1:1617 while 1:1618 value = prompt_func(prompt)1619 if value:1620 break1621 # If a default is set and used, then the confirmation1622 # prompt is always skipped because that's the only thing1623 # that really makes sense.1624 elif default is not None:1625 return default1626 try:1627 result = value_proc(value)1628 except UsageError as e:1629 echo('Error: %s' % e.message)1630 continue1631 if not confirmation_prompt:1632 return result1633 while 1:1634 value2 = prompt_func('Repeat for confirmation: ')1635 if value2:1636 break1637 if value == value2:1638 return result1639 echo('Error: the two entered values do not match')164016411642#: A unicode string parameter type which is the implicit default. This1643#: can also be selected by using ``str`` as type.1644STRING = StringParamType()16451646#: An integer parameter. This can also be selected by using ``int`` as1647#: type.1648INT = IntParamType()16491650#: A floating point value parameter. This can also be selected by using1651#: ``float`` as type.1652FLOAT = FloatParamType()16531654#: A boolean parameter. This is the default for boolean flags. This can1655#: also be selected by using ``bool`` as a type.1656BOOL = BoolParamType()