click.py
This file
Path
click.py
1,533 lines · 54.0 KiB · Python
Last changed by
Merge pull request #9 from ikkebr/patch-3Armin Ronacherbefore adoption3755db7
History of this fileTake it
Initial commitArmin Ronacherbefore adoption4101de3
lines 1–751# -*- 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 chain252627PY2 = sys.version_info[0] == 228if PY2:29 text_type = unicode30 bytes = str3132 def open_stream(filename, mode='r', encoding=None, errors='strict'):33 if filename != '-':34 if encoding is not None:35 return codecs.open(filename, mode, encoding, errors), True36 return open(filename, mode), True37 if 'w' in mode:38 f = sys.stdout39 if encoding is not None:40 f = _wrap_stream_for_codec(f, encoding, errors)41 else:42 f = sys.stdin43 if 'b' not in mode:44 if encoding is None:45 encoding = sys.stdin.encoding46 f = _wrap_stream_for_codec(f, encoding, errors)47 return f, False48else:49 text_type = str50 raw_input = input5152 def open_stream(filename, mode='r', encoding=None, errors='strict'):53 if filename != '-':54 return open(filename, mode, encoding=encoding, errors=errors), True55 if 'w' in mode:56 f = sys.stdout57 if encoding is not None or 'b' in mode:58 f = f.buffer.raw59 if encoding is not None:60 f = _wrap_stream_for_codec(f, encoding, errors)61 else:62 f = sys.stdin63 if 'b' in mode:64 f = f.buffer.raw65 if encoding is not None:66 f = _wrap_stream_for_codec(f, encoding, errors)67 return f, False686970def get_terminal_size():71 """Returns the current size of the terminal as tuple in the form72 ``(width, height)`` in columns and rows.73 """74 def ioctl_gwinsz(fd):75 try:Merge pull request #9 from ikkebr/patch-3Armin Ronacherbefore adoption3755db7
lines 76–77why, one step back76 import fcntl77 import termiosInitial commitArmin Ronacherbefore adoption4101de3
lines 78–153378 cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))79 except Exception:80 return81 return cr8283 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)84 if not cr:85 try:86 fd = os.open(os.ctermid(), os.O_RDONLY)87 try:88 cr = ioctl_gwinsz(fd)89 finally:90 os.close(fd)91 except Exception:92 pass93 if not cr:94 cr = (os.environ.get('LINES', 25),95 os.environ.get('COLUMNS', 80))96 return int(cr[1]), int(cr[0])979899class TextWrapper(textwrap.TextWrapper):100101 def _cutdown(self, ucstr, space_left):102 l = 0103 for i in xrange(len(ucstr)):104 l += len(ucstr[i])105 if space_left < l:106 return (ucstr[:i], ucstr[i:])107 return ucstr, ''108109 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):110 space_left = max(width - cur_len, 1)111112 if self.break_long_words:113 cut, res = self._cutdown(reversed_chunks[-1], space_left)114 cur_line.append(cut)115 reversed_chunks[-1] = res116 elif not cur_line:117 cur_line.append(reversed_chunks.pop())118119 def fill_paragraphs(self, text):120 # Remove unnecessary newlines so that we can fill properly121 p = []122 buf = []123 for line in text.splitlines():124 if not line:125 p.append(' '.join(buf))126 buf = []127 else:128 buf.append(line)129 if buf:130 p.append(' '.join(buf))131132 rv = []133 for text in p:134 rv.append(self.fill(text))135 return '\n\n'.join(rv)136137138def _wrap_stream_for_codec(f, encoding=None, errors='strict'):139 if encoding is None:140 encoding = 'utf-8'141 info = codecs.lookup(encoding)142 f = codecs.StreamReaderWriter(f, info.streamreader,143 info.streamwriter,144 errors)145 f.encoding = encoding146 return f147148149def echo(message=None, file=None):150 if file is None:151 file = sys.stdout152 if message:153 if PY2 and isinstance(message, text_type):154 message = message.encode(file.encoding)155 file.write(message)156 file.write('\n')157 file.flush()158159160class Context(object):161 """The context is a special internal object that holds state relevant162 for the script execution at every single level. It's normally invisible163 to commands unless they opt-in to getting access to it.164165 The context is useful as it can pass internal objects around and can166 control special execution features such as reading data from167 environment variables.168169 A context can be used as context manager in which case it will call170 :meth:`close` on teardown.171172 :param command: the command class for this context.173 :param parent: the parent context.174 :param info_name: the info name for this invokation. Generally this175 is the most descriptive name for the script or176 command. For the toplevel script is is usually177 the name of the script, for commands below it it's178 the name of the script.179 :param obj: an arbitrary object of user data.180 :param auto_envvar_prefix: the prefix to use for automatic environment181 variables. If this is `None` then reading182 from environment variables is disabled. This183 does not affect manually set environment184 variables which are always read.185 """186187 def __init__(self, command, parent=None, info_name=None, obj=None,188 auto_envvar_prefix=None):189 #: the parent context or `None` if none exists.190 self.parent = parent191 #: the :class:`Command` for this context.192 self.command = command193 #: the descriptive information name194 self.info_name = info_name195 #: the parsed parameters except if the value is hidden in which196 #: case it's not remembered.197 self.params = {}198 #: the leftover arguments.199 self.args = []200 #: this flag indicates if a subcommand is going to be executed.201 #: a group callback can use this information to figure out if it's202 #: being executed directly or because the execution flow passes203 #: onwards to a subcommand. By default it's `None` but it can be204 #: the name of the subcommand to execute.205 self.invoked_subcommand = None206 if obj is None and parent is not None:207 obj = parent.obj208 #: the user object stored.209 self.obj = obj210211 # If there is no envvar prefix yet, but the parent has one and212 # the command on this level has a name, we can expand the envvar213 # prefix automatically.214 if auto_envvar_prefix is None:215 if parent is not None \216 and parent.auto_envvar_prefix is not None and \217 self.info_name is not None:218 auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,219 self.info_name.upper())220 else:221 self.auto_envvar_prefix = auto_envvar_prefix.upper()222 self.auto_envvar_prefix = auto_envvar_prefix223224 self._parser = command._make_parser(self)225 self._close_callbacks = []226227 def __enter__(self):228 return self229230 def __exit__(self, exc_type, exc_value, tb):231 self.close()232233 def call_on_close(self, f):234 """This decorator remembers a function as callback that should be235 executed when the context tears down. This is most useful to bind236 resource handling to the script execution. For instance file objects237 opened by the :class:`File` type will register their close callbacks238 here.239240 :param f: the function to execute on teardown.241 """242 self._close_callbacks.append(f)243 return f244245 def close(self):246 """Invokes all close callbacks."""247 for cb in self._close_callbacks:248 cb()249 self._close_callbacks = []250251 @property252 def command_path(self):253 """The computed command path. This is used for the ``usage``254 information on the help page. It's automatically created by255 combining the info names of the chain of contexts to the root.256 """257 rv = ''258 if self.info_name is not None:259 rv = self.info_name260 if self.parent is not None:261 rv = self.parent.command_path + ' ' + rv262 return rv.lstrip()263264 def find_root(self):265 """Finds the outermost context."""266 node = self267 while node.parent is not None:268 node = node.parent269 return node270271 def fail(self, message):272 """Aborts the execution of the program with a specific error273 message.274275 :param message: the error message to fail with.276 """277 raise UsageError(message, self)278279 def abort(self):280 """Aborts the script."""281 raise Abort()282283 def exit(self, code=0):284 """Exits the application with a given exit code."""285 sys.exit(code)286287 def format_usage(self):288 """Helper method to get formatted usage string for the current289 context and command.290 """291 return self._parser.get_usage()292293 def format_help(self):294 """Helper method to get formatted help page for the current295 context and command.296 """297 return self._parser.format_help().rstrip()298299300class UsageError(Exception):301 """An internal exception that signals a usage error. This typically302 aborts any further handling.303 """304305 def __init__(self, message, ctx=None):306 if PY2:307 Exception.__init__(self, message.encode('utf-8'))308 else:309 Exception.__init__(self, message)310 self.message = message311 self.ctx = ctx312313314class Abort(Exception):315 """An internal signalling exception that signals click to abort."""316317318class _SimplifiedFormatter(optparse.IndentedHelpFormatter):319320 def __init__(self):321 optparse.IndentedHelpFormatter.__init__(self,322 width=min(get_terminal_size()[0], 80) - 2)323 self.default_tag = ''324325 def format_usage(self, usage):326 prefix = 'Usage: '327 indent = len(prefix)328 text_width = self.width - indent329 return '%s%s\n' % (prefix, TextWrapper(330 text_width, initial_indent='',331 subsequent_indent=' ' * indent,332 replace_whitespace=False).fill(usage))333334 def _format_text(self, text):335 text_width = self.width - self.current_indent336 indent = ' ' * self.current_indent337338 return TextWrapper(text_width,339 initial_indent=indent,340 subsequent_indent=indent,341 replace_whitespace=False).fill_paragraphs(text)342343 def format_description(self, description):344 if not description:345 return ''346 self.indent()347 rv = self._format_text(description) + '\n'348 self.dedent()349 return rv350351 def format_option_strings(self, option):352 rv = optparse.IndentedHelpFormatter.format_option_strings(self, option)353 if hasattr(option, '_negative_version'):354 rv += ' / ' + optparse.IndentedHelpFormatter.format_option_strings(355 self, option._negative_version)356 return rv357358359class _SimplifiedOptionParser(optparse.OptionParser):360361 def __init__(self, ctx, **extra):362 usage = ctx.command_path + ' ' + ctx.command.options_metavar363 optparse.OptionParser.__init__(self, prog=ctx.command_path,364 usage=usage,365 add_help_option=False,366 formatter=_SimplifiedFormatter(),367 **extra)368 self.__ctx = ctx369370 def expand_prog_name(self, s):371 return s372373 def format_option_help(self, formatter):374 rv = optparse.OptionParser.format_option_help(self, formatter)375 extra_help = self.__ctx.command._format_extra_help(self.__ctx)376 if extra_help:377 rv = '%s\n\n%s' % (extra_help, rv)378 return rv379380 def error(self, msg):381 raise UsageError(msg, self.__ctx)382383384class Command(object):385 """Commands are the basic building block of command line interfaces in386 click. A basic command handles command line parsing and might dispatch387 more parsing to commands nested blow it.388389 :param name: the name of the command to use unless a group overrides it.390 :param callback: the callback to invoke. This is optional.391 :param params: the parameters to register with this command. This can392 be either :class:`Option` or :class:`Argument` objects.393 :param pass_context: if this is set to `True` then the callback will394 be passed the context as first argument.395 :param pass_params: if this is set to `True` then the callback will396 be passed all non hidden parameters as keyword397 arguments.398 :param help: the help string to use for this command.399 :param short_help: the short help to use for this command. This is400 shown on the command listing of the parent command.401 :param add_help_option: by default each command registers a ``--help``402 option. This can be disabled by this parameter.403 """404 allow_extra_args = False405406 def __init__(self, name, callback=None, params=None, pass_context=False,407 pass_params=True, help=None, short_help=None,408 options_metavar='[OPTIONS]', add_help_option=True):409 #: the name the command things it has. Upon registering a command410 #: on a :class:`Group` the group will default the command name411 #: with this information. You should instead use the412 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.413 self.name = name414 #: the callback to execute when the command fires. This might be415 #: `None` in which case nothing happens.416 self.callback = callback417 #: the list of parameters for this command in the order they418 #: should show up in the help page and execute. Eager parameters419 #: will automatically be handled before non eager ones.420 self.params = params or []421 self.pass_context = pass_context422 self.pass_params = pass_params423 self.help = help424 self.options_metavar = options_metavar425 if short_help is None and help:426 short_help = help.split('.')[0].strip()427 if len(short_help) > 45:428 short_help = None429 elif short_help:430 short_help = short_help[0].lower() + short_help[1:] + '.'431 self.short_help = short_help432 if add_help_option:433 help_option()(self)434435 def iter_params_for_processing(self):436 """This returns an iterator over all attached parameters in the437 order of processing. This iterator returns all eager parameters438 first, followed by all non-eager parameters.439 """440 for param in self.params:441 if param.is_eager:442 yield param443 for param in self.params:444 if not param.is_eager:445 yield param446447 def _make_parser(self, ctx):448 parser = _SimplifiedOptionParser(ctx, description=self.help)449 for param in self.params:450 param._add_to_parser(parser, ctx)451 return parser452453 def _format_extra_help(self, ctx):454 pass455456 def make_context(self, info_name, args, parent=None, **extra):457 """This function when given an info name and arguments will kick458 off the parsing and create a new :class:`Context`. It does not459 invoke the actual command callback though.460461 :param info_name: the info name for this invokation. Generally this462 is the most descriptive name for the script or463 command. For the toplevel script is is usually464 the name of the script, for commands below it it's465 the name of the script.466 :param args: the arguments to parse as list of strings.467 :param parent: the parent context if available.468 :param extra: extra keyword arguments forwarded to the context469 constructor.470 """471 ctx = Context(self, info_name=info_name, parent=parent, **extra)472 opts, args = ctx._parser.parse_args(args=args)473 opts = opts.__dict__474475 for param in ctx.command.iter_params_for_processing():476 value, args = param.handle_parse_result(ctx, opts, args)477478 if args and not self.allow_extra_args:479 ctx.fail('Got unexpected extra argument%s (%s)'480 % (len(args) != 1 and 's' or '', ' '.join(args)))481482 ctx.args = args483484 return ctx485486 def invoke(self, ctx):487 """Given a context, this invokes the attached callback (if it exists)488 in the right way.489 """490 func_args = self.pass_context and (ctx,) or ()491 func_kwargs = self.pass_params and ctx.params or {}492 if self.callback is not None:493 self.callback(*func_args, **func_kwargs)494495 def main(self, args=None, prog_name=None, **extra):496 """This is the way to invoke a script with all the bells and497 whistles as command line application. This will always terminate498 the application after calling. If this is not wanted, ``SystemExit``499 needs to be caught.500501 This method is also available by directly calling the instance of502 a :class:`Command`.503504 :param args: the arguments that should be used for parsing. If not505 provided, ``sys.argv[1:]`` is used.506 :param prog_name: the program name that should be used. By default507 the progam name is constructed by taking the file508 name from ``sys.argv[0]``.509 :param extra: extra keyword arguments are forwarded to the context510 constructor.511 """512 if args is None:513 args = sys.argv[1:]514 else:515 args = list(args)516 if prog_name is None:517 prog_name = os.path.basename(sys.argv and sys.argv[0] or __file__)518 try:519 try:520 with self.make_context(prog_name, args, **extra) as ctx:521 self.invoke(ctx)522 ctx.exit()523 except (EOFError, KeyboardInterrupt):524 echo(file=sys.stderr)525 raise Abort()526 except UsageError as e:527 if e.ctx is not None:528 echo(e.ctx.format_usage(), file=sys.stderr)529 echo('Error: %s' % e.message, file=sys.stderr)530 sys.exit(2)531 except Abort:532 echo('Aborted!', file=sys.stderr)533 sys.exit(1)534535 def __call__(self, *args, **kwargs):536 """Alias for :meth:`main`."""537 return self.main(*args, **kwargs)538539540class MultiCommand(Command):541 """A multi command is the basic implementation of a command that542 dispatches to subcommands. The most common version is the543 :class:`Command`.544545 :param invoke_without_command: this controls how the multi command itself546 is invoked. By default it's only invoked547 if a subcommand is provided.548 :param no_args_is_help: this controls what happens if no arguments are549 provided. This option is enabled by default if550 `invoke_without_command` is disabled or disabled551 if it's enabled. If enabled this will add552 ``--help`` as argument if no arguments are553 passed.554 :param subcommand_metavar: the string that is used in the documentation555 to indicate the subcommand place.556 """557 allow_extra_args = True558559 def __init__(self, name=None, invoke_without_command=False,560 no_args_is_help=None,561 subcommand_metavar='COMMAND [ARGS]...', **attrs):562 Command.__init__(self, name, **attrs)563 if no_args_is_help is None:564 no_args_is_help = not invoke_without_command565 self.no_args_is_help = no_args_is_help566 self.invoke_without_command = invoke_without_command567 self.subcommand_metavar = subcommand_metavar568569 def _make_parser(self, ctx):570 parser = Command._make_parser(self, ctx)571 parser.usage += ' ' + self.subcommand_metavar572 parser.disable_interspersed_args()573 return parser574575 def _format_extra_help(self, ctx):576 commands = self.list_commands()577 if not commands:578 return579580 longest = len(sorted(commands, key=len)[-1])581582 subcommand_info = []583 for subcommand in self.list_commands():584 cmd = self.get_command(ctx, subcommand)585 help = cmd.short_help or ''586 subcommand_info.append(' %-*s %s' % (longest, subcommand, help))587588 return 'Commands:\n%s' % '\n'.join(subcommand_info)589590 def make_context(self, info_name, args, parent=None, **extra):591 # Multi-commands invoked without any arguments is a shortcut to592 # invoking it with --help unless supresssed.593 if not args and self.no_args_is_help:594 args = ['--help']595 return Command.make_context(self, info_name, args, parent, **extra)596597 def invoke(self, ctx):598 if not ctx.args:599 if self.invoke_without_command:600 return Command.invoke(self, ctx)601 ctx.fail('Missing command')602 cmd_name = ctx.args[0]603604 cmd = self.get_command(ctx, cmd_name)605 if cmd is None:606 ctx.fail('No such command "%s"' % cmd_name)607608 # Whenever we dispatch to a subcommand we also invoke the regular609 # callback. This is done so that parameters can be handled.610 ctx.invoked_subcommand = cmd_name611 Command.invoke(self, ctx)612613 with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:614 return cmd.invoke(cmd_ctx)615616 def get_command(self, ctx, cmd_name):617 """Given a context and a command name, this returns a618 :class:`Command` object if it exists or returns `None`.619 """620 raise NotImplementedError()621622 def list_commands(self):623 """Returns a list of subcommand names in the order they should624 appear.625 """626 return []627628629class Group(MultiCommand):630 """A group allows a command to have subcommands attached. This is the631 most common way to implement nesting in click.632633 :param commands: a dictionary of commands.634 """635636 def __init__(self, name=None, commands=None, **attrs):637 MultiCommand.__init__(self, name, **attrs)638 #: the registered subcommands by their exported names.639 self.commands = commands or {}640641 def add_command(self, cmd, name=None):642 """Registers another :class:`Command` with this group. If the name643 is not provided, the name of the command is used.644 """645 name = name or cmd.name646 if name is None:647 raise TypeError('Command has no name.')648 self.commands[name] = cmd649650 def command(self, *args, **kwargs):651 """A shortcut decorator for declaring and attaching a command to652 the group. This takes the same arguments as :func:`command` but653 immediately registers the created command with this instance by654 calling into :meth:`add_command`.655 """656 def decorator(f):657 cmd = command(*args, **kwargs)(f)658 self.add_command(cmd)659 return cmd660 return decorator661662 def get_command(self, ctx, cmd_name):663 return self.commands.get(cmd_name)664665 def list_commands(self):666 return sorted(self.commands)667668669class ParamType(object):670 """Helper for converting values through types. The following is671 necessary for a valid type:672673 * it needs a name674 * it needs to pass through None unchanged675 * it needs to convert from a string676 * it needs to convert its result type through unchanged677 (eg: needs to be idempotent)678 * it needs to be able to deal with param and context being none.679 This can be the case when the object is used with prompt680 inputs.681 """682683 #: the descriptive name of this type684 name = None685686 def __call__(self, value, param=None, ctx=None):687 if value is not None:688 return self.convert(value, param, ctx)689690 def convert(self, param, ctx, value):691 """Converts the value. This is not invoked for values that are692 `None` (the missing value).693 """694 return value695696 def fail(self, message, param=None, ctx=None):697 """Helper method to fail with an invalid value message."""698 if param is None:699 message = 'Invalid value: %s' % message700 else:701 message = 'Invalid value for %s: %s' % (param.name, message)702 raise UsageError(message, ctx=ctx)703704705class FuncParamType(ParamType):706707 def __init__(self, func):708 self.name = func.__name__709 self.func = func710711 def convert(self, value, param, ctx):712 try:713 return self.func(value)714 except ValueError:715 try:716 value = unicode(value)717 except UnicodeError:718 value = str(value).decode('utf-8', 'replace')719 self.fail(value, param, ctx)720721722class StringParamType(ParamType):723 name = 'string'724725 def convert(self, value, param, ctx):726 if isinstance(value, bytes):727 try:728 if sys.stdin.encoding is not None:729 value = value.decode(sys.stdin.encoding)730 except UnicodeError:731 try:732 value = value.decode(sys.getfilesystemencoding())733 except UnicodeError:734 value = value.decode('utf-8', 'replace')735 return value736 return value737738 def __repr__(self):739 return 'STRING'740741742class IntParamType(ParamType):743 name = 'integer'744745 def convert(self, value, param, ctx):746 try:747 return int(value)748 except ValueError:749 self.fail('%s is not a valid integer' % value, param, ctx)750751 def __repr__(self):752 return 'INT'753754755class BoolParamType(ParamType):756 name = 'boolean'757758 def convert(self, value, param, ctx):759 if isinstance(value, bool):760 return bool(value)761 value = value.lower()762 if value in ('true', '1', 'yes', 'y'):763 return True764 elif value in ('false', '0', 'no', 'n'):765 return False766 self.fail('%s is not a valid boolean' % value, param, ctx)767768 def __repr__(self):769 return 'BOOL'770771772class FloatParamType(ParamType):773 name = 'float'774775 def convert(self, value, param, ctx):776 try:777 return float(value)778 except ValueError:779 self.fail('%s is not a valid floating point value' %780 value, param, ctx)781782 def __repr__(self):783 return 'FLOAT'784785786class File(ParamType):787 """Declares a parameter to be a file for reading or writing. The file788 is automatically closed once the context tears down (after the command789 finished working).790791 Files can be opened for reading or writing. The special value ``-``792 indicates stdin or stdout depending on the mode.793794 By default the file is opened for reading text data but it can also be795 opened in binary mode or for writing. The encoding parameter can be used796 to force a specific encoding.797 """798 name = 'filename'799800 def __init__(self, mode='r', encoding=None, errors='strict'):801 self.mode = mode802 self.encoding = encoding803 self.errors = errors804805 def convert(self, value, param, ctx):806 try:807 f, was_opened = open_stream(value, self.mode, self.encoding,808 self.errors)809 # If a context is provided we automatically close the file810 # at the end of the context execution (or flush out). If a811 # context does not exist it's the caller's responsibility to812 # properly close the file. This for instance happens when the813 # type is used with prompts.814 if ctx is not None:815 if was_opened:816 ctx.call_on_close(f.close)817 else:818 ctx.call_on_close(f.flush)819 return f820 except (IOError, OSError) as e:821 if isinstance(value, bytes):822 value = value.decode(sys.getfilesystemencoding(), 'replace')823 self.fail('Could not open file %s: %s' % (value, e),824 param, ctx)825826827def convert_type(ty, default=None):828 """Converts a callable or python ty into the most appropriate param829 ty.830 """831 if isinstance(ty, ParamType):832 return ty833 guessed_type = False834 if ty is None and default is not None:835 ty = type(default)836 guessed_type = True837 if ty is text_type or ty is str or ty is None:838 return STRING839 if ty is int:840 return INT841 # Booleans are only okay if not guessed. This is done because for842 # flags the default value is actually a bit of a lie in that it843 # indicates which of the flags is the one we want. See get_default()844 # for more information.845 if ty is bool and not guessed_type:846 return BOOL847 if ty is float:848 return FLOAT849 if guessed_type:850 return STRING851 return FuncParamType(ty)852853854class Parameter(object):855 """A parameter to a command comes in two versions: they are either856 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently857 not supported by design as some of the internals for parsing are858 intentionally not finalized.859860 Some settings are supported by both options and arguments.861862 :param param_decls: the parameter declarations for this option or863 argument. This is a list of flags or argument864 names.865 :param type: the type that should be used. Either a :class:`ParamType`866 or a python type. The latter is converted into the former867 automatically if supported.868 :param required: controls if this is optional or not.869 :param default: the default value if omitted. This can also be a callable870 in which case it's invoked when the default is needed871 without any arguments.872 :param help: the help string.873 :param callback: a callback that should be executed after the parameter874 was matched. This is called as ``fn(ctx, value)`` and875 needs to return the value.876 :param nargs: the number of arguments to match. If not ``1`` the return877 value is a tuple instead of single value.878 :param metavar: how the value is represented in the help page.879 :param expose_value: if this is `True` then the value is passed onwards880 to the command callback and stored on the context,881 otherwise it's skipped.882 :param is_eager: eager values are processed before non eager ones. This883 should not be set for arguments or it will inverse the884 order of processing.885 :param envvar: a string or list of strings that are environment variables886 that should be checked.887 """888 param_type_name = 'parameter'889890 def __init__(self, param_decls=None, type=None, required=False,891 default=None, help=None, callback=None, nargs=1,892 metavar=None, expose_value=True, is_eager=False,893 envvar=None):894 self.name, self.opts, self.secondary_opts = \895 self._parse_decls(param_decls or ())896 self.type = convert_type(type, default)897 self.required = required898 self.help = help899 self.callback = callback900 self.nargs = nargs901 self.expose_value = expose_value902 self.default = default903 self.is_eager = is_eager904 self.metavar = metavar905 self.envvar = envvar906907 def make_metavar(self):908 if self.metavar is not None:909 return self.metavar910 metavar = self.name.upper()911 if self.nargs != 1:912 metavar += '...'913 return metavar914915 def get_default(self, ctx):916 """Given a context variable this calculates the default value."""917 # Otherwise go with the regular default.918 if callable(self.default):919 return self.default()920 return self.default921922 def _add_to_parser(self, parser, ctx):923 raise NotImplementedError()924925 def process_value(self, ctx, value):926 """Given a value and context this runs the logic to convert the927 value as necessary.928 """929 if self.type is not None:930 if self.nargs != 1 and value is not None:931 value = tuple(self.type(x, self, ctx) for x in value)932 else:933 value = self.type(value, self, ctx)934 return value935936 def full_process_value(self, ctx, value):937 value = self.process_value(ctx, value)938939 if value is None:940 value = self.get_default(ctx)941942 if value is None and self.required:943 ctx.fail(self.get_missing_message(ctx))944945 return value946947 def get_missing_message(self, ctx):948 return 'Missing %s "%s".' % (949 self.param_type_name,950 ' / '.join(chain(self.opts, self.secondary_opts)),951 )952953 def value_from_envvar(self, ctx):954 if self.envvar is None:955 return956 if isinstance(self.envvar, (tuple, list)):957 for envvar in self.envvar:958 rv = os.environ.get(envvar)959 if rv is not None:960 return rv961 else:962 return os.environ.get(self.envvar)963964 def consume_value(self, ctx, opts, args):965 return None, args966967 def handle_parse_result(self, ctx, opts, args):968 value, args = self.consume_value(ctx, opts, args)969 value = self.full_process_value(ctx, value)970 if self.callback is not None:971 value = self.callback(ctx, value)972 if self.expose_value:973 ctx.params[self.name] = value974 return value, args975976977class Option(Parameter):978 """Options are usually optionaly values on the command line and979 have some extra features that arguments don't have.980981 All other parameters are passed onwards to the parameter constructor.982983 :param show_default: controls if the default value should be shown on the984 help page. The default is auto detection.985 :param prompt: if set to `True` or a non empty string then the user will986 be prompted for input if not set. If set to `True` the987 prompt will be the option name capitalized.988 :param confirmation_prompt: if set then the value will need to be confirmed989 if it was prompted for.990 :param hide_input: if this is `True` then the input on the prompt will be991 hidden from the user. This is useful for password992 input.993 :param is_flag: forces this option to act as a flag. The default is994 auto detection.995 :param flag_value: which value should be used for this flag if it's996 enabled. This is set to a boolean automatically if997 the option string contains a slash to mark two options.998 :param allow_from_autoenv: if this is enabled then the value of this999 parameter will be pulled from an environment1000 variable in case a prefix is defined on the1001 context.1002 """1003 param_type_name = 'option'10041005 def __init__(self, param_decls=None, show_default=None,1006 prompt=False, confirmation_prompt=False,1007 hide_input=False, is_flag=None, flag_value=None,1008 allow_from_autoenv=True, type=None, **attrs):1009 Parameter.__init__(self, param_decls, type=type, **attrs)1010 if prompt is True:1011 prompt = self.name.replace('_', ' ').capitalize()1012 elif prompt is False:1013 prompt = None1014 self.prompt = prompt1015 self.confirmation_prompt = confirmation_prompt1016 self.hide_input = hide_input10171018 if is_flag is None:1019 if flag_value is not None:1020 is_flag = True1021 else:1022 is_flag = bool(self.secondary_opts)10231024 if is_flag and self.default is None:1025 self.default = False1026 if show_default is None:1027 show_default = False10281029 if flag_value is None:1030 flag_value = not self.default10311032 self.show_default = show_default1033 self.is_flag = is_flag1034 self.flag_value = flag_value10351036 if self.is_flag and isinstance(self.flag_value, bool) \1037 and type is None:1038 self.type = BoolParamType()1039 self.is_bool_flag = True1040 else:1041 self.is_bool_flag = False10421043 self.allow_from_autoenv = allow_from_autoenv10441045 # Sanity check for stuff we don't support1046 if __debug__:1047 if self.prompt and self.is_flag and not self.is_bool_flag:1048 raise TypeError('Cannot prompt for flags that are not bools.')1049 if not self.is_bool_flag and self.secondary_opts:1050 raise TypeError('Got secondary option for non boolean flag.')1051 if self.is_bool_flag and self.hide_input \1052 and self.prompt is not None:1053 raise TypeError('Hidden input does not work with boolean '1054 'flag prompts.')10551056 def _parse_decls(self, decls):1057 opts = []1058 secondary_opts = []1059 name = None1060 possible_names = []10611062 for decl in decls:1063 if not decl.startswith('-'):1064 if name is not None:1065 raise TypeError('Name defined twice')1066 name = decl1067 else:1068 if '/' in decl:1069 first, second = decl.split('/', 1)1070 possible_names.append(first.lstrip('-'))1071 opts.append(first)1072 secondary_opts.append(second)1073 else:1074 possible_names.append(decl.lstrip('-'))1075 opts.append(decl)10761077 if name is None and possible_names:1078 possible_names.sort(key=len)1079 name = possible_names[-1]10801081 if name is None:1082 raise TypeError('Could not determine name for option')10831084 return name.replace('-', '_'), opts, secondary_opts10851086 def _add_to_parser(self, parser, ctx):1087 help = self.help1088 extra = []1089 if self.default is not None and self.show_default:1090 extra.append('default: %s' % self.default)1091 if self.required:1092 extra.append('required')1093 if self.nargs != 1:1094 extra.append('%d arguments' % self.nargs)1095 if extra:1096 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))10971098 kwargs = {1099 'help': help,1100 'dest': self.name,1101 'nargs': self.nargs,1102 'metavar': self.make_metavar(),1103 }11041105 if self.is_flag:1106 kwargs.pop('nargs', None)1107 if self.is_bool_flag and self.secondary_opts:1108 pos_opt = optparse.Option(*self.opts, action='store_true',1109 **kwargs)1110 kwargs.pop('default', None)1111 kwargs.pop('help', None)1112 neg_opt = optparse.Option(*self.secondary_opts,1113 action='store_false',1114 help=optparse.SUPPRESS_HELP,1115 **kwargs)1116 pos_opt._negative_version = neg_opt1117 parser.add_option(pos_opt)1118 parser.add_option(neg_opt)1119 else:1120 parser.add_option(*self.opts, action='store_const',1121 const=self.flag_value,1122 **kwargs)1123 else:1124 parser.add_option(*self.opts, **kwargs)11251126 def get_default(self, ctx):1127 # If we're a non boolean flag out default is more complex because1128 # we need to look at all flags in the same group to figure out1129 # if we're the the default one in which case we return the flag1130 # value as default.1131 if self.is_flag and not self.is_bool_flag:1132 for param in ctx.command.params:1133 if param.name == self.name and param.default:1134 return param.flag_value1135 return None1136 return Parameter.get_default(self, ctx)11371138 def prompt_for_value(self, ctx):1139 """This is an alternative flow that can be activated in the full1140 value processing if a value does not exist. It will prompt the1141 user until a valid value exists and then returns the processed1142 value as result.1143 """1144 # Calculate the default before prompting anything to be stable.1145 default = self.get_default(ctx)11461147 # If this is a prompt for a flag we need to handle this1148 # differently.1149 if self.is_bool_flag:1150 return confirm(self.prompt, default)11511152 return prompt(self.prompt, default=default,1153 hide_input=self.hide_input,1154 confirmation_prompt=self.confirmation_prompt,1155 value_proc=lambda x: self.process_value(ctx, x))11561157 def value_from_envvar(self, ctx):1158 rv = Parameter.value_from_envvar(self, ctx)1159 if rv is not None:1160 return rv1161 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1162 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1163 return os.environ.get(envvar)11641165 def full_process_value(self, ctx, value):1166 if value is None and self.prompt is not None:1167 return self.prompt_for_value(ctx)1168 return Parameter.full_process_value(self, ctx, value)11691170 def consume_value(self, ctx, opts, args):1171 value = opts.get(self.name)1172 if value is None:1173 value = self.value_from_envvar(ctx)1174 return value, args117511761177class Argument(Parameter):1178 param_type_name = 'argument'11791180 def __init__(self, param_decls, required=True, **attrs):1181 Parameter.__init__(self, param_decls, required=required, **attrs)11821183 def make_metavar(self):1184 if self.metavar is not None:1185 return self.metavar1186 var = self.name.upper()1187 if not self.required:1188 var = '[%s]' % var1189 if self.nargs != 1:1190 var += '...'1191 return var11921193 def _parse_decls(self, decls):1194 if not decls:1195 raise TypeError('Could not determine name for argument')1196 if len(decls) == 1:1197 name = arg = decls[0]1198 elif len(decls) == 2:1199 name, arg = decls1200 else:1201 raise TypeError('Arguments take exactly one or two '1202 'parameter declarations, got %d' % len(decls))1203 return name.replace('-', '_'), [arg], []12041205 def _add_to_parser(self, parser, ctx):1206 parser.usage += ' ' + self.make_metavar()12071208 def consume_value(self, ctx, opts, args):1209 found = True1210 if self.nargs == 1:1211 try:1212 value = args.pop(0)1213 except IndexError:1214 found = False1215 elif self.nargs < 0:1216 value = tuple(args)1217 found = not value1218 args = []1219 else:1220 values = args[:self.nargs]1221 values += [None] * (self.nargs - len(values))1222 args = args[self.nargs:]1223 value = tuple(values)1224 found = not value1225 if not found:1226 value = self.value_from_envvar(ctx)1227 if self.nargs != 1:1228 value = (value,)1229 return value, args123012311232def _make_command(f, name, attrs, cls):1233 if isinstance(f, Command):1234 raise TypeError('Attempted to convert a callback into a '1235 'command twice.')1236 try:1237 params = f.__click_params__1238 params.reverse()1239 del f.__click_params__1240 except AttributeError:1241 params = []1242 help = inspect.getdoc(f)1243 if isinstance(help, bytes):1244 help = help.decode('utf-8')1245 attrs.setdefault('help', help)1246 return cls(name=name or f.__name__.lower(),1247 callback=f, params=params, **attrs)124812491250def command(name=None, **attrs):1251 """Creates a new :class:`Command` and uses the decorated function as1252 callback. This will also automatically attach all decorated1253 :func:`option`\s and :func:`argument`\s as paramters to the command.12541255 The name of the command defaults to the name of the function. If you1256 want to change that, you can pass the intended name as the first1257 argument.12581259 All keyword arguments are forwarded to the underlying command class.12601261 Once decorated the function turns into a :class:`Command` instance1262 that can be invoked as a command line utility or be attached to a1263 command :class:`Group`.1264 """1265 def decorator(f):1266 return _make_command(f, name, attrs, Command)1267 return decorator126812691270def group(name=None, **attrs):1271 """Creates a new :class:`Group` with a function as callback. This1272 works otherwise the same as :func:`command` just that the generated1273 class is different.1274 """1275 def decorator(f):1276 return _make_command(f, name, attrs, Group)1277 return decorator127812791280def _param_memo(f, param):1281 if isinstance(f, Command):1282 f.params.append(param)1283 else:1284 if not hasattr(f, '__click_params__'):1285 f.__click_params__ = []1286 f.__click_params__.append(param)128712881289def argument(*param_decls, **attrs):1290 """Attaches an option to the command. All positional arguments are1291 passed as parameter declarations to :class:`Argment`, all keyword1292 arguments are forwarded unchanged. This is equivalent to creating an1293 :class:`Option` instance manually and attaching it to the1294 :attr:`Command.params` list.1295 """1296 def decorator(f):1297 _param_memo(f, Argument(param_decls, **attrs))1298 return f1299 return decorator130013011302def option(*param_decls, **attrs):1303 """Attaches an option to the command. All positional arguments are1304 passed as parameter declarations to :class:`Option`, all keyword1305 arguments are forwarded unchanged. This is equivalent to creating an1306 :class:`Option` instance manually and attaching it to the1307 :attr:`Command.params` list.1308 """1309 def decorator(f):1310 _param_memo(f, Option(param_decls, **attrs))1311 return f1312 return decorator131313141315def confirmation_option(*param_decls, **attrs):1316 """Shortcut for confirmation prompts that can be ignored by bypassed1317 ``--yes`` as parameter.13181319 This is equivalent to decorating a function with :func:`option` with1320 the following parameters::13211322 def callback(ctx, value):1323 if not value:1324 ctx.abort()13251326 @click.command()1327 @click.option('--yes', is_flag=True, callback=callback,1328 expose_value=False, prompt='Do you want to continue?')1329 def dropdb():1330 pass1331 """1332 def decorator(f):1333 def callback(ctx, value):1334 if not value:1335 ctx.abort()1336 attrs.setdefault('is_flag', True)1337 attrs.setdefault('callback', callback)1338 attrs.setdefault('expose_value', False)1339 attrs.setdefault('prompt', 'Do you want to continue?')1340 return option(*(param_decls or ('--yes',)), **attrs)(f)1341 return decorator134213431344def password_option(*param_decls, **attrs):1345 """Shortcut for password prompts.13461347 This is equivalent to decorating a function with :func:`option` with1348 the following parameters::13491350 @click.command()1351 @click.option('--password', prompt=True, confirmation_prompt=True,1352 hide_input=True)1353 def changeadmin(password):1354 pass1355 """1356 def decorator(f):1357 attrs.setdefault('prompt', True)1358 attrs.setdefault('confirmation_prompt', True)1359 attrs.setdefault('hide_input', True)1360 return option(*(param_decls or ('--password',)), **attrs)(f)1361 return decorator136213631364def version_option(version, *param_decls, **attrs):1365 """Adds a ``--version`` option which immediately ends the program1366 printing out the version number. This is implemented as an eager1367 option that prints the version and exits the program in the callback.13681369 :param version: the version number to show1370 :param prog_name: the name of the program (defaults to autodetection)1371 :param message: custom message to show instead of the default1372 (``'%(prog)s, version %(version)s'``)1373 :param others: everything else is forwarded to :func:`option`.1374 """1375 def decorator(f):1376 prog_name = attrs.pop('prog_name', None)1377 message = attrs.pop('message', '%(prog)s, version %(version)s')13781379 def callback(ctx, value):1380 if not value:1381 return1382 prog = prog_name1383 if prog is None:1384 prog = ctx.find_root().info_name1385 echo(message % {1386 'prog': prog,1387 'version': version,1388 })1389 ctx.exit()13901391 attrs.setdefault('is_flag', True)1392 attrs.setdefault('expose_value', False)1393 attrs.setdefault('is_eager', True)1394 attrs.setdefault('help', 'Show the version and exit.')1395 attrs['callback'] = callback1396 return option(*(param_decls or ('--version',)), **attrs)(f)1397 return decorator139813991400def help_option(*param_decls, **attrs):1401 """Adds a ``--help`` option which immediately ends the program1402 printing out the help page. This is usually unnecessary to add as1403 this is added by default to all commands unless supressed.14041405 Like :func:`version_option` this is implemented as eager option that1406 prints in the callback and exits.14071408 All arguments are forwarded to :func:`option`.1409 """1410 def decorator(f):1411 def callback(ctx, value):1412 if value:1413 echo(ctx.format_help())1414 ctx.exit()1415 attrs.setdefault('is_flag', True)1416 attrs.setdefault('expose_value', False)1417 attrs.setdefault('help', 'Show this message and exit.')1418 attrs.setdefault('is_eager', True)1419 attrs['callback'] = callback1420 return option(*(param_decls or ('--help',)), **attrs)(f)1421 return decorator142214231424def confirm(text, default=False, abort=False):1425 """Prompts for confirmation (yes/no question).14261427 If the user aborts the input by sending a interrupt signal this1428 function will catch it and raise a :exc:`Abort` exception.14291430 :param text: the question to ask.1431 :param default: the default for the prompt.1432 :param abort: if this is set to `True` a negative answer aborts the1433 exception by raising :exc:`Abort`.1434 """1435 prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')1436 while 1:1437 try:1438 value = raw_input(prompt).lower().strip()1439 except (KeyboardInterrupt, EOFError):1440 raise Abort()1441 if value in ('y', 'yes'):1442 rv = True1443 elif value in ('n', 'no'):1444 rv = False1445 elif value == '':1446 rv = default1447 else:1448 echo('Error: invalid input')1449 continue1450 break1451 if abort and not rv:1452 raise Abort()1453 return rv145414551456def prompt(text, default=None, hide_input=False,1457 confirmation_prompt=False, type=None,1458 value_proc=None):1459 """Prompts a user for input. This is a convenience function that can1460 be used to prompt a user for input later.14611462 If the user aborts the input by sending a interrupt signal this1463 function will catch it and raise a :exc:`Abort` exception.14641465 :param text: the text to show for the prompt.1466 :param default: the default value to use if no input happens. If this1467 is not given it will prompt until it's aborted.1468 :param hide_input: if this is set to true then the input value will1469 be hidden.1470 :param confirmation_prompt: asks for confirmation for the value.1471 :param type: the type to use to check the value against.1472 :param value_proc: if this parameter is provided it's a function that1473 is invoked instead of the type conversion to1474 convert a value.1475 """1476 result = None14771478 def prompt_func(text):1479 f = hide_input and getpass.getpass or raw_input1480 try:1481 return f(text)1482 except (KeyboardInterrupt, EOFError):1483 raise Abort()14841485 if value_proc is None:1486 value_proc = convert_type(type, default)14871488 prompt = text1489 if default is not None:1490 prompt = '%s [%s]' % (prompt, default)1491 prompt += ': '14921493 while 1:1494 while 1:1495 value = prompt_func(prompt)1496 if value:1497 break1498 # If a default is set and used, then the confirmation1499 # prompt is always skipped because that's the only thing1500 # that really makes sense.1501 elif default is not None:1502 return default1503 try:1504 result = value_proc(value)1505 except UsageError as e:1506 echo('Error: %s' % e.message)1507 continue1508 if not confirmation_prompt:1509 return result1510 while 1:1511 value2 = prompt_func('Repeat for confirmation: ')1512 if value2:1513 break1514 if value == value2:1515 return result1516 echo('Error: the two entered values do not match')151715181519#: A unicode string parameter type which is the implicit default. This1520#: can also be selected by using ``str`` as type.1521STRING = StringParamType()15221523#: An integer parameter. This can also be selected by using ``int`` as1524#: type.1525INT = IntParamType()15261527#: A floating point value parameter. This can also be selected by using1528#: ``float`` as type.1529FLOAT = FloatParamType()15301531#: A boolean parameter. This is the default for boolean flags. This can1532#: also be selected by using ``bool`` as a type.1533BOOL = BoolParamType()