click.py
This file
Path
click.py
1,670 lines · 58.4 KiB · Python
Last changed by
Merge pull request #33 from pfmoore/termsizeArmin Ronacherbefore adoption6904fac
History of this fileTake it
Initial commitArmin Ronacherbefore adoption4101de3
lines 1–231# -*- 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 structMerge pull request #33 from pfmoore/termsizeArmin Ronacherbefore adoption6904fac
line 24why, one step back24import shutil25from itertools import chainAdded docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
line 26why, one step back26from functools import update_wrapperInitial commitArmin Ronacherbefore adoption4101de3
lines 27–75272829PY2 = sys.version_info[0] == 230if PY2:31 text_type = unicode32 bytes = str3334 def open_stream(filename, mode='r', encoding=None, errors='strict'):35 if filename != '-':36 if encoding is not None:37 return codecs.open(filename, mode, encoding, errors), True38 return open(filename, mode), True39 if 'w' in mode:40 f = sys.stdout41 if encoding is not None:42 f = _wrap_stream_for_codec(f, encoding, errors)43 else:44 f = sys.stdin45 if 'b' not in mode:46 if encoding is None:47 encoding = sys.stdin.encoding48 f = _wrap_stream_for_codec(f, encoding, errors)49 return f, False50else:51 text_type = str52 raw_input = input5354 def open_stream(filename, mode='r', encoding=None, errors='strict'):55 if filename != '-':56 return open(filename, mode, encoding=encoding, errors=errors), True57 if 'w' in mode:58 f = sys.stdout59 if encoding is not None or 'b' in mode:60 f = f.buffer.raw61 if encoding is not None:62 f = _wrap_stream_for_codec(f, encoding, errors)63 else:64 f = sys.stdin65 if 'b' in mode:66 f = f.buffer.raw67 if encoding is not None:68 f = _wrap_stream_for_codec(f, encoding, errors)69 return f, False707172def get_terminal_size():73 """Returns the current size of the terminal as tuple in the form74 ``(width, height)`` in columns and rows.75 """Merge pull request #33 from pfmoore/termsizeArmin Ronacherbefore adoption6904fac
lines 76–81why, one step back76 # If shutil has get_terminal_size() (Python 3.3 and later) use that77 shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)78 if shutil_get_terminal_size:79 sz = shutil_get_terminal_size()80 return sz.columns, sz.lines81Initial commitArmin Ronacherbefore adoption4101de3
lines 82–8382 def ioctl_gwinsz(fd):83 try:Merge pull request #9 from ikkebr/patch-3Armin Ronacherbefore adoption3755db7
lines 84–85why, one step back84 import fcntl85 import termiosInitial commitArmin Ronacherbefore adoption4101de3
lines 86–10686 cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))87 except Exception:88 return89 return cr9091 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)92 if not cr:93 try:94 fd = os.open(os.ctermid(), os.O_RDONLY)95 try:96 cr = ioctl_gwinsz(fd)97 finally:98 os.close(fd)99 except Exception:100 pass101 if not cr:102 cr = (os.environ.get('LINES', 25),103 os.environ.get('COLUMNS', 80))104 return int(cr[1]), int(cr[0])105106Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf
lines 107–116why, one step back107def safecall(func):108 """Wraps a function so that it swallows exceptions."""109 def wrapper(*args, **kwargs):110 try:111 return func(*args, **kwargs)112 except Exception:113 pass114 return wrapper115116Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 117–122why, one step back117# The prompt functions to use. The doc tools currently override these118# functions to customize them.119hidden_prompt_func = getpass.getpass120visible_prompt_func = raw_input121122Initial commitArmin Ronacherbefore adoption4101de3
lines 123–177123class TextWrapper(textwrap.TextWrapper):124125 def _cutdown(self, ucstr, space_left):126 l = 0127 for i in xrange(len(ucstr)):128 l += len(ucstr[i])129 if space_left < l:130 return (ucstr[:i], ucstr[i:])131 return ucstr, ''132133 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):134 space_left = max(width - cur_len, 1)135136 if self.break_long_words:137 cut, res = self._cutdown(reversed_chunks[-1], space_left)138 cur_line.append(cut)139 reversed_chunks[-1] = res140 elif not cur_line:141 cur_line.append(reversed_chunks.pop())142143 def fill_paragraphs(self, text):144 # Remove unnecessary newlines so that we can fill properly145 p = []146 buf = []147 for line in text.splitlines():148 if not line:149 p.append(' '.join(buf))150 buf = []151 else:152 buf.append(line)153 if buf:154 p.append(' '.join(buf))155156 rv = []157 for text in p:158 rv.append(self.fill(text))159 return '\n\n'.join(rv)160161162def _wrap_stream_for_codec(f, encoding=None, errors='strict'):163 if encoding is None:164 encoding = 'utf-8'165 info = codecs.lookup(encoding)166 f = codecs.StreamReaderWriter(f, info.streamreader,167 info.streamwriter,168 errors)169 f.encoding = encoding170 return f171172173def echo(message=None, file=None):174 if file is None:175 file = sys.stdout176 if message:177 if PY2 and isinstance(message, text_type):Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 178–179why, one step back178 message = message.encode(getattr(file, 'encoding', None)179 or 'utf-8', 'replace')Initial commitArmin Ronacherbefore adoption4101de3
lines 180–184180 file.write(message)181 file.write('\n')182 file.flush()183184Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
lines 185–236why, one step back185def pass_context(f):186 """Marks a callback that it wants to receive the current context187 object as first argument.188 """189 f.__click_pass_context__ = True190 return f191192193def pass_obj(f):194 """Similar to :func:`pass_context` but only pass the object on the195 context onwards (:attr:`Context.obj`). This is useful if that object196 represents the state of a nested system.197 """198 @pass_context199 def new_func(*args, **kwargs):200 ctx = args[0]201 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)202 return update_wrapper(new_func, f)203204205def make_pass_decorator(object_type):206 """Given an object type this creates a decorator that will work207 similar to :func:`pass_obj` but instead of passing the object of the208 current context, it will find the innermost context of type209 :func:`object_type`.210211 This generates a decorator that works roughly like this::212213 from functools import update_wrapper214215 def decorator(f):216 @pass_context217 def new_func(ctx, *args, **kwargs):218 obj = ctx.find_object(object_type)219 return ctx.invoke(f, obj, *args, **kwargs)220 return update_wrapper(new_func, f)221 return decorator222 """223 def decorator(f):224 @pass_context225 def new_func(*args, **kwargs):226 ctx = args[0]227 obj = ctx.find_object(object_type)228 if obj is None:229 raise RuntimeError('Managed to invoke callback without a '230 'context object of type %r existing'231 % object_type.__name__)232 return ctx.invoke(f, obj, *args[1:], **kwargs)233 return update_wrapper(new_func, f)234 return decorator235236Initial commitArmin Ronacherbefore adoption4101de3
lines 237–347237class Context(object):238 """The context is a special internal object that holds state relevant239 for the script execution at every single level. It's normally invisible240 to commands unless they opt-in to getting access to it.241242 The context is useful as it can pass internal objects around and can243 control special execution features such as reading data from244 environment variables.245246 A context can be used as context manager in which case it will call247 :meth:`close` on teardown.248249 :param command: the command class for this context.250 :param parent: the parent context.251 :param info_name: the info name for this invokation. Generally this252 is the most descriptive name for the script or253 command. For the toplevel script is is usually254 the name of the script, for commands below it it's255 the name of the script.256 :param obj: an arbitrary object of user data.257 :param auto_envvar_prefix: the prefix to use for automatic environment258 variables. If this is `None` then reading259 from environment variables is disabled. This260 does not affect manually set environment261 variables which are always read.262 """263264 def __init__(self, command, parent=None, info_name=None, obj=None,265 auto_envvar_prefix=None):266 #: the parent context or `None` if none exists.267 self.parent = parent268 #: the :class:`Command` for this context.269 self.command = command270 #: the descriptive information name271 self.info_name = info_name272 #: the parsed parameters except if the value is hidden in which273 #: case it's not remembered.274 self.params = {}275 #: the leftover arguments.276 self.args = []277 #: this flag indicates if a subcommand is going to be executed.278 #: a group callback can use this information to figure out if it's279 #: being executed directly or because the execution flow passes280 #: onwards to a subcommand. By default it's `None` but it can be281 #: the name of the subcommand to execute.282 self.invoked_subcommand = None283 if obj is None and parent is not None:284 obj = parent.obj285 #: the user object stored.286 self.obj = obj287288 # If there is no envvar prefix yet, but the parent has one and289 # the command on this level has a name, we can expand the envvar290 # prefix automatically.291 if auto_envvar_prefix is None:292 if parent is not None \293 and parent.auto_envvar_prefix is not None and \294 self.info_name is not None:295 auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,296 self.info_name.upper())297 else:298 self.auto_envvar_prefix = auto_envvar_prefix.upper()299 self.auto_envvar_prefix = auto_envvar_prefix300301 self._parser = command._make_parser(self)302 self._close_callbacks = []303304 def __enter__(self):305 return self306307 def __exit__(self, exc_type, exc_value, tb):308 self.close()309310 def call_on_close(self, f):311 """This decorator remembers a function as callback that should be312 executed when the context tears down. This is most useful to bind313 resource handling to the script execution. For instance file objects314 opened by the :class:`File` type will register their close callbacks315 here.316317 :param f: the function to execute on teardown.318 """319 self._close_callbacks.append(f)320 return f321322 def close(self):323 """Invokes all close callbacks."""324 for cb in self._close_callbacks:325 cb()326 self._close_callbacks = []327328 @property329 def command_path(self):330 """The computed command path. This is used for the ``usage``331 information on the help page. It's automatically created by332 combining the info names of the chain of contexts to the root.333 """334 rv = ''335 if self.info_name is not None:336 rv = self.info_name337 if self.parent is not None:338 rv = self.parent.command_path + ' ' + rv339 return rv.lstrip()340341 def find_root(self):342 """Finds the outermost context."""343 node = self344 while node.parent is not None:345 node = node.parent346 return node347Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
lines 348–355why, one step back348 def find_object(self, object_type):349 """Finds the closest object of a given type."""350 node = self351 while node.parent is not None:352 if isinstance(node.obj, object_type):353 return node.obj354 node = node.parent355Initial commitArmin Ronacherbefore adoption4101de3
lines 356–383356 def fail(self, message):357 """Aborts the execution of the program with a specific error358 message.359360 :param message: the error message to fail with.361 """362 raise UsageError(message, self)363364 def abort(self):365 """Aborts the script."""366 raise Abort()367368 def exit(self, code=0):369 """Exits the application with a given exit code."""370 sys.exit(code)371372 def format_usage(self):373 """Helper method to get formatted usage string for the current374 context and command.375 """376 return self._parser.get_usage()377378 def format_help(self):379 """Helper method to get formatted help page for the current380 context and command.381 """382 return self._parser.format_help().rstrip()383Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
lines 384–391why, one step back384 def invoke(*args, **kwargs):385 """Invokes a command callback in exactly the way it expects.386 """387 self, callback = args[:2]388 args = args[2:]389 if getattr(callback, '__click_pass_context__', False):390 args = (self,) + args391 return callback(*args, **kwargs)392Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
line 393why, one step back393Initial commitArmin Ronacherbefore adoption4101de3
lines 394–487394class UsageError(Exception):395 """An internal exception that signals a usage error. This typically396 aborts any further handling.397 """398399 def __init__(self, message, ctx=None):400 if PY2:401 Exception.__init__(self, message.encode('utf-8'))402 else:403 Exception.__init__(self, message)404 self.message = message405 self.ctx = ctx406407408class Abort(Exception):409 """An internal signalling exception that signals click to abort."""410411412class _SimplifiedFormatter(optparse.IndentedHelpFormatter):413414 def __init__(self):415 optparse.IndentedHelpFormatter.__init__(self,416 width=min(get_terminal_size()[0], 80) - 2)417 self.default_tag = ''418419 def format_usage(self, usage):420 prefix = 'Usage: '421 indent = len(prefix)422 text_width = self.width - indent423 return '%s%s\n' % (prefix, TextWrapper(424 text_width, initial_indent='',425 subsequent_indent=' ' * indent,426 replace_whitespace=False).fill(usage))427428 def _format_text(self, text):429 text_width = self.width - self.current_indent430 indent = ' ' * self.current_indent431432 return TextWrapper(text_width,433 initial_indent=indent,434 subsequent_indent=indent,435 replace_whitespace=False).fill_paragraphs(text)436437 def format_description(self, description):438 if not description:439 return ''440 self.indent()441 rv = self._format_text(description) + '\n'442 self.dedent()443 return rv444445 def format_option_strings(self, option):446 rv = optparse.IndentedHelpFormatter.format_option_strings(self, option)447 if hasattr(option, '_negative_version'):448 rv += ' / ' + optparse.IndentedHelpFormatter.format_option_strings(449 self, option._negative_version)450 return rv451452453class _SimplifiedOptionParser(optparse.OptionParser):454455 def __init__(self, ctx, **extra):456 usage = ctx.command_path + ' ' + ctx.command.options_metavar457 optparse.OptionParser.__init__(self, prog=ctx.command_path,458 usage=usage,459 add_help_option=False,460 formatter=_SimplifiedFormatter(),461 **extra)462 self.__ctx = ctx463464 def expand_prog_name(self, s):465 return s466467 def format_option_help(self, formatter):468 rv = optparse.OptionParser.format_option_help(self, formatter)469 extra_help = self.__ctx.command._format_extra_help(self.__ctx)470 if extra_help:471 rv = '%s\n\n%s' % (extra_help, rv)472 return rv473474 def error(self, msg):475 raise UsageError(msg, self.__ctx)476477478class Command(object):479 """Commands are the basic building block of command line interfaces in480 click. A basic command handles command line parsing and might dispatch481 more parsing to commands nested blow it.482483 :param name: the name of the command to use unless a group overrides it.484 :param callback: the callback to invoke. This is optional.485 :param params: the parameters to register with this command. This can486 be either :class:`Option` or :class:`Argument` objects.487 :param help: the help string to use for this command.Added epilog support.Armin Ronacherbefore adoption9d027aa
lines 488–489why, one step back488 :param epilog: like the help string but it's printed at the end of the489 help page after everything else.Initial commitArmin Ronacherbefore adoption4101de3
lines 490–496490 :param short_help: the short help to use for this command. This is491 shown on the command listing of the parent command.492 :param add_help_option: by default each command registers a ``--help``493 option. This can be disabled by this parameter.494 """495 allow_extra_args = False496Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
line 497why, one step back497 def __init__(self, name, callback=None, params=None, help=None,Added epilog support.Armin Ronacherbefore adoption9d027aa
lines 498–499why, one step back498 epilog=None, short_help=None,499 options_metavar='[OPTIONS]', add_help_option=True):Initial commitArmin Ronacherbefore adoption4101de3
lines 500–512500 #: the name the command things it has. Upon registering a command501 #: on a :class:`Group` the group will default the command name502 #: with this information. You should instead use the503 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.504 self.name = name505 #: the callback to execute when the command fires. This might be506 #: `None` in which case nothing happens.507 self.callback = callback508 #: the list of parameters for this command in the order they509 #: should show up in the help page and execute. Eager parameters510 #: will automatically be handled before non eager ones.511 self.params = params or []512 self.help = helpAdded epilog support.Armin Ronacherbefore adoption9d027aa
line 513why, one step back513 self.epilog = epilogInitial commitArmin Ronacherbefore adoption4101de3
lines 514–537514 self.options_metavar = options_metavar515 if short_help is None and help:516 short_help = help.split('.')[0].strip()517 if len(short_help) > 45:518 short_help = None519 elif short_help:520 short_help = short_help[0].lower() + short_help[1:] + '.'521 self.short_help = short_help522 if add_help_option:523 help_option()(self)524525 def iter_params_for_processing(self):526 """This returns an iterator over all attached parameters in the527 order of processing. This iterator returns all eager parameters528 first, followed by all non-eager parameters.529 """530 for param in self.params:531 if param.is_eager:532 yield param533 for param in self.params:534 if not param.is_eager:535 yield param536537 def _make_parser(self, ctx):Added epilog support.Armin Ronacherbefore adoption9d027aa
lines 538–539why, one step back538 parser = _SimplifiedOptionParser(ctx, description=self.help,539 epilog=self.epilog)Initial commitArmin Ronacherbefore adoption4101de3
lines 540–581540 for param in self.params:541 param._add_to_parser(parser, ctx)542 return parser543544 def _format_extra_help(self, ctx):545 pass546547 def make_context(self, info_name, args, parent=None, **extra):548 """This function when given an info name and arguments will kick549 off the parsing and create a new :class:`Context`. It does not550 invoke the actual command callback though.551552 :param info_name: the info name for this invokation. Generally this553 is the most descriptive name for the script or554 command. For the toplevel script is is usually555 the name of the script, for commands below it it's556 the name of the script.557 :param args: the arguments to parse as list of strings.558 :param parent: the parent context if available.559 :param extra: extra keyword arguments forwarded to the context560 constructor.561 """562 ctx = Context(self, info_name=info_name, parent=parent, **extra)563 opts, args = ctx._parser.parse_args(args=args)564 opts = opts.__dict__565566 for param in ctx.command.iter_params_for_processing():567 value, args = param.handle_parse_result(ctx, opts, args)568569 if args and not self.allow_extra_args:570 ctx.fail('Got unexpected extra argument%s (%s)'571 % (len(args) != 1 and 's' or '', ' '.join(args)))572573 ctx.args = args574575 return ctx576577 def invoke(self, ctx):578 """Given a context, this invokes the attached callback (if it exists)579 in the right way.580 """581 if self.callback is not None:Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68
line 582why, one step back582 ctx.invoke(self.callback, **ctx.params)Initial commitArmin Ronacherbefore adoption4101de3
lines 583–648583584 def main(self, args=None, prog_name=None, **extra):585 """This is the way to invoke a script with all the bells and586 whistles as command line application. This will always terminate587 the application after calling. If this is not wanted, ``SystemExit``588 needs to be caught.589590 This method is also available by directly calling the instance of591 a :class:`Command`.592593 :param args: the arguments that should be used for parsing. If not594 provided, ``sys.argv[1:]`` is used.595 :param prog_name: the program name that should be used. By default596 the progam name is constructed by taking the file597 name from ``sys.argv[0]``.598 :param extra: extra keyword arguments are forwarded to the context599 constructor.600 """601 if args is None:602 args = sys.argv[1:]603 else:604 args = list(args)605 if prog_name is None:606 prog_name = os.path.basename(sys.argv and sys.argv[0] or __file__)607 try:608 try:609 with self.make_context(prog_name, args, **extra) as ctx:610 self.invoke(ctx)611 ctx.exit()612 except (EOFError, KeyboardInterrupt):613 echo(file=sys.stderr)614 raise Abort()615 except UsageError as e:616 if e.ctx is not None:617 echo(e.ctx.format_usage(), file=sys.stderr)618 echo('Error: %s' % e.message, file=sys.stderr)619 sys.exit(2)620 except Abort:621 echo('Aborted!', file=sys.stderr)622 sys.exit(1)623624 def __call__(self, *args, **kwargs):625 """Alias for :meth:`main`."""626 return self.main(*args, **kwargs)627628629class MultiCommand(Command):630 """A multi command is the basic implementation of a command that631 dispatches to subcommands. The most common version is the632 :class:`Command`.633634 :param invoke_without_command: this controls how the multi command itself635 is invoked. By default it's only invoked636 if a subcommand is provided.637 :param no_args_is_help: this controls what happens if no arguments are638 provided. This option is enabled by default if639 `invoke_without_command` is disabled or disabled640 if it's enabled. If enabled this will add641 ``--help`` as argument if no arguments are642 passed.643 :param subcommand_metavar: the string that is used in the documentation644 to indicate the subcommand place.645 """646 allow_extra_args = True647648 def __init__(self, name=None, invoke_without_command=False,Added an example for aliasesArmin Ronacherbefore adoptione2d388e
lines 649–650why, one step back649 no_args_is_help=None, subcommand_metavar='COMMAND [ARGS]...',650 **attrs):Initial commitArmin Ronacherbefore adoption4101de3
lines 651–778651 Command.__init__(self, name, **attrs)652 if no_args_is_help is None:653 no_args_is_help = not invoke_without_command654 self.no_args_is_help = no_args_is_help655 self.invoke_without_command = invoke_without_command656 self.subcommand_metavar = subcommand_metavar657658 def _make_parser(self, ctx):659 parser = Command._make_parser(self, ctx)660 parser.usage += ' ' + self.subcommand_metavar661 parser.disable_interspersed_args()662 return parser663664 def _format_extra_help(self, ctx):665 commands = self.list_commands()666 if not commands:667 return668669 longest = len(sorted(commands, key=len)[-1])670671 subcommand_info = []672 for subcommand in self.list_commands():673 cmd = self.get_command(ctx, subcommand)674 help = cmd.short_help or ''675 subcommand_info.append(' %-*s %s' % (longest, subcommand, help))676677 return 'Commands:\n%s' % '\n'.join(subcommand_info)678679 def make_context(self, info_name, args, parent=None, **extra):680 # Multi-commands invoked without any arguments is a shortcut to681 # invoking it with --help unless supresssed.682 if not args and self.no_args_is_help:683 args = ['--help']684 return Command.make_context(self, info_name, args, parent, **extra)685686 def invoke(self, ctx):687 if not ctx.args:688 if self.invoke_without_command:689 return Command.invoke(self, ctx)690 ctx.fail('Missing command')691 cmd_name = ctx.args[0]692693 cmd = self.get_command(ctx, cmd_name)694 if cmd is None:695 ctx.fail('No such command "%s"' % cmd_name)696697 # Whenever we dispatch to a subcommand we also invoke the regular698 # callback. This is done so that parameters can be handled.699 ctx.invoked_subcommand = cmd_name700 Command.invoke(self, ctx)701702 with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:703 return cmd.invoke(cmd_ctx)704705 def get_command(self, ctx, cmd_name):706 """Given a context and a command name, this returns a707 :class:`Command` object if it exists or returns `None`.708 """709 raise NotImplementedError()710711 def list_commands(self):712 """Returns a list of subcommand names in the order they should713 appear.714 """715 return []716717718class Group(MultiCommand):719 """A group allows a command to have subcommands attached. This is the720 most common way to implement nesting in click.721722 :param commands: a dictionary of commands.723 """724725 def __init__(self, name=None, commands=None, **attrs):726 MultiCommand.__init__(self, name, **attrs)727 #: the registered subcommands by their exported names.728 self.commands = commands or {}729730 def add_command(self, cmd, name=None):731 """Registers another :class:`Command` with this group. If the name732 is not provided, the name of the command is used.733 """734 name = name or cmd.name735 if name is None:736 raise TypeError('Command has no name.')737 self.commands[name] = cmd738739 def command(self, *args, **kwargs):740 """A shortcut decorator for declaring and attaching a command to741 the group. This takes the same arguments as :func:`command` but742 immediately registers the created command with this instance by743 calling into :meth:`add_command`.744 """745 def decorator(f):746 cmd = command(*args, **kwargs)(f)747 self.add_command(cmd)748 return cmd749 return decorator750751 def get_command(self, ctx, cmd_name):752 return self.commands.get(cmd_name)753754 def list_commands(self):755 return sorted(self.commands)756757758class ParamType(object):759 """Helper for converting values through types. The following is760 necessary for a valid type:761762 * it needs a name763 * it needs to pass through None unchanged764 * it needs to convert from a string765 * it needs to convert its result type through unchanged766 (eg: needs to be idempotent)767 * it needs to be able to deal with param and context being none.768 This can be the case when the object is used with prompt769 inputs.770 """771772 #: the descriptive name of this type773 name = None774775 def __call__(self, value, param=None, ctx=None):776 if value is not None:777 return self.convert(value, param, ctx)778Added choice supportArmin Ronacherbefore adoption9eacc90
lines 779–781why, one step back779 def get_metavar(self, param):780 """Returns the metavar default for this param if it provides one."""781Initial commitArmin Ronacherbefore adoption4101de3
lines 782–833782 def convert(self, param, ctx, value):783 """Converts the value. This is not invoked for values that are784 `None` (the missing value).785 """786 return value787788 def fail(self, message, param=None, ctx=None):789 """Helper method to fail with an invalid value message."""790 if param is None:791 message = 'Invalid value: %s' % message792 else:793 message = 'Invalid value for %s: %s' % (param.name, message)794 raise UsageError(message, ctx=ctx)795796797class FuncParamType(ParamType):798799 def __init__(self, func):800 self.name = func.__name__801 self.func = func802803 def convert(self, value, param, ctx):804 try:805 return self.func(value)806 except ValueError:807 try:808 value = unicode(value)809 except UnicodeError:810 value = str(value).decode('utf-8', 'replace')811 self.fail(value, param, ctx)812813814class StringParamType(ParamType):815 name = 'string'816817 def convert(self, value, param, ctx):818 if isinstance(value, bytes):819 try:820 if sys.stdin.encoding is not None:821 value = value.decode(sys.stdin.encoding)822 except UnicodeError:823 try:824 value = value.decode(sys.getfilesystemencoding())825 except UnicodeError:826 value = value.decode('utf-8', 'replace')827 return value828 return value829830 def __repr__(self):831 return 'STRING'832833Added choice supportArmin Ronacherbefore adoption9eacc90
lines 834–845why, one step back834class Choice(ParamType):835 name = 'choice'836837 def __init__(self, choices):838 self.choices = choices839840 def get_metavar(self, param):841 return '[%s]' % '|'.join(self.choices)842843 def convert(self, value, param, ctx):844 if value in self.choices:845 return valueMerge pull request #30 from smorin/masterArmin Ronacherbefore adoption87adb71
line 846why, one step back846 self.fail('invalid choice: %s. (choose from %s)' %Added choice supportArmin Ronacherbefore adoption9eacc90
lines 847–852why, one step back847 (value, ', '.join(self.choices)), param, ctx)848849 def __repr__(self):850 return 'Choice(%r)' % list(self.choices)851852Initial commitArmin Ronacherbefore adoption4101de3
lines 853–917853class IntParamType(ParamType):854 name = 'integer'855856 def convert(self, value, param, ctx):857 try:858 return int(value)859 except ValueError:860 self.fail('%s is not a valid integer' % value, param, ctx)861862 def __repr__(self):863 return 'INT'864865866class BoolParamType(ParamType):867 name = 'boolean'868869 def convert(self, value, param, ctx):870 if isinstance(value, bool):871 return bool(value)872 value = value.lower()873 if value in ('true', '1', 'yes', 'y'):874 return True875 elif value in ('false', '0', 'no', 'n'):876 return False877 self.fail('%s is not a valid boolean' % value, param, ctx)878879 def __repr__(self):880 return 'BOOL'881882883class FloatParamType(ParamType):884 name = 'float'885886 def convert(self, value, param, ctx):887 try:888 return float(value)889 except ValueError:890 self.fail('%s is not a valid floating point value' %891 value, param, ctx)892893 def __repr__(self):894 return 'FLOAT'895896897class File(ParamType):898 """Declares a parameter to be a file for reading or writing. The file899 is automatically closed once the context tears down (after the command900 finished working).901902 Files can be opened for reading or writing. The special value ``-``903 indicates stdin or stdout depending on the mode.904905 By default the file is opened for reading text data but it can also be906 opened in binary mode or for writing. The encoding parameter can be used907 to force a specific encoding.908 """909 name = 'filename'910911 def __init__(self, mode='r', encoding=None, errors='strict'):912 self.mode = mode913 self.encoding = encoding914 self.errors = errors915916 def convert(self, value, param, ctx):917 try:Pass default values through the type system.Armin Ronacherbefore adoption7783631
lines 918–919why, one step back918 if hasattr(value, 'read') or hasattr(value, 'write'):919 return valueInitial commitArmin Ronacherbefore adoption4101de3
lines 920–928920 f, was_opened = open_stream(value, self.mode, self.encoding,921 self.errors)922 # If a context is provided we automatically close the file923 # at the end of the context execution (or flush out). If a924 # context does not exist it's the caller's responsibility to925 # properly close the file. This for instance happens when the926 # type is used with prompts.927 if ctx is not None:928 if was_opened:Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf
line 929why, one step back929 ctx.call_on_close(safecall(f.close))930 else:Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf
line 931why, one step back931 ctx.call_on_close(safecall(f.flush))Initial commitArmin Ronacherbefore adoption4101de3
lines 932–935932 return f933 except (IOError, OSError) as e:934 if isinstance(value, bytes):935 value = value.decode(sys.getfilesystemencoding(), 'replace')Improved error handling for files.Armin Ronacherbefore adoptionbdf4ddf
lines 936–942why, one step back936 if hasattr(e, 'strerror'):937 msg = e.strerror938 else:939 msg = str(e)940 if isinstance(msg, bytes):941 msg = msg.decode('utf-8', 'replace')942 self.fail('Could not open file %s: %s' % (value, msg),Initial commitArmin Ronacherbefore adoption4101de3
lines 943–1019943 param, ctx)944945946def convert_type(ty, default=None):947 """Converts a callable or python ty into the most appropriate param948 ty.949 """950 if isinstance(ty, ParamType):951 return ty952 guessed_type = False953 if ty is None and default is not None:954 ty = type(default)955 guessed_type = True956 if ty is text_type or ty is str or ty is None:957 return STRING958 if ty is int:959 return INT960 # Booleans are only okay if not guessed. This is done because for961 # flags the default value is actually a bit of a lie in that it962 # indicates which of the flags is the one we want. See get_default()963 # for more information.964 if ty is bool and not guessed_type:965 return BOOL966 if ty is float:967 return FLOAT968 if guessed_type:969 return STRING970 return FuncParamType(ty)971972973class Parameter(object):974 """A parameter to a command comes in two versions: they are either975 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently976 not supported by design as some of the internals for parsing are977 intentionally not finalized.978979 Some settings are supported by both options and arguments.980981 :param param_decls: the parameter declarations for this option or982 argument. This is a list of flags or argument983 names.984 :param type: the type that should be used. Either a :class:`ParamType`985 or a python type. The latter is converted into the former986 automatically if supported.987 :param required: controls if this is optional or not.988 :param default: the default value if omitted. This can also be a callable989 in which case it's invoked when the default is needed990 without any arguments.991 :param help: the help string.992 :param callback: a callback that should be executed after the parameter993 was matched. This is called as ``fn(ctx, value)`` and994 needs to return the value.995 :param nargs: the number of arguments to match. If not ``1`` the return996 value is a tuple instead of single value.997 :param metavar: how the value is represented in the help page.998 :param expose_value: if this is `True` then the value is passed onwards999 to the command callback and stored on the context,1000 otherwise it's skipped.1001 :param is_eager: eager values are processed before non eager ones. This1002 should not be set for arguments or it will inverse the1003 order of processing.1004 :param envvar: a string or list of strings that are environment variables1005 that should be checked.1006 """1007 param_type_name = 'parameter'10081009 def __init__(self, param_decls=None, type=None, required=False,1010 default=None, help=None, callback=None, nargs=1,1011 metavar=None, expose_value=True, is_eager=False,1012 envvar=None):1013 self.name, self.opts, self.secondary_opts = \1014 self._parse_decls(param_decls or ())1015 self.type = convert_type(type, default)1016 self.required = required1017 self.help = help1018 self.callback = callback1019 self.nargs = nargsAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
line 1020why, one step back1020 self.multiple = FalseInitial commitArmin Ronacherbefore adoption4101de3
lines 1021–10291021 self.expose_value = expose_value1022 self.default = default1023 self.is_eager = is_eager1024 self.metavar = metavar1025 self.envvar = envvar10261027 def make_metavar(self):1028 if self.metavar is not None:1029 return self.metavarAdded choice supportArmin Ronacherbefore adoption9eacc90
lines 1030–1032why, one step back1030 metavar = self.type.get_metavar(self)1031 if metavar is not None:1032 return metavarInitial commitArmin Ronacherbefore adoption4101de3
lines 1033–10411033 metavar = self.name.upper()1034 if self.nargs != 1:1035 metavar += '...'1036 return metavar10371038 def get_default(self, ctx):1039 """Given a context variable this calculates the default value."""1040 # Otherwise go with the regular default.1041 if callable(self.default):Pass default values through the type system.Armin Ronacherbefore adoption7783631
lines 1042–1045why, one step back1042 rv = self.default()1043 else:1044 rv = self.default1045 return self.type(rv, self, ctx)Initial commitArmin Ronacherbefore adoption4101de3
lines 1046–105310461047 def _add_to_parser(self, parser, ctx):1048 raise NotImplementedError()10491050 def process_value(self, ctx, value):1051 """Given a value and context this runs the logic to convert the1052 value as necessary.1053 """Added support for mixing nargs and multipleArmin Ronacherbefore adoption24efee0
lines 1054–1056why, one step back1054 def _convert(value, level):1055 if level == 0:1056 return self.type(value, self, ctx)Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2
line 1057why, one step back1057 return tuple(_convert(x, level - 1) for x in value or ())Added support for mixing nargs and multipleArmin Ronacherbefore adoption24efee0
line 1058why, one step back1058 return _convert(value, (self.nargs != 1) + bool(self.multiple))Initial commitArmin Ronacherbefore adoption4101de3
lines 1059–112110591060 def full_process_value(self, ctx, value):1061 value = self.process_value(ctx, value)10621063 if value is None:1064 value = self.get_default(ctx)10651066 if value is None and self.required:1067 ctx.fail(self.get_missing_message(ctx))10681069 return value10701071 def get_missing_message(self, ctx):1072 return 'Missing %s "%s".' % (1073 self.param_type_name,1074 ' / '.join(chain(self.opts, self.secondary_opts)),1075 )10761077 def value_from_envvar(self, ctx):1078 if self.envvar is None:1079 return1080 if isinstance(self.envvar, (tuple, list)):1081 for envvar in self.envvar:1082 rv = os.environ.get(envvar)1083 if rv is not None:1084 return rv1085 else:1086 return os.environ.get(self.envvar)10871088 def consume_value(self, ctx, opts, args):1089 return None, args10901091 def handle_parse_result(self, ctx, opts, args):1092 value, args = self.consume_value(ctx, opts, args)1093 value = self.full_process_value(ctx, value)1094 if self.callback is not None:1095 value = self.callback(ctx, value)1096 if self.expose_value:1097 ctx.params[self.name] = value1098 return value, args109911001101class Option(Parameter):1102 """Options are usually optionaly values on the command line and1103 have some extra features that arguments don't have.11041105 All other parameters are passed onwards to the parameter constructor.11061107 :param show_default: controls if the default value should be shown on the1108 help page. The default is auto detection.1109 :param prompt: if set to `True` or a non empty string then the user will1110 be prompted for input if not set. If set to `True` the1111 prompt will be the option name capitalized.1112 :param confirmation_prompt: if set then the value will need to be confirmed1113 if it was prompted for.1114 :param hide_input: if this is `True` then the input on the prompt will be1115 hidden from the user. This is useful for password1116 input.1117 :param is_flag: forces this option to act as a flag. The default is1118 auto detection.1119 :param flag_value: which value should be used for this flag if it's1120 enabled. This is set to a boolean automatically if1121 the option string contains a slash to mark two options.Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 1122–1125why, one step back1122 :param multiple: if this is set to True then the argument is accepted1123 multiple times and recorded. This is similar to nargs1124 in how it works but supports arbitrary number of1125 arguments.Initial commitArmin Ronacherbefore adoption4101de3
lines 1126–11351126 :param allow_from_autoenv: if this is enabled then the value of this1127 parameter will be pulled from an environment1128 variable in case a prefix is defined on the1129 context.1130 """1131 param_type_name = 'option'11321133 def __init__(self, param_decls=None, show_default=None,1134 prompt=False, confirmation_prompt=False,1135 hide_input=False, is_flag=None, flag_value=None,Added support for multiple arguments.Armin Ronacherbefore adoption18fff34
lines 1136–1137why, one step back1136 multiple=False, allow_from_autoenv=True, type=None,1137 **attrs):Initial commitArmin Ronacherbefore adoption4101de3
lines 1138–11631138 Parameter.__init__(self, param_decls, type=type, **attrs)1139 if prompt is True:1140 prompt = self.name.replace('_', ' ').capitalize()1141 elif prompt is False:1142 prompt = None1143 self.prompt = prompt1144 self.confirmation_prompt = confirmation_prompt1145 self.hide_input = hide_input11461147 if is_flag is None:1148 if flag_value is not None:1149 is_flag = True1150 else:1151 is_flag = bool(self.secondary_opts)11521153 if is_flag and self.default is None:1154 self.default = False1155 if show_default is None:1156 show_default = False11571158 if flag_value is None:1159 flag_value = not self.default11601161 self.show_default = show_default1162 self.is_flag = is_flag1163 self.flag_value = flag_valueAdded support for multiple arguments.Armin Ronacherbefore adoption18fff34
line 1164why, one step back1164 self.multiple = multipleInitial commitArmin Ronacherbefore adoption4101de3
lines 1165–123411651166 if self.is_flag and isinstance(self.flag_value, bool) \1167 and type is None:1168 self.type = BoolParamType()1169 self.is_bool_flag = True1170 else:1171 self.is_bool_flag = False11721173 self.allow_from_autoenv = allow_from_autoenv11741175 # Sanity check for stuff we don't support1176 if __debug__:1177 if self.prompt and self.is_flag and not self.is_bool_flag:1178 raise TypeError('Cannot prompt for flags that are not bools.')1179 if not self.is_bool_flag and self.secondary_opts:1180 raise TypeError('Got secondary option for non boolean flag.')1181 if self.is_bool_flag and self.hide_input \1182 and self.prompt is not None:1183 raise TypeError('Hidden input does not work with boolean '1184 'flag prompts.')11851186 def _parse_decls(self, decls):1187 opts = []1188 secondary_opts = []1189 name = None1190 possible_names = []11911192 for decl in decls:1193 if not decl.startswith('-'):1194 if name is not None:1195 raise TypeError('Name defined twice')1196 name = decl1197 else:1198 if '/' in decl:1199 first, second = decl.split('/', 1)1200 possible_names.append(first.lstrip('-'))1201 opts.append(first)1202 secondary_opts.append(second)1203 else:1204 possible_names.append(decl.lstrip('-'))1205 opts.append(decl)12061207 if name is None and possible_names:1208 possible_names.sort(key=len)1209 name = possible_names[-1]12101211 if name is None:1212 raise TypeError('Could not determine name for option')12131214 return name.replace('-', '_'), opts, secondary_opts12151216 def _add_to_parser(self, parser, ctx):1217 help = self.help1218 extra = []1219 if self.default is not None and self.show_default:1220 extra.append('default: %s' % self.default)1221 if self.required:1222 extra.append('required')1223 if self.nargs != 1:1224 extra.append('%d arguments' % self.nargs)1225 if extra:1226 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))12271228 kwargs = {1229 'help': help,1230 'dest': self.name,1231 'nargs': self.nargs,1232 'metavar': self.make_metavar(),1233 }1234Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2
lines 1235–1236why, one step back1235 action = self.multiple and 'append' or 'store'1236Initial commitArmin Ronacherbefore adoption4101de3
lines 1237–12391237 if self.is_flag:1238 kwargs.pop('nargs', None)1239 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 1240why, one step back1240 pos_opt = optparse.Option(*self.opts, action=action + '_true',Initial commitArmin Ronacherbefore adoption4101de3
lines 1241–12441241 **kwargs)1242 kwargs.pop('default', None)1243 kwargs.pop('help', None)1244 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 1245why, one step back1245 action=action + '_false',Initial commitArmin Ronacherbefore adoption4101de3
lines 1246–12511246 help=optparse.SUPPRESS_HELP,1247 **kwargs)1248 pos_opt._negative_version = neg_opt1249 parser.add_option(pos_opt)1250 parser.add_option(neg_opt)1251 else:Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2
line 1252why, one step back1252 parser.add_option(*self.opts, action=action + '_const',Initial commitArmin Ronacherbefore adoption4101de3
lines 1253–12551253 const=self.flag_value,1254 **kwargs)1255 else:Added some more statements on argparse and how verbosity can be implemented in click.Armin Ronacherbefore adoption84fbcb2
line 1256why, one step back1256 kwargs['action'] = actionInitial commitArmin Ronacherbefore adoption4101de3
lines 1257–13491257 parser.add_option(*self.opts, **kwargs)12581259 def get_default(self, ctx):1260 # If we're a non boolean flag out default is more complex because1261 # we need to look at all flags in the same group to figure out1262 # if we're the the default one in which case we return the flag1263 # value as default.1264 if self.is_flag and not self.is_bool_flag:1265 for param in ctx.command.params:1266 if param.name == self.name and param.default:1267 return param.flag_value1268 return None1269 return Parameter.get_default(self, ctx)12701271 def prompt_for_value(self, ctx):1272 """This is an alternative flow that can be activated in the full1273 value processing if a value does not exist. It will prompt the1274 user until a valid value exists and then returns the processed1275 value as result.1276 """1277 # Calculate the default before prompting anything to be stable.1278 default = self.get_default(ctx)12791280 # If this is a prompt for a flag we need to handle this1281 # differently.1282 if self.is_bool_flag:1283 return confirm(self.prompt, default)12841285 return prompt(self.prompt, default=default,1286 hide_input=self.hide_input,1287 confirmation_prompt=self.confirmation_prompt,1288 value_proc=lambda x: self.process_value(ctx, x))12891290 def value_from_envvar(self, ctx):1291 rv = Parameter.value_from_envvar(self, ctx)1292 if rv is not None:1293 return rv1294 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1295 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1296 return os.environ.get(envvar)12971298 def full_process_value(self, ctx, value):1299 if value is None and self.prompt is not None:1300 return self.prompt_for_value(ctx)1301 return Parameter.full_process_value(self, ctx, value)13021303 def consume_value(self, ctx, opts, args):1304 value = opts.get(self.name)1305 if value is None:1306 value = self.value_from_envvar(ctx)1307 return value, args130813091310class Argument(Parameter):1311 param_type_name = 'argument'13121313 def __init__(self, param_decls, required=True, **attrs):1314 Parameter.__init__(self, param_decls, required=required, **attrs)13151316 def make_metavar(self):1317 if self.metavar is not None:1318 return self.metavar1319 var = self.name.upper()1320 if not self.required:1321 var = '[%s]' % var1322 if self.nargs != 1:1323 var += '...'1324 return var13251326 def _parse_decls(self, decls):1327 if not decls:1328 raise TypeError('Could not determine name for argument')1329 if len(decls) == 1:1330 name = arg = decls[0]1331 elif len(decls) == 2:1332 name, arg = decls1333 else:1334 raise TypeError('Arguments take exactly one or two '1335 'parameter declarations, got %d' % len(decls))1336 return name.replace('-', '_'), [arg], []13371338 def _add_to_parser(self, parser, ctx):1339 parser.usage += ' ' + self.make_metavar()13401341 def consume_value(self, ctx, opts, args):1342 found = True1343 if self.nargs == 1:1344 try:1345 value = args.pop(0)1346 except IndexError:1347 found = False1348 elif self.nargs < 0:1349 value = tuple(args)Correct fix for #20Armin Ronacherbefore adoption8ca33a9
line 1350why, one step back1350 found = valueInitial commitArmin Ronacherbefore adoption4101de3
lines 1351–13551351 args = []1352 else:1353 values = args[:self.nargs]1354 args = args[self.nargs:]1355 value = tuple(values)Correct fix for #20Armin Ronacherbefore adoption8ca33a9
line 1356why, one step back1356 found = valueInitial commitArmin Ronacherbefore adoption4101de3
lines 1357–13591357 if not found:1358 value = self.value_from_envvar(ctx)1359 if self.nargs != 1:Correct fix for #20Armin Ronacherbefore adoption8ca33a9
line 1360why, one step back1360 value = value and (value,) or ()Initial commitArmin Ronacherbefore adoption4101de3
lines 1361–13811361 return value, args136213631364def _make_command(f, name, attrs, cls):1365 if isinstance(f, Command):1366 raise TypeError('Attempted to convert a callback into a '1367 'command twice.')1368 try:1369 params = f.__click_params__1370 params.reverse()1371 del f.__click_params__1372 except AttributeError:1373 params = []1374 help = inspect.getdoc(f)1375 if isinstance(help, bytes):1376 help = help.decode('utf-8')1377 attrs.setdefault('help', help)1378 return cls(name=name or f.__name__.lower(),1379 callback=f, params=params, **attrs)13801381Added an example for aliasesArmin Ronacherbefore adoptione2d388e
line 1382why, one step back1382def command(name=None, cls=None, **attrs):Initial commitArmin Ronacherbefore adoption4101de3
lines 1383–13951383 """Creates a new :class:`Command` and uses the decorated function as1384 callback. This will also automatically attach all decorated1385 :func:`option`\s and :func:`argument`\s as paramters to the command.13861387 The name of the command defaults to the name of the function. If you1388 want to change that, you can pass the intended name as the first1389 argument.13901391 All keyword arguments are forwarded to the underlying command class.13921393 Once decorated the function turns into a :class:`Command` instance1394 that can be invoked as a command line utility or be attached to a1395 command :class:`Group`.Added an example for aliasesArmin Ronacherbefore adoptione2d388e
lines 1396–1400why, one step back13961397 :param name: the name of the command. This defaults to the function1398 name.1399 :param cls: the command class to instanciate. This defaults to1400 :class:`Command`.1401 """Added an example for aliasesArmin Ronacherbefore adoptione2d388e
lines 1402–1403why, one step back1402 if cls is None:1403 cls = Command1404 def decorator(f):Added an example for aliasesArmin Ronacherbefore adoptione2d388e
line 1405why, one step back1405 return _make_command(f, name, attrs, cls)Initial commitArmin Ronacherbefore adoption4101de3
lines 1406–14101406 return decorator140714081409def group(name=None, **attrs):1410 """Creates a new :class:`Group` with a function as callback. ThisAdded an example for aliasesArmin Ronacherbefore adoptione2d388e
lines 1411–1412why, one step back1411 works otherwise the same as :func:`command` just that the `cls`1412 parameter is set to :class:`Group`.1413 """Added an example for aliasesArmin Ronacherbefore adoptione2d388e
line 1414why, one step back1414 return command(name, cls=Group, **attrs)Initial commitArmin Ronacherbefore adoption4101de3
lines 1415–1574141514161417def _param_memo(f, param):1418 if isinstance(f, Command):1419 f.params.append(param)1420 else:1421 if not hasattr(f, '__click_params__'):1422 f.__click_params__ = []1423 f.__click_params__.append(param)142414251426def argument(*param_decls, **attrs):1427 """Attaches an option to the command. All positional arguments are1428 passed as parameter declarations to :class:`Argment`, all keyword1429 arguments are forwarded unchanged. This is equivalent to creating an1430 :class:`Option` instance manually and attaching it to the1431 :attr:`Command.params` list.1432 """1433 def decorator(f):1434 _param_memo(f, Argument(param_decls, **attrs))1435 return f1436 return decorator143714381439def option(*param_decls, **attrs):1440 """Attaches an option to the command. All positional arguments are1441 passed as parameter declarations to :class:`Option`, all keyword1442 arguments are forwarded unchanged. This is equivalent to creating an1443 :class:`Option` instance manually and attaching it to the1444 :attr:`Command.params` list.1445 """1446 def decorator(f):1447 _param_memo(f, Option(param_decls, **attrs))1448 return f1449 return decorator145014511452def confirmation_option(*param_decls, **attrs):1453 """Shortcut for confirmation prompts that can be ignored by bypassed1454 ``--yes`` as parameter.14551456 This is equivalent to decorating a function with :func:`option` with1457 the following parameters::14581459 def callback(ctx, value):1460 if not value:1461 ctx.abort()14621463 @click.command()1464 @click.option('--yes', is_flag=True, callback=callback,1465 expose_value=False, prompt='Do you want to continue?')1466 def dropdb():1467 pass1468 """1469 def decorator(f):1470 def callback(ctx, value):1471 if not value:1472 ctx.abort()1473 attrs.setdefault('is_flag', True)1474 attrs.setdefault('callback', callback)1475 attrs.setdefault('expose_value', False)1476 attrs.setdefault('prompt', 'Do you want to continue?')1477 return option(*(param_decls or ('--yes',)), **attrs)(f)1478 return decorator147914801481def password_option(*param_decls, **attrs):1482 """Shortcut for password prompts.14831484 This is equivalent to decorating a function with :func:`option` with1485 the following parameters::14861487 @click.command()1488 @click.option('--password', prompt=True, confirmation_prompt=True,1489 hide_input=True)1490 def changeadmin(password):1491 pass1492 """1493 def decorator(f):1494 attrs.setdefault('prompt', True)1495 attrs.setdefault('confirmation_prompt', True)1496 attrs.setdefault('hide_input', True)1497 return option(*(param_decls or ('--password',)), **attrs)(f)1498 return decorator149915001501def version_option(version, *param_decls, **attrs):1502 """Adds a ``--version`` option which immediately ends the program1503 printing out the version number. This is implemented as an eager1504 option that prints the version and exits the program in the callback.15051506 :param version: the version number to show1507 :param prog_name: the name of the program (defaults to autodetection)1508 :param message: custom message to show instead of the default1509 (``'%(prog)s, version %(version)s'``)1510 :param others: everything else is forwarded to :func:`option`.1511 """1512 def decorator(f):1513 prog_name = attrs.pop('prog_name', None)1514 message = attrs.pop('message', '%(prog)s, version %(version)s')15151516 def callback(ctx, value):1517 if not value:1518 return1519 prog = prog_name1520 if prog is None:1521 prog = ctx.find_root().info_name1522 echo(message % {1523 'prog': prog,1524 'version': version,1525 })1526 ctx.exit()15271528 attrs.setdefault('is_flag', True)1529 attrs.setdefault('expose_value', False)1530 attrs.setdefault('is_eager', True)1531 attrs.setdefault('help', 'Show the version and exit.')1532 attrs['callback'] = callback1533 return option(*(param_decls or ('--version',)), **attrs)(f)1534 return decorator153515361537def help_option(*param_decls, **attrs):1538 """Adds a ``--help`` option which immediately ends the program1539 printing out the help page. This is usually unnecessary to add as1540 this is added by default to all commands unless supressed.15411542 Like :func:`version_option` this is implemented as eager option that1543 prints in the callback and exits.15441545 All arguments are forwarded to :func:`option`.1546 """1547 def decorator(f):1548 def callback(ctx, value):1549 if value:1550 echo(ctx.format_help())1551 ctx.exit()1552 attrs.setdefault('is_flag', True)1553 attrs.setdefault('expose_value', False)1554 attrs.setdefault('help', 'Show this message and exit.')1555 attrs.setdefault('is_eager', True)1556 attrs['callback'] = callback1557 return option(*(param_decls or ('--help',)), **attrs)(f)1558 return decorator155915601561def confirm(text, default=False, abort=False):1562 """Prompts for confirmation (yes/no question).15631564 If the user aborts the input by sending a interrupt signal this1565 function will catch it and raise a :exc:`Abort` exception.15661567 :param text: the question to ask.1568 :param default: the default for the prompt.1569 :param abort: if this is set to `True` a negative answer aborts the1570 exception by raising :exc:`Abort`.1571 """1572 prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')1573 while 1:1574 try:Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
line 1575why, one step back1575 value = visible_prompt_func(prompt).lower().strip()Initial commitArmin Ronacherbefore adoption4101de3
lines 1576–16151576 except (KeyboardInterrupt, EOFError):1577 raise Abort()1578 if value in ('y', 'yes'):1579 rv = True1580 elif value in ('n', 'no'):1581 rv = False1582 elif value == '':1583 rv = default1584 else:1585 echo('Error: invalid input')1586 continue1587 break1588 if abort and not rv:1589 raise Abort()1590 return rv159115921593def prompt(text, default=None, hide_input=False,1594 confirmation_prompt=False, type=None,1595 value_proc=None):1596 """Prompts a user for input. This is a convenience function that can1597 be used to prompt a user for input later.15981599 If the user aborts the input by sending a interrupt signal this1600 function will catch it and raise a :exc:`Abort` exception.16011602 :param text: the text to show for the prompt.1603 :param default: the default value to use if no input happens. If this1604 is not given it will prompt until it's aborted.1605 :param hide_input: if this is set to true then the input value will1606 be hidden.1607 :param confirmation_prompt: asks for confirmation for the value.1608 :param type: the type to use to check the value against.1609 :param value_proc: if this parameter is provided it's a function that1610 is invoked instead of the type conversion to1611 convert a value.1612 """1613 result = None16141615 def prompt_func(text):Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
line 1616why, one step back1616 f = hide_input and hidden_prompt_func or visible_prompt_funcInitial commitArmin Ronacherbefore adoption4101de3
lines 1617–16701617 try:1618 return f(text)1619 except (KeyboardInterrupt, EOFError):1620 raise Abort()16211622 if value_proc is None:1623 value_proc = convert_type(type, default)16241625 prompt = text1626 if default is not None:1627 prompt = '%s [%s]' % (prompt, default)1628 prompt += ': '16291630 while 1:1631 while 1:1632 value = prompt_func(prompt)1633 if value:1634 break1635 # If a default is set and used, then the confirmation1636 # prompt is always skipped because that's the only thing1637 # that really makes sense.1638 elif default is not None:1639 return default1640 try:1641 result = value_proc(value)1642 except UsageError as e:1643 echo('Error: %s' % e.message)1644 continue1645 if not confirmation_prompt:1646 return result1647 while 1:1648 value2 = prompt_func('Repeat for confirmation: ')1649 if value2:1650 break1651 if value == value2:1652 return result1653 echo('Error: the two entered values do not match')165416551656#: A unicode string parameter type which is the implicit default. This1657#: can also be selected by using ``str`` as type.1658STRING = StringParamType()16591660#: An integer parameter. This can also be selected by using ``int`` as1661#: type.1662INT = IntParamType()16631664#: A floating point value parameter. This can also be selected by using1665#: ``float`` as type.1666FLOAT = FloatParamType()16671668#: A boolean parameter. This is the default for boolean flags. This can1669#: also be selected by using ``bool`` as a type.1670BOOL = BoolParamType()