Skip to content
Myr

Split up click into a package

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 2b0e31c · Browse files · 14 files+1803 added−1708 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+1803 added−1708 removed

  • other:+1803 added−1708 removed

14 files+1803 added−1708 removed

added:click/__init__.py+54 added
1# -*- coding: utf-8 -*-2"""3 click4 ~~~~~56 click is a simple Python module that wraps the stdlib's optparse to make7 writing command line scripts fun. Unlike other modules it's based around8 a simple API that does not come with too much magic and is composable.910 In case optparse ever goes away from the stdlib it will be shipped by11 this module.1213 :copyright: (c) 2014 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""1617# Core classes18from .core import Context, Command, MultiCommand, Group, Parameter, \19 Option, Argument2021# Decorators22from .decorators import pass_context, pass_obj, make_pass_decorator, \23 command, group, argument, option, confirmation_option, \24 password_option, version_option, help_option2526# Types27from .types import ParamType, File, Choice, STRING, INT, FLOAT, BOOL2829# Helper functions30from .helpers import prompt, confirm, get_terminal_size3132# Exceptions33from .exceptions import UsageError, Abort343536__all__ = [37 # Core classes38 'Context', 'Command', 'MultiCommand', 'Group', 'Parameter',39 'Option', 'Argument',4041 # Decorators42 'pass_context', 'pass_obj', 'make_pass_decorator', 'command', 'group',43 'argument', 'option', 'confirmation_option', 'password_option',44 'version_option', 'help_option',4546 # Types47 'ParamType', 'File', 'Choice', 'STRING', 'INT', 'FLOAT', 'BOOL',4849 # Helper functions50 'prompt', 'confirm', 'get_terminal_size',5152 # Exceptions53 'UsageError', 'Abort',54]
added:click/_compat.py+72 added
1import sys2import codecs345def _wrap_stream_for_codec(f, encoding=None, errors='strict'):6 if encoding is None:7 encoding = 'utf-8'8 info = codecs.lookup(encoding)9 f = codecs.StreamReaderWriter(f, info.streamreader,10 info.streamwriter,11 errors)12 f.encoding = encoding13 return f141516PY2 = sys.version_info[0] == 217if PY2:18 text_type = unicode19 bytes = str20 raw_input = raw_input2122 def open_stream(filename, mode='r', encoding=None, errors='strict'):23 if filename != '-':24 if encoding is not None:25 return codecs.open(filename, mode, encoding, errors), True26 return open(filename, mode), True27 if 'w' in mode:28 f = sys.stdout29 if encoding is not None:30 f = _wrap_stream_for_codec(f, encoding, errors)31 else:32 f = sys.stdin33 if 'b' not in mode:34 if encoding is None:35 encoding = sys.stdin.encoding36 f = _wrap_stream_for_codec(f, encoding, errors)37 return f, False38else:39 import io40 text_type = str41 raw_input = input4243 def _make_binary_stream(f, stream_name):44 buf = getattr(f, 'buffer', None)45 if buf is not None and isinstance(buf, io.BufferedReader):46 return buf47 raise TypeError('%s is a stream that does not give access to its '48 'underlying binary stream. Please do not set '49 'sys.stdout directly to a StringIO object or '50 'something similar.' % stream_name)5152 def open_stream(filename, mode='r', encoding=None, errors='strict'):53 if filename != '-':54 if encoding is not None:55 return open(filename, mode, encoding=encoding,56 errors=errors), True57 return open(filename, mode), True5859 if 'w' in mode:60 f = sys.stdout61 if encoding is not None or 'b' in mode:62 f = _make_binary_stream(f, 'stdout')63 if encoding is not None:64 f = _wrap_stream_for_codec(f, encoding, errors)65 else:66 f = sys.stdin67 if 'b' in mode:68 f = _make_binary_stream(f, 'stdin')69 if encoding is not None:70 f = _wrap_stream_for_codec(f, encoding, errors)7172 return f, False
added:click/_optparse.py+71 added
1import optparse23from .helpers import get_terminal_size4from .formatting import TextWrapper5from .exceptions import UsageError678class _SimplifiedFormatter(optparse.IndentedHelpFormatter):910 def __init__(self):11 optparse.IndentedHelpFormatter.__init__(self,12 width=min(get_terminal_size()[0], 80) - 2)13 self.default_tag = ''1415 def format_usage(self, usage):16 prefix = 'Usage: '17 indent = len(prefix)18 text_width = self.width - indent19 return '%s%s\n' % (prefix, TextWrapper(20 text_width, initial_indent='',21 subsequent_indent=' ' * indent,22 replace_whitespace=False).fill(usage))2324 def _format_text(self, text):25 text_width = self.width - self.current_indent26 indent = ' ' * self.current_indent2728 return TextWrapper(text_width,29 initial_indent=indent,30 subsequent_indent=indent,31 replace_whitespace=False).fill_paragraphs(text)3233 def format_description(self, description):34 if not description:35 return ''36 self.indent()37 rv = self._format_text(description) + '\n'38 self.dedent()39 return rv4041 def format_option_strings(self, option):42 rv = optparse.IndentedHelpFormatter.format_option_strings(self, option)43 if hasattr(option, '_negative_version'):44 rv += ' / ' + optparse.IndentedHelpFormatter.format_option_strings(45 self, option._negative_version)46 return rv474849class _SimplifiedOptionParser(optparse.OptionParser):5051 def __init__(self, ctx, **extra):52 usage = ctx.command_path + ' ' + ctx.command.options_metavar53 optparse.OptionParser.__init__(self, prog=ctx.command_path,54 usage=usage,55 add_help_option=False,56 formatter=_SimplifiedFormatter(),57 **extra)58 self.__ctx = ctx5960 def expand_prog_name(self, s):61 return s6263 def format_option_help(self, formatter):64 rv = optparse.OptionParser.format_option_help(self, formatter)65 extra_help = self.__ctx.command._format_extra_help(self.__ctx)66 if extra_help:67 rv = '%s\n\n%s' % (extra_help, rv)68 return rv6970 def error(self, msg):71 raise UsageError(msg, self.__ctx)
added:click/core.py+850 added
1import os2import sys3import optparse4from itertools import chain56from .types import convert_type, BOOL7from .utils import echo8from .exceptions import UsageError, Abort9from .helpers import prompt, confirm10from ._optparse import _SimplifiedOptionParser111213class Context(object):14 """The context is a special internal object that holds state relevant15 for the script execution at every single level. It's normally invisible16 to commands unless they opt-in to getting access to it.1718 The context is useful as it can pass internal objects around and can19 control special execution features such as reading data from20 environment variables.2122 A context can be used as context manager in which case it will call23 :meth:`close` on teardown.2425 :param command: the command class for this context.26 :param parent: the parent context.27 :param info_name: the info name for this invokation. Generally this28 is the most descriptive name for the script or29 command. For the toplevel script is is usually30 the name of the script, for commands below it it's31 the name of the script.32 :param obj: an arbitrary object of user data.33 :param auto_envvar_prefix: the prefix to use for automatic environment34 variables. If this is `None` then reading35 from environment variables is disabled. This36 does not affect manually set environment37 variables which are always read.38 """3940 def __init__(self, command, parent=None, info_name=None, obj=None,41 auto_envvar_prefix=None):42 #: the parent context or `None` if none exists.43 self.parent = parent44 #: the :class:`Command` for this context.45 self.command = command46 #: the descriptive information name47 self.info_name = info_name48 #: the parsed parameters except if the value is hidden in which49 #: case it's not remembered.50 self.params = {}51 #: the leftover arguments.52 self.args = []53 #: this flag indicates if a subcommand is going to be executed.54 #: a group callback can use this information to figure out if it's55 #: being executed directly or because the execution flow passes56 #: onwards to a subcommand. By default it's `None` but it can be57 #: the name of the subcommand to execute.58 self.invoked_subcommand = None59 if obj is None and parent is not None:60 obj = parent.obj61 #: the user object stored.62 self.obj = obj6364 # If there is no envvar prefix yet, but the parent has one and65 # the command on this level has a name, we can expand the envvar66 # prefix automatically.67 if auto_envvar_prefix is None:68 if parent is not None \69 and parent.auto_envvar_prefix is not None and \70 self.info_name is not None:71 auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,72 self.info_name.upper())73 else:74 self.auto_envvar_prefix = auto_envvar_prefix.upper()75 self.auto_envvar_prefix = auto_envvar_prefix7677 self._parser = command._make_parser(self)78 self._close_callbacks = []7980 def __enter__(self):81 return self8283 def __exit__(self, exc_type, exc_value, tb):84 self.close()8586 def call_on_close(self, f):87 """This decorator remembers a function as callback that should be88 executed when the context tears down. This is most useful to bind89 resource handling to the script execution. For instance file objects90 opened by the :class:`File` type will register their close callbacks91 here.9293 :param f: the function to execute on teardown.94 """95 self._close_callbacks.append(f)96 return f9798 def close(self):99 """Invokes all close callbacks."""100 for cb in self._close_callbacks:101 cb()102 self._close_callbacks = []103104 @property105 def command_path(self):106 """The computed command path. This is used for the ``usage``107 information on the help page. It's automatically created by108 combining the info names of the chain of contexts to the root.109 """110 rv = ''111 if self.info_name is not None:112 rv = self.info_name113 if self.parent is not None:114 rv = self.parent.command_path + ' ' + rv115 return rv.lstrip()116117 def find_root(self):118 """Finds the outermost context."""119 node = self120 while node.parent is not None:121 node = node.parent122 return node123124 def find_object(self, object_type):125 """Finds the closest object of a given type."""126 node = self127 while node.parent is not None:128 if isinstance(node.obj, object_type):129 return node.obj130 node = node.parent131132 def fail(self, message):133 """Aborts the execution of the program with a specific error134 message.135136 :param message: the error message to fail with.137 """138 raise UsageError(message, self)139140 def abort(self):141 """Aborts the script."""142 raise Abort()143144 def exit(self, code=0):145 """Exits the application with a given exit code."""146 sys.exit(code)147148 def format_usage(self):149 """Helper method to get formatted usage string for the current150 context and command.151 """152 return self._parser.get_usage()153154 def format_help(self):155 """Helper method to get formatted help page for the current156 context and command.157 """158 return self._parser.format_help().rstrip()159160 def invoke(*args, **kwargs):161 """Invokes a command callback in exactly the way it expects.162 """163 self, callback = args[:2]164 args = args[2:]165 if getattr(callback, '__click_pass_context__', False):166 args = (self,) + args167 return callback(*args, **kwargs)168169170class Command(object):171 """Commands are the basic building block of command line interfaces in172 click. A basic command handles command line parsing and might dispatch173 more parsing to commands nested blow it.174175 :param name: the name of the command to use unless a group overrides it.176 :param callback: the callback to invoke. This is optional.177 :param params: the parameters to register with this command. This can178 be either :class:`Option` or :class:`Argument` objects.179 :param help: the help string to use for this command.180 :param epilog: like the help string but it's printed at the end of the181 help page after everything else.182 :param short_help: the short help to use for this command. This is183 shown on the command listing of the parent command.184 :param add_help_option: by default each command registers a ``--help``185 option. This can be disabled by this parameter.186 """187 allow_extra_args = False188189 def __init__(self, name, callback=None, params=None, help=None,190 epilog=None, short_help=None,191 options_metavar='[OPTIONS]', add_help_option=True):192 #: the name the command things it has. Upon registering a command193 #: on a :class:`Group` the group will default the command name194 #: with this information. You should instead use the195 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.196 self.name = name197 #: the callback to execute when the command fires. This might be198 #: `None` in which case nothing happens.199 self.callback = callback200 #: the list of parameters for this command in the order they201 #: should show up in the help page and execute. Eager parameters202 #: will automatically be handled before non eager ones.203 self.params = params or []204 self.help = help205 self.epilog = epilog206 self.options_metavar = options_metavar207 if short_help is None and help:208 short_help = help.split('.')[0].strip()209 if len(short_help) > 45:210 short_help = None211 elif short_help:212 short_help = short_help[0].lower() + short_help[1:] + '.'213 self.short_help = short_help214 if add_help_option:215 help_option()(self)216217 def iter_params_for_processing(self):218 """This returns an iterator over all attached parameters in the219 order of processing. This iterator returns all eager parameters220 first, followed by all non-eager parameters.221 """222 for param in self.params:223 if param.is_eager:224 yield param225 for param in self.params:226 if not param.is_eager:227 yield param228229 def _make_parser(self, ctx):230 parser = _SimplifiedOptionParser(231 ctx, description=self.help, epilog=self.epilog)232 for param in self.params:233 param._add_to_parser(parser, ctx)234 return parser235236 def _format_extra_help(self, ctx):237 pass238239 def make_context(self, info_name, args, parent=None, **extra):240 """This function when given an info name and arguments will kick241 off the parsing and create a new :class:`Context`. It does not242 invoke the actual command callback though.243244 :param info_name: the info name for this invokation. Generally this245 is the most descriptive name for the script or246 command. For the toplevel script is is usually247 the name of the script, for commands below it it's248 the name of the script.249 :param args: the arguments to parse as list of strings.250 :param parent: the parent context if available.251 :param extra: extra keyword arguments forwarded to the context252 constructor.253 """254 ctx = Context(self, info_name=info_name, parent=parent, **extra)255 opts, args = ctx._parser.parse_args(args=args)256 opts = opts.__dict__257258 for param in ctx.command.iter_params_for_processing():259 value, args = param.handle_parse_result(ctx, opts, args)260261 if args and not self.allow_extra_args:262 ctx.fail('Got unexpected extra argument%s (%s)'263 % (len(args) != 1 and 's' or '', ' '.join(args)))264265 ctx.args = args266267 return ctx268269 def invoke(self, ctx):270 """Given a context, this invokes the attached callback (if it exists)271 in the right way.272 """273 if self.callback is not None:274 ctx.invoke(self.callback, **ctx.params)275276 def main(self, args=None, prog_name=None, **extra):277 """This is the way to invoke a script with all the bells and278 whistles as command line application. This will always terminate279 the application after calling. If this is not wanted, ``SystemExit``280 needs to be caught.281282 This method is also available by directly calling the instance of283 a :class:`Command`.284285 :param args: the arguments that should be used for parsing. If not286 provided, ``sys.argv[1:]`` is used.287 :param prog_name: the program name that should be used. By default288 the progam name is constructed by taking the file289 name from ``sys.argv[0]``.290 :param extra: extra keyword arguments are forwarded to the context291 constructor.292 """293 if args is None:294 args = sys.argv[1:]295 else:296 args = list(args)297 if prog_name is None:298 prog_name = os.path.basename(sys.argv and sys.argv[0] or __file__)299 try:300 try:301 with self.make_context(prog_name, args, **extra) as ctx:302 self.invoke(ctx)303 ctx.exit()304 except (EOFError, KeyboardInterrupt):305 echo(file=sys.stderr)306 raise Abort()307 except UsageError as e:308 if e.ctx is not None:309 echo(e.ctx.format_usage(), file=sys.stderr)310 echo('Error: %s' % e.message, file=sys.stderr)311 sys.exit(2)312 except Abort:313 echo('Aborted!', file=sys.stderr)314 sys.exit(1)315316 def __call__(self, *args, **kwargs):317 """Alias for :meth:`main`."""318 return self.main(*args, **kwargs)319320321class MultiCommand(Command):322 """A multi command is the basic implementation of a command that323 dispatches to subcommands. The most common version is the324 :class:`Command`.325326 :param invoke_without_command: this controls how the multi command itself327 is invoked. By default it's only invoked328 if a subcommand is provided.329 :param no_args_is_help: this controls what happens if no arguments are330 provided. This option is enabled by default if331 `invoke_without_command` is disabled or disabled332 if it's enabled. If enabled this will add333 ``--help`` as argument if no arguments are334 passed.335 :param subcommand_metavar: the string that is used in the documentation336 to indicate the subcommand place.337 """338 allow_extra_args = True339340 def __init__(self, name=None, invoke_without_command=False,341 no_args_is_help=None, subcommand_metavar='COMMAND [ARGS]...',342 **attrs):343 Command.__init__(self, name, **attrs)344 if no_args_is_help is None:345 no_args_is_help = not invoke_without_command346 self.no_args_is_help = no_args_is_help347 self.invoke_without_command = invoke_without_command348 self.subcommand_metavar = subcommand_metavar349350 def _make_parser(self, ctx):351 parser = Command._make_parser(self, ctx)352 parser.usage += ' ' + self.subcommand_metavar353 parser.disable_interspersed_args()354 return parser355356 def _format_extra_help(self, ctx):357 commands = self.list_commands()358 if not commands:359 return360361 longest = len(sorted(commands, key=len)[-1])362363 subcommand_info = []364 for subcommand in self.list_commands():365 cmd = self.get_command(ctx, subcommand)366 help = cmd.short_help or ''367 subcommand_info.append(' %-*s %s' % (longest, subcommand, help))368369 return 'Commands:\n%s' % '\n'.join(subcommand_info)370371 def make_context(self, info_name, args, parent=None, **extra):372 # Multi-commands invoked without any arguments is a shortcut to373 # invoking it with --help unless supresssed.374 if not args and self.no_args_is_help:375 args = ['--help']376 return Command.make_context(self, info_name, args, parent, **extra)377378 def invoke(self, ctx):379 if not ctx.args:380 if self.invoke_without_command:381 return Command.invoke(self, ctx)382 ctx.fail('Missing command')383 cmd_name = ctx.args[0]384385 cmd = self.get_command(ctx, cmd_name)386 if cmd is None:387 ctx.fail('No such command "%s"' % cmd_name)388389 # Whenever we dispatch to a subcommand we also invoke the regular390 # callback. This is done so that parameters can be handled.391 ctx.invoked_subcommand = cmd_name392 Command.invoke(self, ctx)393394 with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:395 return cmd.invoke(cmd_ctx)396397 def get_command(self, ctx, cmd_name):398 """Given a context and a command name, this returns a399 :class:`Command` object if it exists or returns `None`.400 """401 raise NotImplementedError()402403 def list_commands(self):404 """Returns a list of subcommand names in the order they should405 appear.406 """407 return []408409410class Group(MultiCommand):411 """A group allows a command to have subcommands attached. This is the412 most common way to implement nesting in click.413414 :param commands: a dictionary of commands.415 """416417 def __init__(self, name=None, commands=None, **attrs):418 MultiCommand.__init__(self, name, **attrs)419 #: the registered subcommands by their exported names.420 self.commands = commands or {}421422 def add_command(self, cmd, name=None):423 """Registers another :class:`Command` with this group. If the name424 is not provided, the name of the command is used.425 """426 name = name or cmd.name427 if name is None:428 raise TypeError('Command has no name.')429 self.commands[name] = cmd430431 def command(self, *args, **kwargs):432 """A shortcut decorator for declaring and attaching a command to433 the group. This takes the same arguments as :func:`command` but434 immediately registers the created command with this instance by435 calling into :meth:`add_command`.436 """437 def decorator(f):438 cmd = command(*args, **kwargs)(f)439 self.add_command(cmd)440 return cmd441 return decorator442443 def get_command(self, ctx, cmd_name):444 return self.commands.get(cmd_name)445446 def list_commands(self):447 return sorted(self.commands)448449450class Parameter(object):451 """A parameter to a command comes in two versions: they are either452 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently453 not supported by design as some of the internals for parsing are454 intentionally not finalized.455456 Some settings are supported by both options and arguments.457458 :param param_decls: the parameter declarations for this option or459 argument. This is a list of flags or argument460 names.461 :param type: the type that should be used. Either a :class:`ParamType`462 or a python type. The latter is converted into the former463 automatically if supported.464 :param required: controls if this is optional or not.465 :param default: the default value if omitted. This can also be a callable466 in which case it's invoked when the default is needed467 without any arguments.468 :param help: the help string.469 :param callback: a callback that should be executed after the parameter470 was matched. This is called as ``fn(ctx, value)`` and471 needs to return the value.472 :param nargs: the number of arguments to match. If not ``1`` the return473 value is a tuple instead of single value.474 :param metavar: how the value is represented in the help page.475 :param expose_value: if this is `True` then the value is passed onwards476 to the command callback and stored on the context,477 otherwise it's skipped.478 :param is_eager: eager values are processed before non eager ones. This479 should not be set for arguments or it will inverse the480 order of processing.481 :param envvar: a string or list of strings that are environment variables482 that should be checked.483 """484 param_type_name = 'parameter'485486 def __init__(self, param_decls=None, type=None, required=False,487 default=None, help=None, callback=None, nargs=1,488 metavar=None, expose_value=True, is_eager=False,489 envvar=None):490 self.name, self.opts, self.secondary_opts = \491 self._parse_decls(param_decls or ())492 self.type = convert_type(type, default)493 self.required = required494 self.help = help495 self.callback = callback496 self.nargs = nargs497 self.multiple = False498 self.expose_value = expose_value499 self.default = default500 self.is_eager = is_eager501 self.metavar = metavar502 self.envvar = envvar503504 def make_metavar(self):505 if self.metavar is not None:506 return self.metavar507 metavar = self.type.get_metavar(self)508 if metavar is not None:509 return metavar510 metavar = self.name.upper()511 if self.nargs != 1:512 metavar += '...'513 return metavar514515 def get_default(self, ctx):516 """Given a context variable this calculates the default value."""517 # Otherwise go with the regular default.518 if callable(self.default):519 rv = self.default()520 else:521 rv = self.default522 return self.type(rv, self, ctx)523524 def _add_to_parser(self, parser, ctx):525 raise NotImplementedError()526527 def process_value(self, ctx, value):528 """Given a value and context this runs the logic to convert the529 value as necessary.530 """531 def _convert(value, level):532 if level == 0:533 return self.type(value, self, ctx)534 return tuple(_convert(x, level - 1) for x in value or ())535 return _convert(value, (self.nargs != 1) + bool(self.multiple))536537 def full_process_value(self, ctx, value):538 value = self.process_value(ctx, value)539540 if value is None:541 value = self.get_default(ctx)542543 if value is None and self.required:544 ctx.fail(self.get_missing_message(ctx))545546 return value547548 def get_missing_message(self, ctx):549 return 'Missing %s "%s".' % (550 self.param_type_name,551 ' / '.join(chain(self.opts, self.secondary_opts)),552 )553554 def value_from_envvar(self, ctx):555 if self.envvar is None:556 return557 if isinstance(self.envvar, (tuple, list)):558 for envvar in self.envvar:559 rv = os.environ.get(envvar)560 if rv is not None:561 return rv562 else:563 return os.environ.get(self.envvar)564565 def consume_value(self, ctx, opts, args):566 return None, args567568 def handle_parse_result(self, ctx, opts, args):569 value, args = self.consume_value(ctx, opts, args)570 value = self.full_process_value(ctx, value)571 if self.callback is not None:572 value = self.callback(ctx, value)573 if self.expose_value:574 ctx.params[self.name] = value575 return value, args576577578class Option(Parameter):579 """Options are usually optionaly values on the command line and580 have some extra features that arguments don't have.581582 All other parameters are passed onwards to the parameter constructor.583584 :param show_default: controls if the default value should be shown on the585 help page. The default is auto detection.586 :param prompt: if set to `True` or a non empty string then the user will587 be prompted for input if not set. If set to `True` the588 prompt will be the option name capitalized.589 :param confirmation_prompt: if set then the value will need to be confirmed590 if it was prompted for.591 :param hide_input: if this is `True` then the input on the prompt will be592 hidden from the user. This is useful for password593 input.594 :param is_flag: forces this option to act as a flag. The default is595 auto detection.596 :param flag_value: which value should be used for this flag if it's597 enabled. This is set to a boolean automatically if598 the option string contains a slash to mark two options.599 :param multiple: if this is set to True then the argument is accepted600 multiple times and recorded. This is similar to nargs601 in how it works but supports arbitrary number of602 arguments.603 :param allow_from_autoenv: if this is enabled then the value of this604 parameter will be pulled from an environment605 variable in case a prefix is defined on the606 context.607 """608 param_type_name = 'option'609610 def __init__(self, param_decls=None, show_default=None,611 prompt=False, confirmation_prompt=False,612 hide_input=False, is_flag=None, flag_value=None,613 multiple=False, allow_from_autoenv=True, type=None,614 **attrs):615 Parameter.__init__(self, param_decls, type=type, **attrs)616 if prompt is True:617 prompt_text = self.name.replace('_', ' ').capitalize()618 elif prompt is False:619 prompt_text = None620 else:621 prompt_text = prompt622 self.prompt = prompt_text623 self.confirmation_prompt = confirmation_prompt624 self.hide_input = hide_input625626 if is_flag is None:627 if flag_value is not None:628 is_flag = True629 else:630 is_flag = bool(self.secondary_opts)631632 if is_flag and self.default is None:633 self.default = False634 if show_default is None:635 show_default = False636637 if flag_value is None:638 flag_value = not self.default639640 self.show_default = show_default641 self.is_flag = is_flag642 self.flag_value = flag_value643 self.multiple = multiple644645 if self.is_flag and isinstance(self.flag_value, bool) \646 and type is None:647 self.type = BOOL648 self.is_bool_flag = True649 else:650 self.is_bool_flag = False651652 self.allow_from_autoenv = allow_from_autoenv653654 # Sanity check for stuff we don't support655 if __debug__:656 if self.prompt and self.is_flag and not self.is_bool_flag:657 raise TypeError('Cannot prompt for flags that are not bools.')658 if not self.is_bool_flag and self.secondary_opts:659 raise TypeError('Got secondary option for non boolean flag.')660 if self.is_bool_flag and self.hide_input \661 and self.prompt is not None:662 raise TypeError('Hidden input does not work with boolean '663 'flag prompts.')664665 def _parse_decls(self, decls):666 opts = []667 secondary_opts = []668 name = None669 possible_names = []670671 for decl in decls:672 if not decl.startswith('-'):673 if name is not None:674 raise TypeError('Name defined twice')675 name = decl676 else:677 if '/' in decl:678 first, second = decl.split('/', 1)679 possible_names.append(first.lstrip('-'))680 opts.append(first)681 secondary_opts.append(second)682 else:683 possible_names.append(decl.lstrip('-'))684 opts.append(decl)685686 if name is None and possible_names:687 possible_names.sort(key=len)688 name = possible_names[-1]689690 if name is None:691 raise TypeError('Could not determine name for option')692693 return name.replace('-', '_'), opts, secondary_opts694695 def _add_to_parser(self, parser, ctx):696 help = self.help697 extra = []698 if self.default is not None and self.show_default:699 extra.append('default: %s' % self.default)700 if self.required:701 extra.append('required')702 if self.nargs != 1:703 extra.append('%d arguments' % self.nargs)704 if extra:705 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))706707 kwargs = {708 'help': help,709 'dest': self.name,710 'nargs': self.nargs,711 'metavar': self.make_metavar(),712 }713714 action = self.multiple and 'append' or 'store'715716 if self.is_flag:717 kwargs.pop('nargs', None)718 if self.is_bool_flag and self.secondary_opts:719 pos_opt = optparse.Option(*self.opts, action=action + '_true',720 **kwargs)721 kwargs.pop('default', None)722 kwargs.pop('help', None)723 neg_opt = optparse.Option(*self.secondary_opts,724 action=action + '_false',725 help=optparse.SUPPRESS_HELP,726 **kwargs)727 pos_opt._negative_version = neg_opt728 parser.add_option(pos_opt)729 parser.add_option(neg_opt)730 else:731 parser.add_option(*self.opts, action=action + '_const',732 const=self.flag_value,733 **kwargs)734 else:735 kwargs['action'] = action736 parser.add_option(*self.opts, **kwargs)737738 def get_default(self, ctx):739 # If we're a non boolean flag out default is more complex because740 # we need to look at all flags in the same group to figure out741 # if we're the the default one in which case we return the flag742 # value as default.743 if self.is_flag and not self.is_bool_flag:744 for param in ctx.command.params:745 if param.name == self.name and param.default:746 return param.flag_value747 return None748 return Parameter.get_default(self, ctx)749750 def prompt_for_value(self, ctx):751 """This is an alternative flow that can be activated in the full752 value processing if a value does not exist. It will prompt the753 user until a valid value exists and then returns the processed754 value as result.755 """756 # Calculate the default before prompting anything to be stable.757 default = self.get_default(ctx)758759 # If this is a prompt for a flag we need to handle this760 # differently.761 if self.is_bool_flag:762 return confirm(self.prompt, default)763764 return prompt(self.prompt, default=default,765 hide_input=self.hide_input,766 confirmation_prompt=self.confirmation_prompt,767 value_proc=lambda x: self.process_value(ctx, x))768769 def value_from_envvar(self, ctx):770 rv = Parameter.value_from_envvar(self, ctx)771 if rv is not None:772 return rv773 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:774 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())775 return os.environ.get(envvar)776777 def full_process_value(self, ctx, value):778 if value is None and self.prompt is not None:779 return self.prompt_for_value(ctx)780 return Parameter.full_process_value(self, ctx, value)781782 def consume_value(self, ctx, opts, args):783 value = opts.get(self.name)784 if value is None:785 value = self.value_from_envvar(ctx)786 return value, args787788789class Argument(Parameter):790 """Arguments are positional parameters to a command. They generally791 provide fewer features than options but can have infinite ``nargs``792 and are required by default.793794 All parameters are passed onwards to the parameter constructor.795 """796 param_type_name = 'argument'797798 def __init__(self, param_decls, required=True, **attrs):799 Parameter.__init__(self, param_decls, required=required, **attrs)800801 def make_metavar(self):802 if self.metavar is not None:803 return self.metavar804 var = self.name.upper()805 if not self.required:806 var = '[%s]' % var807 if self.nargs != 1:808 var += '...'809 return var810811 def _parse_decls(self, decls):812 if not decls:813 raise TypeError('Could not determine name for argument')814 if len(decls) == 1:815 name = arg = decls[0]816 elif len(decls) == 2:817 name, arg = decls818 else:819 raise TypeError('Arguments take exactly one or two '820 'parameter declarations, got %d' % len(decls))821 return name.replace('-', '_'), [arg], []822823 def _add_to_parser(self, parser, ctx):824 parser.usage += ' ' + self.make_metavar()825826 def consume_value(self, ctx, opts, args):827 found = True828 if self.nargs == 1:829 try:830 value = args.pop(0)831 except IndexError:832 found = False833 elif self.nargs < 0:834 value = tuple(args)835 found = value836 args = []837 else:838 values = args[:self.nargs]839 args = args[self.nargs:]840 value = tuple(values)841 found = value842 if not found:843 value = self.value_from_envvar(ctx)844 if self.nargs != 1:845 value = value and (value,) or ()846 return value, args847848849# Circular dependency between decorators and core850from .decorators import command, help_option
added:click/decorators.py+258 added
1import inspect23from functools import update_wrapper45from .utils import echo678def pass_context(f):9 """Marks a callback that it wants to receive the current context10 object as first argument.11 """12 f.__click_pass_context__ = True13 return f141516def pass_obj(f):17 """Similar to :func:`pass_context` but only pass the object on the18 context onwards (:attr:`Context.obj`). This is useful if that object19 represents the state of a nested system.20 """21 @pass_context22 def new_func(*args, **kwargs):23 ctx = args[0]24 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)25 return update_wrapper(new_func, f)262728def make_pass_decorator(object_type):29 """Given an object type this creates a decorator that will work30 similar to :func:`pass_obj` but instead of passing the object of the31 current context, it will find the innermost context of type32 :func:`object_type`.3334 This generates a decorator that works roughly like this::3536 from functools import update_wrapper3738 def decorator(f):39 @pass_context40 def new_func(ctx, *args, **kwargs):41 obj = ctx.find_object(object_type)42 return ctx.invoke(f, obj, *args, **kwargs)43 return update_wrapper(new_func, f)44 return decorator45 """46 def decorator(f):47 @pass_context48 def new_func(*args, **kwargs):49 ctx = args[0]50 obj = ctx.find_object(object_type)51 if obj is None:52 raise RuntimeError('Managed to invoke callback without a '53 'context object of type %r existing'54 % object_type.__name__)55 return ctx.invoke(f, obj, *args[1:], **kwargs)56 return update_wrapper(new_func, f)57 return decorator585960def _make_command(f, name, attrs, cls):61 if isinstance(f, Command):62 raise TypeError('Attempted to convert a callback into a '63 'command twice.')64 try:65 params = f.__click_params__66 params.reverse()67 del f.__click_params__68 except AttributeError:69 params = []70 help = inspect.getdoc(f)71 if isinstance(help, bytes):72 help = help.decode('utf-8')73 attrs.setdefault('help', help)74 return cls(name=name or f.__name__.lower(),75 callback=f, params=params, **attrs)767778def command(name=None, cls=None, **attrs):79 """Creates a new :class:`Command` and uses the decorated function as80 callback. This will also automatically attach all decorated81 :func:`option`\s and :func:`argument`\s as paramters to the command.8283 The name of the command defaults to the name of the function. If you84 want to change that, you can pass the intended name as the first85 argument.8687 All keyword arguments are forwarded to the underlying command class.8889 Once decorated the function turns into a :class:`Command` instance90 that can be invoked as a command line utility or be attached to a91 command :class:`Group`.9293 :param name: the name of the command. This defaults to the function94 name.95 :param cls: the command class to instanciate. This defaults to96 :class:`Command`.97 """98 if cls is None:99 cls = Command100 def decorator(f):101 return _make_command(f, name, attrs, cls)102 return decorator103104105def group(name=None, **attrs):106 """Creates a new :class:`Group` with a function as callback. This107 works otherwise the same as :func:`command` just that the `cls`108 parameter is set to :class:`Group`.109 """110 return command(name, cls=Group, **attrs)111112113def _param_memo(f, param):114 if isinstance(f, Command):115 f.params.append(param)116 else:117 if not hasattr(f, '__click_params__'):118 f.__click_params__ = []119 f.__click_params__.append(param)120121122def argument(*param_decls, **attrs):123 """Attaches an option to the command. All positional arguments are124 passed as parameter declarations to :class:`Argment`, all keyword125 arguments are forwarded unchanged. This is equivalent to creating an126 :class:`Option` instance manually and attaching it to the127 :attr:`Command.params` list.128 """129 def decorator(f):130 _param_memo(f, Argument(param_decls, **attrs))131 return f132 return decorator133134135def option(*param_decls, **attrs):136 """Attaches an option to the command. All positional arguments are137 passed as parameter declarations to :class:`Option`, all keyword138 arguments are forwarded unchanged. This is equivalent to creating an139 :class:`Option` instance manually and attaching it to the140 :attr:`Command.params` list.141 """142 def decorator(f):143 _param_memo(f, Option(param_decls, **attrs))144 return f145 return decorator146147148def confirmation_option(*param_decls, **attrs):149 """Shortcut for confirmation prompts that can be ignored by bypassed150 ``--yes`` as parameter.151152 This is equivalent to decorating a function with :func:`option` with153 the following parameters::154155 def callback(ctx, value):156 if not value:157 ctx.abort()158159 @click.command()160 @click.option('--yes', is_flag=True, callback=callback,161 expose_value=False, prompt='Do you want to continue?')162 def dropdb():163 pass164 """165 def decorator(f):166 def callback(ctx, value):167 if not value:168 ctx.abort()169 attrs.setdefault('is_flag', True)170 attrs.setdefault('callback', callback)171 attrs.setdefault('expose_value', False)172 attrs.setdefault('prompt', 'Do you want to continue?')173 return option(*(param_decls or ('--yes',)), **attrs)(f)174 return decorator175176177def password_option(*param_decls, **attrs):178 """Shortcut for password prompts.179180 This is equivalent to decorating a function with :func:`option` with181 the following parameters::182183 @click.command()184 @click.option('--password', prompt=True, confirmation_prompt=True,185 hide_input=True)186 def changeadmin(password):187 pass188 """189 def decorator(f):190 attrs.setdefault('prompt', True)191 attrs.setdefault('confirmation_prompt', True)192 attrs.setdefault('hide_input', True)193 return option(*(param_decls or ('--password',)), **attrs)(f)194 return decorator195196197def version_option(version, *param_decls, **attrs):198 """Adds a ``--version`` option which immediately ends the program199 printing out the version number. This is implemented as an eager200 option that prints the version and exits the program in the callback.201202 :param version: the version number to show203 :param prog_name: the name of the program (defaults to autodetection)204 :param message: custom message to show instead of the default205 (``'%(prog)s, version %(version)s'``)206 :param others: everything else is forwarded to :func:`option`.207 """208 def decorator(f):209 prog_name = attrs.pop('prog_name', None)210 message = attrs.pop('message', '%(prog)s, version %(version)s')211212 def callback(ctx, value):213 if not value:214 return215 prog = prog_name216 if prog is None:217 prog = ctx.find_root().info_name218 echo(message % {219 'prog': prog,220 'version': version,221 })222 ctx.exit()223224 attrs.setdefault('is_flag', True)225 attrs.setdefault('expose_value', False)226 attrs.setdefault('is_eager', True)227 attrs.setdefault('help', 'Show the version and exit.')228 attrs['callback'] = callback229 return option(*(param_decls or ('--version',)), **attrs)(f)230 return decorator231232233def help_option(*param_decls, **attrs):234 """Adds a ``--help`` option which immediately ends the program235 printing out the help page. This is usually unnecessary to add as236 this is added by default to all commands unless supressed.237238 Like :func:`version_option` this is implemented as eager option that239 prints in the callback and exits.240241 All arguments are forwarded to :func:`option`.242 """243 def decorator(f):244 def callback(ctx, value):245 if value:246 echo(ctx.format_help())247 ctx.exit()248 attrs.setdefault('is_flag', True)249 attrs.setdefault('expose_value', False)250 attrs.setdefault('help', 'Show this message and exit.')251 attrs.setdefault('is_eager', True)252 attrs['callback'] = callback253 return option(*(param_decls or ('--help',)), **attrs)(f)254 return decorator255256257# Circular dependencies between core and decorators258from .core import Command, Group, Argument, Option
added:click/exceptions.py+19 added
1from ._compat import PY2234class UsageError(Exception):5 """An internal exception that signals a usage error. This typically6 aborts any further handling.7 """89 def __init__(self, message, ctx=None):10 if PY2:11 Exception.__init__(self, message.encode('utf-8'))12 else:13 Exception.__init__(self, message)14 self.message = message15 self.ctx = ctx161718class Abort(KeyboardInterrupt):19 """An internal signalling exception that signals click to abort."""
added:click/formatting.py+40 added
1import textwrap234class TextWrapper(textwrap.TextWrapper):56 def _cutdown(self, ucstr, space_left):7 l = 08 for i in xrange(len(ucstr)):9 l += len(ucstr[i])10 if space_left < l:11 return (ucstr[:i], ucstr[i:])12 return ucstr, ''1314 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):15 space_left = max(width - cur_len, 1)1617 if self.break_long_words:18 cut, res = self._cutdown(reversed_chunks[-1], space_left)19 cur_line.append(cut)20 reversed_chunks[-1] = res21 elif not cur_line:22 cur_line.append(reversed_chunks.pop())2324 def fill_paragraphs(self, text):25 # Remove unnecessary newlines so that we can fill properly26 p = []27 buf = []28 for line in text.splitlines():29 if not line:30 p.append(' '.join(buf))31 buf = []32 else:33 buf.append(line)34 if buf:35 p.append(' '.join(buf))3637 rv = []38 for text in p:39 rv.append(self.fill(text))40 return '\n\n'.join(rv)
added:click/helpers.py+146 added
1import os2import shutil3import struct4import getpass56from ._compat import raw_input7from .utils import echo8from .exceptions import Abort, UsageError9from .types import convert_type101112# The prompt functions to use. The doc tools currently override these13# functions to customize how they work.14hidden_prompt_func = getpass.getpass15visible_prompt_func = raw_input161718def prompt(text, default=None, hide_input=False,19 confirmation_prompt=False, type=None,20 value_proc=None):21 """Prompts a user for input. This is a convenience function that can22 be used to prompt a user for input later.2324 If the user aborts the input by sending a interrupt signal this25 function will catch it and raise a :exc:`Abort` exception.2627 :param text: the text to show for the prompt.28 :param default: the default value to use if no input happens. If this29 is not given it will prompt until it's aborted.30 :param hide_input: if this is set to true then the input value will31 be hidden.32 :param confirmation_prompt: asks for confirmation for the value.33 :param type: the type to use to check the value against.34 :param value_proc: if this parameter is provided it's a function that35 is invoked instead of the type conversion to36 convert a value.37 """38 result = None3940 def prompt_func(text):41 f = hide_input and hidden_prompt_func or visible_prompt_func42 try:43 return f(text)44 except (KeyboardInterrupt, EOFError):45 raise Abort()4647 if value_proc is None:48 value_proc = convert_type(type, default)4950 prompt = text51 if default is not None:52 prompt = '%s [%s]' % (prompt, default)53 prompt += ': '5455 while 1:56 while 1:57 value = prompt_func(prompt)58 if value:59 break60 # If a default is set and used, then the confirmation61 # prompt is always skipped because that's the only thing62 # that really makes sense.63 elif default is not None:64 return default65 try:66 result = value_proc(value)67 except UsageError as e:68 echo('Error: %s' % e.message)69 continue70 if not confirmation_prompt:71 return result72 while 1:73 value2 = prompt_func('Repeat for confirmation: ')74 if value2:75 break76 if value == value2:77 return result78 echo('Error: the two entered values do not match')798081def confirm(text, default=False, abort=False):82 """Prompts for confirmation (yes/no question).8384 If the user aborts the input by sending a interrupt signal this85 function will catch it and raise a :exc:`Abort` exception.8687 :param text: the question to ask.88 :param default: the default for the prompt.89 :param abort: if this is set to `True` a negative answer aborts the90 exception by raising :exc:`Abort`.91 """92 prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')93 while 1:94 try:95 value = visible_prompt_func(prompt).lower().strip()96 except (KeyboardInterrupt, EOFError):97 raise Abort()98 if value in ('y', 'yes'):99 rv = True100 elif value in ('n', 'no'):101 rv = False102 elif value == '':103 rv = default104 else:105 echo('Error: invalid input')106 continue107 break108 if abort and not rv:109 raise Abort()110 return rv111112113def get_terminal_size():114 """Returns the current size of the terminal as tuple in the form115 ``(width, height)`` in columns and rows.116 """117 # If shutil has get_terminal_size() (Python 3.3 and later) use that118 shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)119 if shutil_get_terminal_size:120 sz = shutil_get_terminal_size()121 return sz.columns, sz.lines122123 def ioctl_gwinsz(fd):124 try:125 import fcntl126 import termios127 cr = struct.unpack(128 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))129 except Exception:130 return131 return cr132133 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)134 if not cr:135 try:136 fd = os.open(os.ctermid(), os.O_RDONLY)137 try:138 cr = ioctl_gwinsz(fd)139 finally:140 os.close(fd)141 except Exception:142 pass143 if not cr:144 cr = (os.environ.get('LINES', 25),145 os.environ.get('COLUMNS', 80))146 return int(cr[1]), int(cr[0])
added:click/types.py+240 added
1import sys23from ._compat import open_stream, text_type4from .exceptions import UsageError5from .utils import safecall678class ParamType(object):9 """Helper for converting values through types. The following is10 necessary for a valid type:1112 * it needs a name13 * it needs to pass through None unchanged14 * it needs to convert from a string15 * it needs to convert its result type through unchanged16 (eg: needs to be idempotent)17 * it needs to be able to deal with param and context being none.18 This can be the case when the object is used with prompt19 inputs.20 """2122 #: the descriptive name of this type23 name = None2425 def __call__(self, value, param=None, ctx=None):26 if value is not None:27 return self.convert(value, param, ctx)2829 def get_metavar(self, param):30 """Returns the metavar default for this param if it provides one."""3132 def convert(self, param, ctx, value):33 """Converts the value. This is not invoked for values that are34 `None` (the missing value).35 """36 return value3738 def fail(self, message, param=None, ctx=None):39 """Helper method to fail with an invalid value message."""40 if param is None:41 message = 'Invalid value: %s' % message42 else:43 message = 'Invalid value for %s: %s' % (param.name, message)44 raise UsageError(message, ctx=ctx)454647class FuncParamType(ParamType):4849 def __init__(self, func):50 self.name = func.__name__51 self.func = func5253 def convert(self, value, param, ctx):54 try:55 return self.func(value)56 except ValueError:57 try:58 value = unicode(value)59 except UnicodeError:60 value = str(value).decode('utf-8', 'replace')61 self.fail(value, param, ctx)626364class StringParamType(ParamType):65 name = 'string'6667 def convert(self, value, param, ctx):68 if isinstance(value, bytes):69 try:70 if sys.stdin.encoding is not None:71 value = value.decode(sys.stdin.encoding)72 except UnicodeError:73 try:74 value = value.decode(sys.getfilesystemencoding())75 except UnicodeError:76 value = value.decode('utf-8', 'replace')77 return value78 return value7980 def __repr__(self):81 return 'STRING'828384class Choice(ParamType):85 """The choice type allows a value to checked against a fixed set of86 supported values. All of these values have to be integers.87 """88 name = 'choice'8990 def __init__(self, choices):91 self.choices = choices9293 def get_metavar(self, param):94 return '[%s]' % '|'.join(self.choices)9596 def convert(self, value, param, ctx):97 if value in self.choices:98 return value99 self.fail('invalid choice: %s. (choose from %s)' %100 (value, ', '.join(self.choices)), param, ctx)101102 def __repr__(self):103 return 'Choice(%r)' % list(self.choices)104105106class IntParamType(ParamType):107 name = 'integer'108109 def convert(self, value, param, ctx):110 try:111 return int(value)112 except ValueError:113 self.fail('%s is not a valid integer' % value, param, ctx)114115 def __repr__(self):116 return 'INT'117118119class BoolParamType(ParamType):120 name = 'boolean'121122 def convert(self, value, param, ctx):123 if isinstance(value, bool):124 return bool(value)125 value = value.lower()126 if value in ('true', '1', 'yes', 'y'):127 return True128 elif value in ('false', '0', 'no', 'n'):129 return False130 self.fail('%s is not a valid boolean' % value, param, ctx)131132 def __repr__(self):133 return 'BOOL'134135136class FloatParamType(ParamType):137 name = 'float'138139 def convert(self, value, param, ctx):140 try:141 return float(value)142 except ValueError:143 self.fail('%s is not a valid floating point value' %144 value, param, ctx)145146 def __repr__(self):147 return 'FLOAT'148149150class File(ParamType):151 """Declares a parameter to be a file for reading or writing. The file152 is automatically closed once the context tears down (after the command153 finished working).154155 Files can be opened for reading or writing. The special value ``-``156 indicates stdin or stdout depending on the mode.157158 By default the file is opened for reading text data but it can also be159 opened in binary mode or for writing. The encoding parameter can be used160 to force a specific encoding.161 """162 name = 'filename'163164 def __init__(self, mode='r', encoding=None, errors='strict'):165 self.mode = mode166 self.encoding = encoding167 self.errors = errors168169 def convert(self, value, param, ctx):170 try:171 if hasattr(value, 'read') or hasattr(value, 'write'):172 return value173 f, was_opened = open_stream(value, self.mode, self.encoding,174 self.errors)175 # If a context is provided we automatically close the file176 # at the end of the context execution (or flush out). If a177 # context does not exist it's the caller's responsibility to178 # properly close the file. This for instance happens when the179 # type is used with prompts.180 if ctx is not None:181 if was_opened:182 ctx.call_on_close(safecall(f.close))183 else:184 ctx.call_on_close(safecall(f.flush))185 return f186 except (IOError, OSError) as e:187 if isinstance(value, bytes):188 value = value.decode(sys.getfilesystemencoding(), 'replace')189 if hasattr(e, 'strerror'):190 msg = e.strerror191 else:192 msg = str(e)193 if isinstance(msg, bytes):194 msg = msg.decode('utf-8', 'replace')195 self.fail('Could not open file %s: %s' % (value, msg),196 param, ctx)197198199def convert_type(ty, default=None):200 """Converts a callable or python ty into the most appropriate param201 ty.202 """203 if isinstance(ty, ParamType):204 return ty205 guessed_type = False206 if ty is None and default is not None:207 ty = type(default)208 guessed_type = True209 if ty is text_type or ty is str or ty is None:210 return STRING211 if ty is int:212 return INT213 # Booleans are only okay if not guessed. This is done because for214 # flags the default value is actually a bit of a lie in that it215 # indicates which of the flags is the one we want. See get_default()216 # for more information.217 if ty is bool and not guessed_type:218 return BOOL219 if ty is float:220 return FLOAT221 if guessed_type:222 return STRING223 return FuncParamType(ty)224225226#: A unicode string parameter type which is the implicit default. This227#: can also be selected by using ``str`` as type.228STRING = StringParamType()229230#: An integer parameter. This can also be selected by using ``int`` as231#: type.232INT = IntParamType()233234#: A floating point value parameter. This can also be selected by using235#: ``float`` as type.236FLOAT = FloatParamType()237238#: A boolean parameter. This is the default for boolean flags. This can239#: also be selected by using ``bool`` as a type.240BOOL = BoolParamType()
added:click/utils.py+26 added
1import sys23from ._compat import PY2, text_type456def safecall(func):7 """Wraps a function so that it swallows exceptions."""8 def wrapper(*args, **kwargs):9 try:10 return func(*args, **kwargs)11 except Exception:12 pass13 return wrapper141516def echo(message=None, file=None):17 """Prints a message to the given file or stdout."""18 if file is None:19 file = sys.stdout20 if message:21 if PY2 and isinstance(message, text_type):22 message = message.encode(getattr(file, 'encoding', None)23 or 'utf-8', 'replace')24 file.write(message)25 file.write('\n')26 file.flush()
modified:docs/arguments.rst+2 added-1 removed
88 unmodified lines
8990.. click:run::9192 with isolated_filesystem():93 invoke(inout, args=['-', 'hello.txt'], input=['hello'])93 invoke(inout, args=['-', 'hello.txt'], input=['hello'],94 terminate_input=True)95 invoke(inout, args=['hello.txt', '-'])9697Environment Variables98---------------------
28 unmodified lines
modified:docs/clickdoctools.py+24 added-20 removed
24 unmodified lines
2526 def __getattr__(self, x):27 return getattr(self._input, x)2829 def read(self, n=-1):30 rv = self._input.read(n)29 def _echo(self, rv):30 mark = False31 if rv.endswith('\xff'):32 rv = rv[:-1]33 mark = True34 self._output.write(rv)35 if mark:36 self._output.write('^D\n')37 return rv3839 def read(self, n=-1):40 return self._echo(self._input.read(n))4142 def readline(self, n=-1):35 rv = self._input.readline(n)36 self._output.write(rv)37 return rv43 return self._echo(self._input.readline(n))4445 def readlines(self):40 rv = self._input.readlines()41 for line in rv:42 self._output.write(rv)43 return rv46 return [self._echo(x) for x in self._input.readlines()]4748 def __iter__(self):46 for x in self._input:47 self._output.write(x)48 yield x49 return iter(self._echo(x) for x in self._input)505152@contextlib.contextmanager53def isolation(input=None, env=None):53 if click.PY2 and isinstance(input, unicode):54 if isinstance(input, unicode):55 input = input.encode('utf-8')56 input = StringIO(input or '')57 output = StringIO()58 sys.stdin = EchoingStdin(input, output)
12 unmodified lines
71 return input.readline().rstrip('\r\n')7273 sys.stdout = output74 sys.stderr = output74 old_visible_prompt_func = click.visible_prompt_func75 old_hidden_prompt_func = click.hidden_prompt_func76 click.visible_prompt_func = visible_input77 click.hidden_prompt_func = hidden_input75 old_visible_prompt_func = click.helpers.visible_prompt_func76 old_hidden_prompt_func = click.helpers.hidden_prompt_func77 click.helpers.visible_prompt_func = visible_input78 click.helpers.hidden_prompt_func = hidden_input7980 old_env = {}81 try:82 if env:
11 unmodified lines
94 else:95 os.environ[key] = value96 sys.stdout = sys.__stdout__97 sys.stderr = sys.__stderr__97 click.visible_prompt_func = old_visible_prompt_func98 click.hidden_prompt_func = old_hidden_prompt_func98 click.helpers.visible_prompt_func = old_visible_prompt_func99 click.helpers.hidden_prompt_func = old_hidden_prompt_func100101102@contextlib.contextmanager103def isolated_filesystem():
26 unmodified lines
130 code = compile(source, '<docs>', 'exec')131 buffer = []132133 def invoke(cmd, args=None, prog_name=None, prog_prefix='python ',133 input=None, env=None, auto_envvar_prefix=None):134 input=None, terminate_input=False, env=None,135 auto_envvar_prefix=None):136 if env:137 for key, value in sorted(env.items()):138 if ' ' in value:139 value = '"%s"' % value
7 unmodified lines
147 ' '.join(('"%s"' % x) if ' ' in x else x for x in args)148 )).rstrip())149 if isinstance(input, (tuple, list)):150 input = '\n'.join(input) + '\n'151 if terminate_input:152 input += '\xff'153 with isolation(input=input, env=env) as output:154 try:155 cmd.main(args=args, prog_name=prog_name,156 auto_envvar_prefix=auto_envvar_prefix)
100 unmodified lines
deleted:click.py-1686 removed
1# -*- coding: utf-8 -*-2"""3 click4 ~~~~~56 click is a simple Python module that wraps the stdlib's optparse to make7 writing command line scripts fun. Unlike other modules it's based around8 a simple API that does not come with too much magic and is composable.910 In case optparse ever goes away from the stdlib it will be shipped by11 this module.1213 :copyright: (c) 2014 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16import os17import sys18import codecs19import inspect20import getpass21import optparse22import textwrap23import struct24import shutil25from itertools import chain26from functools import update_wrapper272829PY2 = 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 import io52 text_type = str53 raw_input = input5455 def _make_binary_stream(f, stream_name):56 buf = getattr(f, 'buffer', None)57 if buf is not None and isinstance(buf, io.BufferedReader):58 return buf59 raise TypeError('%s is a stream that does not give access to its '60 'underlying binary stream. Please do not set '61 'sys.stdout directly to a StringIO object or '62 'something similar.' % stream_name)6364 def open_stream(filename, mode='r', encoding=None, errors='strict'):65 if filename != '-':66 if encoding is not None:67 return open(filename, mode, encoding=encoding,68 errors=errors), True69 return open(filename, mode), True7071 if 'w' in mode:72 f = sys.stdout73 if encoding is not None or 'b' in mode:74 f = _make_binary_stream(f, 'stdout')75 if encoding is not None:76 f = _wrap_stream_for_codec(f, encoding, errors)77 else:78 f = sys.stdin79 if 'b' in mode:80 f = _make_binary_stream(f, 'stdin')81 if encoding is not None:82 f = _wrap_stream_for_codec(f, encoding, errors)8384 return f, False858687def get_terminal_size():88 """Returns the current size of the terminal as tuple in the form89 ``(width, height)`` in columns and rows.90 """91 # If shutil has get_terminal_size() (Python 3.3 and later) use that92 shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)93 if shutil_get_terminal_size:94 sz = shutil_get_terminal_size()95 return sz.columns, sz.lines9697 def ioctl_gwinsz(fd):98 try:99 import fcntl100 import termios101 cr = struct.unpack(102 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))103 except Exception:104 return105 return cr106107 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)108 if not cr:109 try:110 fd = os.open(os.ctermid(), os.O_RDONLY)111 try:112 cr = ioctl_gwinsz(fd)113 finally:114 os.close(fd)115 except Exception:116 pass117 if not cr:118 cr = (os.environ.get('LINES', 25),119 os.environ.get('COLUMNS', 80))120 return int(cr[1]), int(cr[0])121122123def safecall(func):124 """Wraps a function so that it swallows exceptions."""125 def wrapper(*args, **kwargs):126 try:127 return func(*args, **kwargs)128 except Exception:129 pass130 return wrapper131132133# The prompt functions to use. The doc tools currently override these134# functions to customize them.135hidden_prompt_func = getpass.getpass136visible_prompt_func = raw_input137138139class TextWrapper(textwrap.TextWrapper):140141 def _cutdown(self, ucstr, space_left):142 l = 0143 for i in xrange(len(ucstr)):144 l += len(ucstr[i])145 if space_left < l:146 return (ucstr[:i], ucstr[i:])147 return ucstr, ''148149 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):150 space_left = max(width - cur_len, 1)151152 if self.break_long_words:153 cut, res = self._cutdown(reversed_chunks[-1], space_left)154 cur_line.append(cut)155 reversed_chunks[-1] = res156 elif not cur_line:157 cur_line.append(reversed_chunks.pop())158159 def fill_paragraphs(self, text):160 # Remove unnecessary newlines so that we can fill properly161 p = []162 buf = []163 for line in text.splitlines():164 if not line:165 p.append(' '.join(buf))166 buf = []167 else:168 buf.append(line)169 if buf:170 p.append(' '.join(buf))171172 rv = []173 for text in p:174 rv.append(self.fill(text))175 return '\n\n'.join(rv)176177178def _wrap_stream_for_codec(f, encoding=None, errors='strict'):179 if encoding is None:180 encoding = 'utf-8'181 info = codecs.lookup(encoding)182 f = codecs.StreamReaderWriter(f, info.streamreader,183 info.streamwriter,184 errors)185 f.encoding = encoding186 return f187188189def echo(message=None, file=None):190 if file is None:191 file = sys.stdout192 if message:193 if PY2 and isinstance(message, text_type):194 message = message.encode(getattr(file, 'encoding', None)195 or 'utf-8', 'replace')196 file.write(message)197 file.write('\n')198 file.flush()199200201def pass_context(f):202 """Marks a callback that it wants to receive the current context203 object as first argument.204 """205 f.__click_pass_context__ = True206 return f207208209def pass_obj(f):210 """Similar to :func:`pass_context` but only pass the object on the211 context onwards (:attr:`Context.obj`). This is useful if that object212 represents the state of a nested system.213 """214 @pass_context215 def new_func(*args, **kwargs):216 ctx = args[0]217 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)218 return update_wrapper(new_func, f)219220221def make_pass_decorator(object_type):222 """Given an object type this creates a decorator that will work223 similar to :func:`pass_obj` but instead of passing the object of the224 current context, it will find the innermost context of type225 :func:`object_type`.226227 This generates a decorator that works roughly like this::228229 from functools import update_wrapper230231 def decorator(f):232 @pass_context233 def new_func(ctx, *args, **kwargs):234 obj = ctx.find_object(object_type)235 return ctx.invoke(f, obj, *args, **kwargs)236 return update_wrapper(new_func, f)237 return decorator238 """239 def decorator(f):240 @pass_context241 def new_func(*args, **kwargs):242 ctx = args[0]243 obj = ctx.find_object(object_type)244 if obj is None:245 raise RuntimeError('Managed to invoke callback without a '246 'context object of type %r existing'247 % object_type.__name__)248 return ctx.invoke(f, obj, *args[1:], **kwargs)249 return update_wrapper(new_func, f)250 return decorator251252253class Context(object):254 """The context is a special internal object that holds state relevant255 for the script execution at every single level. It's normally invisible256 to commands unless they opt-in to getting access to it.257258 The context is useful as it can pass internal objects around and can259 control special execution features such as reading data from260 environment variables.261262 A context can be used as context manager in which case it will call263 :meth:`close` on teardown.264265 :param command: the command class for this context.266 :param parent: the parent context.267 :param info_name: the info name for this invokation. Generally this268 is the most descriptive name for the script or269 command. For the toplevel script is is usually270 the name of the script, for commands below it it's271 the name of the script.272 :param obj: an arbitrary object of user data.273 :param auto_envvar_prefix: the prefix to use for automatic environment274 variables. If this is `None` then reading275 from environment variables is disabled. This276 does not affect manually set environment277 variables which are always read.278 """279280 def __init__(self, command, parent=None, info_name=None, obj=None,281 auto_envvar_prefix=None):282 #: the parent context or `None` if none exists.283 self.parent = parent284 #: the :class:`Command` for this context.285 self.command = command286 #: the descriptive information name287 self.info_name = info_name288 #: the parsed parameters except if the value is hidden in which289 #: case it's not remembered.290 self.params = {}291 #: the leftover arguments.292 self.args = []293 #: this flag indicates if a subcommand is going to be executed.294 #: a group callback can use this information to figure out if it's295 #: being executed directly or because the execution flow passes296 #: onwards to a subcommand. By default it's `None` but it can be297 #: the name of the subcommand to execute.298 self.invoked_subcommand = None299 if obj is None and parent is not None:300 obj = parent.obj301 #: the user object stored.302 self.obj = obj303304 # If there is no envvar prefix yet, but the parent has one and305 # the command on this level has a name, we can expand the envvar306 # prefix automatically.307 if auto_envvar_prefix is None:308 if parent is not None \309 and parent.auto_envvar_prefix is not None and \310 self.info_name is not None:311 auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,312 self.info_name.upper())313 else:314 self.auto_envvar_prefix = auto_envvar_prefix.upper()315 self.auto_envvar_prefix = auto_envvar_prefix316317 self._parser = command._make_parser(self)318 self._close_callbacks = []319320 def __enter__(self):321 return self322323 def __exit__(self, exc_type, exc_value, tb):324 self.close()325326 def call_on_close(self, f):327 """This decorator remembers a function as callback that should be328 executed when the context tears down. This is most useful to bind329 resource handling to the script execution. For instance file objects330 opened by the :class:`File` type will register their close callbacks331 here.332333 :param f: the function to execute on teardown.334 """335 self._close_callbacks.append(f)336 return f337338 def close(self):339 """Invokes all close callbacks."""340 for cb in self._close_callbacks:341 cb()342 self._close_callbacks = []343344 @property345 def command_path(self):346 """The computed command path. This is used for the ``usage``347 information on the help page. It's automatically created by348 combining the info names of the chain of contexts to the root.349 """350 rv = ''351 if self.info_name is not None:352 rv = self.info_name353 if self.parent is not None:354 rv = self.parent.command_path + ' ' + rv355 return rv.lstrip()356357 def find_root(self):358 """Finds the outermost context."""359 node = self360 while node.parent is not None:361 node = node.parent362 return node363364 def find_object(self, object_type):365 """Finds the closest object of a given type."""366 node = self367 while node.parent is not None:368 if isinstance(node.obj, object_type):369 return node.obj370 node = node.parent371372 def fail(self, message):373 """Aborts the execution of the program with a specific error374 message.375376 :param message: the error message to fail with.377 """378 raise UsageError(message, self)379380 def abort(self):381 """Aborts the script."""382 raise Abort()383384 def exit(self, code=0):385 """Exits the application with a given exit code."""386 sys.exit(code)387388 def format_usage(self):389 """Helper method to get formatted usage string for the current390 context and command.391 """392 return self._parser.get_usage()393394 def format_help(self):395 """Helper method to get formatted help page for the current396 context and command.397 """398 return self._parser.format_help().rstrip()399400 def invoke(*args, **kwargs):401 """Invokes a command callback in exactly the way it expects.402 """403 self, callback = args[:2]404 args = args[2:]405 if getattr(callback, '__click_pass_context__', False):406 args = (self,) + args407 return callback(*args, **kwargs)408409410class UsageError(Exception):411 """An internal exception that signals a usage error. This typically412 aborts any further handling.413 """414415 def __init__(self, message, ctx=None):416 if PY2:417 Exception.__init__(self, message.encode('utf-8'))418 else:419 Exception.__init__(self, message)420 self.message = message421 self.ctx = ctx422423424class Abort(Exception):425 """An internal signalling exception that signals click to abort."""426427428class _SimplifiedFormatter(optparse.IndentedHelpFormatter):429430 def __init__(self):431 optparse.IndentedHelpFormatter.__init__(self,432 width=min(get_terminal_size()[0], 80) - 2)433 self.default_tag = ''434435 def format_usage(self, usage):436 prefix = 'Usage: '437 indent = len(prefix)438 text_width = self.width - indent439 return '%s%s\n' % (prefix, TextWrapper(440 text_width, initial_indent='',441 subsequent_indent=' ' * indent,442 replace_whitespace=False).fill(usage))443444 def _format_text(self, text):445 text_width = self.width - self.current_indent446 indent = ' ' * self.current_indent447448 return TextWrapper(text_width,449 initial_indent=indent,450 subsequent_indent=indent,451 replace_whitespace=False).fill_paragraphs(text)452453 def format_description(self, description):454 if not description:455 return ''456 self.indent()457 rv = self._format_text(description) + '\n'458 self.dedent()459 return rv460461 def format_option_strings(self, option):462 rv = optparse.IndentedHelpFormatter.format_option_strings(self, option)463 if hasattr(option, '_negative_version'):464 rv += ' / ' + optparse.IndentedHelpFormatter.format_option_strings(465 self, option._negative_version)466 return rv467468469class _SimplifiedOptionParser(optparse.OptionParser):470471 def __init__(self, ctx, **extra):472 usage = ctx.command_path + ' ' + ctx.command.options_metavar473 optparse.OptionParser.__init__(self, prog=ctx.command_path,474 usage=usage,475 add_help_option=False,476 formatter=_SimplifiedFormatter(),477 **extra)478 self.__ctx = ctx479480 def expand_prog_name(self, s):481 return s482483 def format_option_help(self, formatter):484 rv = optparse.OptionParser.format_option_help(self, formatter)485 extra_help = self.__ctx.command._format_extra_help(self.__ctx)486 if extra_help:487 rv = '%s\n\n%s' % (extra_help, rv)488 return rv489490 def error(self, msg):491 raise UsageError(msg, self.__ctx)492493494class Command(object):495 """Commands are the basic building block of command line interfaces in496 click. A basic command handles command line parsing and might dispatch497 more parsing to commands nested blow it.498499 :param name: the name of the command to use unless a group overrides it.500 :param callback: the callback to invoke. This is optional.501 :param params: the parameters to register with this command. This can502 be either :class:`Option` or :class:`Argument` objects.503 :param help: the help string to use for this command.504 :param epilog: like the help string but it's printed at the end of the505 help page after everything else.506 :param short_help: the short help to use for this command. This is507 shown on the command listing of the parent command.508 :param add_help_option: by default each command registers a ``--help``509 option. This can be disabled by this parameter.510 """511 allow_extra_args = False512513 def __init__(self, name, callback=None, params=None, help=None,514 epilog=None, short_help=None,515 options_metavar='[OPTIONS]', add_help_option=True):516 #: the name the command things it has. Upon registering a command517 #: on a :class:`Group` the group will default the command name518 #: with this information. You should instead use the519 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.520 self.name = name521 #: the callback to execute when the command fires. This might be522 #: `None` in which case nothing happens.523 self.callback = callback524 #: the list of parameters for this command in the order they525 #: should show up in the help page and execute. Eager parameters526 #: will automatically be handled before non eager ones.527 self.params = params or []528 self.help = help529 self.epilog = epilog530 self.options_metavar = options_metavar531 if short_help is None and help:532 short_help = help.split('.')[0].strip()533 if len(short_help) > 45:534 short_help = None535 elif short_help:536 short_help = short_help[0].lower() + short_help[1:] + '.'537 self.short_help = short_help538 if add_help_option:539 help_option()(self)540541 def iter_params_for_processing(self):542 """This returns an iterator over all attached parameters in the543 order of processing. This iterator returns all eager parameters544 first, followed by all non-eager parameters.545 """546 for param in self.params:547 if param.is_eager:548 yield param549 for param in self.params:550 if not param.is_eager:551 yield param552553 def _make_parser(self, ctx):554 parser = _SimplifiedOptionParser(ctx, description=self.help,555 epilog=self.epilog)556 for param in self.params:557 param._add_to_parser(parser, ctx)558 return parser559560 def _format_extra_help(self, ctx):561 pass562563 def make_context(self, info_name, args, parent=None, **extra):564 """This function when given an info name and arguments will kick565 off the parsing and create a new :class:`Context`. It does not566 invoke the actual command callback though.567568 :param info_name: the info name for this invokation. Generally this569 is the most descriptive name for the script or570 command. For the toplevel script is is usually571 the name of the script, for commands below it it's572 the name of the script.573 :param args: the arguments to parse as list of strings.574 :param parent: the parent context if available.575 :param extra: extra keyword arguments forwarded to the context576 constructor.577 """578 ctx = Context(self, info_name=info_name, parent=parent, **extra)579 opts, args = ctx._parser.parse_args(args=args)580 opts = opts.__dict__581582 for param in ctx.command.iter_params_for_processing():583 value, args = param.handle_parse_result(ctx, opts, args)584585 if args and not self.allow_extra_args:586 ctx.fail('Got unexpected extra argument%s (%s)'587 % (len(args) != 1 and 's' or '', ' '.join(args)))588589 ctx.args = args590591 return ctx592593 def invoke(self, ctx):594 """Given a context, this invokes the attached callback (if it exists)595 in the right way.596 """597 if self.callback is not None:598 ctx.invoke(self.callback, **ctx.params)599600 def main(self, args=None, prog_name=None, **extra):601 """This is the way to invoke a script with all the bells and602 whistles as command line application. This will always terminate603 the application after calling. If this is not wanted, ``SystemExit``604 needs to be caught.605606 This method is also available by directly calling the instance of607 a :class:`Command`.608609 :param args: the arguments that should be used for parsing. If not610 provided, ``sys.argv[1:]`` is used.611 :param prog_name: the program name that should be used. By default612 the progam name is constructed by taking the file613 name from ``sys.argv[0]``.614 :param extra: extra keyword arguments are forwarded to the context615 constructor.616 """617 if args is None:618 args = sys.argv[1:]619 else:620 args = list(args)621 if prog_name is None:622 prog_name = os.path.basename(sys.argv and sys.argv[0] or __file__)623 try:624 try:625 with self.make_context(prog_name, args, **extra) as ctx:626 self.invoke(ctx)627 ctx.exit()628 except (EOFError, KeyboardInterrupt):629 echo(file=sys.stderr)630 raise Abort()631 except UsageError as e:632 if e.ctx is not None:633 echo(e.ctx.format_usage(), file=sys.stderr)634 echo('Error: %s' % e.message, file=sys.stderr)635 sys.exit(2)636 except Abort:637 echo('Aborted!', file=sys.stderr)638 sys.exit(1)639640 def __call__(self, *args, **kwargs):641 """Alias for :meth:`main`."""642 return self.main(*args, **kwargs)643644645class MultiCommand(Command):646 """A multi command is the basic implementation of a command that647 dispatches to subcommands. The most common version is the648 :class:`Command`.649650 :param invoke_without_command: this controls how the multi command itself651 is invoked. By default it's only invoked652 if a subcommand is provided.653 :param no_args_is_help: this controls what happens if no arguments are654 provided. This option is enabled by default if655 `invoke_without_command` is disabled or disabled656 if it's enabled. If enabled this will add657 ``--help`` as argument if no arguments are658 passed.659 :param subcommand_metavar: the string that is used in the documentation660 to indicate the subcommand place.661 """662 allow_extra_args = True663664 def __init__(self, name=None, invoke_without_command=False,665 no_args_is_help=None, subcommand_metavar='COMMAND [ARGS]...',666 **attrs):667 Command.__init__(self, name, **attrs)668 if no_args_is_help is None:669 no_args_is_help = not invoke_without_command670 self.no_args_is_help = no_args_is_help671 self.invoke_without_command = invoke_without_command672 self.subcommand_metavar = subcommand_metavar673674 def _make_parser(self, ctx):675 parser = Command._make_parser(self, ctx)676 parser.usage += ' ' + self.subcommand_metavar677 parser.disable_interspersed_args()678 return parser679680 def _format_extra_help(self, ctx):681 commands = self.list_commands()682 if not commands:683 return684685 longest = len(sorted(commands, key=len)[-1])686687 subcommand_info = []688 for subcommand in self.list_commands():689 cmd = self.get_command(ctx, subcommand)690 help = cmd.short_help or ''691 subcommand_info.append(' %-*s %s' % (longest, subcommand, help))692693 return 'Commands:\n%s' % '\n'.join(subcommand_info)694695 def make_context(self, info_name, args, parent=None, **extra):696 # Multi-commands invoked without any arguments is a shortcut to697 # invoking it with --help unless supresssed.698 if not args and self.no_args_is_help:699 args = ['--help']700 return Command.make_context(self, info_name, args, parent, **extra)701702 def invoke(self, ctx):703 if not ctx.args:704 if self.invoke_without_command:705 return Command.invoke(self, ctx)706 ctx.fail('Missing command')707 cmd_name = ctx.args[0]708709 cmd = self.get_command(ctx, cmd_name)710 if cmd is None:711 ctx.fail('No such command "%s"' % cmd_name)712713 # Whenever we dispatch to a subcommand we also invoke the regular714 # callback. This is done so that parameters can be handled.715 ctx.invoked_subcommand = cmd_name716 Command.invoke(self, ctx)717718 with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:719 return cmd.invoke(cmd_ctx)720721 def get_command(self, ctx, cmd_name):722 """Given a context and a command name, this returns a723 :class:`Command` object if it exists or returns `None`.724 """725 raise NotImplementedError()726727 def list_commands(self):728 """Returns a list of subcommand names in the order they should729 appear.730 """731 return []732733734class Group(MultiCommand):735 """A group allows a command to have subcommands attached. This is the736 most common way to implement nesting in click.737738 :param commands: a dictionary of commands.739 """740741 def __init__(self, name=None, commands=None, **attrs):742 MultiCommand.__init__(self, name, **attrs)743 #: the registered subcommands by their exported names.744 self.commands = commands or {}745746 def add_command(self, cmd, name=None):747 """Registers another :class:`Command` with this group. If the name748 is not provided, the name of the command is used.749 """750 name = name or cmd.name751 if name is None:752 raise TypeError('Command has no name.')753 self.commands[name] = cmd754755 def command(self, *args, **kwargs):756 """A shortcut decorator for declaring and attaching a command to757 the group. This takes the same arguments as :func:`command` but758 immediately registers the created command with this instance by759 calling into :meth:`add_command`.760 """761 def decorator(f):762 cmd = command(*args, **kwargs)(f)763 self.add_command(cmd)764 return cmd765 return decorator766767 def get_command(self, ctx, cmd_name):768 return self.commands.get(cmd_name)769770 def list_commands(self):771 return sorted(self.commands)772773774class ParamType(object):775 """Helper for converting values through types. The following is776 necessary for a valid type:777778 * it needs a name779 * it needs to pass through None unchanged780 * it needs to convert from a string781 * it needs to convert its result type through unchanged782 (eg: needs to be idempotent)783 * it needs to be able to deal with param and context being none.784 This can be the case when the object is used with prompt785 inputs.786 """787788 #: the descriptive name of this type789 name = None790791 def __call__(self, value, param=None, ctx=None):792 if value is not None:793 return self.convert(value, param, ctx)794795 def get_metavar(self, param):796 """Returns the metavar default for this param if it provides one."""797798 def convert(self, param, ctx, value):799 """Converts the value. This is not invoked for values that are800 `None` (the missing value).801 """802 return value803804 def fail(self, message, param=None, ctx=None):805 """Helper method to fail with an invalid value message."""806 if param is None:807 message = 'Invalid value: %s' % message808 else:809 message = 'Invalid value for %s: %s' % (param.name, message)810 raise UsageError(message, ctx=ctx)811812813class FuncParamType(ParamType):814815 def __init__(self, func):816 self.name = func.__name__817 self.func = func818819 def convert(self, value, param, ctx):820 try:821 return self.func(value)822 except ValueError:823 try:824 value = unicode(value)825 except UnicodeError:826 value = str(value).decode('utf-8', 'replace')827 self.fail(value, param, ctx)828829830class StringParamType(ParamType):831 name = 'string'832833 def convert(self, value, param, ctx):834 if isinstance(value, bytes):835 try:836 if sys.stdin.encoding is not None:837 value = value.decode(sys.stdin.encoding)838 except UnicodeError:839 try:840 value = value.decode(sys.getfilesystemencoding())841 except UnicodeError:842 value = value.decode('utf-8', 'replace')843 return value844 return value845846 def __repr__(self):847 return 'STRING'848849850class Choice(ParamType):851 name = 'choice'852853 def __init__(self, choices):854 self.choices = choices855856 def get_metavar(self, param):857 return '[%s]' % '|'.join(self.choices)858859 def convert(self, value, param, ctx):860 if value in self.choices:861 return value862 self.fail('invalid choice: %s. (choose from %s)' %863 (value, ', '.join(self.choices)), param, ctx)864865 def __repr__(self):866 return 'Choice(%r)' % list(self.choices)867868869class IntParamType(ParamType):870 name = 'integer'871872 def convert(self, value, param, ctx):873 try:874 return int(value)875 except ValueError:876 self.fail('%s is not a valid integer' % value, param, ctx)877878 def __repr__(self):879 return 'INT'880881882class BoolParamType(ParamType):883 name = 'boolean'884885 def convert(self, value, param, ctx):886 if isinstance(value, bool):887 return bool(value)888 value = value.lower()889 if value in ('true', '1', 'yes', 'y'):890 return True891 elif value in ('false', '0', 'no', 'n'):892 return False893 self.fail('%s is not a valid boolean' % value, param, ctx)894895 def __repr__(self):896 return 'BOOL'897898899class FloatParamType(ParamType):900 name = 'float'901902 def convert(self, value, param, ctx):903 try:904 return float(value)905 except ValueError:906 self.fail('%s is not a valid floating point value' %907 value, param, ctx)908909 def __repr__(self):910 return 'FLOAT'911912913class File(ParamType):914 """Declares a parameter to be a file for reading or writing. The file915 is automatically closed once the context tears down (after the command916 finished working).917918 Files can be opened for reading or writing. The special value ``-``919 indicates stdin or stdout depending on the mode.920921 By default the file is opened for reading text data but it can also be922 opened in binary mode or for writing. The encoding parameter can be used923 to force a specific encoding.924 """925 name = 'filename'926927 def __init__(self, mode='r', encoding=None, errors='strict'):928 self.mode = mode929 self.encoding = encoding930 self.errors = errors931932 def convert(self, value, param, ctx):933 try:934 if hasattr(value, 'read') or hasattr(value, 'write'):935 return value936 f, was_opened = open_stream(value, self.mode, self.encoding,937 self.errors)938 # If a context is provided we automatically close the file939 # at the end of the context execution (or flush out). If a940 # context does not exist it's the caller's responsibility to941 # properly close the file. This for instance happens when the942 # type is used with prompts.943 if ctx is not None:944 if was_opened:945 ctx.call_on_close(safecall(f.close))946 else:947 ctx.call_on_close(safecall(f.flush))948 return f949 except (IOError, OSError) as e:950 if isinstance(value, bytes):951 value = value.decode(sys.getfilesystemencoding(), 'replace')952 if hasattr(e, 'strerror'):953 msg = e.strerror954 else:955 msg = str(e)956 if isinstance(msg, bytes):957 msg = msg.decode('utf-8', 'replace')958 self.fail('Could not open file %s: %s' % (value, msg),959 param, ctx)960961962def convert_type(ty, default=None):963 """Converts a callable or python ty into the most appropriate param964 ty.965 """966 if isinstance(ty, ParamType):967 return ty968 guessed_type = False969 if ty is None and default is not None:970 ty = type(default)971 guessed_type = True972 if ty is text_type or ty is str or ty is None:973 return STRING974 if ty is int:975 return INT976 # Booleans are only okay if not guessed. This is done because for977 # flags the default value is actually a bit of a lie in that it978 # indicates which of the flags is the one we want. See get_default()979 # for more information.980 if ty is bool and not guessed_type:981 return BOOL982 if ty is float:983 return FLOAT984 if guessed_type:985 return STRING986 return FuncParamType(ty)987988989class Parameter(object):990 """A parameter to a command comes in two versions: they are either991 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently992 not supported by design as some of the internals for parsing are993 intentionally not finalized.994995 Some settings are supported by both options and arguments.996997 :param param_decls: the parameter declarations for this option or998 argument. This is a list of flags or argument999 names.1000 :param type: the type that should be used. Either a :class:`ParamType`1001 or a python type. The latter is converted into the former1002 automatically if supported.1003 :param required: controls if this is optional or not.1004 :param default: the default value if omitted. This can also be a callable1005 in which case it's invoked when the default is needed1006 without any arguments.1007 :param help: the help string.1008 :param callback: a callback that should be executed after the parameter1009 was matched. This is called as ``fn(ctx, value)`` and1010 needs to return the value.1011 :param nargs: the number of arguments to match. If not ``1`` the return1012 value is a tuple instead of single value.1013 :param metavar: how the value is represented in the help page.1014 :param expose_value: if this is `True` then the value is passed onwards1015 to the command callback and stored on the context,1016 otherwise it's skipped.1017 :param is_eager: eager values are processed before non eager ones. This1018 should not be set for arguments or it will inverse the1019 order of processing.1020 :param envvar: a string or list of strings that are environment variables1021 that should be checked.1022 """1023 param_type_name = 'parameter'10241025 def __init__(self, param_decls=None, type=None, required=False,1026 default=None, help=None, callback=None, nargs=1,1027 metavar=None, expose_value=True, is_eager=False,1028 envvar=None):1029 self.name, self.opts, self.secondary_opts = \1030 self._parse_decls(param_decls or ())1031 self.type = convert_type(type, default)1032 self.required = required1033 self.help = help1034 self.callback = callback1035 self.nargs = nargs1036 self.multiple = False1037 self.expose_value = expose_value1038 self.default = default1039 self.is_eager = is_eager1040 self.metavar = metavar1041 self.envvar = envvar10421043 def make_metavar(self):1044 if self.metavar is not None:1045 return self.metavar1046 metavar = self.type.get_metavar(self)1047 if metavar is not None:1048 return metavar1049 metavar = self.name.upper()1050 if self.nargs != 1:1051 metavar += '...'1052 return metavar10531054 def get_default(self, ctx):1055 """Given a context variable this calculates the default value."""1056 # Otherwise go with the regular default.1057 if callable(self.default):1058 rv = self.default()1059 else:1060 rv = self.default1061 return self.type(rv, self, ctx)10621063 def _add_to_parser(self, parser, ctx):1064 raise NotImplementedError()10651066 def process_value(self, ctx, value):1067 """Given a value and context this runs the logic to convert the1068 value as necessary.1069 """1070 def _convert(value, level):1071 if level == 0:1072 return self.type(value, self, ctx)1073 return tuple(_convert(x, level - 1) for x in value or ())1074 return _convert(value, (self.nargs != 1) + bool(self.multiple))10751076 def full_process_value(self, ctx, value):1077 value = self.process_value(ctx, value)10781079 if value is None:1080 value = self.get_default(ctx)10811082 if value is None and self.required:1083 ctx.fail(self.get_missing_message(ctx))10841085 return value10861087 def get_missing_message(self, ctx):1088 return 'Missing %s "%s".' % (1089 self.param_type_name,1090 ' / '.join(chain(self.opts, self.secondary_opts)),1091 )10921093 def value_from_envvar(self, ctx):1094 if self.envvar is None:1095 return1096 if isinstance(self.envvar, (tuple, list)):1097 for envvar in self.envvar:1098 rv = os.environ.get(envvar)1099 if rv is not None:1100 return rv1101 else:1102 return os.environ.get(self.envvar)11031104 def consume_value(self, ctx, opts, args):1105 return None, args11061107 def handle_parse_result(self, ctx, opts, args):1108 value, args = self.consume_value(ctx, opts, args)1109 value = self.full_process_value(ctx, value)1110 if self.callback is not None:1111 value = self.callback(ctx, value)1112 if self.expose_value:1113 ctx.params[self.name] = value1114 return value, args111511161117class Option(Parameter):1118 """Options are usually optionaly values on the command line and1119 have some extra features that arguments don't have.11201121 All other parameters are passed onwards to the parameter constructor.11221123 :param show_default: controls if the default value should be shown on the1124 help page. The default is auto detection.1125 :param prompt: if set to `True` or a non empty string then the user will1126 be prompted for input if not set. If set to `True` the1127 prompt will be the option name capitalized.1128 :param confirmation_prompt: if set then the value will need to be confirmed1129 if it was prompted for.1130 :param hide_input: if this is `True` then the input on the prompt will be1131 hidden from the user. This is useful for password1132 input.1133 :param is_flag: forces this option to act as a flag. The default is1134 auto detection.1135 :param flag_value: which value should be used for this flag if it's1136 enabled. This is set to a boolean automatically if1137 the option string contains a slash to mark two options.1138 :param multiple: if this is set to True then the argument is accepted1139 multiple times and recorded. This is similar to nargs1140 in how it works but supports arbitrary number of1141 arguments.1142 :param allow_from_autoenv: if this is enabled then the value of this1143 parameter will be pulled from an environment1144 variable in case a prefix is defined on the1145 context.1146 """1147 param_type_name = 'option'11481149 def __init__(self, param_decls=None, show_default=None,1150 prompt=False, confirmation_prompt=False,1151 hide_input=False, is_flag=None, flag_value=None,1152 multiple=False, allow_from_autoenv=True, type=None,1153 **attrs):1154 Parameter.__init__(self, param_decls, type=type, **attrs)1155 if prompt is True:1156 prompt = self.name.replace('_', ' ').capitalize()1157 elif prompt is False:1158 prompt = None1159 self.prompt = prompt1160 self.confirmation_prompt = confirmation_prompt1161 self.hide_input = hide_input11621163 if is_flag is None:1164 if flag_value is not None:1165 is_flag = True1166 else:1167 is_flag = bool(self.secondary_opts)11681169 if is_flag and self.default is None:1170 self.default = False1171 if show_default is None:1172 show_default = False11731174 if flag_value is None:1175 flag_value = not self.default11761177 self.show_default = show_default1178 self.is_flag = is_flag1179 self.flag_value = flag_value1180 self.multiple = multiple11811182 if self.is_flag and isinstance(self.flag_value, bool) \1183 and type is None:1184 self.type = BoolParamType()1185 self.is_bool_flag = True1186 else:1187 self.is_bool_flag = False11881189 self.allow_from_autoenv = allow_from_autoenv11901191 # Sanity check for stuff we don't support1192 if __debug__:1193 if self.prompt and self.is_flag and not self.is_bool_flag:1194 raise TypeError('Cannot prompt for flags that are not bools.')1195 if not self.is_bool_flag and self.secondary_opts:1196 raise TypeError('Got secondary option for non boolean flag.')1197 if self.is_bool_flag and self.hide_input \1198 and self.prompt is not None:1199 raise TypeError('Hidden input does not work with boolean '1200 'flag prompts.')12011202 def _parse_decls(self, decls):1203 opts = []1204 secondary_opts = []1205 name = None1206 possible_names = []12071208 for decl in decls:1209 if not decl.startswith('-'):1210 if name is not None:1211 raise TypeError('Name defined twice')1212 name = decl1213 else:1214 if '/' in decl:1215 first, second = decl.split('/', 1)1216 possible_names.append(first.lstrip('-'))1217 opts.append(first)1218 secondary_opts.append(second)1219 else:1220 possible_names.append(decl.lstrip('-'))1221 opts.append(decl)12221223 if name is None and possible_names:1224 possible_names.sort(key=len)1225 name = possible_names[-1]12261227 if name is None:1228 raise TypeError('Could not determine name for option')12291230 return name.replace('-', '_'), opts, secondary_opts12311232 def _add_to_parser(self, parser, ctx):1233 help = self.help1234 extra = []1235 if self.default is not None and self.show_default:1236 extra.append('default: %s' % self.default)1237 if self.required:1238 extra.append('required')1239 if self.nargs != 1:1240 extra.append('%d arguments' % self.nargs)1241 if extra:1242 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))12431244 kwargs = {1245 'help': help,1246 'dest': self.name,1247 'nargs': self.nargs,1248 'metavar': self.make_metavar(),1249 }12501251 action = self.multiple and 'append' or 'store'12521253 if self.is_flag:1254 kwargs.pop('nargs', None)1255 if self.is_bool_flag and self.secondary_opts:1256 pos_opt = optparse.Option(*self.opts, action=action + '_true',1257 **kwargs)1258 kwargs.pop('default', None)1259 kwargs.pop('help', None)1260 neg_opt = optparse.Option(*self.secondary_opts,1261 action=action + '_false',1262 help=optparse.SUPPRESS_HELP,1263 **kwargs)1264 pos_opt._negative_version = neg_opt1265 parser.add_option(pos_opt)1266 parser.add_option(neg_opt)1267 else:1268 parser.add_option(*self.opts, action=action + '_const',1269 const=self.flag_value,1270 **kwargs)1271 else:1272 kwargs['action'] = action1273 parser.add_option(*self.opts, **kwargs)12741275 def get_default(self, ctx):1276 # If we're a non boolean flag out default is more complex because1277 # we need to look at all flags in the same group to figure out1278 # if we're the the default one in which case we return the flag1279 # value as default.1280 if self.is_flag and not self.is_bool_flag:1281 for param in ctx.command.params:1282 if param.name == self.name and param.default:1283 return param.flag_value1284 return None1285 return Parameter.get_default(self, ctx)12861287 def prompt_for_value(self, ctx):1288 """This is an alternative flow that can be activated in the full1289 value processing if a value does not exist. It will prompt the1290 user until a valid value exists and then returns the processed1291 value as result.1292 """1293 # Calculate the default before prompting anything to be stable.1294 default = self.get_default(ctx)12951296 # If this is a prompt for a flag we need to handle this1297 # differently.1298 if self.is_bool_flag:1299 return confirm(self.prompt, default)13001301 return prompt(self.prompt, default=default,1302 hide_input=self.hide_input,1303 confirmation_prompt=self.confirmation_prompt,1304 value_proc=lambda x: self.process_value(ctx, x))13051306 def value_from_envvar(self, ctx):1307 rv = Parameter.value_from_envvar(self, ctx)1308 if rv is not None:1309 return rv1310 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1311 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1312 return os.environ.get(envvar)13131314 def full_process_value(self, ctx, value):1315 if value is None and self.prompt is not None:1316 return self.prompt_for_value(ctx)1317 return Parameter.full_process_value(self, ctx, value)13181319 def consume_value(self, ctx, opts, args):1320 value = opts.get(self.name)1321 if value is None:1322 value = self.value_from_envvar(ctx)1323 return value, args132413251326class Argument(Parameter):1327 param_type_name = 'argument'13281329 def __init__(self, param_decls, required=True, **attrs):1330 Parameter.__init__(self, param_decls, required=required, **attrs)13311332 def make_metavar(self):1333 if self.metavar is not None:1334 return self.metavar1335 var = self.name.upper()1336 if not self.required:1337 var = '[%s]' % var1338 if self.nargs != 1:1339 var += '...'1340 return var13411342 def _parse_decls(self, decls):1343 if not decls:1344 raise TypeError('Could not determine name for argument')1345 if len(decls) == 1:1346 name = arg = decls[0]1347 elif len(decls) == 2:1348 name, arg = decls1349 else:1350 raise TypeError('Arguments take exactly one or two '1351 'parameter declarations, got %d' % len(decls))1352 return name.replace('-', '_'), [arg], []13531354 def _add_to_parser(self, parser, ctx):1355 parser.usage += ' ' + self.make_metavar()13561357 def consume_value(self, ctx, opts, args):1358 found = True1359 if self.nargs == 1:1360 try:1361 value = args.pop(0)1362 except IndexError:1363 found = False1364 elif self.nargs < 0:1365 value = tuple(args)1366 found = value1367 args = []1368 else:1369 values = args[:self.nargs]1370 args = args[self.nargs:]1371 value = tuple(values)1372 found = value1373 if not found:1374 value = self.value_from_envvar(ctx)1375 if self.nargs != 1:1376 value = value and (value,) or ()1377 return value, args137813791380def _make_command(f, name, attrs, cls):1381 if isinstance(f, Command):1382 raise TypeError('Attempted to convert a callback into a '1383 'command twice.')1384 try:1385 params = f.__click_params__1386 params.reverse()1387 del f.__click_params__1388 except AttributeError:1389 params = []1390 help = inspect.getdoc(f)1391 if isinstance(help, bytes):1392 help = help.decode('utf-8')1393 attrs.setdefault('help', help)1394 return cls(name=name or f.__name__.lower(),1395 callback=f, params=params, **attrs)139613971398def command(name=None, cls=None, **attrs):1399 """Creates a new :class:`Command` and uses the decorated function as1400 callback. This will also automatically attach all decorated1401 :func:`option`\s and :func:`argument`\s as paramters to the command.14021403 The name of the command defaults to the name of the function. If you1404 want to change that, you can pass the intended name as the first1405 argument.14061407 All keyword arguments are forwarded to the underlying command class.14081409 Once decorated the function turns into a :class:`Command` instance1410 that can be invoked as a command line utility or be attached to a1411 command :class:`Group`.14121413 :param name: the name of the command. This defaults to the function1414 name.1415 :param cls: the command class to instanciate. This defaults to1416 :class:`Command`.1417 """1418 if cls is None:1419 cls = Command1420 def decorator(f):1421 return _make_command(f, name, attrs, cls)1422 return decorator142314241425def group(name=None, **attrs):1426 """Creates a new :class:`Group` with a function as callback. This1427 works otherwise the same as :func:`command` just that the `cls`1428 parameter is set to :class:`Group`.1429 """1430 return command(name, cls=Group, **attrs)143114321433def _param_memo(f, param):1434 if isinstance(f, Command):1435 f.params.append(param)1436 else:1437 if not hasattr(f, '__click_params__'):1438 f.__click_params__ = []1439 f.__click_params__.append(param)144014411442def argument(*param_decls, **attrs):1443 """Attaches an option to the command. All positional arguments are1444 passed as parameter declarations to :class:`Argment`, all keyword1445 arguments are forwarded unchanged. This is equivalent to creating an1446 :class:`Option` instance manually and attaching it to the1447 :attr:`Command.params` list.1448 """1449 def decorator(f):1450 _param_memo(f, Argument(param_decls, **attrs))1451 return f1452 return decorator145314541455def option(*param_decls, **attrs):1456 """Attaches an option to the command. All positional arguments are1457 passed as parameter declarations to :class:`Option`, all keyword1458 arguments are forwarded unchanged. This is equivalent to creating an1459 :class:`Option` instance manually and attaching it to the1460 :attr:`Command.params` list.1461 """1462 def decorator(f):1463 _param_memo(f, Option(param_decls, **attrs))1464 return f1465 return decorator146614671468def confirmation_option(*param_decls, **attrs):1469 """Shortcut for confirmation prompts that can be ignored by bypassed1470 ``--yes`` as parameter.14711472 This is equivalent to decorating a function with :func:`option` with1473 the following parameters::14741475 def callback(ctx, value):1476 if not value:1477 ctx.abort()14781479 @click.command()1480 @click.option('--yes', is_flag=True, callback=callback,1481 expose_value=False, prompt='Do you want to continue?')1482 def dropdb():1483 pass1484 """1485 def decorator(f):1486 def callback(ctx, value):1487 if not value:1488 ctx.abort()1489 attrs.setdefault('is_flag', True)1490 attrs.setdefault('callback', callback)1491 attrs.setdefault('expose_value', False)1492 attrs.setdefault('prompt', 'Do you want to continue?')1493 return option(*(param_decls or ('--yes',)), **attrs)(f)1494 return decorator149514961497def password_option(*param_decls, **attrs):1498 """Shortcut for password prompts.14991500 This is equivalent to decorating a function with :func:`option` with1501 the following parameters::15021503 @click.command()1504 @click.option('--password', prompt=True, confirmation_prompt=True,1505 hide_input=True)1506 def changeadmin(password):1507 pass1508 """1509 def decorator(f):1510 attrs.setdefault('prompt', True)1511 attrs.setdefault('confirmation_prompt', True)1512 attrs.setdefault('hide_input', True)1513 return option(*(param_decls or ('--password',)), **attrs)(f)1514 return decorator151515161517def version_option(version, *param_decls, **attrs):1518 """Adds a ``--version`` option which immediately ends the program1519 printing out the version number. This is implemented as an eager1520 option that prints the version and exits the program in the callback.15211522 :param version: the version number to show1523 :param prog_name: the name of the program (defaults to autodetection)1524 :param message: custom message to show instead of the default1525 (``'%(prog)s, version %(version)s'``)1526 :param others: everything else is forwarded to :func:`option`.1527 """1528 def decorator(f):1529 prog_name = attrs.pop('prog_name', None)1530 message = attrs.pop('message', '%(prog)s, version %(version)s')15311532 def callback(ctx, value):1533 if not value:1534 return1535 prog = prog_name1536 if prog is None:1537 prog = ctx.find_root().info_name1538 echo(message % {1539 'prog': prog,1540 'version': version,1541 })1542 ctx.exit()15431544 attrs.setdefault('is_flag', True)1545 attrs.setdefault('expose_value', False)1546 attrs.setdefault('is_eager', True)1547 attrs.setdefault('help', 'Show the version and exit.')1548 attrs['callback'] = callback1549 return option(*(param_decls or ('--version',)), **attrs)(f)1550 return decorator155115521553def help_option(*param_decls, **attrs):1554 """Adds a ``--help`` option which immediately ends the program1555 printing out the help page. This is usually unnecessary to add as1556 this is added by default to all commands unless supressed.15571558 Like :func:`version_option` this is implemented as eager option that1559 prints in the callback and exits.15601561 All arguments are forwarded to :func:`option`.1562 """1563 def decorator(f):1564 def callback(ctx, value):1565 if value:1566 echo(ctx.format_help())1567 ctx.exit()1568 attrs.setdefault('is_flag', True)1569 attrs.setdefault('expose_value', False)1570 attrs.setdefault('help', 'Show this message and exit.')1571 attrs.setdefault('is_eager', True)1572 attrs['callback'] = callback1573 return option(*(param_decls or ('--help',)), **attrs)(f)1574 return decorator157515761577def confirm(text, default=False, abort=False):1578 """Prompts for confirmation (yes/no question).15791580 If the user aborts the input by sending a interrupt signal this1581 function will catch it and raise a :exc:`Abort` exception.15821583 :param text: the question to ask.1584 :param default: the default for the prompt.1585 :param abort: if this is set to `True` a negative answer aborts the1586 exception by raising :exc:`Abort`.1587 """1588 prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')1589 while 1:1590 try:1591 value = visible_prompt_func(prompt).lower().strip()1592 except (KeyboardInterrupt, EOFError):1593 raise Abort()1594 if value in ('y', 'yes'):1595 rv = True1596 elif value in ('n', 'no'):1597 rv = False1598 elif value == '':1599 rv = default1600 else:1601 echo('Error: invalid input')1602 continue1603 break1604 if abort and not rv:1605 raise Abort()1606 return rv160716081609def prompt(text, default=None, hide_input=False,1610 confirmation_prompt=False, type=None,1611 value_proc=None):1612 """Prompts a user for input. This is a convenience function that can1613 be used to prompt a user for input later.16141615 If the user aborts the input by sending a interrupt signal this1616 function will catch it and raise a :exc:`Abort` exception.16171618 :param text: the text to show for the prompt.1619 :param default: the default value to use if no input happens. If this1620 is not given it will prompt until it's aborted.1621 :param hide_input: if this is set to true then the input value will1622 be hidden.1623 :param confirmation_prompt: asks for confirmation for the value.1624 :param type: the type to use to check the value against.1625 :param value_proc: if this parameter is provided it's a function that1626 is invoked instead of the type conversion to1627 convert a value.1628 """1629 result = None16301631 def prompt_func(text):1632 f = hide_input and hidden_prompt_func or visible_prompt_func1633 try:1634 return f(text)1635 except (KeyboardInterrupt, EOFError):1636 raise Abort()16371638 if value_proc is None:1639 value_proc = convert_type(type, default)16401641 prompt = text1642 if default is not None:1643 prompt = '%s [%s]' % (prompt, default)1644 prompt += ': '16451646 while 1:1647 while 1:1648 value = prompt_func(prompt)1649 if value:1650 break1651 # If a default is set and used, then the confirmation1652 # prompt is always skipped because that's the only thing1653 # that really makes sense.1654 elif default is not None:1655 return default1656 try:1657 result = value_proc(value)1658 except UsageError as e:1659 echo('Error: %s' % e.message)1660 continue1661 if not confirmation_prompt:1662 return result1663 while 1:1664 value2 = prompt_func('Repeat for confirmation: ')1665 if value2:1666 break1667 if value == value2:1668 return result1669 echo('Error: the two entered values do not match')167016711672#: A unicode string parameter type which is the implicit default. This1673#: can also be selected by using ``str`` as type.1674STRING = StringParamType()16751676#: An integer parameter. This can also be selected by using ``int`` as1677#: type.1678INT = IntParamType()16791680#: A floating point value parameter. This can also be selected by using1681#: ``float`` as type.1682FLOAT = FloatParamType()16831684#: A boolean parameter. This is the default for boolean flags. This can1685#: also be selected by using ``bool`` as a type.1686BOOL = BoolParamType()
modified:setup.py+1 added-1 removed
5 unmodified lines
6 author='Armin Ronacher',7 author_email='armin.ronacher@active-4.com',8 version='0.1',9 url='http://github.com/mitsuhiko/click',10 py_modules=['click'],10 packages=['click'],11 description='A simple wrapper around optparse for '12 'powerful command line utilities.',13 classifiers=[14 'License :: OSI Approved :: BSD License',
4 unmodified lines