Merge pull request #1490 from pallets/style
Before adoption: this commit came in with the history the project adopted, so no landing records it.
move to src directory, add pre-commit
authored by David Lord · committed by GitHub · parents 3d1dcc2, 718485b · Browse files · 82 files·+10134 added−9485 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
82 files+10134 added−9485 removed
- tests:+1523 added−1449 removed
- other:+8611 added−8036 removed
Provenance
- Commit
38ba2e6- Tree
0fa1b49- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
3d1dcc2- Parent 2
718485b
82 files changed+10134 added−9485 removed
modified:.github/ISSUE_TEMPLATE.md+1 added-1 removed
122345627 unmodified lines**This issue tracker is a tool to address bugs in Click itself.Please use the #pocoo IRC channel on freenode, the Discord server or Please use the #pocoo IRC channel on freenode, the Discord server orStack Overflow for general questions about using Flask or issuesnot related to Click.**
If you'd like to report a bug in Click, fill out the template below. Provide27 unmodified linesdeleted:click/__init__.py-91 removed
1-# -*- coding: utf-8 -*-2-"""3-Click is a simple Python module inspired by the stdlib optparse to make4-writing command line scripts fun. Unlike other modules, it's based5-around a simple API that does not come with too much magic and is6-composable.7-"""8-9-# Core classes10-from .core import Context, BaseCommand, Command, MultiCommand, Group, \11- CommandCollection, Parameter, Option, Argument12-13-# Globals14-from .globals import get_current_context15-16-# Decorators17-from .decorators import pass_context, pass_obj, make_pass_decorator, \18- command, group, argument, option, confirmation_option, \19- password_option, version_option, help_option20-21-# Types22-from .types import ParamType, File, Path, Choice, IntRange, Tuple, \23- DateTime, STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange24-25-# Utilities26-from .utils import echo, get_binary_stream, get_text_stream, open_file, \27- format_filename, get_app_dir, get_os_args28-29-# Terminal functions30-from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \31- progressbar, clear, style, unstyle, secho, edit, launch, getchar, \32- pause33-34-# Exceptions35-from .exceptions import ClickException, UsageError, BadParameter, \36- FileError, Abort, NoSuchOption, BadOptionUsage, BadArgumentUsage, \37- MissingParameter38-39-# Formatting40-from .formatting import HelpFormatter, wrap_text41-42-# Parsing43-from .parser import OptionParser44-45-46-__all__ = [47- # Core classes48- 'Context', 'BaseCommand', 'Command', 'MultiCommand', 'Group',49- 'CommandCollection', 'Parameter', 'Option', 'Argument',50-51- # Globals52- 'get_current_context',53-54- # Decorators55- 'pass_context', 'pass_obj', 'make_pass_decorator', 'command', 'group',56- 'argument', 'option', 'confirmation_option', 'password_option',57- 'version_option', 'help_option',58-59- # Types60- 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple',61- 'DateTime', 'STRING', 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',62- 'FloatRange',63-64- # Utilities65- 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',66- 'format_filename', 'get_app_dir', 'get_os_args',67-68- # Terminal functions69- 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',70- 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit', 'launch',71- 'getchar', 'pause',72-73- # Exceptions74- 'ClickException', 'UsageError', 'BadParameter', 'FileError',75- 'Abort', 'NoSuchOption', 'BadOptionUsage', 'BadArgumentUsage',76- 'MissingParameter',77-78- # Formatting79- 'HelpFormatter', 'wrap_text',80-81- # Parsing82- 'OptionParser',83-]84-85-86-# Controls if click should emit the warning about the use of unicode87-# literals.88-disable_unicode_literals_warning = False89-90-91-__version__ = '7.1.dev'deleted:click/_bashcomplete.py-334 removed
1-import copy2-import os3-import re4-5-from .utils import echo6-from .parser import split_arg_string7-from .core import MultiCommand, Option, Argument8-from .types import Choice9-10-try:11- from collections import abc12-except ImportError:13- import collections as abc14-15-WORDBREAK = '='16-17-# Note, only BASH version 4.4 and later have the nosort option.18-COMPLETION_SCRIPT_BASH = '''19-%(complete_func)s() {20- local IFS=$'\n'21- COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\22- COMP_CWORD=$COMP_CWORD \\23- %(autocomplete_var)s=complete $1 ) )24- return 025-}26-27-%(complete_func)setup() {28- local COMPLETION_OPTIONS=""29- local BASH_VERSION_ARR=(${BASH_VERSION//./ })30- # Only BASH version 4.4 and later have the nosort option.31- if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] && [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then32- COMPLETION_OPTIONS="-o nosort"33- fi34-35- complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s36-}37-38-%(complete_func)setup39-'''40-41-COMPLETION_SCRIPT_ZSH = '''42-#compdef %(script_names)s43-44-%(complete_func)s() {45- local -a completions46- local -a completions_with_descriptions47- local -a response48- (( ! $+commands[%(script_names)s] )) && return 149-50- response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\51- COMP_CWORD=$((CURRENT-1)) \\52- %(autocomplete_var)s=\"complete_zsh\" \\53- %(script_names)s )}")54-55- for key descr in ${(kv)response}; do56- if [[ "$descr" == "_" ]]; then57- completions+=("$key")58- else59- completions_with_descriptions+=("$key":"$descr")60- fi61- done62-63- if [ -n "$completions_with_descriptions" ]; then64- _describe -V unsorted completions_with_descriptions -U65- fi66-67- if [ -n "$completions" ]; then68- compadd -U -V unsorted -a completions69- fi70- compstate[insert]="automenu"71-}72-73-compdef %(complete_func)s %(script_names)s74-'''75-76-COMPLETION_SCRIPT_FISH = '''77-complete --no-files --command %(script_names)s --arguments "(env %(autocomplete_var)s=complete_fish COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(script_names)s)"78-'''79-80-_completion_scripts = {81- "bash": COMPLETION_SCRIPT_BASH,82- "zsh": COMPLETION_SCRIPT_ZSH,83- "fish": COMPLETION_SCRIPT_FISH,84-}85-86-_invalid_ident_char_re = re.compile(r'[^a-zA-Z0-9_]')87-88-89-def get_completion_script(prog_name, complete_var, shell):90- cf_name = _invalid_ident_char_re.sub('', prog_name.replace('-', '_'))91- script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)92- return (script % {93- 'complete_func': '_%s_completion' % cf_name,94- 'script_names': prog_name,95- 'autocomplete_var': complete_var,96- }).strip() + ';'97-98-99-def resolve_ctx(cli, prog_name, args):100- """101- Parse into a hierarchy of contexts. Contexts are connected through the parent variable.102- :param cli: command definition103- :param prog_name: the program that is running104- :param args: full list of args105- :return: the final context/command parsed106- """107- ctx = cli.make_context(prog_name, args, resilient_parsing=True)108- args = ctx.protected_args + ctx.args109- while args:110- if isinstance(ctx.command, MultiCommand):111- if not ctx.command.chain:112- cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)113- if cmd is None:114- return ctx115- ctx = cmd.make_context(cmd_name, args, parent=ctx,116- resilient_parsing=True)117- args = ctx.protected_args + ctx.args118- else:119- # Walk chained subcommand contexts saving the last one.120- while args:121- cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)122- if cmd is None:123- return ctx124- sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,125- allow_extra_args=True,126- allow_interspersed_args=False,127- resilient_parsing=True)128- args = sub_ctx.args129- ctx = sub_ctx130- args = sub_ctx.protected_args + sub_ctx.args131- else:132- break133- return ctx134-135-136-def start_of_option(param_str):137- """138- :param param_str: param_str to check139- :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")140- """141- return param_str and param_str[:1] == '-'142-143-144-def is_incomplete_option(all_args, cmd_param):145- """146- :param all_args: the full original list of args supplied147- :param cmd_param: the current command paramter148- :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and149- corresponds to this cmd_param. In other words whether this cmd_param option can still accept150- values151- """152- if not isinstance(cmd_param, Option):153- return False154- if cmd_param.is_flag:155- return False156- last_option = None157- for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):158- if index + 1 > cmd_param.nargs:159- break160- if start_of_option(arg_str):161- last_option = arg_str162-163- return True if last_option and last_option in cmd_param.opts else False164-165-166-def is_incomplete_argument(current_params, cmd_param):167- """168- :param current_params: the current params and values for this argument as already entered169- :param cmd_param: the current command parameter170- :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In171- other words whether or not the this cmd_param argument can still accept values172- """173- if not isinstance(cmd_param, Argument):174- return False175- current_param_values = current_params[cmd_param.name]176- if current_param_values is None:177- return True178- if cmd_param.nargs == -1:179- return True180- if isinstance(current_param_values, abc.Iterable) \181- and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:182- return True183- return False184-185-186-def get_user_autocompletions(ctx, args, incomplete, cmd_param):187- """188- :param ctx: context associated with the parsed command189- :param args: full list of args190- :param incomplete: the incomplete text to autocomplete191- :param cmd_param: command definition192- :return: all the possible user-specified completions for the param193- """194- results = []195- if isinstance(cmd_param.type, Choice):196- # Choices don't support descriptions.197- results = [(c, None)198- for c in cmd_param.type.choices if str(c).startswith(incomplete)]199- elif cmd_param.autocompletion is not None:200- dynamic_completions = cmd_param.autocompletion(ctx=ctx,201- args=args,202- incomplete=incomplete)203- results = [c if isinstance(c, tuple) else (c, None)204- for c in dynamic_completions]205- return results206-207-208-def get_visible_commands_starting_with(ctx, starts_with):209- """210- :param ctx: context associated with the parsed command211- :starts_with: string that visible commands must start with.212- :return: all visible (not hidden) commands that start with starts_with.213- """214- for c in ctx.command.list_commands(ctx):215- if c.startswith(starts_with):216- command = ctx.command.get_command(ctx, c)217- if not command.hidden:218- yield command219-220-221-def add_subcommand_completions(ctx, incomplete, completions_out):222- # Add subcommand completions.223- if isinstance(ctx.command, MultiCommand):224- completions_out.extend(225- [(c.name, c.get_short_help_str()) for c in get_visible_commands_starting_with(ctx, incomplete)])226-227- # Walk up the context list and add any other completion possibilities from chained commands228- while ctx.parent is not None:229- ctx = ctx.parent230- if isinstance(ctx.command, MultiCommand) and ctx.command.chain:231- remaining_commands = [c for c in get_visible_commands_starting_with(ctx, incomplete)232- if c.name not in ctx.protected_args]233- completions_out.extend([(c.name, c.get_short_help_str()) for c in remaining_commands])234-235-236-def get_choices(cli, prog_name, args, incomplete):237- """238- :param cli: command definition239- :param prog_name: the program that is running240- :param args: full list of args241- :param incomplete: the incomplete text to autocomplete242- :return: all the possible completions for the incomplete243- """244- all_args = copy.deepcopy(args)245-246- ctx = resolve_ctx(cli, prog_name, args)247- if ctx is None:248- return []249-250- has_double_dash = "--" in all_args251-252- # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse253- # without the '='254- if start_of_option(incomplete) and WORDBREAK in incomplete:255- partition_incomplete = incomplete.partition(WORDBREAK)256- all_args.append(partition_incomplete[0])257- incomplete = partition_incomplete[2]258- elif incomplete == WORDBREAK:259- incomplete = ''260-261- completions = []262- if not has_double_dash and start_of_option(incomplete):263- # completions for partial options264- for param in ctx.command.params:265- if isinstance(param, Option) and not param.hidden:266- param_opts = [param_opt for param_opt in param.opts +267- param.secondary_opts if param_opt not in all_args or param.multiple]268- completions.extend([(o, param.help) for o in param_opts if o.startswith(incomplete)])269- return completions270- # completion for option values from user supplied values271- for param in ctx.command.params:272- if is_incomplete_option(all_args, param):273- return get_user_autocompletions(ctx, all_args, incomplete, param)274- # completion for argument values from user supplied values275- for param in ctx.command.params:276- if is_incomplete_argument(ctx.params, param):277- return get_user_autocompletions(ctx, all_args, incomplete, param)278-279- add_subcommand_completions(ctx, incomplete, completions)280- # Sort before returning so that proper ordering can be enforced in custom types.281- return sorted(completions)282-283-284-def do_complete(cli, prog_name, include_descriptions):285- cwords = split_arg_string(os.environ['COMP_WORDS'])286- cword = int(os.environ['COMP_CWORD'])287- args = cwords[1:cword]288- try:289- incomplete = cwords[cword]290- except IndexError:291- incomplete = ''292-293- for item in get_choices(cli, prog_name, args, incomplete):294- echo(item[0])295- if include_descriptions:296- # ZSH has trouble dealing with empty array parameters when297- # returned from commands, use '_' to indicate no description298- # is present.299- echo(item[1] if item[1] else '_')300-301- return True302-303-304-def do_complete_fish(cli, prog_name):305- cwords = split_arg_string(os.environ["COMP_WORDS"])306- incomplete = os.environ["COMP_CWORD"]307- args = cwords[1:]308-309- for item in get_choices(cli, prog_name, args, incomplete):310- if item[1]:311- echo("%(arg)s\t%(desc)s" % {"arg": item[0], "desc": item[1]})312- else:313- echo(item[0])314-315- return True316-317-318-def bashcomplete(cli, prog_name, complete_var, complete_instr):319- if "_" in complete_instr:320- command, shell = complete_instr.split("_", 1)321- else:322- command = complete_instr323- shell = "bash"324-325- if command == "source":326- echo(get_completion_script(prog_name, complete_var, shell))327- return True328- elif command == "complete":329- if shell == "fish":330- return do_complete_fish(cli, prog_name)331- elif shell in {"bash", "zsh"}:332- return do_complete(cli, prog_name, shell == "zsh")333-334- return Falsedeleted:click/_compat.py-774 removed
1-import re2-import io3-import os4-import sys5-import codecs6-from weakref import WeakKeyDictionary7-8-9-PY2 = sys.version_info[0] == 210-CYGWIN = sys.platform.startswith('cygwin')11-MSYS2 = sys.platform.startswith('win') and ('GCC' in sys.version)12-# Determine local App Engine environment, per Google's own suggestion13-APP_ENGINE = ('APPENGINE_RUNTIME' in os.environ and14- 'Development/' in os.environ.get('SERVER_SOFTWARE', ''))15-WIN = sys.platform.startswith('win') and not APP_ENGINE and not MSYS216-DEFAULT_COLUMNS = 8017-18-19-_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")20-21-22-def get_filesystem_encoding():23- return sys.getfilesystemencoding() or sys.getdefaultencoding()24-25-26-def _make_text_stream(stream, encoding, errors,27- force_readable=False, force_writable=False):28- if encoding is None:29- encoding = get_best_encoding(stream)30- if errors is None:31- errors = 'replace'32- return _NonClosingTextIOWrapper(stream, encoding, errors,33- line_buffering=True,34- force_readable=force_readable,35- force_writable=force_writable)36-37-38-def is_ascii_encoding(encoding):39- """Checks if a given encoding is ascii."""40- try:41- return codecs.lookup(encoding).name == 'ascii'42- except LookupError:43- return False44-45-46-def get_best_encoding(stream):47- """Returns the default stream encoding if not found."""48- rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()49- if is_ascii_encoding(rv):50- return 'utf-8'51- return rv52-53-54-class _NonClosingTextIOWrapper(io.TextIOWrapper):55-56- def __init__(self, stream, encoding, errors,57- force_readable=False, force_writable=False, **extra):58- self._stream = stream = _FixupStream(stream, force_readable,59- force_writable)60- io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)61-62- # The io module is a place where the Python 3 text behavior63- # was forced upon Python 2, so we need to unbreak64- # it to look like Python 2.65- if PY2:66- def write(self, x):67- if isinstance(x, str) or is_bytes(x):68- try:69- self.flush()70- except Exception:71- pass72- return self.buffer.write(str(x))73- return io.TextIOWrapper.write(self, x)74-75- def writelines(self, lines):76- for line in lines:77- self.write(line)78-79- def __del__(self):80- try:81- self.detach()82- except Exception:83- pass84-85- def isatty(self):86- # https://bitbucket.org/pypy/pypy/issue/180387- return self._stream.isatty()88-89-90-class _FixupStream(object):91- """The new io interface needs more from streams than streams92- traditionally implement. As such, this fix-up code is necessary in93- some circumstances.94-95- The forcing of readable and writable flags are there because some tools96- put badly patched objects on sys (one such offender are certain version97- of jupyter notebook).98- """99-100- def __init__(self, stream, force_readable=False, force_writable=False):101- self._stream = stream102- self._force_readable = force_readable103- self._force_writable = force_writable104-105- def __getattr__(self, name):106- return getattr(self._stream, name)107-108- def read1(self, size):109- f = getattr(self._stream, 'read1', None)110- if f is not None:111- return f(size)112- # We only dispatch to readline instead of read in Python 2 as we113- # do not want cause problems with the different implementation114- # of line buffering.115- if PY2:116- return self._stream.readline(size)117- return self._stream.read(size)118-119- def readable(self):120- if self._force_readable:121- return True122- x = getattr(self._stream, 'readable', None)123- if x is not None:124- return x()125- try:126- self._stream.read(0)127- except Exception:128- return False129- return True130-131- def writable(self):132- if self._force_writable:133- return True134- x = getattr(self._stream, 'writable', None)135- if x is not None:136- return x()137- try:138- self._stream.write('')139- except Exception:140- try:141- self._stream.write(b'')142- except Exception:143- return False144- return True145-146- def seekable(self):147- x = getattr(self._stream, 'seekable', None)148- if x is not None:149- return x()150- try:151- self._stream.seek(self._stream.tell())152- except Exception:153- return False154- return True155-156-157-if PY2:158- text_type = unicode159- raw_input = raw_input160- string_types = (str, unicode)161- int_types = (int, long)162- iteritems = lambda x: x.iteritems()163- range_type = xrange164-165- from pipes import quote as shlex_quote166-167- def is_bytes(x):168- return isinstance(x, (buffer, bytearray))169-170- _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')171-172- # For Windows, we need to force stdout/stdin/stderr to binary if it's173- # fetched for that. This obviously is not the most correct way to do174- # it as it changes global state. Unfortunately, there does not seem to175- # be a clear better way to do it as just reopening the file in binary176- # mode does not change anything.177- #178- # An option would be to do what Python 3 does and to open the file as179- # binary only, patch it back to the system, and then use a wrapper180- # stream that converts newlines. It's not quite clear what's the181- # correct option here.182- #183- # This code also lives in _winconsole for the fallback to the console184- # emulation stream.185- #186- # There are also Windows environments where the `msvcrt` module is not187- # available (which is why we use try-catch instead of the WIN variable188- # here), such as the Google App Engine development server on Windows. In189- # those cases there is just nothing we can do.190- def set_binary_mode(f):191- return f192-193- try:194- import msvcrt195- except ImportError:196- pass197- else:198- def set_binary_mode(f):199- try:200- fileno = f.fileno()201- except Exception:202- pass203- else:204- msvcrt.setmode(fileno, os.O_BINARY)205- return f206-207- try:208- import fcntl209- except ImportError:210- pass211- else:212- def set_binary_mode(f):213- try:214- fileno = f.fileno()215- except Exception:216- pass217- else:218- flags = fcntl.fcntl(fileno, fcntl.F_GETFL)219- fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)220- return f221-222- def isidentifier(x):223- return _identifier_re.search(x) is not None224-225- def get_binary_stdin():226- return set_binary_mode(sys.stdin)227-228- def get_binary_stdout():229- _wrap_std_stream('stdout')230- return set_binary_mode(sys.stdout)231-232- def get_binary_stderr():233- _wrap_std_stream('stderr')234- return set_binary_mode(sys.stderr)235-236- def get_text_stdin(encoding=None, errors=None):237- rv = _get_windows_console_stream(sys.stdin, encoding, errors)238- if rv is not None:239- return rv240- return _make_text_stream(sys.stdin, encoding, errors,241- force_readable=True)242-243- def get_text_stdout(encoding=None, errors=None):244- _wrap_std_stream('stdout')245- rv = _get_windows_console_stream(sys.stdout, encoding, errors)246- if rv is not None:247- return rv248- return _make_text_stream(sys.stdout, encoding, errors,249- force_writable=True)250-251- def get_text_stderr(encoding=None, errors=None):252- _wrap_std_stream('stderr')253- rv = _get_windows_console_stream(sys.stderr, encoding, errors)254- if rv is not None:255- return rv256- return _make_text_stream(sys.stderr, encoding, errors,257- force_writable=True)258-259- def filename_to_ui(value):260- if isinstance(value, bytes):261- value = value.decode(get_filesystem_encoding(), 'replace')262- return value263-else:264- import io265- text_type = str266- raw_input = input267- string_types = (str,)268- int_types = (int,)269- range_type = range270- isidentifier = lambda x: x.isidentifier()271- iteritems = lambda x: iter(x.items())272-273- from shlex import quote as shlex_quote274-275- def is_bytes(x):276- return isinstance(x, (bytes, memoryview, bytearray))277-278- def _is_binary_reader(stream, default=False):279- try:280- return isinstance(stream.read(0), bytes)281- except Exception:282- return default283- # This happens in some cases where the stream was already284- # closed. In this case, we assume the default.285-286- def _is_binary_writer(stream, default=False):287- try:288- stream.write(b'')289- except Exception:290- try:291- stream.write('')292- return False293- except Exception:294- pass295- return default296- return True297-298- def _find_binary_reader(stream):299- # We need to figure out if the given stream is already binary.300- # This can happen because the official docs recommend detaching301- # the streams to get binary streams. Some code might do this, so302- # we need to deal with this case explicitly.303- if _is_binary_reader(stream, False):304- return stream305-306- buf = getattr(stream, 'buffer', None)307-308- # Same situation here; this time we assume that the buffer is309- # actually binary in case it's closed.310- if buf is not None and _is_binary_reader(buf, True):311- return buf312-313- def _find_binary_writer(stream):314- # We need to figure out if the given stream is already binary.315- # This can happen because the official docs recommend detatching316- # the streams to get binary streams. Some code might do this, so317- # we need to deal with this case explicitly.318- if _is_binary_writer(stream, False):319- return stream320-321- buf = getattr(stream, 'buffer', None)322-323- # Same situation here; this time we assume that the buffer is324- # actually binary in case it's closed.325- if buf is not None and _is_binary_writer(buf, True):326- return buf327-328- def _stream_is_misconfigured(stream):329- """A stream is misconfigured if its encoding is ASCII."""330- # If the stream does not have an encoding set, we assume it's set331- # to ASCII. This appears to happen in certain unittest332- # environments. It's not quite clear what the correct behavior is333- # but this at least will force Click to recover somehow.334- return is_ascii_encoding(getattr(stream, 'encoding', None) or 'ascii')335-336- def _is_compat_stream_attr(stream, attr, value):337- """A stream attribute is compatible if it is equal to the338- desired value or the desired value is unset and the attribute339- has a value.340- """341- stream_value = getattr(stream, attr, None)342- return stream_value == value or (value is None and stream_value is not None)343-344- def _is_compatible_text_stream(stream, encoding, errors):345- """Check if a stream's encoding and errors attributes are346- compatible with the desired values.347- """348- return (349- _is_compat_stream_attr(stream, "encoding", encoding)350- and _is_compat_stream_attr(stream, "errors", errors)351- )352-353- def _force_correct_text_stream(354- text_stream,355- encoding,356- errors,357- is_binary,358- find_binary,359- force_readable=False,360- force_writable=False,361- ):362- if is_binary(text_stream, False):363- binary_reader = text_stream364- else:365- # If the stream looks compatible, and won't default to a366- # misconfigured ascii encoding, return it as-is.367- if (368- _is_compatible_text_stream(text_stream, encoding, errors)369- and not (370- encoding is None371- and _stream_is_misconfigured(text_stream)372- )373- ):374- return text_stream375-376- # Otherwise, get the underlying binary reader.377- binary_reader = find_binary(text_stream)378-379- # If that's not possible, silently use the original reader380- # and get mojibake instead of exceptions.381- if binary_reader is None:382- return text_stream383-384- # Default errors to replace instead of strict in order to get385- # something that works.386- if errors is None:387- errors = "replace"388-389- # Wrap the binary stream in a text stream with the correct390- # encoding parameters.391- return _make_text_stream(392- binary_reader,393- encoding,394- errors,395- force_readable=force_readable,396- force_writable=force_writable,397- )398-399- def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):400- return _force_correct_text_stream(401- text_reader,402- encoding,403- errors,404- _is_binary_reader,405- _find_binary_reader,406- force_readable=force_readable,407- )408-409- def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):410- return _force_correct_text_stream(411- text_writer,412- encoding,413- errors,414- _is_binary_writer,415- _find_binary_writer,416- force_writable=force_writable,417- )418-419- def get_binary_stdin():420- reader = _find_binary_reader(sys.stdin)421- if reader is None:422- raise RuntimeError('Was not able to determine binary '423- 'stream for sys.stdin.')424- return reader425-426- def get_binary_stdout():427- writer = _find_binary_writer(sys.stdout)428- if writer is None:429- raise RuntimeError('Was not able to determine binary '430- 'stream for sys.stdout.')431- return writer432-433- def get_binary_stderr():434- writer = _find_binary_writer(sys.stderr)435- if writer is None:436- raise RuntimeError('Was not able to determine binary '437- 'stream for sys.stderr.')438- return writer439-440- def get_text_stdin(encoding=None, errors=None):441- rv = _get_windows_console_stream(sys.stdin, encoding, errors)442- if rv is not None:443- return rv444- return _force_correct_text_reader(sys.stdin, encoding, errors,445- force_readable=True)446-447- def get_text_stdout(encoding=None, errors=None):448- rv = _get_windows_console_stream(sys.stdout, encoding, errors)449- if rv is not None:450- return rv451- return _force_correct_text_writer(sys.stdout, encoding, errors,452- force_writable=True)453-454- def get_text_stderr(encoding=None, errors=None):455- rv = _get_windows_console_stream(sys.stderr, encoding, errors)456- if rv is not None:457- return rv458- return _force_correct_text_writer(sys.stderr, encoding, errors,459- force_writable=True)460-461- def filename_to_ui(value):462- if isinstance(value, bytes):463- value = value.decode(get_filesystem_encoding(), 'replace')464- else:465- value = value.encode('utf-8', 'surrogateescape') \466- .decode('utf-8', 'replace')467- return value468-469-470-def get_streerror(e, default=None):471- if hasattr(e, 'strerror'):472- msg = e.strerror473- else:474- if default is not None:475- msg = default476- else:477- msg = str(e)478- if isinstance(msg, bytes):479- msg = msg.decode('utf-8', 'replace')480- return msg481-482-483-def _wrap_io_open(file, mode, encoding, errors):484- """On Python 2, :func:`io.open` returns a text file wrapper that485- requires passing ``unicode`` to ``write``. Need to open the file in486- binary mode then wrap it in a subclass that can write ``str`` and487- ``unicode``.488-489- Also handles not passing ``encoding`` and ``errors`` in binary mode.490- """491- binary = "b" in mode492-493- if binary:494- kwargs = {}495- else:496- kwargs = {"encoding": encoding, "errors": errors}497-498- if not PY2 or binary:499- return io.open(file, mode, **kwargs)500-501- f = io.open(file, "b" + mode.replace("t", ""))502- return _make_text_stream(f, **kwargs)503-504-505-def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):506- binary = "b" in mode507-508- # Standard streams first. These are simple because they don't need509- # special handling for the atomic flag. It's entirely ignored.510- if filename == '-':511- if any(m in mode for m in ['w', 'a', 'x']):512- if binary:513- return get_binary_stdout(), False514- return get_text_stdout(encoding=encoding, errors=errors), False515- if binary:516- return get_binary_stdin(), False517- return get_text_stdin(encoding=encoding, errors=errors), False518-519- # Non-atomic writes directly go out through the regular open functions.520- if not atomic:521- return _wrap_io_open(filename, mode, encoding, errors), True522-523- # Some usability stuff for atomic writes524- if 'a' in mode:525- raise ValueError(526- 'Appending to an existing file is not supported, because that '527- 'would involve an expensive `copy`-operation to a temporary '528- 'file. Open the file in normal `w`-mode and copy explicitly '529- 'if that\'s what you\'re after.'530- )531- if 'x' in mode:532- raise ValueError('Use the `overwrite`-parameter instead.')533- if 'w' not in mode:534- raise ValueError('Atomic writes only make sense with `w`-mode.')535-536- # Atomic writes are more complicated. They work by opening a file537- # as a proxy in the same folder and then using the fdopen538- # functionality to wrap it in a Python file. Then we wrap it in an539- # atomic file that moves the file over on close.540- import errno541- import random542-543- try:544- perm = os.stat(filename).st_mode545- except OSError:546- perm = None547-548- flags = os.O_RDWR | os.O_CREAT | os.O_EXCL549-550- if binary:551- flags |= getattr(os, 'O_BINARY', 0)552-553- while True:554- tmp_filename = os.path.join(555- os.path.dirname(filename),556- '.__atomic-write%08x' % (random.randrange(1 << 32),),557- )558- try:559- fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)560- break561- except OSError as e:562- if e.errno == errno.EEXIST or (563- os.name == "nt"564- and e.errno == errno.EACCES565- and os.path.isdir(e.filename)566- and os.access(e.filename, os.W_OK)567- ):568- continue569- raise570-571- if perm is not None:572- os.chmod(tmp_filename, perm) # in case perm includes bits in umask573-574- f = _wrap_io_open(fd, mode, encoding, errors)575- return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True576-577-578-# Used in a destructor call, needs extra protection from interpreter cleanup.579-if hasattr(os, 'replace'):580- _replace = os.replace581- _can_replace = True582-else:583- _replace = os.rename584- _can_replace = not WIN585-586-587-class _AtomicFile(object):588-589- def __init__(self, f, tmp_filename, real_filename):590- self._f = f591- self._tmp_filename = tmp_filename592- self._real_filename = real_filename593- self.closed = False594-595- @property596- def name(self):597- return self._real_filename598-599- def close(self, delete=False):600- if self.closed:601- return602- self._f.close()603- if not _can_replace:604- try:605- os.remove(self._real_filename)606- except OSError:607- pass608- _replace(self._tmp_filename, self._real_filename)609- self.closed = True610-611- def __getattr__(self, name):612- return getattr(self._f, name)613-614- def __enter__(self):615- return self616-617- def __exit__(self, exc_type, exc_value, tb):618- self.close(delete=exc_type is not None)619-620- def __repr__(self):621- return repr(self._f)622-623-624-auto_wrap_for_ansi = None625-colorama = None626-get_winterm_size = None627-628-629-def strip_ansi(value):630- return _ansi_re.sub('', value)631-632-633-def _is_jupyter_kernel_output(stream):634- if WIN:635- # TODO: Couldn't test on Windows, should't try to support until636- # someone tests the details wrt colorama.637- return638-639- while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):640- stream = stream._stream641-642- return stream.__class__.__module__.startswith("ipykernel.")643-644-645-def should_strip_ansi(stream=None, color=None):646- if color is None:647- if stream is None:648- stream = sys.stdin649- return not isatty(stream) and not _is_jupyter_kernel_output(stream)650- return not color651-652-653-# If we're on Windows, we provide transparent integration through654-# colorama. This will make ANSI colors through the echo function655-# work automatically.656-if WIN:657- # Windows has a smaller terminal658- DEFAULT_COLUMNS = 79659-660- from ._winconsole import _get_windows_console_stream, _wrap_std_stream661-662- def _get_argv_encoding():663- import locale664- return locale.getpreferredencoding()665-666- if PY2:667- def raw_input(prompt=''):668- sys.stderr.flush()669- if prompt:670- stdout = _default_text_stdout()671- stdout.write(prompt)672- stdin = _default_text_stdin()673- return stdin.readline().rstrip('\r\n')674-675- try:676- import colorama677- except ImportError:678- pass679- else:680- _ansi_stream_wrappers = WeakKeyDictionary()681-682- def auto_wrap_for_ansi(stream, color=None):683- """This function wraps a stream so that calls through colorama684- are issued to the win32 console API to recolor on demand. It685- also ensures to reset the colors if a write call is interrupted686- to not destroy the console afterwards.687- """688- try:689- cached = _ansi_stream_wrappers.get(stream)690- except Exception:691- cached = None692- if cached is not None:693- return cached694- strip = should_strip_ansi(stream, color)695- ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)696- rv = ansi_wrapper.stream697- _write = rv.write698-699- def _safe_write(s):700- try:701- return _write(s)702- except:703- ansi_wrapper.reset_all()704- raise705-706- rv.write = _safe_write707- try:708- _ansi_stream_wrappers[stream] = rv709- except Exception:710- pass711- return rv712-713- def get_winterm_size():714- win = colorama.win32.GetConsoleScreenBufferInfo(715- colorama.win32.STDOUT).srWindow716- return win.Right - win.Left, win.Bottom - win.Top717-else:718- def _get_argv_encoding():719- return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()720-721- _get_windows_console_stream = lambda *x: None722- _wrap_std_stream = lambda *x: None723-724-725-def term_len(x):726- return len(strip_ansi(x))727-728-729-def isatty(stream):730- try:731- return stream.isatty()732- except Exception:733- return False734-735-736-def _make_cached_stream_func(src_func, wrapper_func):737- cache = WeakKeyDictionary()738- def func():739- stream = src_func()740- try:741- rv = cache.get(stream)742- except Exception:743- rv = None744- if rv is not None:745- return rv746- rv = wrapper_func()747- try:748- stream = src_func() # In case wrapper_func() modified the stream749- cache[stream] = rv750- except Exception:751- pass752- return rv753- return func754-755-756-_default_text_stdin = _make_cached_stream_func(757- lambda: sys.stdin, get_text_stdin)758-_default_text_stdout = _make_cached_stream_func(759- lambda: sys.stdout, get_text_stdout)760-_default_text_stderr = _make_cached_stream_func(761- lambda: sys.stderr, get_text_stderr)762-763-764-binary_streams = {765- 'stdin': get_binary_stdin,766- 'stdout': get_binary_stdout,767- 'stderr': get_binary_stderr,768-}769-770-text_streams = {771- 'stdin': get_text_stdin,772- 'stdout': get_text_stdout,773- 'stderr': get_text_stderr,774-}deleted:click/_termui_impl.py-632 removed
1-# -*- coding: utf-8 -*-2-"""3-This module contains implementations for the termui module. To keep the4-import time of Click down, some infrequently used functionality is5-placed in this module and only imported as needed.6-"""7-8-import os9-import sys10-import time11-import math12-import contextlib13-from ._compat import _default_text_stdout, range_type, isatty, \14- open_stream, shlex_quote, strip_ansi, term_len, get_best_encoding, WIN, \15- int_types, CYGWIN16-from .utils import echo17-from .exceptions import ClickException18-19-20-if os.name == 'nt':21- BEFORE_BAR = '\r'22- AFTER_BAR = '\n'23-else:24- BEFORE_BAR = '\r\033[?25l'25- AFTER_BAR = '\033[?25h\n'26-27-28-def _length_hint(obj):29- """Returns the length hint of an object."""30- try:31- return len(obj)32- except (AttributeError, TypeError):33- try:34- get_hint = type(obj).__length_hint__35- except AttributeError:36- return None37- try:38- hint = get_hint(obj)39- except TypeError:40- return None41- if hint is NotImplemented or \42- not isinstance(hint, int_types) or \43- hint < 0:44- return None45- return hint46-47-48-class ProgressBar(object):49-50- def __init__(self, iterable, length=None, fill_char='#', empty_char=' ',51- bar_template='%(bar)s', info_sep=' ', show_eta=True,52- show_percent=None, show_pos=False, item_show_func=None,53- label=None, file=None, color=None, width=30):54- self.fill_char = fill_char55- self.empty_char = empty_char56- self.bar_template = bar_template57- self.info_sep = info_sep58- self.show_eta = show_eta59- self.show_percent = show_percent60- self.show_pos = show_pos61- self.item_show_func = item_show_func62- self.label = label or ''63- if file is None:64- file = _default_text_stdout()65- self.file = file66- self.color = color67- self.width = width68- self.autowidth = width == 069-70- if length is None:71- length = _length_hint(iterable)72- if iterable is None:73- if length is None:74- raise TypeError('iterable or length is required')75- iterable = range_type(length)76- self.iter = iter(iterable)77- self.length = length78- self.length_known = length is not None79- self.pos = 080- self.avg = []81- self.start = self.last_eta = time.time()82- self.eta_known = False83- self.finished = False84- self.max_width = None85- self.entered = False86- self.current_item = None87- self.is_hidden = not isatty(self.file)88- self._last_line = None89- self.short_limit = 0.590-91- def __enter__(self):92- self.entered = True93- self.render_progress()94- return self95-96- def __exit__(self, exc_type, exc_value, tb):97- self.render_finish()98-99- def __iter__(self):100- if not self.entered:101- raise RuntimeError('You need to use progress bars in a with block.')102- self.render_progress()103- return self.generator()104-105- def __next__(self):106- # Iteration is defined in terms of a generator function,107- # returned by iter(self); use that to define next(). This works108- # because `self.iter` is an iterable consumed by that generator,109- # so it is re-entry safe. Calling `next(self.generator())`110- # twice works and does "what you want".111- return next(iter(self))112-113- # Python 2 compat114- next = __next__115-116- def is_fast(self):117- return time.time() - self.start <= self.short_limit118-119- def render_finish(self):120- if self.is_hidden or self.is_fast():121- return122- self.file.write(AFTER_BAR)123- self.file.flush()124-125- @property126- def pct(self):127- if self.finished:128- return 1.0129- return min(self.pos / (float(self.length) or 1), 1.0)130-131- @property132- def time_per_iteration(self):133- if not self.avg:134- return 0.0135- return sum(self.avg) / float(len(self.avg))136-137- @property138- def eta(self):139- if self.length_known and not self.finished:140- return self.time_per_iteration * (self.length - self.pos)141- return 0.0142-143- def format_eta(self):144- if self.eta_known:145- t = int(self.eta)146- seconds = t % 60147- t //= 60148- minutes = t % 60149- t //= 60150- hours = t % 24151- t //= 24152- if t > 0:153- days = t154- return '%dd %02d:%02d:%02d' % (days, hours, minutes, seconds)155- else:156- return '%02d:%02d:%02d' % (hours, minutes, seconds)157- return ''158-159- def format_pos(self):160- pos = str(self.pos)161- if self.length_known:162- pos += '/%s' % self.length163- return pos164-165- def format_pct(self):166- return ('% 4d%%' % int(self.pct * 100))[1:]167-168- def format_bar(self):169- if self.length_known:170- bar_length = int(self.pct * self.width)171- bar = self.fill_char * bar_length172- bar += self.empty_char * (self.width - bar_length)173- elif self.finished:174- bar = self.fill_char * self.width175- else:176- bar = list(self.empty_char * (self.width or 1))177- if self.time_per_iteration != 0:178- bar[int((math.cos(self.pos * self.time_per_iteration)179- / 2.0 + 0.5) * self.width)] = self.fill_char180- bar = ''.join(bar)181- return bar182-183- def format_progress_line(self):184- show_percent = self.show_percent185-186- info_bits = []187- if self.length_known and show_percent is None:188- show_percent = not self.show_pos189-190- if self.show_pos:191- info_bits.append(self.format_pos())192- if show_percent:193- info_bits.append(self.format_pct())194- if self.show_eta and self.eta_known and not self.finished:195- info_bits.append(self.format_eta())196- if self.item_show_func is not None:197- item_info = self.item_show_func(self.current_item)198- if item_info is not None:199- info_bits.append(item_info)200-201- return (self.bar_template % {202- 'label': self.label,203- 'bar': self.format_bar(),204- 'info': self.info_sep.join(info_bits)205- }).rstrip()206-207- def render_progress(self):208- from .termui import get_terminal_size209-210- if self.is_hidden:211- return212-213- buf = []214- # Update width in case the terminal has been resized215- if self.autowidth:216- old_width = self.width217- self.width = 0218- clutter_length = term_len(self.format_progress_line())219- new_width = max(0, get_terminal_size()[0] - clutter_length)220- if new_width < old_width:221- buf.append(BEFORE_BAR)222- buf.append(' ' * self.max_width)223- self.max_width = new_width224- self.width = new_width225-226- clear_width = self.width227- if self.max_width is not None:228- clear_width = self.max_width229-230- buf.append(BEFORE_BAR)231- line = self.format_progress_line()232- line_len = term_len(line)233- if self.max_width is None or self.max_width < line_len:234- self.max_width = line_len235-236- buf.append(line)237- buf.append(' ' * (clear_width - line_len))238- line = ''.join(buf)239- # Render the line only if it changed.240-241- if line != self._last_line and not self.is_fast():242- self._last_line = line243- echo(line, file=self.file, color=self.color, nl=False)244- self.file.flush()245-246- def make_step(self, n_steps):247- self.pos += n_steps248- if self.length_known and self.pos >= self.length:249- self.finished = True250-251- if (time.time() - self.last_eta) < 1.0:252- return253-254- self.last_eta = time.time()255-256- # self.avg is a rolling list of length <= 7 of steps where steps are257- # defined as time elapsed divided by the total progress through258- # self.length.259- if self.pos:260- step = (time.time() - self.start) / self.pos261- else:262- step = time.time() - self.start263-264- self.avg = self.avg[-6:] + [step]265-266- self.eta_known = self.length_known267-268- def update(self, n_steps):269- self.make_step(n_steps)270- self.render_progress()271-272- def finish(self):273- self.eta_known = 0274- self.current_item = None275- self.finished = True276-277- def generator(self):278- """Return a generator which yields the items added to the bar279- during construction, and updates the progress bar *after* the280- yielded block returns.281- """282- # WARNING: the iterator interface for `ProgressBar` relies on283- # this and only works because this is a simple generator which284- # doesn't create or manage additional state. If this function285- # changes, the impact should be evaluated both against286- # `iter(bar)` and `next(bar)`. `next()` in particular may call287- # `self.generator()` repeatedly, and this must remain safe in288- # order for that interface to work.289- if not self.entered:290- raise RuntimeError('You need to use progress bars in a with block.')291-292- if self.is_hidden:293- for rv in self.iter:294- yield rv295- else:296- for rv in self.iter:297- self.current_item = rv298- yield rv299- self.update(1)300- self.finish()301- self.render_progress()302-303-304-def pager(generator, color=None):305- """Decide what method to use for paging through text."""306- stdout = _default_text_stdout()307- if not isatty(sys.stdin) or not isatty(stdout):308- return _nullpager(stdout, generator, color)309- pager_cmd = (os.environ.get('PAGER', None) or '').strip()310- if pager_cmd:311- if WIN:312- return _tempfilepager(generator, pager_cmd, color)313- return _pipepager(generator, pager_cmd, color)314- if os.environ.get('TERM') in ('dumb', 'emacs'):315- return _nullpager(stdout, generator, color)316- if WIN or sys.platform.startswith('os2'):317- return _tempfilepager(generator, 'more <', color)318- if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:319- return _pipepager(generator, 'less', color)320-321- import tempfile322- fd, filename = tempfile.mkstemp()323- os.close(fd)324- try:325- if hasattr(os, 'system') and os.system("more %s" % shlex_quote(filename)) == 0:326- return _pipepager(generator, 'more', color)327- return _nullpager(stdout, generator, color)328- finally:329- os.unlink(filename)330-331-332-def _pipepager(generator, cmd, color):333- """Page through text by feeding it to another program. Invoking a334- pager through this might support colors.335- """336- import subprocess337- env = dict(os.environ)338-339- # If we're piping to less we might support colors under the340- # condition that341- cmd_detail = cmd.rsplit('/', 1)[-1].split()342- if color is None and cmd_detail[0] == 'less':343- less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])344- if not less_flags:345- env['LESS'] = '-R'346- color = True347- elif 'r' in less_flags or 'R' in less_flags:348- color = True349-350- c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,351- env=env)352- encoding = get_best_encoding(c.stdin)353- try:354- for text in generator:355- if not color:356- text = strip_ansi(text)357-358- c.stdin.write(text.encode(encoding, 'replace'))359- except (IOError, KeyboardInterrupt):360- pass361- else:362- c.stdin.close()363-364- # Less doesn't respect ^C, but catches it for its own UI purposes (aborting365- # search or other commands inside less).366- #367- # That means when the user hits ^C, the parent process (click) terminates,368- # but less is still alive, paging the output and messing up the terminal.369- #370- # If the user wants to make the pager exit on ^C, they should set371- # `LESS='-K'`. It's not our decision to make.372- while True:373- try:374- c.wait()375- except KeyboardInterrupt:376- pass377- else:378- break379-380-381-def _tempfilepager(generator, cmd, color):382- """Page through text by invoking a program on a temporary file."""383- import tempfile384- filename = tempfile.mktemp()385- # TODO: This never terminates if the passed generator never terminates.386- text = "".join(generator)387- if not color:388- text = strip_ansi(text)389- encoding = get_best_encoding(sys.stdout)390- with open_stream(filename, 'wb')[0] as f:391- f.write(text.encode(encoding))392- try:393- os.system("%s %s" % (shlex_quote(cmd), shlex_quote(filename)))394- finally:395- os.unlink(filename)396-397-398-def _nullpager(stream, generator, color):399- """Simply print unformatted text. This is the ultimate fallback."""400- for text in generator:401- if not color:402- text = strip_ansi(text)403- stream.write(text)404-405-406-class Editor(object):407-408- def __init__(self, editor=None, env=None, require_save=True,409- extension='.txt'):410- self.editor = editor411- self.env = env412- self.require_save = require_save413- self.extension = extension414-415- def get_editor(self):416- if self.editor is not None:417- return self.editor418- for key in 'VISUAL', 'EDITOR':419- rv = os.environ.get(key)420- if rv:421- return rv422- if WIN:423- return 'notepad'424- for editor in 'sensible-editor', 'vim', 'nano':425- if os.system('which %s >/dev/null 2>&1' % editor) == 0:426- return editor427- return 'vi'428-429- def edit_file(self, filename):430- import subprocess431- editor = self.get_editor()432- if self.env:433- environ = os.environ.copy()434- environ.update(self.env)435- else:436- environ = None437- try:438- c = subprocess.Popen(439- "%s %s" % (shlex_quote(editor), shlex_quote(filename)),440- env=environ,441- shell=True442- )443- exit_code = c.wait()444- if exit_code != 0:445- raise ClickException('%s: Editing failed!' % editor)446- except OSError as e:447- raise ClickException('%s: Editing failed: %s' % (editor, e))448-449- def edit(self, text):450- import tempfile451-452- text = text or ''453- if text and not text.endswith('\n'):454- text += '\n'455-456- fd, name = tempfile.mkstemp(prefix='editor-', suffix=self.extension)457- try:458- if WIN:459- encoding = 'utf-8-sig'460- text = text.replace('\n', '\r\n')461- else:462- encoding = 'utf-8'463- text = text.encode(encoding)464-465- f = os.fdopen(fd, 'wb')466- f.write(text)467- f.close()468- timestamp = os.path.getmtime(name)469-470- self.edit_file(name)471-472- if self.require_save \473- and os.path.getmtime(name) == timestamp:474- return None475-476- f = open(name, 'rb')477- try:478- rv = f.read()479- finally:480- f.close()481- return rv.decode('utf-8-sig').replace('\r\n', '\n')482- finally:483- os.unlink(name)484-485-486-def open_url(url, wait=False, locate=False):487- import subprocess488-489- def _unquote_file(url):490- try:491- import urllib492- except ImportError:493- import urllib494- if url.startswith('file://'):495- url = urllib.unquote(url[7:])496- return url497-498- if sys.platform == 'darwin':499- args = ['open']500- if wait:501- args.append('-W')502- if locate:503- args.append('-R')504- args.append(_unquote_file(url))505- null = open('/dev/null', 'w')506- try:507- return subprocess.Popen(args, stderr=null).wait()508- finally:509- null.close()510- elif WIN:511- if locate:512- url = _unquote_file(url)513- args = "explorer /select,%s" % (shlex_quote(url),)514- else:515- args = 'start %s "" %s' % ("/WAIT" if wait else "", shlex_quote(url))516- return os.system(args)517- elif CYGWIN:518- if locate:519- url = _unquote_file(url)520- args = "cygstart %s" % (shlex_quote(os.path.dirname(url)),)521- else:522- args = "cygstart %s %s" % ("-w" if wait else "", shlex_quote(url))523- return os.system(args)524-525- try:526- if locate:527- url = os.path.dirname(_unquote_file(url)) or '.'528- else:529- url = _unquote_file(url)530- c = subprocess.Popen(['xdg-open', url])531- if wait:532- return c.wait()533- return 0534- except OSError:535- if url.startswith(('http://', 'https://')) and not locate and not wait:536- import webbrowser537- webbrowser.open(url)538- return 0539- return 1540-541-542-def _translate_ch_to_exc(ch):543- if ch == u'\x03':544- raise KeyboardInterrupt()545- if ch == u'\x04' and not WIN: # Unix-like, Ctrl+D546- raise EOFError()547- if ch == u'\x1a' and WIN: # Windows, Ctrl+Z548- raise EOFError()549-550-551-if WIN:552- import msvcrt553-554- @contextlib.contextmanager555- def raw_terminal():556- yield557-558- def getchar(echo):559- # The function `getch` will return a bytes object corresponding to560- # the pressed character. Since Windows 10 build 1803, it will also561- # return \x00 when called a second time after pressing a regular key.562- #563- # `getwch` does not share this probably-bugged behavior. Moreover, it564- # returns a Unicode object by default, which is what we want.565- #566- # Either of these functions will return \x00 or \xe0 to indicate567- # a special key, and you need to call the same function again to get568- # the "rest" of the code. The fun part is that \u00e0 is569- # "latin small letter a with grave", so if you type that on a French570- # keyboard, you _also_ get a \xe0.571- # E.g., consider the Up arrow. This returns \xe0 and then \x48. The572- # resulting Unicode string reads as "a with grave" + "capital H".573- # This is indistinguishable from when the user actually types574- # "a with grave" and then "capital H".575- #576- # When \xe0 is returned, we assume it's part of a special-key sequence577- # and call `getwch` again, but that means that when the user types578- # the \u00e0 character, `getchar` doesn't return until a second579- # character is typed.580- # The alternative is returning immediately, but that would mess up581- # cross-platform handling of arrow keys and others that start with582- # \xe0. Another option is using `getch`, but then we can't reliably583- # read non-ASCII characters, because return values of `getch` are584- # limited to the current 8-bit codepage.585- #586- # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`587- # is doing the right thing in more situations than with `getch`.588- if echo:589- func = msvcrt.getwche590- else:591- func = msvcrt.getwch592-593- rv = func()594- if rv in (u'\x00', u'\xe0'):595- # \x00 and \xe0 are control characters that indicate special key,596- # see above.597- rv += func()598- _translate_ch_to_exc(rv)599- return rv600-else:601- import tty602- import termios603-604- @contextlib.contextmanager605- def raw_terminal():606- if not isatty(sys.stdin):607- f = open('/dev/tty')608- fd = f.fileno()609- else:610- fd = sys.stdin.fileno()611- f = None612- try:613- old_settings = termios.tcgetattr(fd)614- try:615- tty.setraw(fd)616- yield fd617- finally:618- termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)619- sys.stdout.flush()620- if f is not None:621- f.close()622- except termios.error:623- pass624-625- def getchar(echo):626- with raw_terminal() as fd:627- ch = os.read(fd, 32)628- ch = ch.decode(get_best_encoding(sys.stdin), 'replace')629- if echo and isatty(sys.stdout):630- sys.stdout.write(ch)631- _translate_ch_to_exc(ch)632- return chdeleted:click/_textwrap.py-38 removed
1-import textwrap2-from contextlib import contextmanager3-4-5-class TextWrapper(textwrap.TextWrapper):6-7- def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):8- space_left = max(width - cur_len, 1)9-10- if self.break_long_words:11- last = reversed_chunks[-1]12- cut = last[:space_left]13- res = last[space_left:]14- cur_line.append(cut)15- reversed_chunks[-1] = res16- elif not cur_line:17- cur_line.append(reversed_chunks.pop())18-19- @contextmanager20- def extra_indent(self, indent):21- old_initial_indent = self.initial_indent22- old_subsequent_indent = self.subsequent_indent23- self.initial_indent += indent24- self.subsequent_indent += indent25- try:26- yield27- finally:28- self.initial_indent = old_initial_indent29- self.subsequent_indent = old_subsequent_indent30-31- def indent_only(self, text):32- rv = []33- for idx, line in enumerate(text.splitlines()):34- indent = self.initial_indent35- if idx > 0:36- indent = self.subsequent_indent37- rv.append(indent + line)38- return '\n'.join(rv)deleted:click/_unicodefun.py-125 removed
1-import os2-import sys3-import codecs4-5-from ._compat import PY26-7-8-# If someone wants to vendor click, we want to ensure the9-# correct package is discovered. Ideally we could use a10-# relative import here but unfortunately Python does not11-# support that.12-click = sys.modules[__name__.rsplit('.', 1)[0]]13-14-15-def _find_unicode_literals_frame():16- import __future__17- if not hasattr(sys, '_getframe'): # not all Python implementations have it18- return 019- frm = sys._getframe(1)20- idx = 121- while frm is not None:22- if frm.f_globals.get('__name__', '').startswith('click.'):23- frm = frm.f_back24- idx += 125- elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:26- return idx27- else:28- break29- return 030-31-32-def _check_for_unicode_literals():33- if not __debug__:34- return35- if not PY2 or click.disable_unicode_literals_warning:36- return37- bad_frame = _find_unicode_literals_frame()38- if bad_frame <= 0:39- return40- from warnings import warn41- warn(Warning('Click detected the use of the unicode_literals '42- '__future__ import. This is heavily discouraged '43- 'because it can introduce subtle bugs in your '44- 'code. You should instead use explicit u"" literals '45- 'for your unicode strings. For more information see '46- 'https://click.palletsprojects.com/en/7.x/python3/'),47- stacklevel=bad_frame)48-49-50-def _verify_python3_env():51- """Ensures that the environment is good for unicode on Python 3."""52- if PY2:53- return54- try:55- import locale56- fs_enc = codecs.lookup(locale.getpreferredencoding()).name57- except Exception:58- fs_enc = 'ascii'59- if fs_enc != 'ascii':60- return61-62- extra = ''63- if os.name == 'posix':64- import subprocess65- try:66- rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,67- stderr=subprocess.PIPE).communicate()[0]68- except OSError:69- rv = b''70- good_locales = set()71- has_c_utf8 = False72-73- # Make sure we're operating on text here.74- if isinstance(rv, bytes):75- rv = rv.decode('ascii', 'replace')76-77- for line in rv.splitlines():78- locale = line.strip()79- if locale.lower().endswith(('.utf-8', '.utf8')):80- good_locales.add(locale)81- if locale.lower() in ('c.utf8', 'c.utf-8'):82- has_c_utf8 = True83-84- extra += '\n\n'85- if not good_locales:86- extra += (87- 'Additional information: on this system no suitable UTF-8\n'88- 'locales were discovered. This most likely requires resolving\n'89- 'by reconfiguring the locale system.'90- )91- elif has_c_utf8:92- extra += (93- 'This system supports the C.UTF-8 locale which is recommended.\n'94- 'You might be able to resolve your issue by exporting the\n'95- 'following environment variables:\n\n'96- ' export LC_ALL=C.UTF-8\n'97- ' export LANG=C.UTF-8'98- )99- else:100- extra += (101- 'This system lists a couple of UTF-8 supporting locales that\n'102- 'you can pick from. The following suitable locales were\n'103- 'discovered: %s'104- ) % ', '.join(sorted(good_locales))105-106- bad_locale = None107- for locale in os.environ.get('LC_ALL'), os.environ.get('LANG'):108- if locale and locale.lower().endswith(('.utf-8', '.utf8')):109- bad_locale = locale110- if locale is not None:111- break112- if bad_locale is not None:113- extra += (114- '\n\nClick discovered that you exported a UTF-8 locale\n'115- 'but the locale system could not pick up from it because\n'116- 'it does not exist. The exported locale is "%s" but it\n'117- 'is not supported'118- ) % bad_locale119-120- raise RuntimeError(121- 'Click will abort further execution because Python 3 was'122- ' configured to use ASCII as encoding for the environment.'123- ' Consult https://click.palletsprojects.com/en/7.x/python3/ for'124- ' mitigation steps.' + extra125- )deleted:click/_winconsole.py-330 removed
1-# -*- coding: utf-8 -*-2-# This module is based on the excellent work by Adam Bartoš who3-# provided a lot of what went into the implementation here in4-# the discussion to issue1602 in the Python bug tracker.5-#6-# There are some general differences in regards to how this works7-# compared to the original patches as we do not need to patch8-# the entire interpreter but just work in our little world of9-# echo and prmopt.10-11-import io12-import os13-import sys14-import zlib15-import time16-import ctypes17-import msvcrt18-from ._compat import _NonClosingTextIOWrapper, text_type, PY219-from ctypes import byref, POINTER, c_int, c_char, c_char_p, \20- c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE, \21- WinError22-try:23- from ctypes import pythonapi24- PyObject_GetBuffer = pythonapi.PyObject_GetBuffer25- PyBuffer_Release = pythonapi.PyBuffer_Release26-except ImportError:27- pythonapi = None28-from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE29-30-31-c_ssize_p = POINTER(c_ssize_t)32-33-kernel32 = windll.kernel3234-GetStdHandle = kernel32.GetStdHandle35-ReadConsoleW = kernel32.ReadConsoleW36-WriteConsoleW = kernel32.WriteConsoleW37-GetConsoleMode = kernel32.GetConsoleMode38-GetLastError = kernel32.GetLastError39-GetCommandLineW = WINFUNCTYPE(LPWSTR)(40- ('GetCommandLineW', windll.kernel32))41-CommandLineToArgvW = WINFUNCTYPE(42- POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(43- ('CommandLineToArgvW', windll.shell32))44-LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(45- ('LocalFree', windll.kernel32))46-47-48-STDIN_HANDLE = GetStdHandle(-10)49-STDOUT_HANDLE = GetStdHandle(-11)50-STDERR_HANDLE = GetStdHandle(-12)51-52-53-PyBUF_SIMPLE = 054-PyBUF_WRITABLE = 155-56-ERROR_SUCCESS = 057-ERROR_NOT_ENOUGH_MEMORY = 858-ERROR_OPERATION_ABORTED = 99559-60-STDIN_FILENO = 061-STDOUT_FILENO = 162-STDERR_FILENO = 263-64-EOF = b'\x1a'65-MAX_BYTES_WRITTEN = 3276766-67-68-class Py_buffer(ctypes.Structure):69- _fields_ = [70- ('buf', c_void_p),71- ('obj', py_object),72- ('len', c_ssize_t),73- ('itemsize', c_ssize_t),74- ('readonly', c_int),75- ('ndim', c_int),76- ('format', c_char_p),77- ('shape', c_ssize_p),78- ('strides', c_ssize_p),79- ('suboffsets', c_ssize_p),80- ('internal', c_void_p)81- ]82-83- if PY2:84- _fields_.insert(-1, ('smalltable', c_ssize_t * 2))85-86-87-# On PyPy we cannot get buffers so our ability to operate here is88-# serverly limited.89-if pythonapi is None:90- get_buffer = None91-else:92- def get_buffer(obj, writable=False):93- buf = Py_buffer()94- flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE95- PyObject_GetBuffer(py_object(obj), byref(buf), flags)96- try:97- buffer_type = c_char * buf.len98- return buffer_type.from_address(buf.buf)99- finally:100- PyBuffer_Release(byref(buf))101-102-103-class _WindowsConsoleRawIOBase(io.RawIOBase):104-105- def __init__(self, handle):106- self.handle = handle107-108- def isatty(self):109- io.RawIOBase.isatty(self)110- return True111-112-113-class _WindowsConsoleReader(_WindowsConsoleRawIOBase):114-115- def readable(self):116- return True117-118- def readinto(self, b):119- bytes_to_be_read = len(b)120- if not bytes_to_be_read:121- return 0122- elif bytes_to_be_read % 2:123- raise ValueError('cannot read odd number of bytes from '124- 'UTF-16-LE encoded console')125-126- buffer = get_buffer(b, writable=True)127- code_units_to_be_read = bytes_to_be_read // 2128- code_units_read = c_ulong()129-130- rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,131- byref(code_units_read), None)132- if GetLastError() == ERROR_OPERATION_ABORTED:133- # wait for KeyboardInterrupt134- time.sleep(0.1)135- if not rv:136- raise OSError('Windows error: %s' % GetLastError())137-138- if buffer[0] == EOF:139- return 0140- return 2 * code_units_read.value141-142-143-class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):144-145- def writable(self):146- return True147-148- @staticmethod149- def _get_error_message(errno):150- if errno == ERROR_SUCCESS:151- return 'ERROR_SUCCESS'152- elif errno == ERROR_NOT_ENOUGH_MEMORY:153- return 'ERROR_NOT_ENOUGH_MEMORY'154- return 'Windows error %s' % errno155-156- def write(self, b):157- bytes_to_be_written = len(b)158- buf = get_buffer(b)159- code_units_to_be_written = min(bytes_to_be_written,160- MAX_BYTES_WRITTEN) // 2161- code_units_written = c_ulong()162-163- WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,164- byref(code_units_written), None)165- bytes_written = 2 * code_units_written.value166-167- if bytes_written == 0 and bytes_to_be_written > 0:168- raise OSError(self._get_error_message(GetLastError()))169- return bytes_written170-171-172-class ConsoleStream(object):173-174- def __init__(self, text_stream, byte_stream):175- self._text_stream = text_stream176- self.buffer = byte_stream177-178- @property179- def name(self):180- return self.buffer.name181-182- def write(self, x):183- if isinstance(x, text_type):184- return self._text_stream.write(x)185- try:186- self.flush()187- except Exception:188- pass189- return self.buffer.write(x)190-191- def writelines(self, lines):192- for line in lines:193- self.write(line)194-195- def __getattr__(self, name):196- return getattr(self._text_stream, name)197-198- def isatty(self):199- return self.buffer.isatty()200-201- def __repr__(self):202- return '<ConsoleStream name=%r encoding=%r>' % (203- self.name,204- self.encoding,205- )206-207-208-class WindowsChunkedWriter(object):209- """210- Wraps a stream (such as stdout), acting as a transparent proxy for all211- attribute access apart from method 'write()' which we wrap to write in212- limited chunks due to a Windows limitation on binary console streams.213- """214- def __init__(self, wrapped):215- # double-underscore everything to prevent clashes with names of216- # attributes on the wrapped stream object.217- self.__wrapped = wrapped218-219- def __getattr__(self, name):220- return getattr(self.__wrapped, name)221-222- def write(self, text):223- total_to_write = len(text)224- written = 0225-226- while written < total_to_write:227- to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)228- self.__wrapped.write(text[written:written+to_write])229- written += to_write230-231-232-_wrapped_std_streams = set()233-234-235-def _wrap_std_stream(name):236- # Python 2 & Windows 7 and below237- if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:238- setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))239- _wrapped_std_streams.add(name)240-241-242-def _get_text_stdin(buffer_stream):243- text_stream = _NonClosingTextIOWrapper(244- io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),245- 'utf-16-le', 'strict', line_buffering=True)246- return ConsoleStream(text_stream, buffer_stream)247-248-249-def _get_text_stdout(buffer_stream):250- text_stream = _NonClosingTextIOWrapper(251- io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),252- 'utf-16-le', 'strict', line_buffering=True)253- return ConsoleStream(text_stream, buffer_stream)254-255-256-def _get_text_stderr(buffer_stream):257- text_stream = _NonClosingTextIOWrapper(258- io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),259- 'utf-16-le', 'strict', line_buffering=True)260- return ConsoleStream(text_stream, buffer_stream)261-262-263-if PY2:264- def _hash_py_argv():265- return zlib.crc32('\x00'.join(sys.argv[1:]))266-267- _initial_argv_hash = _hash_py_argv()268-269- def _get_windows_argv():270- argc = c_int(0)271- argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))272- if not argv_unicode:273- raise WinError()274- try:275- argv = [argv_unicode[i] for i in range(0, argc.value)]276- finally:277- LocalFree(argv_unicode)278- del argv_unicode279-280- if not hasattr(sys, 'frozen'):281- argv = argv[1:]282- while len(argv) > 0:283- arg = argv[0]284- if not arg.startswith('-') or arg == '-':285- break286- argv = argv[1:]287- if arg.startswith(('-c', '-m')):288- break289-290- return argv[1:]291-292-293-_stream_factories = {294- 0: _get_text_stdin,295- 1: _get_text_stdout,296- 2: _get_text_stderr,297-}298-299-300-def _is_console(f):301- if not hasattr(f, 'fileno'):302- return False303-304- try:305- fileno = f.fileno()306- except OSError:307- return False308-309- handle = msvcrt.get_osfhandle(fileno)310- return bool(GetConsoleMode(handle, byref(DWORD())))311-312-313-def _get_windows_console_stream(f, encoding, errors):314- if get_buffer is not None and \315- encoding in ('utf-16-le', None) \316- and errors in ('strict', None) and \317- _is_console(f):318- func = _stream_factories.get(f.fileno())319- if func is not None:320- if not PY2:321- f = getattr(f, 'buffer', None)322- if f is None:323- return None324- else:325- # If we are on Python 2 we need to set the stream that we326- # deal with to binary mode as otherwise the exercise if a327- # bit moot. The same problems apply as for328- # get_binary_stdin and friends from _compat.329- msvcrt.setmode(f.fileno(), os.O_BINARY)330- return func(f)deleted:click/core.py-1901 removed
1-import errno2-import inspect3-import os4-import sys5-from contextlib import contextmanager6-from itertools import repeat7-from functools import update_wrapper8-9-from .types import convert_type, IntRange, BOOL10-from .utils import PacifyFlushWrapper, make_str, make_default_short_help, \11- echo, get_os_args12-from .exceptions import ClickException, UsageError, BadParameter, Abort, \13- MissingParameter, Exit14-from .termui import prompt, confirm, style15-from .formatting import HelpFormatter, join_options16-from .parser import OptionParser, split_opt17-from .globals import push_context, pop_context18-19-from ._compat import PY2, isidentifier, iteritems, string_types20-from ._unicodefun import _check_for_unicode_literals, _verify_python3_env21-22-23-_missing = object()24-25-26-SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'27-SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'28-29-DEPRECATED_HELP_NOTICE = ' (DEPRECATED)'30-DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \31- 'The command %(name)s is deprecated.'32-33-34-def _maybe_show_deprecated_notice(cmd):35- if cmd.deprecated:36- echo(style(DEPRECATED_INVOKE_NOTICE % {'name': cmd.name}, fg='red'), err=True)37-38-39-def fast_exit(code):40- """Exit without garbage collection, this speeds up exit by about 10ms for41- things like bash completion.42- """43- sys.stdout.flush()44- sys.stderr.flush()45- os._exit(code)46-47-48-def _bashcomplete(cmd, prog_name, complete_var=None):49- """Internal handler for the bash completion support."""50- if complete_var is None:51- complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()52- complete_instr = os.environ.get(complete_var)53- if not complete_instr:54- return55-56- from ._bashcomplete import bashcomplete57- if bashcomplete(cmd, prog_name, complete_var, complete_instr):58- fast_exit(1)59-60-61-def _check_multicommand(base_command, cmd_name, cmd, register=False):62- if not base_command.chain or not isinstance(cmd, MultiCommand):63- return64- if register:65- hint = 'It is not possible to add multi commands as children to ' \66- 'another multi command that is in chain mode'67- else:68- hint = 'Found a multi command as subcommand to a multi command ' \69- 'that is in chain mode. This is not supported'70- raise RuntimeError('%s. Command "%s" is set to chain and "%s" was '71- 'added as subcommand but it in itself is a '72- 'multi command. ("%s" is a %s within a chained '73- '%s named "%s").' % (74- hint, base_command.name, cmd_name,75- cmd_name, cmd.__class__.__name__,76- base_command.__class__.__name__,77- base_command.name))78-79-80-def batch(iterable, batch_size):81- return list(zip(*repeat(iter(iterable), batch_size)))82-83-84-def invoke_param_callback(callback, ctx, param, value):85- code = getattr(callback, '__code__', None)86- args = getattr(code, 'co_argcount', 3)87-88- if args < 3:89- # This will become a warning in Click 3.0:90- from warnings import warn91- warn(Warning('Invoked legacy parameter callback "%s". The new '92- 'signature for such callbacks starting with '93- 'click 2.0 is (ctx, param, value).'94- % callback), stacklevel=3)95- return callback(ctx, value)96- return callback(ctx, param, value)97-98-99-@contextmanager100-def augment_usage_errors(ctx, param=None):101- """Context manager that attaches extra information to exceptions that102- fly.103- """104- try:105- yield106- except BadParameter as e:107- if e.ctx is None:108- e.ctx = ctx109- if param is not None and e.param is None:110- e.param = param111- raise112- except UsageError as e:113- if e.ctx is None:114- e.ctx = ctx115- raise116-117-118-def iter_params_for_processing(invocation_order, declaration_order):119- """Given a sequence of parameters in the order as should be considered120- for processing and an iterable of parameters that exist, this returns121- a list in the correct order as they should be processed.122- """123- def sort_key(item):124- try:125- idx = invocation_order.index(item)126- except ValueError:127- idx = float('inf')128- return (not item.is_eager, idx)129-130- return sorted(declaration_order, key=sort_key)131-132-133-class Context(object):134- """The context is a special internal object that holds state relevant135- for the script execution at every single level. It's normally invisible136- to commands unless they opt-in to getting access to it.137-138- The context is useful as it can pass internal objects around and can139- control special execution features such as reading data from140- environment variables.141-142- A context can be used as context manager in which case it will call143- :meth:`close` on teardown.144-145- .. versionadded:: 2.0146- Added the `resilient_parsing`, `help_option_names`,147- `token_normalize_func` parameters.148-149- .. versionadded:: 3.0150- Added the `allow_extra_args` and `allow_interspersed_args`151- parameters.152-153- .. versionadded:: 4.0154- Added the `color`, `ignore_unknown_options`, and155- `max_content_width` parameters.156-157- .. versionadded:: 7.1158- Added the `show_default` parameter.159-160- :param command: the command class for this context.161- :param parent: the parent context.162- :param info_name: the info name for this invocation. Generally this163- is the most descriptive name for the script or164- command. For the toplevel script it is usually165- the name of the script, for commands below it it's166- the name of the script.167- :param obj: an arbitrary object of user data.168- :param auto_envvar_prefix: the prefix to use for automatic environment169- variables. If this is `None` then reading170- from environment variables is disabled. This171- does not affect manually set environment172- variables which are always read.173- :param default_map: a dictionary (like object) with default values174- for parameters.175- :param terminal_width: the width of the terminal. The default is176- inherit from parent context. If no context177- defines the terminal width then auto178- detection will be applied.179- :param max_content_width: the maximum width for content rendered by180- Click (this currently only affects help181- pages). This defaults to 80 characters if182- not overridden. In other words: even if the183- terminal is larger than that, Click will not184- format things wider than 80 characters by185- default. In addition to that, formatters might186- add some safety mapping on the right.187- :param resilient_parsing: if this flag is enabled then Click will188- parse without any interactivity or callback189- invocation. Default values will also be190- ignored. This is useful for implementing191- things such as completion support.192- :param allow_extra_args: if this is set to `True` then extra arguments193- at the end will not raise an error and will be194- kept on the context. The default is to inherit195- from the command.196- :param allow_interspersed_args: if this is set to `False` then options197- and arguments cannot be mixed. The198- default is to inherit from the command.199- :param ignore_unknown_options: instructs click to ignore options it does200- not know and keeps them for later201- processing.202- :param help_option_names: optionally a list of strings that define how203- the default help parameter is named. The204- default is ``['--help']``.205- :param token_normalize_func: an optional function that is used to206- normalize tokens (options, choices,207- etc.). This for instance can be used to208- implement case insensitive behavior.209- :param color: controls if the terminal supports ANSI colors or not. The210- default is autodetection. This is only needed if ANSI211- codes are used in texts that Click prints which is by212- default not the case. This for instance would affect213- help output.214- :param show_default: if True, shows defaults for all options.215- Even if an option is later created with show_default=False,216- this command-level setting overrides it.217- """218-219- def __init__(self, command, parent=None, info_name=None, obj=None,220- auto_envvar_prefix=None, default_map=None,221- terminal_width=None, max_content_width=None,222- resilient_parsing=False, allow_extra_args=None,223- allow_interspersed_args=None,224- ignore_unknown_options=None, help_option_names=None,225- token_normalize_func=None, color=None, show_default=None):226- #: the parent context or `None` if none exists.227- self.parent = parent228- #: the :class:`Command` for this context.229- self.command = command230- #: the descriptive information name231- self.info_name = info_name232- #: the parsed parameters except if the value is hidden in which233- #: case it's not remembered.234- self.params = {}235- #: the leftover arguments.236- self.args = []237- #: protected arguments. These are arguments that are prepended238- #: to `args` when certain parsing scenarios are encountered but239- #: must be never propagated to another arguments. This is used240- #: to implement nested parsing.241- self.protected_args = []242- if obj is None and parent is not None:243- obj = parent.obj244- #: the user object stored.245- self.obj = obj246- self._meta = getattr(parent, 'meta', {})247-248- #: A dictionary (-like object) with defaults for parameters.249- if default_map is None \250- and parent is not None \251- and parent.default_map is not None:252- default_map = parent.default_map.get(info_name)253- self.default_map = default_map254-255- #: This flag indicates if a subcommand is going to be executed. A256- #: group callback can use this information to figure out if it's257- #: being executed directly or because the execution flow passes258- #: onwards to a subcommand. By default it's None, but it can be259- #: the name of the subcommand to execute.260- #:261- #: If chaining is enabled this will be set to ``'*'`` in case262- #: any commands are executed. It is however not possible to263- #: figure out which ones. If you require this knowledge you264- #: should use a :func:`resultcallback`.265- self.invoked_subcommand = None266-267- if terminal_width is None and parent is not None:268- terminal_width = parent.terminal_width269- #: The width of the terminal (None is autodetection).270- self.terminal_width = terminal_width271-272- if max_content_width is None and parent is not None:273- max_content_width = parent.max_content_width274- #: The maximum width of formatted content (None implies a sensible275- #: default which is 80 for most things).276- self.max_content_width = max_content_width277-278- if allow_extra_args is None:279- allow_extra_args = command.allow_extra_args280- #: Indicates if the context allows extra args or if it should281- #: fail on parsing.282- #:283- #: .. versionadded:: 3.0284- self.allow_extra_args = allow_extra_args285-286- if allow_interspersed_args is None:287- allow_interspersed_args = command.allow_interspersed_args288- #: Indicates if the context allows mixing of arguments and289- #: options or not.290- #:291- #: .. versionadded:: 3.0292- self.allow_interspersed_args = allow_interspersed_args293-294- if ignore_unknown_options is None:295- ignore_unknown_options = command.ignore_unknown_options296- #: Instructs click to ignore options that a command does not297- #: understand and will store it on the context for later298- #: processing. This is primarily useful for situations where you299- #: want to call into external programs. Generally this pattern is300- #: strongly discouraged because it's not possibly to losslessly301- #: forward all arguments.302- #:303- #: .. versionadded:: 4.0304- self.ignore_unknown_options = ignore_unknown_options305-306- if help_option_names is None:307- if parent is not None:308- help_option_names = parent.help_option_names309- else:310- help_option_names = ['--help']311-312- #: The names for the help options.313- self.help_option_names = help_option_names314-315- if token_normalize_func is None and parent is not None:316- token_normalize_func = parent.token_normalize_func317-318- #: An optional normalization function for tokens. This is319- #: options, choices, commands etc.320- self.token_normalize_func = token_normalize_func321-322- #: Indicates if resilient parsing is enabled. In that case Click323- #: will do its best to not cause any failures and default values324- #: will be ignored. Useful for completion.325- self.resilient_parsing = resilient_parsing326-327- # If there is no envvar prefix yet, but the parent has one and328- # the command on this level has a name, we can expand the envvar329- # prefix automatically.330- if auto_envvar_prefix is None:331- if parent is not None \332- and parent.auto_envvar_prefix is not None and \333- self.info_name is not None:334- auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,335- self.info_name.upper())336- else:337- auto_envvar_prefix = auto_envvar_prefix.upper()338- if auto_envvar_prefix is not None:339- auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")340- self.auto_envvar_prefix = auto_envvar_prefix341-342- if color is None and parent is not None:343- color = parent.color344-345- #: Controls if styling output is wanted or not.346- self.color = color347-348- self.show_default = show_default349-350- self._close_callbacks = []351- self._depth = 0352-353- def __enter__(self):354- self._depth += 1355- push_context(self)356- return self357-358- def __exit__(self, exc_type, exc_value, tb):359- self._depth -= 1360- if self._depth == 0:361- self.close()362- pop_context()363-364- @contextmanager365- def scope(self, cleanup=True):366- """This helper method can be used with the context object to promote367- it to the current thread local (see :func:`get_current_context`).368- The default behavior of this is to invoke the cleanup functions which369- can be disabled by setting `cleanup` to `False`. The cleanup370- functions are typically used for things such as closing file handles.371-372- If the cleanup is intended the context object can also be directly373- used as a context manager.374-375- Example usage::376-377- with ctx.scope():378- assert get_current_context() is ctx379-380- This is equivalent::381-382- with ctx:383- assert get_current_context() is ctx384-385- .. versionadded:: 5.0386-387- :param cleanup: controls if the cleanup functions should be run or388- not. The default is to run these functions. In389- some situations the context only wants to be390- temporarily pushed in which case this can be disabled.391- Nested pushes automatically defer the cleanup.392- """393- if not cleanup:394- self._depth += 1395- try:396- with self as rv:397- yield rv398- finally:399- if not cleanup:400- self._depth -= 1401-402- @property403- def meta(self):404- """This is a dictionary which is shared with all the contexts405- that are nested. It exists so that click utilities can store some406- state here if they need to. It is however the responsibility of407- that code to manage this dictionary well.408-409- The keys are supposed to be unique dotted strings. For instance410- module paths are a good choice for it. What is stored in there is411- irrelevant for the operation of click. However what is important is412- that code that places data here adheres to the general semantics of413- the system.414-415- Example usage::416-417- LANG_KEY = __name__ + '.lang'418-419- def set_language(value):420- ctx = get_current_context()421- ctx.meta[LANG_KEY] = value422-423- def get_language():424- return get_current_context().meta.get(LANG_KEY, 'en_US')425-426- .. versionadded:: 5.0427- """428- return self._meta429-430- def make_formatter(self):431- """Creates the formatter for the help and usage output."""432- return HelpFormatter(width=self.terminal_width,433- max_width=self.max_content_width)434-435- def call_on_close(self, f):436- """This decorator remembers a function as callback that should be437- executed when the context tears down. This is most useful to bind438- resource handling to the script execution. For instance, file objects439- opened by the :class:`File` type will register their close callbacks440- here.441-442- :param f: the function to execute on teardown.443- """444- self._close_callbacks.append(f)445- return f446-447- def close(self):448- """Invokes all close callbacks."""449- for cb in self._close_callbacks:450- cb()451- self._close_callbacks = []452-453- @property454- def command_path(self):455- """The computed command path. This is used for the ``usage``456- information on the help page. It's automatically created by457- combining the info names of the chain of contexts to the root.458- """459- rv = ''460- if self.info_name is not None:461- rv = self.info_name462- if self.parent is not None:463- rv = self.parent.command_path + ' ' + rv464- return rv.lstrip()465-466- def find_root(self):467- """Finds the outermost context."""468- node = self469- while node.parent is not None:470- node = node.parent471- return node472-473- def find_object(self, object_type):474- """Finds the closest object of a given type."""475- node = self476- while node is not None:477- if isinstance(node.obj, object_type):478- return node.obj479- node = node.parent480-481- def ensure_object(self, object_type):482- """Like :meth:`find_object` but sets the innermost object to a483- new instance of `object_type` if it does not exist.484- """485- rv = self.find_object(object_type)486- if rv is None:487- self.obj = rv = object_type()488- return rv489-490- def lookup_default(self, name):491- """Looks up the default for a parameter name. This by default492- looks into the :attr:`default_map` if available.493- """494- if self.default_map is not None:495- rv = self.default_map.get(name)496- if callable(rv):497- rv = rv()498- return rv499-500- def fail(self, message):501- """Aborts the execution of the program with a specific error502- message.503-504- :param message: the error message to fail with.505- """506- raise UsageError(message, self)507-508- def abort(self):509- """Aborts the script."""510- raise Abort()511-512- def exit(self, code=0):513- """Exits the application with a given exit code."""514- raise Exit(code)515-516- def get_usage(self):517- """Helper method to get formatted usage string for the current518- context and command.519- """520- return self.command.get_usage(self)521-522- def get_help(self):523- """Helper method to get formatted help page for the current524- context and command.525- """526- return self.command.get_help(self)527-528- def invoke(*args, **kwargs):529- """Invokes a command callback in exactly the way it expects. There530- are two ways to invoke this method:531-532- 1. the first argument can be a callback and all other arguments and533- keyword arguments are forwarded directly to the function.534- 2. the first argument is a click command object. In that case all535- arguments are forwarded as well but proper click parameters536- (options and click arguments) must be keyword arguments and Click537- will fill in defaults.538-539- Note that before Click 3.2 keyword arguments were not properly filled540- in against the intention of this code and no context was created. For541- more information about this change and why it was done in a bugfix542- release see :ref:`upgrade-to-3.2`.543- """544- self, callback = args[:2]545- ctx = self546-547- # It's also possible to invoke another command which might or548- # might not have a callback. In that case we also fill549- # in defaults and make a new context for this command.550- if isinstance(callback, Command):551- other_cmd = callback552- callback = other_cmd.callback553- ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)554- if callback is None:555- raise TypeError('The given command does not have a '556- 'callback that can be invoked.')557-558- for param in other_cmd.params:559- if param.name not in kwargs and param.expose_value:560- kwargs[param.name] = param.get_default(ctx)561-562- args = args[2:]563- with augment_usage_errors(self):564- with ctx:565- return callback(*args, **kwargs)566-567- def forward(*args, **kwargs):568- """Similar to :meth:`invoke` but fills in default keyword569- arguments from the current context if the other command expects570- it. This cannot invoke callbacks directly, only other commands.571- """572- self, cmd = args[:2]573-574- # It's also possible to invoke another command which might or575- # might not have a callback.576- if not isinstance(cmd, Command):577- raise TypeError('Callback is not a command.')578-579- for param in self.params:580- if param not in kwargs:581- kwargs[param] = self.params[param]582-583- return self.invoke(cmd, **kwargs)584-585-586-class BaseCommand(object):587- """The base command implements the minimal API contract of commands.588- Most code will never use this as it does not implement a lot of useful589- functionality but it can act as the direct subclass of alternative590- parsing methods that do not depend on the Click parser.591-592- For instance, this can be used to bridge Click and other systems like593- argparse or docopt.594-595- Because base commands do not implement a lot of the API that other596- parts of Click take for granted, they are not supported for all597- operations. For instance, they cannot be used with the decorators598- usually and they have no built-in callback system.599-600- .. versionchanged:: 2.0601- Added the `context_settings` parameter.602-603- :param name: the name of the command to use unless a group overrides it.604- :param context_settings: an optional dictionary with defaults that are605- passed to the context object.606- """607- #: the default for the :attr:`Context.allow_extra_args` flag.608- allow_extra_args = False609- #: the default for the :attr:`Context.allow_interspersed_args` flag.610- allow_interspersed_args = True611- #: the default for the :attr:`Context.ignore_unknown_options` flag.612- ignore_unknown_options = False613-614- def __init__(self, name, context_settings=None):615- #: the name the command thinks it has. Upon registering a command616- #: on a :class:`Group` the group will default the command name617- #: with this information. You should instead use the618- #: :class:`Context`\'s :attr:`~Context.info_name` attribute.619- self.name = name620- if context_settings is None:621- context_settings = {}622- #: an optional dictionary with defaults passed to the context.623- self.context_settings = context_settings624-625- def __repr__(self):626- return "<%s %s>" % (self.__class__.__name__, self.name)627-628- def get_usage(self, ctx):629- raise NotImplementedError('Base commands cannot get usage')630-631- def get_help(self, ctx):632- raise NotImplementedError('Base commands cannot get help')633-634- def make_context(self, info_name, args, parent=None, **extra):635- """This function when given an info name and arguments will kick636- off the parsing and create a new :class:`Context`. It does not637- invoke the actual command callback though.638-639- :param info_name: the info name for this invokation. Generally this640- is the most descriptive name for the script or641- command. For the toplevel script it's usually642- the name of the script, for commands below it it's643- the name of the script.644- :param args: the arguments to parse as list of strings.645- :param parent: the parent context if available.646- :param extra: extra keyword arguments forwarded to the context647- constructor.648- """649- for key, value in iteritems(self.context_settings):650- if key not in extra:651- extra[key] = value652- ctx = Context(self, info_name=info_name, parent=parent, **extra)653- with ctx.scope(cleanup=False):654- self.parse_args(ctx, args)655- return ctx656-657- def parse_args(self, ctx, args):658- """Given a context and a list of arguments this creates the parser659- and parses the arguments, then modifies the context as necessary.660- This is automatically invoked by :meth:`make_context`.661- """662- raise NotImplementedError('Base commands do not know how to parse '663- 'arguments.')664-665- def invoke(self, ctx):666- """Given a context, this invokes the command. The default667- implementation is raising a not implemented error.668- """669- raise NotImplementedError('Base commands are not invokable by default')670-671- def main(self, args=None, prog_name=None, complete_var=None,672- standalone_mode=True, **extra):673- """This is the way to invoke a script with all the bells and674- whistles as a command line application. This will always terminate675- the application after a call. If this is not wanted, ``SystemExit``676- needs to be caught.677-678- This method is also available by directly calling the instance of679- a :class:`Command`.680-681- .. versionadded:: 3.0682- Added the `standalone_mode` flag to control the standalone mode.683-684- :param args: the arguments that should be used for parsing. If not685- provided, ``sys.argv[1:]`` is used.686- :param prog_name: the program name that should be used. By default687- the program name is constructed by taking the file688- name from ``sys.argv[0]``.689- :param complete_var: the environment variable that controls the690- bash completion support. The default is691- ``"_<prog_name>_COMPLETE"`` with prog_name in692- uppercase.693- :param standalone_mode: the default behavior is to invoke the script694- in standalone mode. Click will then695- handle exceptions and convert them into696- error messages and the function will never697- return but shut down the interpreter. If698- this is set to `False` they will be699- propagated to the caller and the return700- value of this function is the return value701- of :meth:`invoke`.702- :param extra: extra keyword arguments are forwarded to the context703- constructor. See :class:`Context` for more information.704- """705- # If we are in Python 3, we will verify that the environment is706- # sane at this point or reject further execution to avoid a707- # broken script.708- if not PY2:709- _verify_python3_env()710- else:711- _check_for_unicode_literals()712-713- if args is None:714- args = get_os_args()715- else:716- args = list(args)717-718- if prog_name is None:719- prog_name = make_str(os.path.basename(720- sys.argv and sys.argv[0] or __file__))721-722- # Hook for the Bash completion. This only activates if the Bash723- # completion is actually enabled, otherwise this is quite a fast724- # noop.725- _bashcomplete(self, prog_name, complete_var)726-727- try:728- try:729- with self.make_context(prog_name, args, **extra) as ctx:730- rv = self.invoke(ctx)731- if not standalone_mode:732- return rv733- # it's not safe to `ctx.exit(rv)` here!734- # note that `rv` may actually contain data like "1" which735- # has obvious effects736- # more subtle case: `rv=[None, None]` can come out of737- # chained commands which all returned `None` -- so it's not738- # even always obvious that `rv` indicates success/failure739- # by its truthiness/falsiness740- ctx.exit()741- except (EOFError, KeyboardInterrupt):742- echo(file=sys.stderr)743- raise Abort()744- except ClickException as e:745- if not standalone_mode:746- raise747- e.show()748- sys.exit(e.exit_code)749- except IOError as e:750- if e.errno == errno.EPIPE:751- sys.stdout = PacifyFlushWrapper(sys.stdout)752- sys.stderr = PacifyFlushWrapper(sys.stderr)753- sys.exit(1)754- else:755- raise756- except Exit as e:757- if standalone_mode:758- sys.exit(e.exit_code)759- else:760- # in non-standalone mode, return the exit code761- # note that this is only reached if `self.invoke` above raises762- # an Exit explicitly -- thus bypassing the check there which763- # would return its result764- # the results of non-standalone execution may therefore be765- # somewhat ambiguous: if there are codepaths which lead to766- # `ctx.exit(1)` and to `return 1`, the caller won't be able to767- # tell the difference between the two768- return e.exit_code769- except Abort:770- if not standalone_mode:771- raise772- echo('Aborted!', file=sys.stderr)773- sys.exit(1)774-775- def __call__(self, *args, **kwargs):776- """Alias for :meth:`main`."""777- return self.main(*args, **kwargs)778-779-780-class Command(BaseCommand):781- """Commands are the basic building block of command line interfaces in782- Click. A basic command handles command line parsing and might dispatch783- more parsing to commands nested below it.784-785- .. versionchanged:: 2.0786- Added the `context_settings` parameter.787- .. versionchanged:: 7.1788- Added the `no_args_is_help` parameter.789-790- :param name: the name of the command to use unless a group overrides it.791- :param context_settings: an optional dictionary with defaults that are792- passed to the context object.793- :param callback: the callback to invoke. This is optional.794- :param params: the parameters to register with this command. This can795- be either :class:`Option` or :class:`Argument` objects.796- :param help: the help string to use for this command.797- :param epilog: like the help string but it's printed at the end of the798- help page after everything else.799- :param short_help: the short help to use for this command. This is800- shown on the command listing of the parent command.801- :param add_help_option: by default each command registers a ``--help``802- option. This can be disabled by this parameter.803- :param no_args_is_help: this controls what happens if no arguments are804- provided. This option is disabled by default.805- If enabled this will add ``--help`` as argument806- if no arguments are passed807- :param hidden: hide this command from help outputs.808-809- :param deprecated: issues a message indicating that810- the command is deprecated.811- """812-813- def __init__(self, name, context_settings=None, callback=None,814- params=None, help=None, epilog=None, short_help=None,815- options_metavar='[OPTIONS]', add_help_option=True,816- no_args_is_help=False, hidden=False, deprecated=False):817- BaseCommand.__init__(self, name, context_settings)818- #: the callback to execute when the command fires. This might be819- #: `None` in which case nothing happens.820- self.callback = callback821- #: the list of parameters for this command in the order they822- #: should show up in the help page and execute. Eager parameters823- #: will automatically be handled before non eager ones.824- self.params = params or []825- # if a form feed (page break) is found in the help text, truncate help826- # text to the content preceding the first form feed827- if help and '\f' in help:828- help = help.split('\f', 1)[0]829- self.help = help830- self.epilog = epilog831- self.options_metavar = options_metavar832- self.short_help = short_help833- self.add_help_option = add_help_option834- self.no_args_is_help = no_args_is_help835- self.hidden = hidden836- self.deprecated = deprecated837-838- def get_usage(self, ctx):839- """Formats the usage line into a string and returns it.840-841- Calls :meth:`format_usage` internally.842- """843- formatter = ctx.make_formatter()844- self.format_usage(ctx, formatter)845- return formatter.getvalue().rstrip('\n')846-847- def get_params(self, ctx):848- rv = self.params849- help_option = self.get_help_option(ctx)850- if help_option is not None:851- rv = rv + [help_option]852- return rv853-854- def format_usage(self, ctx, formatter):855- """Writes the usage line into the formatter.856-857- This is a low-level method called by :meth:`get_usage`.858- """859- pieces = self.collect_usage_pieces(ctx)860- formatter.write_usage(ctx.command_path, ' '.join(pieces))861-862- def collect_usage_pieces(self, ctx):863- """Returns all the pieces that go into the usage line and returns864- it as a list of strings.865- """866- rv = [self.options_metavar]867- for param in self.get_params(ctx):868- rv.extend(param.get_usage_pieces(ctx))869- return rv870-871- def get_help_option_names(self, ctx):872- """Returns the names for the help option."""873- all_names = set(ctx.help_option_names)874- for param in self.params:875- all_names.difference_update(param.opts)876- all_names.difference_update(param.secondary_opts)877- return all_names878-879- def get_help_option(self, ctx):880- """Returns the help option object."""881- help_options = self.get_help_option_names(ctx)882- if not help_options or not self.add_help_option:883- return884-885- def show_help(ctx, param, value):886- if value and not ctx.resilient_parsing:887- echo(ctx.get_help(), color=ctx.color)888- ctx.exit()889- return Option(help_options, is_flag=True,890- is_eager=True, expose_value=False,891- callback=show_help,892- help='Show this message and exit.')893-894- def make_parser(self, ctx):895- """Creates the underlying option parser for this command."""896- parser = OptionParser(ctx)897- for param in self.get_params(ctx):898- param.add_to_parser(parser, ctx)899- return parser900-901- def get_help(self, ctx):902- """Formats the help into a string and returns it.903-904- Calls :meth:`format_help` internally.905- """906- formatter = ctx.make_formatter()907- self.format_help(ctx, formatter)908- return formatter.getvalue().rstrip('\n')909-910- def get_short_help_str(self, limit=45):911- """Gets short help for the command or makes it by shortening the long help string."""912- return self.short_help or self.help and make_default_short_help(self.help, limit) or ''913-914- def format_help(self, ctx, formatter):915- """Writes the help into the formatter if it exists.916-917- This is a low-level method called by :meth:`get_help`.918-919- This calls the following methods:920-921- - :meth:`format_usage`922- - :meth:`format_help_text`923- - :meth:`format_options`924- - :meth:`format_epilog`925- """926- self.format_usage(ctx, formatter)927- self.format_help_text(ctx, formatter)928- self.format_options(ctx, formatter)929- self.format_epilog(ctx, formatter)930-931- def format_help_text(self, ctx, formatter):932- """Writes the help text to the formatter if it exists."""933- if self.help:934- formatter.write_paragraph()935- with formatter.indentation():936- help_text = self.help937- if self.deprecated:938- help_text += DEPRECATED_HELP_NOTICE939- formatter.write_text(help_text)940- elif self.deprecated:941- formatter.write_paragraph()942- with formatter.indentation():943- formatter.write_text(DEPRECATED_HELP_NOTICE)944-945- def format_options(self, ctx, formatter):946- """Writes all the options into the formatter if they exist."""947- opts = []948- for param in self.get_params(ctx):949- rv = param.get_help_record(ctx)950- if rv is not None:951- opts.append(rv)952-953- if opts:954- with formatter.section('Options'):955- formatter.write_dl(opts)956-957- def format_epilog(self, ctx, formatter):958- """Writes the epilog into the formatter if it exists."""959- if self.epilog:960- formatter.write_paragraph()961- with formatter.indentation():962- formatter.write_text(self.epilog)963-964- def parse_args(self, ctx, args):965- if not args and self.no_args_is_help and not ctx.resilient_parsing:966- echo(ctx.get_help(), color=ctx.color)967- ctx.exit()968-969- parser = self.make_parser(ctx)970- opts, args, param_order = parser.parse_args(args=args)971-972- for param in iter_params_for_processing(973- param_order, self.get_params(ctx)):974- value, args = param.handle_parse_result(ctx, opts, args)975-976- if args and not ctx.allow_extra_args and not ctx.resilient_parsing:977- ctx.fail('Got unexpected extra argument%s (%s)'978- % (len(args) != 1 and 's' or '',979- ' '.join(map(make_str, args))))980-981- ctx.args = args982- return args983-984- def invoke(self, ctx):985- """Given a context, this invokes the attached callback (if it exists)986- in the right way.987- """988- _maybe_show_deprecated_notice(self)989- if self.callback is not None:990- return ctx.invoke(self.callback, **ctx.params)991-992-993-class MultiCommand(Command):994- """A multi command is the basic implementation of a command that995- dispatches to subcommands. The most common version is the996- :class:`Group`.997-998- :param invoke_without_command: this controls how the multi command itself999- is invoked. By default it's only invoked1000- if a subcommand is provided.1001- :param no_args_is_help: this controls what happens if no arguments are1002- provided. This option is enabled by default if1003- `invoke_without_command` is disabled or disabled1004- if it's enabled. If enabled this will add1005- ``--help`` as argument if no arguments are1006- passed.1007- :param subcommand_metavar: the string that is used in the documentation1008- to indicate the subcommand place.1009- :param chain: if this is set to `True` chaining of multiple subcommands1010- is enabled. This restricts the form of commands in that1011- they cannot have optional arguments but it allows1012- multiple commands to be chained together.1013- :param result_callback: the result callback to attach to this multi1014- command.1015- """1016- allow_extra_args = True1017- allow_interspersed_args = False1018-1019- def __init__(self, name=None, invoke_without_command=False,1020- no_args_is_help=None, subcommand_metavar=None,1021- chain=False, result_callback=None, **attrs):1022- Command.__init__(self, name, **attrs)1023- if no_args_is_help is None:1024- no_args_is_help = not invoke_without_command1025- self.no_args_is_help = no_args_is_help1026- self.invoke_without_command = invoke_without_command1027- if subcommand_metavar is None:1028- if chain:1029- subcommand_metavar = SUBCOMMANDS_METAVAR1030- else:1031- subcommand_metavar = SUBCOMMAND_METAVAR1032- self.subcommand_metavar = subcommand_metavar1033- self.chain = chain1034- #: The result callback that is stored. This can be set or1035- #: overridden with the :func:`resultcallback` decorator.1036- self.result_callback = result_callback1037-1038- if self.chain:1039- for param in self.params:1040- if isinstance(param, Argument) and not param.required:1041- raise RuntimeError('Multi commands in chain mode cannot '1042- 'have optional arguments.')1043-1044- def collect_usage_pieces(self, ctx):1045- rv = Command.collect_usage_pieces(self, ctx)1046- rv.append(self.subcommand_metavar)1047- return rv1048-1049- def format_options(self, ctx, formatter):1050- Command.format_options(self, ctx, formatter)1051- self.format_commands(ctx, formatter)1052-1053- def resultcallback(self, replace=False):1054- """Adds a result callback to the chain command. By default if a1055- result callback is already registered this will chain them but1056- this can be disabled with the `replace` parameter. The result1057- callback is invoked with the return value of the subcommand1058- (or the list of return values from all subcommands if chaining1059- is enabled) as well as the parameters as they would be passed1060- to the main callback.1061-1062- Example::1063-1064- @click.group()1065- @click.option('-i', '--input', default=23)1066- def cli(input):1067- return 421068-1069- @cli.resultcallback()1070- def process_result(result, input):1071- return result + input1072-1073- .. versionadded:: 3.01074-1075- :param replace: if set to `True` an already existing result1076- callback will be removed.1077- """1078- def decorator(f):1079- old_callback = self.result_callback1080- if old_callback is None or replace:1081- self.result_callback = f1082- return f1083- def function(__value, *args, **kwargs):1084- return f(old_callback(__value, *args, **kwargs),1085- *args, **kwargs)1086- self.result_callback = rv = update_wrapper(function, f)1087- return rv1088- return decorator1089-1090- def format_commands(self, ctx, formatter):1091- """Extra format methods for multi methods that adds all the commands1092- after the options.1093- """1094- commands = []1095- for subcommand in self.list_commands(ctx):1096- cmd = self.get_command(ctx, subcommand)1097- # What is this, the tool lied about a command. Ignore it1098- if cmd is None:1099- continue1100- if cmd.hidden:1101- continue1102-1103- commands.append((subcommand, cmd))1104-1105- # allow for 3 times the default spacing1106- if len(commands):1107- limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)1108-1109- rows = []1110- for subcommand, cmd in commands:1111- help = cmd.get_short_help_str(limit)1112- rows.append((subcommand, help))1113-1114- if rows:1115- with formatter.section('Commands'):1116- formatter.write_dl(rows)1117-1118- def parse_args(self, ctx, args):1119- if not args and self.no_args_is_help and not ctx.resilient_parsing:1120- echo(ctx.get_help(), color=ctx.color)1121- ctx.exit()1122-1123- rest = Command.parse_args(self, ctx, args)1124- if self.chain:1125- ctx.protected_args = rest1126- ctx.args = []1127- elif rest:1128- ctx.protected_args, ctx.args = rest[:1], rest[1:]1129-1130- return ctx.args1131-1132- def invoke(self, ctx):1133- def _process_result(value):1134- if self.result_callback is not None:1135- value = ctx.invoke(self.result_callback, value,1136- **ctx.params)1137- return value1138-1139- if not ctx.protected_args:1140- # If we are invoked without command the chain flag controls1141- # how this happens. If we are not in chain mode, the return1142- # value here is the return value of the command.1143- # If however we are in chain mode, the return value is the1144- # return value of the result processor invoked with an empty1145- # list (which means that no subcommand actually was executed).1146- if self.invoke_without_command:1147- if not self.chain:1148- return Command.invoke(self, ctx)1149- with ctx:1150- Command.invoke(self, ctx)1151- return _process_result([])1152- ctx.fail('Missing command.')1153-1154- # Fetch args back out1155- args = ctx.protected_args + ctx.args1156- ctx.args = []1157- ctx.protected_args = []1158-1159- # If we're not in chain mode, we only allow the invocation of a1160- # single command but we also inform the current context about the1161- # name of the command to invoke.1162- if not self.chain:1163- # Make sure the context is entered so we do not clean up1164- # resources until the result processor has worked.1165- with ctx:1166- cmd_name, cmd, args = self.resolve_command(ctx, args)1167- ctx.invoked_subcommand = cmd_name1168- Command.invoke(self, ctx)1169- sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1170- with sub_ctx:1171- return _process_result(sub_ctx.command.invoke(sub_ctx))1172-1173- # In chain mode we create the contexts step by step, but after the1174- # base command has been invoked. Because at that point we do not1175- # know the subcommands yet, the invoked subcommand attribute is1176- # set to ``*`` to inform the command that subcommands are executed1177- # but nothing else.1178- with ctx:1179- ctx.invoked_subcommand = args and '*' or None1180- Command.invoke(self, ctx)1181-1182- # Otherwise we make every single context and invoke them in a1183- # chain. In that case the return value to the result processor1184- # is the list of all invoked subcommand's results.1185- contexts = []1186- while args:1187- cmd_name, cmd, args = self.resolve_command(ctx, args)1188- sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,1189- allow_extra_args=True,1190- allow_interspersed_args=False)1191- contexts.append(sub_ctx)1192- args, sub_ctx.args = sub_ctx.args, []1193-1194- rv = []1195- for sub_ctx in contexts:1196- with sub_ctx:1197- rv.append(sub_ctx.command.invoke(sub_ctx))1198- return _process_result(rv)1199-1200- def resolve_command(self, ctx, args):1201- cmd_name = make_str(args[0])1202- original_cmd_name = cmd_name1203-1204- # Get the command1205- cmd = self.get_command(ctx, cmd_name)1206-1207- # If we can't find the command but there is a normalization1208- # function available, we try with that one.1209- if cmd is None and ctx.token_normalize_func is not None:1210- cmd_name = ctx.token_normalize_func(cmd_name)1211- cmd = self.get_command(ctx, cmd_name)1212-1213- # If we don't find the command we want to show an error message1214- # to the user that it was not provided. However, there is1215- # something else we should do: if the first argument looks like1216- # an option we want to kick off parsing again for arguments to1217- # resolve things like --help which now should go to the main1218- # place.1219- if cmd is None and not ctx.resilient_parsing:1220- if split_opt(cmd_name)[0]:1221- self.parse_args(ctx, ctx.args)1222- ctx.fail('No such command "%s".' % original_cmd_name)1223-1224- return cmd_name, cmd, args[1:]1225-1226- def get_command(self, ctx, cmd_name):1227- """Given a context and a command name, this returns a1228- :class:`Command` object if it exists or returns `None`.1229- """1230- raise NotImplementedError()1231-1232- def list_commands(self, ctx):1233- """Returns a list of subcommand names in the order they should1234- appear.1235- """1236- return []1237-1238-1239-class Group(MultiCommand):1240- """A group allows a command to have subcommands attached. This is the1241- most common way to implement nesting in Click.1242-1243- :param commands: a dictionary of commands.1244- """1245-1246- def __init__(self, name=None, commands=None, **attrs):1247- MultiCommand.__init__(self, name, **attrs)1248- #: the registered subcommands by their exported names.1249- self.commands = commands or {}1250-1251- def add_command(self, cmd, name=None):1252- """Registers another :class:`Command` with this group. If the name1253- is not provided, the name of the command is used.1254- """1255- name = name or cmd.name1256- if name is None:1257- raise TypeError('Command has no name.')1258- _check_multicommand(self, name, cmd, register=True)1259- self.commands[name] = cmd1260-1261- def command(self, *args, **kwargs):1262- """A shortcut decorator for declaring and attaching a command to1263- the group. This takes the same arguments as :func:`command` but1264- immediately registers the created command with this instance by1265- calling into :meth:`add_command`.1266- """1267- def decorator(f):1268- cmd = command(*args, **kwargs)(f)1269- self.add_command(cmd)1270- return cmd1271- return decorator1272-1273- def group(self, *args, **kwargs):1274- """A shortcut decorator for declaring and attaching a group to1275- the group. This takes the same arguments as :func:`group` but1276- immediately registers the created command with this instance by1277- calling into :meth:`add_command`.1278- """1279- def decorator(f):1280- cmd = group(*args, **kwargs)(f)1281- self.add_command(cmd)1282- return cmd1283- return decorator1284-1285- def get_command(self, ctx, cmd_name):1286- return self.commands.get(cmd_name)1287-1288- def list_commands(self, ctx):1289- return sorted(self.commands)1290-1291-1292-class CommandCollection(MultiCommand):1293- """A command collection is a multi command that merges multiple multi1294- commands together into one. This is a straightforward implementation1295- that accepts a list of different multi commands as sources and1296- provides all the commands for each of them.1297- """1298-1299- def __init__(self, name=None, sources=None, **attrs):1300- MultiCommand.__init__(self, name, **attrs)1301- #: The list of registered multi commands.1302- self.sources = sources or []1303-1304- def add_source(self, multi_cmd):1305- """Adds a new multi command to the chain dispatcher."""1306- self.sources.append(multi_cmd)1307-1308- def get_command(self, ctx, cmd_name):1309- for source in self.sources:1310- rv = source.get_command(ctx, cmd_name)1311- if rv is not None:1312- if self.chain:1313- _check_multicommand(self, cmd_name, rv)1314- return rv1315-1316- def list_commands(self, ctx):1317- rv = set()1318- for source in self.sources:1319- rv.update(source.list_commands(ctx))1320- return sorted(rv)1321-1322-1323-class Parameter(object):1324- r"""A parameter to a command comes in two versions: they are either1325- :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1326- not supported by design as some of the internals for parsing are1327- intentionally not finalized.1328-1329- Some settings are supported by both options and arguments.1330-1331- :param param_decls: the parameter declarations for this option or1332- argument. This is a list of flags or argument1333- names.1334- :param type: the type that should be used. Either a :class:`ParamType`1335- or a Python type. The later is converted into the former1336- automatically if supported.1337- :param required: controls if this is optional or not.1338- :param default: the default value if omitted. This can also be a callable,1339- in which case it's invoked when the default is needed1340- without any arguments.1341- :param callback: a callback that should be executed after the parameter1342- was matched. This is called as ``fn(ctx, param,1343- value)`` and needs to return the value. Before Click1344- 2.0, the signature was ``(ctx, value)``.1345- :param nargs: the number of arguments to match. If not ``1`` the return1346- value is a tuple instead of single value. The default for1347- nargs is ``1`` (except if the type is a tuple, then it's1348- the arity of the tuple).1349- :param metavar: how the value is represented in the help page.1350- :param expose_value: if this is `True` then the value is passed onwards1351- to the command callback and stored on the context,1352- otherwise it's skipped.1353- :param is_eager: eager values are processed before non eager ones. This1354- should not be set for arguments or it will inverse the1355- order of processing.1356- :param envvar: a string or list of strings that are environment variables1357- that should be checked.1358-1359- .. versionchanged:: 7.11360- Empty environment variables are ignored rather than taking the1361- empty string value. This makes it possible for scripts to clear1362- variables if they can't unset them.1363-1364- .. versionchanged:: 2.01365- Changed signature for parameter callback to also be passed the1366- parameter. The old callback format will still work, but it will1367- raise a warning to give you a chance to migrate the code easier.1368- """1369- param_type_name = 'parameter'1370-1371- def __init__(self, param_decls=None, type=None, required=False,1372- default=None, callback=None, nargs=None, metavar=None,1373- expose_value=True, is_eager=False, envvar=None,1374- autocompletion=None):1375- self.name, self.opts, self.secondary_opts = \1376- self._parse_decls(param_decls or (), expose_value)1377-1378- self.type = convert_type(type, default)1379-1380- # Default nargs to what the type tells us if we have that1381- # information available.1382- if nargs is None:1383- if self.type.is_composite:1384- nargs = self.type.arity1385- else:1386- nargs = 11387-1388- self.required = required1389- self.callback = callback1390- self.nargs = nargs1391- self.multiple = False1392- self.expose_value = expose_value1393- self.default = default1394- self.is_eager = is_eager1395- self.metavar = metavar1396- self.envvar = envvar1397- self.autocompletion = autocompletion1398-1399- def __repr__(self):1400- return "<%s %s>" % (self.__class__.__name__, self.name)1401-1402- @property1403- def human_readable_name(self):1404- """Returns the human readable name of this parameter. This is the1405- same as the name for options, but the metavar for arguments.1406- """1407- return self.name1408-1409- def make_metavar(self):1410- if self.metavar is not None:1411- return self.metavar1412- metavar = self.type.get_metavar(self)1413- if metavar is None:1414- metavar = self.type.name.upper()1415- if self.nargs != 1:1416- metavar += '...'1417- return metavar1418-1419- def get_default(self, ctx):1420- """Given a context variable this calculates the default value."""1421- # Otherwise go with the regular default.1422- if callable(self.default):1423- rv = self.default()1424- else:1425- rv = self.default1426- return self.type_cast_value(ctx, rv)1427-1428- def add_to_parser(self, parser, ctx):1429- pass1430-1431- def consume_value(self, ctx, opts):1432- value = opts.get(self.name)1433- if value is None:1434- value = self.value_from_envvar(ctx)1435- if value is None:1436- value = ctx.lookup_default(self.name)1437- return value1438-1439- def type_cast_value(self, ctx, value):1440- """Given a value this runs it properly through the type system.1441- This automatically handles things like `nargs` and `multiple` as1442- well as composite types.1443- """1444- if self.type.is_composite:1445- if self.nargs <= 1:1446- raise TypeError('Attempted to invoke composite type '1447- 'but nargs has been set to %s. This is '1448- 'not supported; nargs needs to be set to '1449- 'a fixed value > 1.' % self.nargs)1450- if self.multiple:1451- return tuple(self.type(x or (), self, ctx) for x in value or ())1452- return self.type(value or (), self, ctx)1453-1454- def _convert(value, level):1455- if level == 0:1456- return self.type(value, self, ctx)1457- return tuple(_convert(x, level - 1) for x in value or ())1458- return _convert(value, (self.nargs != 1) + bool(self.multiple))1459-1460- def process_value(self, ctx, value):1461- """Given a value and context this runs the logic to convert the1462- value as necessary.1463- """1464- # If the value we were given is None we do nothing. This way1465- # code that calls this can easily figure out if something was1466- # not provided. Otherwise it would be converted into an empty1467- # tuple for multiple invocations which is inconvenient.1468- if value is not None:1469- return self.type_cast_value(ctx, value)1470-1471- def value_is_missing(self, value):1472- if value is None:1473- return True1474- if (self.nargs != 1 or self.multiple) and value == ():1475- return True1476- return False1477-1478- def full_process_value(self, ctx, value):1479- value = self.process_value(ctx, value)1480-1481- if value is None and not ctx.resilient_parsing:1482- value = self.get_default(ctx)1483-1484- if self.required and self.value_is_missing(value):1485- raise MissingParameter(ctx=ctx, param=self)1486-1487- return value1488-1489- def resolve_envvar_value(self, ctx):1490- if self.envvar is None:1491- return1492- if isinstance(self.envvar, (tuple, list)):1493- for envvar in self.envvar:1494- rv = os.environ.get(envvar)1495- if rv is not None:1496- return rv1497- else:1498- rv = os.environ.get(self.envvar)1499-1500- if rv != "":1501- return rv1502-1503- def value_from_envvar(self, ctx):1504- rv = self.resolve_envvar_value(ctx)1505- if rv is not None and self.nargs != 1:1506- rv = self.type.split_envvar_value(rv)1507- return rv1508-1509- def handle_parse_result(self, ctx, opts, args):1510- with augment_usage_errors(ctx, param=self):1511- value = self.consume_value(ctx, opts)1512- try:1513- value = self.full_process_value(ctx, value)1514- except Exception:1515- if not ctx.resilient_parsing:1516- raise1517- value = None1518- if self.callback is not None:1519- try:1520- value = invoke_param_callback(1521- self.callback, ctx, self, value)1522- except Exception:1523- if not ctx.resilient_parsing:1524- raise1525-1526- if self.expose_value:1527- ctx.params[self.name] = value1528- return value, args1529-1530- def get_help_record(self, ctx):1531- pass1532-1533- def get_usage_pieces(self, ctx):1534- return []1535-1536- def get_error_hint(self, ctx):1537- """Get a stringified version of the param for use in error messages to1538- indicate which param caused the error.1539- """1540- hint_list = self.opts or [self.human_readable_name]1541- return ' / '.join('"%s"' % x for x in hint_list)1542-1543-1544-class Option(Parameter):1545- """Options are usually optional values on the command line and1546- have some extra features that arguments don't have.1547-1548- All other parameters are passed onwards to the parameter constructor.1549-1550- :param show_default: controls if the default value should be shown on the1551- help page. Normally, defaults are not shown. If this1552- value is a string, it shows the string instead of the1553- value. This is particularly useful for dynamic options.1554- :param show_envvar: controls if an environment variable should be shown on1555- the help page. Normally, environment variables1556- are not shown.1557- :param prompt: if set to `True` or a non empty string then the user will be1558- prompted for input. If set to `True` the prompt will be the1559- option name capitalized.1560- :param confirmation_prompt: if set then the value will need to be confirmed1561- if it was prompted for.1562- :param hide_input: if this is `True` then the input on the prompt will be1563- hidden from the user. This is useful for password1564- input.1565- :param is_flag: forces this option to act as a flag. The default is1566- auto detection.1567- :param flag_value: which value should be used for this flag if it's1568- enabled. This is set to a boolean automatically if1569- the option string contains a slash to mark two options.1570- :param multiple: if this is set to `True` then the argument is accepted1571- multiple times and recorded. This is similar to ``nargs``1572- in how it works but supports arbitrary number of1573- arguments.1574- :param count: this flag makes an option increment an integer.1575- :param allow_from_autoenv: if this is enabled then the value of this1576- parameter will be pulled from an environment1577- variable in case a prefix is defined on the1578- context.1579- :param help: the help string.1580- :param hidden: hide this option from help outputs.1581- """1582- param_type_name = 'option'1583-1584- def __init__(self, param_decls=None, show_default=False,1585- prompt=False, confirmation_prompt=False,1586- hide_input=False, is_flag=None, flag_value=None,1587- multiple=False, count=False, allow_from_autoenv=True,1588- type=None, help=None, hidden=False, show_choices=True,1589- show_envvar=False, **attrs):1590- default_is_missing = attrs.get('default', _missing) is _missing1591- Parameter.__init__(self, param_decls, type=type, **attrs)1592-1593- if prompt is True:1594- prompt_text = self.name.replace('_', ' ').capitalize()1595- elif prompt is False:1596- prompt_text = None1597- else:1598- prompt_text = prompt1599- self.prompt = prompt_text1600- self.confirmation_prompt = confirmation_prompt1601- self.hide_input = hide_input1602- self.hidden = hidden1603-1604- # Flags1605- if is_flag is None:1606- if flag_value is not None:1607- is_flag = True1608- else:1609- is_flag = bool(self.secondary_opts)1610- if is_flag and default_is_missing:1611- self.default = False1612- if flag_value is None:1613- flag_value = not self.default1614- self.is_flag = is_flag1615- self.flag_value = flag_value1616- if self.is_flag and isinstance(self.flag_value, bool) \1617- and type in [None, bool]:1618- self.type = BOOL1619- self.is_bool_flag = True1620- else:1621- self.is_bool_flag = False1622-1623- # Counting1624- self.count = count1625- if count:1626- if type is None:1627- self.type = IntRange(min=0)1628- if default_is_missing:1629- self.default = 01630-1631- self.multiple = multiple1632- self.allow_from_autoenv = allow_from_autoenv1633- self.help = help1634- self.show_default = show_default1635- self.show_choices = show_choices1636- self.show_envvar = show_envvar1637-1638- # Sanity check for stuff we don't support1639- if __debug__:1640- if self.nargs < 0:1641- raise TypeError('Options cannot have nargs < 0')1642- if self.prompt and self.is_flag and not self.is_bool_flag:1643- raise TypeError('Cannot prompt for flags that are not bools.')1644- if not self.is_bool_flag and self.secondary_opts:1645- raise TypeError('Got secondary option for non boolean flag.')1646- if self.is_bool_flag and self.hide_input \1647- and self.prompt is not None:1648- raise TypeError('Hidden input does not work with boolean '1649- 'flag prompts.')1650- if self.count:1651- if self.multiple:1652- raise TypeError('Options cannot be multiple and count '1653- 'at the same time.')1654- elif self.is_flag:1655- raise TypeError('Options cannot be count and flags at '1656- 'the same time.')1657-1658- def _parse_decls(self, decls, expose_value):1659- opts = []1660- secondary_opts = []1661- name = None1662- possible_names = []1663-1664- for decl in decls:1665- if isidentifier(decl):1666- if name is not None:1667- raise TypeError('Name defined twice')1668- name = decl1669- else:1670- split_char = decl[:1] == '/' and ';' or '/'1671- if split_char in decl:1672- first, second = decl.split(split_char, 1)1673- first = first.rstrip()1674- if first:1675- possible_names.append(split_opt(first))1676- opts.append(first)1677- second = second.lstrip()1678- if second:1679- secondary_opts.append(second.lstrip())1680- else:1681- possible_names.append(split_opt(decl))1682- opts.append(decl)1683-1684- if name is None and possible_names:1685- possible_names.sort(key=lambda x: -len(x[0])) # group long options first1686- name = possible_names[0][1].replace('-', '_').lower()1687- if not isidentifier(name):1688- name = None1689-1690- if name is None:1691- if not expose_value:1692- return None, opts, secondary_opts1693- raise TypeError('Could not determine name for option')1694-1695- if not opts and not secondary_opts:1696- raise TypeError('No options defined but a name was passed (%s). '1697- 'Did you mean to declare an argument instead '1698- 'of an option?' % name)1699-1700- return name, opts, secondary_opts1701-1702- def add_to_parser(self, parser, ctx):1703- kwargs = {1704- 'dest': self.name,1705- 'nargs': self.nargs,1706- 'obj': self,1707- }1708-1709- if self.multiple:1710- action = 'append'1711- elif self.count:1712- action = 'count'1713- else:1714- action = 'store'1715-1716- if self.is_flag:1717- kwargs.pop('nargs', None)1718- if self.is_bool_flag and self.secondary_opts:1719- parser.add_option(self.opts, action=action + '_const',1720- const=True, **kwargs)1721- parser.add_option(self.secondary_opts, action=action +1722- '_const', const=False, **kwargs)1723- else:1724- parser.add_option(self.opts, action=action + '_const',1725- const=self.flag_value,1726- **kwargs)1727- else:1728- kwargs['action'] = action1729- parser.add_option(self.opts, **kwargs)1730-1731- def get_help_record(self, ctx):1732- if self.hidden:1733- return1734- any_prefix_is_slash = []1735-1736- def _write_opts(opts):1737- rv, any_slashes = join_options(opts)1738- if any_slashes:1739- any_prefix_is_slash[:] = [True]1740- if not self.is_flag and not self.count:1741- rv += ' ' + self.make_metavar()1742- return rv1743-1744- rv = [_write_opts(self.opts)]1745- if self.secondary_opts:1746- rv.append(_write_opts(self.secondary_opts))1747-1748- help = self.help or ''1749- extra = []1750- if self.show_envvar:1751- envvar = self.envvar1752- if envvar is None:1753- if self.allow_from_autoenv and \1754- ctx.auto_envvar_prefix is not None:1755- envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1756- if envvar is not None:1757- extra.append('env var: %s' % (1758- ', '.join('%s' % d for d in envvar)1759- if isinstance(envvar, (list, tuple))1760- else envvar, ))1761- if self.default is not None and \1762- (self.show_default or ctx.show_default):1763- if isinstance(self.show_default, string_types):1764- default_string = '({})'.format(self.show_default)1765- elif isinstance(self.default, (list, tuple)):1766- default_string = ', '.join('%s' % d for d in self.default)1767- elif inspect.isfunction(self.default):1768- default_string = "(dynamic)"1769- else:1770- default_string = self.default1771- extra.append('default: {}'.format(default_string))1772-1773- if self.required:1774- extra.append('required')1775- if extra:1776- help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))1777-1778- return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)1779-1780- def get_default(self, ctx):1781- # If we're a non boolean flag our default is more complex because1782- # we need to look at all flags in the same group to figure out1783- # if we're the the default one in which case we return the flag1784- # value as default.1785- if self.is_flag and not self.is_bool_flag:1786- for param in ctx.command.params:1787- if param.name == self.name and param.default:1788- return param.flag_value1789- return None1790- return Parameter.get_default(self, ctx)1791-1792- def prompt_for_value(self, ctx):1793- """This is an alternative flow that can be activated in the full1794- value processing if a value does not exist. It will prompt the1795- user until a valid value exists and then returns the processed1796- value as result.1797- """1798- # Calculate the default before prompting anything to be stable.1799- default = self.get_default(ctx)1800-1801- # If this is a prompt for a flag we need to handle this1802- # differently.1803- if self.is_bool_flag:1804- return confirm(self.prompt, default)1805-1806- return prompt(self.prompt, default=default, type=self.type,1807- hide_input=self.hide_input, show_choices=self.show_choices,1808- confirmation_prompt=self.confirmation_prompt,1809- value_proc=lambda x: self.process_value(ctx, x))1810-1811- def resolve_envvar_value(self, ctx):1812- rv = Parameter.resolve_envvar_value(self, ctx)1813- if rv is not None:1814- return rv1815- if self.allow_from_autoenv and \1816- ctx.auto_envvar_prefix is not None:1817- envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1818- return os.environ.get(envvar)1819-1820- def value_from_envvar(self, ctx):1821- rv = self.resolve_envvar_value(ctx)1822- if rv is None:1823- return None1824- value_depth = (self.nargs != 1) + bool(self.multiple)1825- if value_depth > 0 and rv is not None:1826- rv = self.type.split_envvar_value(rv)1827- if self.multiple and self.nargs != 1:1828- rv = batch(rv, self.nargs)1829- return rv1830-1831- def full_process_value(self, ctx, value):1832- if value is None and self.prompt is not None \1833- and not ctx.resilient_parsing:1834- return self.prompt_for_value(ctx)1835- return Parameter.full_process_value(self, ctx, value)1836-1837-1838-class Argument(Parameter):1839- """Arguments are positional parameters to a command. They generally1840- provide fewer features than options but can have infinite ``nargs``1841- and are required by default.1842-1843- All parameters are passed onwards to the parameter constructor.1844- """1845- param_type_name = 'argument'1846-1847- def __init__(self, param_decls, required=None, **attrs):1848- if required is None:1849- if attrs.get('default') is not None:1850- required = False1851- else:1852- required = attrs.get('nargs', 1) > 01853- Parameter.__init__(self, param_decls, required=required, **attrs)1854- if self.default is not None and self.nargs < 0:1855- raise TypeError('nargs=-1 in combination with a default value '1856- 'is not supported.')1857-1858- @property1859- def human_readable_name(self):1860- if self.metavar is not None:1861- return self.metavar1862- return self.name.upper()1863-1864- def make_metavar(self):1865- if self.metavar is not None:1866- return self.metavar1867- var = self.type.get_metavar(self)1868- if not var:1869- var = self.name.upper()1870- if not self.required:1871- var = '[%s]' % var1872- if self.nargs != 1:1873- var += '...'1874- return var1875-1876- def _parse_decls(self, decls, expose_value):1877- if not decls:1878- if not expose_value:1879- return None, [], []1880- raise TypeError('Could not determine name for argument')1881- if len(decls) == 1:1882- name = arg = decls[0]1883- name = name.replace('-', '_').lower()1884- else:1885- raise TypeError('Arguments take exactly one '1886- 'parameter declaration, got %d' % len(decls))1887- return name, [arg], []1888-1889- def get_usage_pieces(self, ctx):1890- return [self.make_metavar()]1891-1892- def get_error_hint(self, ctx):1893- return '"%s"' % self.make_metavar()1894-1895- def add_to_parser(self, parser, ctx):1896- parser.add_argument(dest=self.name, nargs=self.nargs,1897- obj=self)1898-1899-1900-# Circular dependency between decorators and core1901-from .decorators import command, groupdeleted:click/decorators.py-311 removed
1-import sys2-import inspect3-4-from functools import update_wrapper5-6-from ._compat import iteritems7-from ._unicodefun import _check_for_unicode_literals8-from .utils import echo9-from .globals import get_current_context10-11-12-def pass_context(f):13- """Marks a callback as wanting to receive the current context14- object as first argument.15- """16- def new_func(*args, **kwargs):17- return f(get_current_context(), *args, **kwargs)18- return update_wrapper(new_func, f)19-20-21-def pass_obj(f):22- """Similar to :func:`pass_context`, but only pass the object on the23- context onwards (:attr:`Context.obj`). This is useful if that object24- represents the state of a nested system.25- """26- def new_func(*args, **kwargs):27- return f(get_current_context().obj, *args, **kwargs)28- return update_wrapper(new_func, f)29-30-31-def make_pass_decorator(object_type, ensure=False):32- """Given an object type this creates a decorator that will work33- similar to :func:`pass_obj` but instead of passing the object of the34- current context, it will find the innermost context of type35- :func:`object_type`.36-37- This generates a decorator that works roughly like this::38-39- from functools import update_wrapper40-41- def decorator(f):42- @pass_context43- def new_func(ctx, *args, **kwargs):44- obj = ctx.find_object(object_type)45- return ctx.invoke(f, obj, *args, **kwargs)46- return update_wrapper(new_func, f)47- return decorator48-49- :param object_type: the type of the object to pass.50- :param ensure: if set to `True`, a new object will be created and51- remembered on the context if it's not there yet.52- """53- def decorator(f):54- def new_func(*args, **kwargs):55- ctx = get_current_context()56- if ensure:57- obj = ctx.ensure_object(object_type)58- else:59- obj = ctx.find_object(object_type)60- if obj is None:61- raise RuntimeError('Managed to invoke callback without a '62- 'context object of type %r existing'63- % object_type.__name__)64- return ctx.invoke(f, obj, *args, **kwargs)65- return update_wrapper(new_func, f)66- return decorator67-68-69-def _make_command(f, name, attrs, cls):70- if isinstance(f, Command):71- raise TypeError('Attempted to convert a callback into a '72- 'command twice.')73- try:74- params = f.__click_params__75- params.reverse()76- del f.__click_params__77- except AttributeError:78- params = []79- help = attrs.get('help')80- if help is None:81- help = inspect.getdoc(f)82- if isinstance(help, bytes):83- help = help.decode('utf-8')84- else:85- help = inspect.cleandoc(help)86- attrs['help'] = help87- _check_for_unicode_literals()88- return cls(name=name or f.__name__.lower().replace('_', '-'),89- callback=f, params=params, **attrs)90-91-92-def command(name=None, cls=None, **attrs):93- r"""Creates a new :class:`Command` and uses the decorated function as94- callback. This will also automatically attach all decorated95- :func:`option`\s and :func:`argument`\s as parameters to the command.96-97- The name of the command defaults to the name of the function with98- underscores replaced by dashes. If you want to change that, you can99- pass the intended name as the first argument.100-101- All keyword arguments are forwarded to the underlying command class.102-103- Once decorated the function turns into a :class:`Command` instance104- that can be invoked as a command line utility or be attached to a105- command :class:`Group`.106-107- :param name: the name of the command. This defaults to the function108- name with underscores replaced by dashes.109- :param cls: the command class to instantiate. This defaults to110- :class:`Command`.111- """112- if cls is None:113- cls = Command114- def decorator(f):115- cmd = _make_command(f, name, attrs, cls)116- cmd.__doc__ = f.__doc__117- return cmd118- return decorator119-120-121-def group(name=None, **attrs):122- """Creates a new :class:`Group` with a function as callback. This123- works otherwise the same as :func:`command` just that the `cls`124- parameter is set to :class:`Group`.125- """126- attrs.setdefault('cls', Group)127- return command(name, **attrs)128-129-130-def _param_memo(f, param):131- if isinstance(f, Command):132- f.params.append(param)133- else:134- if not hasattr(f, '__click_params__'):135- f.__click_params__ = []136- f.__click_params__.append(param)137-138-139-def argument(*param_decls, **attrs):140- """Attaches an argument to the command. All positional arguments are141- passed as parameter declarations to :class:`Argument`; all keyword142- arguments are forwarded unchanged (except ``cls``).143- This is equivalent to creating an :class:`Argument` instance manually144- and attaching it to the :attr:`Command.params` list.145-146- :param cls: the argument class to instantiate. This defaults to147- :class:`Argument`.148- """149- def decorator(f):150- ArgumentClass = attrs.pop('cls', Argument)151- _param_memo(f, ArgumentClass(param_decls, **attrs))152- return f153- return decorator154-155-156-def option(*param_decls, **attrs):157- """Attaches an option to the command. All positional arguments are158- passed as parameter declarations to :class:`Option`; all keyword159- arguments are forwarded unchanged (except ``cls``).160- This is equivalent to creating an :class:`Option` instance manually161- and attaching it to the :attr:`Command.params` list.162-163- :param cls: the option class to instantiate. This defaults to164- :class:`Option`.165- """166- def decorator(f):167- # Issue 926, copy attrs, so pre-defined options can re-use the same cls=168- option_attrs = attrs.copy()169-170- if 'help' in option_attrs:171- option_attrs['help'] = inspect.cleandoc(option_attrs['help'])172- OptionClass = option_attrs.pop('cls', Option)173- _param_memo(f, OptionClass(param_decls, **option_attrs))174- return f175- return decorator176-177-178-def confirmation_option(*param_decls, **attrs):179- """Shortcut for confirmation prompts that can be ignored by passing180- ``--yes`` as parameter.181-182- This is equivalent to decorating a function with :func:`option` with183- the following parameters::184-185- def callback(ctx, param, value):186- if not value:187- ctx.abort()188-189- @click.command()190- @click.option('--yes', is_flag=True, callback=callback,191- expose_value=False, prompt='Do you want to continue?')192- def dropdb():193- pass194- """195- def decorator(f):196- def callback(ctx, param, value):197- if not value:198- ctx.abort()199- attrs.setdefault('is_flag', True)200- attrs.setdefault('callback', callback)201- attrs.setdefault('expose_value', False)202- attrs.setdefault('prompt', 'Do you want to continue?')203- attrs.setdefault('help', 'Confirm the action without prompting.')204- return option(*(param_decls or ('--yes',)), **attrs)(f)205- return decorator206-207-208-def password_option(*param_decls, **attrs):209- """Shortcut for password prompts.210-211- This is equivalent to decorating a function with :func:`option` with212- the following parameters::213-214- @click.command()215- @click.option('--password', prompt=True, confirmation_prompt=True,216- hide_input=True)217- def changeadmin(password):218- pass219- """220- def decorator(f):221- attrs.setdefault('prompt', True)222- attrs.setdefault('confirmation_prompt', True)223- attrs.setdefault('hide_input', True)224- return option(*(param_decls or ('--password',)), **attrs)(f)225- return decorator226-227-228-def version_option(version=None, *param_decls, **attrs):229- """Adds a ``--version`` option which immediately ends the program230- printing out the version number. This is implemented as an eager231- option that prints the version and exits the program in the callback.232-233- :param version: the version number to show. If not provided Click234- attempts an auto discovery via setuptools.235- :param prog_name: the name of the program (defaults to autodetection)236- :param message: custom message to show instead of the default237- (``'%(prog)s, version %(version)s'``)238- :param others: everything else is forwarded to :func:`option`.239- """240- if version is None:241- if hasattr(sys, '_getframe'):242- module = sys._getframe(1).f_globals.get('__name__')243- else:244- module = ''245-246- def decorator(f):247- prog_name = attrs.pop('prog_name', None)248- message = attrs.pop('message', '%(prog)s, version %(version)s')249-250- def callback(ctx, param, value):251- if not value or ctx.resilient_parsing:252- return253- prog = prog_name254- if prog is None:255- prog = ctx.find_root().info_name256- ver = version257- if ver is None:258- try:259- import pkg_resources260- except ImportError:261- pass262- else:263- for dist in pkg_resources.working_set:264- scripts = dist.get_entry_map().get('console_scripts') or {}265- for script_name, entry_point in iteritems(scripts):266- if entry_point.module_name == module:267- ver = dist.version268- break269- if ver is None:270- raise RuntimeError('Could not determine version')271- echo(message % {272- 'prog': prog,273- 'version': ver,274- }, color=ctx.color)275- ctx.exit()276-277- attrs.setdefault('is_flag', True)278- attrs.setdefault('expose_value', False)279- attrs.setdefault('is_eager', True)280- attrs.setdefault('help', 'Show the version and exit.')281- attrs['callback'] = callback282- return option(*(param_decls or ('--version',)), **attrs)(f)283- return decorator284-285-286-def help_option(*param_decls, **attrs):287- """Adds a ``--help`` option which immediately ends the program288- printing out the help page. This is usually unnecessary to add as289- this is added by default to all commands unless suppressed.290-291- Like :func:`version_option`, this is implemented as eager option that292- prints in the callback and exits.293-294- All arguments are forwarded to :func:`option`.295- """296- def decorator(f):297- def callback(ctx, param, value):298- if value and not ctx.resilient_parsing:299- echo(ctx.get_help(), color=ctx.color)300- ctx.exit()301- attrs.setdefault('is_flag', True)302- attrs.setdefault('expose_value', False)303- attrs.setdefault('help', 'Show this message and exit.')304- attrs.setdefault('is_eager', True)305- attrs['callback'] = callback306- return option(*(param_decls or ('--help',)), **attrs)(f)307- return decorator308-309-310-# Circular dependencies between core and decorators311-from .core import Command, Group, Argument, Optiondeleted:click/exceptions.py-248 removed
1-from ._compat import PY2, filename_to_ui, get_text_stderr2-from .utils import echo3-4-5-def _join_param_hints(param_hint):6- if isinstance(param_hint, (tuple, list)):7- return ' / '.join('"%s"' % x for x in param_hint)8- return param_hint9-10-11-class ClickException(Exception):12- """An exception that Click can handle and show to the user."""13-14- #: The exit code for this exception15- exit_code = 116-17- def __init__(self, message):18- ctor_msg = message19- if PY2:20- if ctor_msg is not None:21- ctor_msg = ctor_msg.encode('utf-8')22- Exception.__init__(self, ctor_msg)23- self.message = message24-25- def format_message(self):26- return self.message27-28- def __str__(self):29- return self.message30-31- if PY2:32- __unicode__ = __str__33-34- def __str__(self):35- return self.message.encode('utf-8')36-37- def show(self, file=None):38- if file is None:39- file = get_text_stderr()40- echo('Error: %s' % self.format_message(), file=file)41-42-43-class UsageError(ClickException):44- """An internal exception that signals a usage error. This typically45- aborts any further handling.46-47- :param message: the error message to display.48- :param ctx: optionally the context that caused this error. Click will49- fill in the context automatically in some situations.50- """51- exit_code = 252-53- def __init__(self, message, ctx=None):54- ClickException.__init__(self, message)55- self.ctx = ctx56- self.cmd = self.ctx and self.ctx.command or None57-58- def show(self, file=None):59- if file is None:60- file = get_text_stderr()61- color = None62- hint = ''63- if (self.cmd is not None and64- self.cmd.get_help_option(self.ctx) is not None):65- hint = ('Try "%s %s" for help.\n'66- % (self.ctx.command_path, self.ctx.help_option_names[0]))67- if self.ctx is not None:68- color = self.ctx.color69- echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)70- echo('Error: %s' % self.format_message(), file=file, color=color)71-72-73-class BadParameter(UsageError):74- """An exception that formats out a standardized error message for a75- bad parameter. This is useful when thrown from a callback or type as76- Click will attach contextual information to it (for instance, which77- parameter it is).78-79- .. versionadded:: 2.080-81- :param param: the parameter object that caused this error. This can82- be left out, and Click will attach this info itself83- if possible.84- :param param_hint: a string that shows up as parameter name. This85- can be used as alternative to `param` in cases86- where custom validation should happen. If it is87- a string it's used as such, if it's a list then88- each item is quoted and separated.89- """90-91- def __init__(self, message, ctx=None, param=None,92- param_hint=None):93- UsageError.__init__(self, message, ctx)94- self.param = param95- self.param_hint = param_hint96-97- def format_message(self):98- if self.param_hint is not None:99- param_hint = self.param_hint100- elif self.param is not None:101- param_hint = self.param.get_error_hint(self.ctx)102- else:103- return 'Invalid value: %s' % self.message104- param_hint = _join_param_hints(param_hint)105-106- return 'Invalid value for %s: %s' % (param_hint, self.message)107-108-109-class MissingParameter(BadParameter):110- """Raised if click required an option or argument but it was not111- provided when invoking the script.112-113- .. versionadded:: 4.0114-115- :param param_type: a string that indicates the type of the parameter.116- The default is to inherit the parameter type from117- the given `param`. Valid values are ``'parameter'``,118- ``'option'`` or ``'argument'``.119- """120-121- def __init__(self, message=None, ctx=None, param=None,122- param_hint=None, param_type=None):123- BadParameter.__init__(self, message, ctx, param, param_hint)124- self.param_type = param_type125-126- def format_message(self):127- if self.param_hint is not None:128- param_hint = self.param_hint129- elif self.param is not None:130- param_hint = self.param.get_error_hint(self.ctx)131- else:132- param_hint = None133- param_hint = _join_param_hints(param_hint)134-135- param_type = self.param_type136- if param_type is None and self.param is not None:137- param_type = self.param.param_type_name138-139- msg = self.message140- if self.param is not None:141- msg_extra = self.param.type.get_missing_message(self.param)142- if msg_extra:143- if msg:144- msg += '. ' + msg_extra145- else:146- msg = msg_extra147-148- return 'Missing %s%s%s%s' % (149- param_type,150- param_hint and ' %s' % param_hint or '',151- msg and '. ' or '.',152- msg or '',153- )154-155- def __str__(self):156- if self.message is None:157- param_name = self.param.name if self.param else None158- return "missing parameter: {}".format(param_name)159- else:160- return self.message161-162- if PY2:163- __unicode__ = __str__164-165- def __str__(self):166- return self.__unicode__().encode("utf-8")167-168-169-class NoSuchOption(UsageError):170- """Raised if click attempted to handle an option that does not171- exist.172-173- .. versionadded:: 4.0174- """175-176- def __init__(self, option_name, message=None, possibilities=None,177- ctx=None):178- if message is None:179- message = 'no such option: %s' % option_name180- UsageError.__init__(self, message, ctx)181- self.option_name = option_name182- self.possibilities = possibilities183-184- def format_message(self):185- bits = [self.message]186- if self.possibilities:187- if len(self.possibilities) == 1:188- bits.append('Did you mean %s?' % self.possibilities[0])189- else:190- possibilities = sorted(self.possibilities)191- bits.append('(Possible options: %s)' % ', '.join(possibilities))192- return ' '.join(bits)193-194-195-class BadOptionUsage(UsageError):196- """Raised if an option is generally supplied but the use of the option197- was incorrect. This is for instance raised if the number of arguments198- for an option is not correct.199-200- .. versionadded:: 4.0201-202- :param option_name: the name of the option being used incorrectly.203- """204-205- def __init__(self, option_name, message, ctx=None):206- UsageError.__init__(self, message, ctx)207- self.option_name = option_name208-209-210-class BadArgumentUsage(UsageError):211- """Raised if an argument is generally supplied but the use of the argument212- was incorrect. This is for instance raised if the number of values213- for an argument is not correct.214-215- .. versionadded:: 6.0216- """217-218- def __init__(self, message, ctx=None):219- UsageError.__init__(self, message, ctx)220-221-222-class FileError(ClickException):223- """Raised if a file cannot be opened."""224-225- def __init__(self, filename, hint=None):226- ui_filename = filename_to_ui(filename)227- if hint is None:228- hint = 'unknown error'229- ClickException.__init__(self, hint)230- self.ui_filename = ui_filename231- self.filename = filename232-233- def format_message(self):234- return 'Could not open file %s: %s' % (self.ui_filename, self.message)235-236-237-class Abort(RuntimeError):238- """An internal signalling exception that signals Click to abort."""239-240-241-class Exit(RuntimeError):242- """An exception that indicates that the application should exit with some243- status code.244-245- :param code: the status code to exit with.246- """247- def __init__(self, code=0):248- self.exit_code = codedeleted:click/formatting.py-262 removed
1-from contextlib import contextmanager2-from .termui import get_terminal_size3-from .parser import split_opt4-from ._compat import term_len5-6-7-# Can force a width. This is used by the test system8-FORCED_WIDTH = None9-10-11-def measure_table(rows):12- widths = {}13- for row in rows:14- for idx, col in enumerate(row):15- widths[idx] = max(widths.get(idx, 0), term_len(col))16- return tuple(y for x, y in sorted(widths.items()))17-18-19-def iter_rows(rows, col_count):20- for row in rows:21- row = tuple(row)22- yield row + ('',) * (col_count - len(row))23-24-25-def wrap_text(text, width=78, initial_indent='', subsequent_indent='',26- preserve_paragraphs=False):27- """A helper function that intelligently wraps text. By default, it28- assumes that it operates on a single paragraph of text but if the29- `preserve_paragraphs` parameter is provided it will intelligently30- handle paragraphs (defined by two empty lines).31-32- If paragraphs are handled, a paragraph can be prefixed with an empty33- line containing the ``\\b`` character (``\\x08``) to indicate that34- no rewrapping should happen in that block.35-36- :param text: the text that should be rewrapped.37- :param width: the maximum width for the text.38- :param initial_indent: the initial indent that should be placed on the39- first line as a string.40- :param subsequent_indent: the indent string that should be placed on41- each consecutive line.42- :param preserve_paragraphs: if this flag is set then the wrapping will43- intelligently handle paragraphs.44- """45- from ._textwrap import TextWrapper46- text = text.expandtabs()47- wrapper = TextWrapper(width, initial_indent=initial_indent,48- subsequent_indent=subsequent_indent,49- replace_whitespace=False)50- if not preserve_paragraphs:51- return wrapper.fill(text)52-53- p = []54- buf = []55- indent = None56-57- def _flush_par():58- if not buf:59- return60- if buf[0].strip() == '\b':61- p.append((indent or 0, True, '\n'.join(buf[1:])))62- else:63- p.append((indent or 0, False, ' '.join(buf)))64- del buf[:]65-66- for line in text.splitlines():67- if not line:68- _flush_par()69- indent = None70- else:71- if indent is None:72- orig_len = term_len(line)73- line = line.lstrip()74- indent = orig_len - term_len(line)75- buf.append(line)76- _flush_par()77-78- rv = []79- for indent, raw, text in p:80- with wrapper.extra_indent(' ' * indent):81- if raw:82- rv.append(wrapper.indent_only(text))83- else:84- rv.append(wrapper.fill(text))85-86- return '\n\n'.join(rv)87-88-89-class HelpFormatter(object):90- """This class helps with formatting text-based help pages. It's91- usually just needed for very special internal cases, but it's also92- exposed so that developers can write their own fancy outputs.93-94- At present, it always writes into memory.95-96- :param indent_increment: the additional increment for each level.97- :param width: the width for the text. This defaults to the terminal98- width clamped to a maximum of 78.99- """100-101- def __init__(self, indent_increment=2, width=None, max_width=None):102- self.indent_increment = indent_increment103- if max_width is None:104- max_width = 80105- if width is None:106- width = FORCED_WIDTH107- if width is None:108- width = max(min(get_terminal_size()[0], max_width) - 2, 50)109- self.width = width110- self.current_indent = 0111- self.buffer = []112-113- def write(self, string):114- """Writes a unicode string into the internal buffer."""115- self.buffer.append(string)116-117- def indent(self):118- """Increases the indentation."""119- self.current_indent += self.indent_increment120-121- def dedent(self):122- """Decreases the indentation."""123- self.current_indent -= self.indent_increment124-125- def write_usage(self, prog, args='', prefix='Usage: '):126- """Writes a usage line into the buffer.127-128- :param prog: the program name.129- :param args: whitespace separated list of arguments.130- :param prefix: the prefix for the first line.131- """132- usage_prefix = '%*s%s ' % (self.current_indent, prefix, prog)133- text_width = self.width - self.current_indent134-135- if text_width >= (term_len(usage_prefix) + 20):136- # The arguments will fit to the right of the prefix.137- indent = ' ' * term_len(usage_prefix)138- self.write(wrap_text(args, text_width,139- initial_indent=usage_prefix,140- subsequent_indent=indent))141- else:142- # The prefix is too long, put the arguments on the next line.143- self.write(usage_prefix)144- self.write('\n')145- indent = ' ' * (max(self.current_indent, term_len(prefix)) + 4)146- self.write(wrap_text(args, text_width,147- initial_indent=indent,148- subsequent_indent=indent))149-150- self.write('\n')151-152- def write_heading(self, heading):153- """Writes a heading into the buffer."""154- self.write('%*s%s:\n' % (self.current_indent, '', heading))155-156- def write_paragraph(self):157- """Writes a paragraph into the buffer."""158- if self.buffer:159- self.write('\n')160-161- def write_text(self, text):162- """Writes re-indented text into the buffer. This rewraps and163- preserves paragraphs.164- """165- text_width = max(self.width - self.current_indent, 11)166- indent = ' ' * self.current_indent167- self.write(wrap_text(text, text_width,168- initial_indent=indent,169- subsequent_indent=indent,170- preserve_paragraphs=True))171- self.write('\n')172-173- def write_dl(self, rows, col_max=30, col_spacing=2):174- """Writes a definition list into the buffer. This is how options175- and commands are usually formatted.176-177- :param rows: a list of two item tuples for the terms and values.178- :param col_max: the maximum width of the first column.179- :param col_spacing: the number of spaces between the first and180- second column.181- """182- rows = list(rows)183- widths = measure_table(rows)184- if len(widths) != 2:185- raise TypeError('Expected two columns for definition list')186-187- first_col = min(widths[0], col_max) + col_spacing188-189- for first, second in iter_rows(rows, len(widths)):190- self.write('%*s%s' % (self.current_indent, '', first))191- if not second:192- self.write('\n')193- continue194- if term_len(first) <= first_col - col_spacing:195- self.write(' ' * (first_col - term_len(first)))196- else:197- self.write('\n')198- self.write(' ' * (first_col + self.current_indent))199-200- text_width = max(self.width - first_col - 2, 10)201- wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)202- lines = wrapped_text.splitlines()203-204- if lines:205- self.write(lines[0] + '\n')206-207- for line in lines[1:]:208- self.write('%*s%s\n' % (first_col + self.current_indent, '', line))209-210- if len(lines) > 1:211- # separate long help from next option212- self.write("\n")213- else:214- self.write('\n')215-216- @contextmanager217- def section(self, name):218- """Helpful context manager that writes a paragraph, a heading,219- and the indents.220-221- :param name: the section name that is written as heading.222- """223- self.write_paragraph()224- self.write_heading(name)225- self.indent()226- try:227- yield228- finally:229- self.dedent()230-231- @contextmanager232- def indentation(self):233- """A context manager that increases the indentation."""234- self.indent()235- try:236- yield237- finally:238- self.dedent()239-240- def getvalue(self):241- """Returns the buffer contents."""242- return ''.join(self.buffer)243-244-245-def join_options(options):246- """Given a list of option strings this joins them in the most appropriate247- way and returns them in the form ``(formatted_string,248- any_prefix_is_slash)`` where the second item in the tuple is a flag that249- indicates if any of the option prefixes was a slash.250- """251- rv = []252- any_prefix_is_slash = False253- for opt in options:254- prefix = split_opt(opt)[0]255- if prefix == '/':256- any_prefix_is_slash = True257- rv.append((len(prefix), opt))258-259- rv.sort(key=lambda x: x[0])260-261- rv = ', '.join(x[1] for x in rv)262- return rv, any_prefix_is_slashdeleted:click/globals.py-48 removed
1-from threading import local2-3-4-_local = local()5-6-7-def get_current_context(silent=False):8- """Returns the current click context. This can be used as a way to9- access the current context object from anywhere. This is a more implicit10- alternative to the :func:`pass_context` decorator. This function is11- primarily useful for helpers such as :func:`echo` which might be12- interested in changing its behavior based on the current context.13-14- To push the current context, :meth:`Context.scope` can be used.15-16- .. versionadded:: 5.017-18- :param silent: if set to `True` the return value is `None` if no context19- is available. The default behavior is to raise a20- :exc:`RuntimeError`.21- """22- try:23- return getattr(_local, 'stack')[-1]24- except (AttributeError, IndexError):25- if not silent:26- raise RuntimeError('There is no active click context.')27-28-29-def push_context(ctx):30- """Pushes a new context to the current stack."""31- _local.__dict__.setdefault('stack', []).append(ctx)32-33-34-def pop_context():35- """Removes the top level from the stack."""36- _local.stack.pop()37-38-39-def resolve_color_default(color=None):40- """"Internal helper to get the default value of the color flag. If a41- value is passed it's returned unchanged, otherwise it's looked up from42- the current context.43- """44- if color is not None:45- return color46- ctx = get_current_context(silent=True)47- if ctx is not None:48- return ctx.colordeleted:click/parser.py-430 removed
1-# -*- coding: utf-8 -*-2-"""3-This module started out as largely a copy paste from the stdlib's4-optparse module with the features removed that we do not need from5-optparse because we implement them in Click on a higher level (for6-instance type handling, help formatting and a lot more).7-8-The plan is to remove more and more from here over time.9-10-The reason this is a different module and not optparse from the stdlib11-is that there are differences in 2.x and 3.x about the error messages12-generated and optparse in the stdlib uses gettext for no good reason13-and might cause us issues.14-15-Click uses parts of optparse written by Gregory P. Ward and maintained16-by the Python Software Foundation. This is limited to code in parser.py.17-18-Copyright 2001-2006 Gregory P. Ward. All rights reserved.19-Copyright 2002-2006 Python Software Foundation. All rights reserved.20-"""21-22-import re23-from collections import deque24-from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \25- BadArgumentUsage26-27-28-def _unpack_args(args, nargs_spec):29- """Given an iterable of arguments and an iterable of nargs specifications,30- it returns a tuple with all the unpacked arguments at the first index31- and all remaining arguments as the second.32-33- The nargs specification is the number of arguments that should be consumed34- or `-1` to indicate that this position should eat up all the remainders.35-36- Missing items are filled with `None`.37- """38- args = deque(args)39- nargs_spec = deque(nargs_spec)40- rv = []41- spos = None42-43- def _fetch(c):44- try:45- if spos is None:46- return c.popleft()47- else:48- return c.pop()49- except IndexError:50- return None51-52- while nargs_spec:53- nargs = _fetch(nargs_spec)54- if nargs == 1:55- rv.append(_fetch(args))56- elif nargs > 1:57- x = [_fetch(args) for _ in range(nargs)]58- # If we're reversed, we're pulling in the arguments in reverse,59- # so we need to turn them around.60- if spos is not None:61- x.reverse()62- rv.append(tuple(x))63- elif nargs < 0:64- if spos is not None:65- raise TypeError('Cannot have two nargs < 0')66- spos = len(rv)67- rv.append(None)68-69- # spos is the position of the wildcard (star). If it's not `None`,70- # we fill it with the remainder.71- if spos is not None:72- rv[spos] = tuple(args)73- args = []74- rv[spos + 1:] = reversed(rv[spos + 1:])75-76- return tuple(rv), list(args)77-78-79-def _error_opt_args(nargs, opt):80- if nargs == 1:81- raise BadOptionUsage(opt, '%s option requires an argument' % opt)82- raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))83-84-85-def split_opt(opt):86- first = opt[:1]87- if first.isalnum():88- return '', opt89- if opt[1:2] == first:90- return opt[:2], opt[2:]91- return first, opt[1:]92-93-94-def normalize_opt(opt, ctx):95- if ctx is None or ctx.token_normalize_func is None:96- return opt97- prefix, opt = split_opt(opt)98- return prefix + ctx.token_normalize_func(opt)99-100-101-def split_arg_string(string):102- """Given an argument string this attempts to split it into small parts."""103- rv = []104- for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"105- r'|"([^"\\]*(?:\\.[^"\\]*)*)"'106- r'|\S+)\s*', string, re.S):107- arg = match.group().strip()108- if arg[:1] == arg[-1:] and arg[:1] in '"\'':109- arg = arg[1:-1].encode('ascii', 'backslashreplace') \110- .decode('unicode-escape')111- try:112- arg = type(string)(arg)113- except UnicodeError:114- pass115- rv.append(arg)116- return rv117-118-119-class Option(object):120-121- def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):122- self._short_opts = []123- self._long_opts = []124- self.prefixes = set()125-126- for opt in opts:127- prefix, value = split_opt(opt)128- if not prefix:129- raise ValueError('Invalid start character for option (%s)'130- % opt)131- self.prefixes.add(prefix[0])132- if len(prefix) == 1 and len(value) == 1:133- self._short_opts.append(opt)134- else:135- self._long_opts.append(opt)136- self.prefixes.add(prefix)137-138- if action is None:139- action = 'store'140-141- self.dest = dest142- self.action = action143- self.nargs = nargs144- self.const = const145- self.obj = obj146-147- @property148- def takes_value(self):149- return self.action in ('store', 'append')150-151- def process(self, value, state):152- if self.action == 'store':153- state.opts[self.dest] = value154- elif self.action == 'store_const':155- state.opts[self.dest] = self.const156- elif self.action == 'append':157- state.opts.setdefault(self.dest, []).append(value)158- elif self.action == 'append_const':159- state.opts.setdefault(self.dest, []).append(self.const)160- elif self.action == 'count':161- state.opts[self.dest] = state.opts.get(self.dest, 0) + 1162- else:163- raise ValueError('unknown action %r' % self.action)164- state.order.append(self.obj)165-166-167-class Argument(object):168-169- def __init__(self, dest, nargs=1, obj=None):170- self.dest = dest171- self.nargs = nargs172- self.obj = obj173-174- def process(self, value, state):175- if self.nargs > 1:176- holes = sum(1 for x in value if x is None)177- if holes == len(value):178- value = None179- elif holes != 0:180- raise BadArgumentUsage('argument %s takes %d values'181- % (self.dest, self.nargs))182- state.opts[self.dest] = value183- state.order.append(self.obj)184-185-186-class ParsingState(object):187-188- def __init__(self, rargs):189- self.opts = {}190- self.largs = []191- self.rargs = rargs192- self.order = []193-194-195-class OptionParser(object):196- """The option parser is an internal class that is ultimately used to197- parse options and arguments. It's modelled after optparse and brings198- a similar but vastly simplified API. It should generally not be used199- directly as the high level Click classes wrap it for you.200-201- It's not nearly as extensible as optparse or argparse as it does not202- implement features that are implemented on a higher level (such as203- types or defaults).204-205- :param ctx: optionally the :class:`~click.Context` where this parser206- should go with.207- """208-209- def __init__(self, ctx=None):210- #: The :class:`~click.Context` for this parser. This might be211- #: `None` for some advanced use cases.212- self.ctx = ctx213- #: This controls how the parser deals with interspersed arguments.214- #: If this is set to `False`, the parser will stop on the first215- #: non-option. Click uses this to implement nested subcommands216- #: safely.217- self.allow_interspersed_args = True218- #: This tells the parser how to deal with unknown options. By219- #: default it will error out (which is sensible), but there is a220- #: second mode where it will ignore it and continue processing221- #: after shifting all the unknown options into the resulting args.222- self.ignore_unknown_options = False223- if ctx is not None:224- self.allow_interspersed_args = ctx.allow_interspersed_args225- self.ignore_unknown_options = ctx.ignore_unknown_options226- self._short_opt = {}227- self._long_opt = {}228- self._opt_prefixes = set(['-', '--'])229- self._args = []230-231- def add_option(self, opts, dest, action=None, nargs=1, const=None,232- obj=None):233- """Adds a new option named `dest` to the parser. The destination234- is not inferred (unlike with optparse) and needs to be explicitly235- provided. Action can be any of ``store``, ``store_const``,236- ``append``, ``appnd_const`` or ``count``.237-238- The `obj` can be used to identify the option in the order list239- that is returned from the parser.240- """241- if obj is None:242- obj = dest243- opts = [normalize_opt(opt, self.ctx) for opt in opts]244- option = Option(opts, dest, action=action, nargs=nargs,245- const=const, obj=obj)246- self._opt_prefixes.update(option.prefixes)247- for opt in option._short_opts:248- self._short_opt[opt] = option249- for opt in option._long_opts:250- self._long_opt[opt] = option251-252- def add_argument(self, dest, nargs=1, obj=None):253- """Adds a positional argument named `dest` to the parser.254-255- The `obj` can be used to identify the option in the order list256- that is returned from the parser.257- """258- if obj is None:259- obj = dest260- self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))261-262- def parse_args(self, args):263- """Parses positional arguments and returns ``(values, args, order)``264- for the parsed options and arguments as well as the leftover265- arguments if there are any. The order is a list of objects as they266- appear on the command line. If arguments appear multiple times they267- will be memorized multiple times as well.268- """269- state = ParsingState(args)270- try:271- self._process_args_for_options(state)272- self._process_args_for_args(state)273- except UsageError:274- if self.ctx is None or not self.ctx.resilient_parsing:275- raise276- return state.opts, state.largs, state.order277-278- def _process_args_for_args(self, state):279- pargs, args = _unpack_args(state.largs + state.rargs,280- [x.nargs for x in self._args])281-282- for idx, arg in enumerate(self._args):283- arg.process(pargs[idx], state)284-285- state.largs = args286- state.rargs = []287-288- def _process_args_for_options(self, state):289- while state.rargs:290- arg = state.rargs.pop(0)291- arglen = len(arg)292- # Double dashes always handled explicitly regardless of what293- # prefixes are valid.294- if arg == '--':295- return296- elif arg[:1] in self._opt_prefixes and arglen > 1:297- self._process_opts(arg, state)298- elif self.allow_interspersed_args:299- state.largs.append(arg)300- else:301- state.rargs.insert(0, arg)302- return303-304- # Say this is the original argument list:305- # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]306- # ^307- # (we are about to process arg(i)).308- #309- # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of310- # [arg0, ..., arg(i-1)] (any options and their arguments will have311- # been removed from largs).312- #313- # The while loop will usually consume 1 or more arguments per pass.314- # If it consumes 1 (eg. arg is an option that takes no arguments),315- # then after _process_arg() is done the situation is:316- #317- # largs = subset of [arg0, ..., arg(i)]318- # rargs = [arg(i+1), ..., arg(N-1)]319- #320- # If allow_interspersed_args is false, largs will always be321- # *empty* -- still a subset of [arg0, ..., arg(i-1)], but322- # not a very interesting subset!323-324- def _match_long_opt(self, opt, explicit_value, state):325- if opt not in self._long_opt:326- possibilities = [word for word in self._long_opt327- if word.startswith(opt)]328- raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)329-330- option = self._long_opt[opt]331- if option.takes_value:332- # At this point it's safe to modify rargs by injecting the333- # explicit value, because no exception is raised in this334- # branch. This means that the inserted value will be fully335- # consumed.336- if explicit_value is not None:337- state.rargs.insert(0, explicit_value)338-339- nargs = option.nargs340- if len(state.rargs) < nargs:341- _error_opt_args(nargs, opt)342- elif nargs == 1:343- value = state.rargs.pop(0)344- else:345- value = tuple(state.rargs[:nargs])346- del state.rargs[:nargs]347-348- elif explicit_value is not None:349- raise BadOptionUsage(opt, '%s option does not take a value' % opt)350-351- else:352- value = None353-354- option.process(value, state)355-356- def _match_short_opt(self, arg, state):357- stop = False358- i = 1359- prefix = arg[0]360- unknown_options = []361-362- for ch in arg[1:]:363- opt = normalize_opt(prefix + ch, self.ctx)364- option = self._short_opt.get(opt)365- i += 1366-367- if not option:368- if self.ignore_unknown_options:369- unknown_options.append(ch)370- continue371- raise NoSuchOption(opt, ctx=self.ctx)372- if option.takes_value:373- # Any characters left in arg? Pretend they're the374- # next arg, and stop consuming characters of arg.375- if i < len(arg):376- state.rargs.insert(0, arg[i:])377- stop = True378-379- nargs = option.nargs380- if len(state.rargs) < nargs:381- _error_opt_args(nargs, opt)382- elif nargs == 1:383- value = state.rargs.pop(0)384- else:385- value = tuple(state.rargs[:nargs])386- del state.rargs[:nargs]387-388- else:389- value = None390-391- option.process(value, state)392-393- if stop:394- break395-396- # If we got any unknown options we re-combinate the string of the397- # remaining options and re-attach the prefix, then report that398- # to the state as new larg. This way there is basic combinatorics399- # that can be achieved while still ignoring unknown arguments.400- if self.ignore_unknown_options and unknown_options:401- state.largs.append(prefix + ''.join(unknown_options))402-403- def _process_opts(self, arg, state):404- explicit_value = None405- # Long option handling happens in two parts. The first part is406- # supporting explicitly attached values. In any case, we will try407- # to long match the option first.408- if '=' in arg:409- long_opt, explicit_value = arg.split('=', 1)410- else:411- long_opt = arg412- norm_long_opt = normalize_opt(long_opt, self.ctx)413-414- # At this point we will match the (assumed) long option through415- # the long option matching code. Note that this allows options416- # like "-foo" to be matched as long options.417- try:418- self._match_long_opt(norm_long_opt, explicit_value, state)419- except NoSuchOption:420- # At this point the long option matching failed, and we need421- # to try with short options. However there is a special rule422- # which says, that if we have a two character options prefix423- # (applies to "--foo" for instance), we do not dispatch to the424- # short option code and will instead raise the no option425- # error.426- if arg[:2] not in self._opt_prefixes:427- return self._match_short_opt(arg, state)428- if not self.ignore_unknown_options:429- raise430- state.largs.append(arg)deleted:click/termui.py-621 removed
1-import io2-import os3-import sys4-import struct5-import inspect6-import itertools7-8-from ._compat import raw_input, text_type, string_types, \9- isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN10-from .utils import echo11-from .exceptions import Abort, UsageError12-from .types import convert_type, Choice, Path13-from .globals import resolve_color_default14-from .utils import LazyFile15-16-17-# The prompt functions to use. The doc tools currently override these18-# functions to customize how they work.19-visible_prompt_func = raw_input20-21-_ansi_colors = {22- 'black': 30,23- 'red': 31,24- 'green': 32,25- 'yellow': 33,26- 'blue': 34,27- 'magenta': 35,28- 'cyan': 36,29- 'white': 37,30- 'reset': 39,31- 'bright_black': 90,32- 'bright_red': 91,33- 'bright_green': 92,34- 'bright_yellow': 93,35- 'bright_blue': 94,36- 'bright_magenta': 95,37- 'bright_cyan': 96,38- 'bright_white': 97,39-}40-_ansi_reset_all = '\033[0m'41-42-43-def hidden_prompt_func(prompt):44- import getpass45- return getpass.getpass(prompt)46-47-48-def _build_prompt(text, suffix, show_default=False, default=None, show_choices=True, type=None):49- prompt = text50- if type is not None and show_choices and isinstance(type, Choice):51- prompt += ' (' + ", ".join(map(str, type.choices)) + ')'52- if default is not None and show_default:53- prompt = '%s [%s]' % (prompt, _format_default(default))54- return prompt + suffix55-56-57-def _format_default(default):58- if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):59- return default.name60-61- return default62-63-64-def prompt(text, default=None, hide_input=False, confirmation_prompt=False,65- type=None, value_proc=None, prompt_suffix=': ', show_default=True,66- err=False, show_choices=True):67- """Prompts a user for input. This is a convenience function that can68- be used to prompt a user for input later.69-70- If the user aborts the input by sending a interrupt signal, this71- function will catch it and raise a :exc:`Abort` exception.72-73- .. versionadded:: 7.074- Added the show_choices parameter.75-76- .. versionadded:: 6.077- Added unicode support for cmd.exe on Windows.78-79- .. versionadded:: 4.080- Added the `err` parameter.81-82- :param text: the text to show for the prompt.83- :param default: the default value to use if no input happens. If this84- is not given it will prompt until it's aborted.85- :param hide_input: if this is set to true then the input value will86- be hidden.87- :param confirmation_prompt: asks for confirmation for the value.88- :param type: the type to use to check the value against.89- :param value_proc: if this parameter is provided it's a function that90- is invoked instead of the type conversion to91- convert a value.92- :param prompt_suffix: a suffix that should be added to the prompt.93- :param show_default: shows or hides the default value in the prompt.94- :param err: if set to true the file defaults to ``stderr`` instead of95- ``stdout``, the same as with echo.96- :param show_choices: Show or hide choices if the passed type is a Choice.97- For example if type is a Choice of either day or week,98- show_choices is true and text is "Group by" then the99- prompt will be "Group by (day, week): ".100- """101- result = None102-103- def prompt_func(text):104- f = hide_input and hidden_prompt_func or visible_prompt_func105- try:106- # Write the prompt separately so that we get nice107- # coloring through colorama on Windows108- echo(text, nl=False, err=err)109- return f('')110- except (KeyboardInterrupt, EOFError):111- # getpass doesn't print a newline if the user aborts input with ^C.112- # Allegedly this behavior is inherited from getpass(3).113- # A doc bug has been filed at https://bugs.python.org/issue24711114- if hide_input:115- echo(None, err=err)116- raise Abort()117-118- if value_proc is None:119- value_proc = convert_type(type, default)120-121- prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)122-123- while 1:124- while 1:125- value = prompt_func(prompt)126- if value:127- break128- elif default is not None:129- if isinstance(value_proc, Path):130- # validate Path default value(exists, dir_okay etc.)131- value = default132- break133- return default134- try:135- result = value_proc(value)136- except UsageError as e:137- echo('Error: %s' % e.message, err=err)138- continue139- if not confirmation_prompt:140- return result141- while 1:142- value2 = prompt_func('Repeat for confirmation: ')143- if value2:144- break145- if value == value2:146- return result147- echo('Error: the two entered values do not match', err=err)148-149-150-def confirm(text, default=False, abort=False, prompt_suffix=': ',151- show_default=True, err=False):152- """Prompts for confirmation (yes/no question).153-154- If the user aborts the input by sending a interrupt signal this155- function will catch it and raise a :exc:`Abort` exception.156-157- .. versionadded:: 4.0158- Added the `err` parameter.159-160- :param text: the question to ask.161- :param default: the default for the prompt.162- :param abort: if this is set to `True` a negative answer aborts the163- exception by raising :exc:`Abort`.164- :param prompt_suffix: a suffix that should be added to the prompt.165- :param show_default: shows or hides the default value in the prompt.166- :param err: if set to true the file defaults to ``stderr`` instead of167- ``stdout``, the same as with echo.168- """169- prompt = _build_prompt(text, prompt_suffix, show_default,170- default and 'Y/n' or 'y/N')171- while 1:172- try:173- # Write the prompt separately so that we get nice174- # coloring through colorama on Windows175- echo(prompt, nl=False, err=err)176- value = visible_prompt_func('').lower().strip()177- except (KeyboardInterrupt, EOFError):178- raise Abort()179- if value in ('y', 'yes'):180- rv = True181- elif value in ('n', 'no'):182- rv = False183- elif value == '':184- rv = default185- else:186- echo('Error: invalid input', err=err)187- continue188- break189- if abort and not rv:190- raise Abort()191- return rv192-193-194-def get_terminal_size():195- """Returns the current size of the terminal as tuple in the form196- ``(width, height)`` in columns and rows.197- """198- # If shutil has get_terminal_size() (Python 3.3 and later) use that199- if sys.version_info >= (3, 3):200- import shutil201- shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)202- if shutil_get_terminal_size:203- sz = shutil_get_terminal_size()204- return sz.columns, sz.lines205-206- # We provide a sensible default for get_winterm_size() when being invoked207- # inside a subprocess. Without this, it would not provide a useful input.208- if get_winterm_size is not None:209- size = get_winterm_size()210- if size == (0, 0):211- return (79, 24)212- else:213- return size214-215- def ioctl_gwinsz(fd):216- try:217- import fcntl218- import termios219- cr = struct.unpack(220- 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))221- except Exception:222- return223- return cr224-225- cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)226- if not cr:227- try:228- fd = os.open(os.ctermid(), os.O_RDONLY)229- try:230- cr = ioctl_gwinsz(fd)231- finally:232- os.close(fd)233- except Exception:234- pass235- if not cr or not cr[0] or not cr[1]:236- cr = (os.environ.get('LINES', 25),237- os.environ.get('COLUMNS', DEFAULT_COLUMNS))238- return int(cr[1]), int(cr[0])239-240-241-def echo_via_pager(text_or_generator, color=None):242- """This function takes a text and shows it via an environment specific243- pager on stdout.244-245- .. versionchanged:: 3.0246- Added the `color` flag.247-248- :param text_or_generator: the text to page, or alternatively, a249- generator emitting the text to page.250- :param color: controls if the pager supports ANSI colors or not. The251- default is autodetection.252- """253- color = resolve_color_default(color)254-255- if inspect.isgeneratorfunction(text_or_generator):256- i = text_or_generator()257- elif isinstance(text_or_generator, string_types):258- i = [text_or_generator]259- else:260- i = iter(text_or_generator)261-262- # convert every element of i to a text type if necessary263- text_generator = (el if isinstance(el, string_types) else text_type(el)264- for el in i)265-266- from ._termui_impl import pager267- return pager(itertools.chain(text_generator, "\n"), color)268-269-270-def progressbar(iterable=None, length=None, label=None, show_eta=True,271- show_percent=None, show_pos=False,272- item_show_func=None, fill_char='#', empty_char='-',273- bar_template='%(label)s [%(bar)s] %(info)s',274- info_sep=' ', width=36, file=None, color=None):275- """This function creates an iterable context manager that can be used276- to iterate over something while showing a progress bar. It will277- either iterate over the `iterable` or `length` items (that are counted278- up). While iteration happens, this function will print a rendered279- progress bar to the given `file` (defaults to stdout) and will attempt280- to calculate remaining time and more. By default, this progress bar281- will not be rendered if the file is not a terminal.282-283- The context manager creates the progress bar. When the context284- manager is entered the progress bar is already created. With every285- iteration over the progress bar, the iterable passed to the bar is286- advanced and the bar is updated. When the context manager exits,287- a newline is printed and the progress bar is finalized on screen.288-289- Note: The progress bar is currently designed for use cases where the290- total progress can be expected to take at least several seconds.291- Because of this, the ProgressBar class object won't display292- progress that is considered too fast, and progress where the time293- between steps is less than a second.294-295- No printing must happen or the progress bar will be unintentionally296- destroyed.297-298- Example usage::299-300- with progressbar(items) as bar:301- for item in bar:302- do_something_with(item)303-304- Alternatively, if no iterable is specified, one can manually update the305- progress bar through the `update()` method instead of directly306- iterating over the progress bar. The update method accepts the number307- of steps to increment the bar with::308-309- with progressbar(length=chunks.total_bytes) as bar:310- for chunk in chunks:311- process_chunk(chunk)312- bar.update(chunks.bytes)313-314- .. versionadded:: 2.0315-316- .. versionadded:: 4.0317- Added the `color` parameter. Added a `update` method to the318- progressbar object.319-320- :param iterable: an iterable to iterate over. If not provided the length321- is required.322- :param length: the number of items to iterate over. By default the323- progressbar will attempt to ask the iterator about its324- length, which might or might not work. If an iterable is325- also provided this parameter can be used to override the326- length. If an iterable is not provided the progress bar327- will iterate over a range of that length.328- :param label: the label to show next to the progress bar.329- :param show_eta: enables or disables the estimated time display. This is330- automatically disabled if the length cannot be331- determined.332- :param show_percent: enables or disables the percentage display. The333- default is `True` if the iterable has a length or334- `False` if not.335- :param show_pos: enables or disables the absolute position display. The336- default is `False`.337- :param item_show_func: a function called with the current item which338- can return a string to show the current item339- next to the progress bar. Note that the current340- item can be `None`!341- :param fill_char: the character to use to show the filled part of the342- progress bar.343- :param empty_char: the character to use to show the non-filled part of344- the progress bar.345- :param bar_template: the format string to use as template for the bar.346- The parameters in it are ``label`` for the label,347- ``bar`` for the progress bar and ``info`` for the348- info section.349- :param info_sep: the separator between multiple info items (eta etc.)350- :param width: the width of the progress bar in characters, 0 means full351- terminal width352- :param file: the file to write to. If this is not a terminal then353- only the label is printed.354- :param color: controls if the terminal supports ANSI colors or not. The355- default is autodetection. This is only needed if ANSI356- codes are included anywhere in the progress bar output357- which is not the case by default.358- """359- from ._termui_impl import ProgressBar360- color = resolve_color_default(color)361- return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,362- show_percent=show_percent, show_pos=show_pos,363- item_show_func=item_show_func, fill_char=fill_char,364- empty_char=empty_char, bar_template=bar_template,365- info_sep=info_sep, file=file, label=label,366- width=width, color=color)367-368-369-def clear():370- """Clears the terminal screen. This will have the effect of clearing371- the whole visible space of the terminal and moving the cursor to the372- top left. This does not do anything if not connected to a terminal.373-374- .. versionadded:: 2.0375- """376- if not isatty(sys.stdout):377- return378- # If we're on Windows and we don't have colorama available, then we379- # clear the screen by shelling out. Otherwise we can use an escape380- # sequence.381- if WIN:382- os.system('cls')383- else:384- sys.stdout.write('\033[2J\033[1;1H')385-386-387-def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,388- blink=None, reverse=None, reset=True):389- """Styles a text with ANSI styles and returns the new string. By390- default the styling is self contained which means that at the end391- of the string a reset code is issued. This can be prevented by392- passing ``reset=False``.393-394- Examples::395-396- click.echo(click.style('Hello World!', fg='green'))397- click.echo(click.style('ATTENTION!', blink=True))398- click.echo(click.style('Some things', reverse=True, fg='cyan'))399-400- Supported color names:401-402- * ``black`` (might be a gray)403- * ``red``404- * ``green``405- * ``yellow`` (might be an orange)406- * ``blue``407- * ``magenta``408- * ``cyan``409- * ``white`` (might be light gray)410- * ``bright_black``411- * ``bright_red``412- * ``bright_green``413- * ``bright_yellow``414- * ``bright_blue``415- * ``bright_magenta``416- * ``bright_cyan``417- * ``bright_white``418- * ``reset`` (reset the color code only)419-420- .. versionadded:: 2.0421-422- .. versionadded:: 7.0423- Added support for bright colors.424-425- :param text: the string to style with ansi codes.426- :param fg: if provided this will become the foreground color.427- :param bg: if provided this will become the background color.428- :param bold: if provided this will enable or disable bold mode.429- :param dim: if provided this will enable or disable dim mode. This is430- badly supported.431- :param underline: if provided this will enable or disable underline.432- :param blink: if provided this will enable or disable blinking.433- :param reverse: if provided this will enable or disable inverse434- rendering (foreground becomes background and the435- other way round).436- :param reset: by default a reset-all code is added at the end of the437- string which means that styles do not carry over. This438- can be disabled to compose styles.439- """440- bits = []441- if fg:442- try:443- bits.append('\033[%dm' % (_ansi_colors[fg]))444- except KeyError:445- raise TypeError('Unknown color %r' % fg)446- if bg:447- try:448- bits.append('\033[%dm' % (_ansi_colors[bg] + 10))449- except KeyError:450- raise TypeError('Unknown color %r' % bg)451- if bold is not None:452- bits.append('\033[%dm' % (1 if bold else 22))453- if dim is not None:454- bits.append('\033[%dm' % (2 if dim else 22))455- if underline is not None:456- bits.append('\033[%dm' % (4 if underline else 24))457- if blink is not None:458- bits.append('\033[%dm' % (5 if blink else 25))459- if reverse is not None:460- bits.append('\033[%dm' % (7 if reverse else 27))461- bits.append(text)462- if reset:463- bits.append(_ansi_reset_all)464- return ''.join(bits)465-466-467-def unstyle(text):468- """Removes ANSI styling information from a string. Usually it's not469- necessary to use this function as Click's echo function will470- automatically remove styling if necessary.471-472- .. versionadded:: 2.0473-474- :param text: the text to remove style information from.475- """476- return strip_ansi(text)477-478-479-def secho(message=None, file=None, nl=True, err=False, color=None, **styles):480- """This function combines :func:`echo` and :func:`style` into one481- call. As such the following two calls are the same::482-483- click.secho('Hello World!', fg='green')484- click.echo(click.style('Hello World!', fg='green'))485-486- All keyword arguments are forwarded to the underlying functions487- depending on which one they go with.488-489- .. versionadded:: 2.0490- """491- if message is not None:492- message = style(message, **styles)493- return echo(message, file=file, nl=nl, err=err, color=color)494-495-496-def edit(text=None, editor=None, env=None, require_save=True,497- extension='.txt', filename=None):498- r"""Edits the given text in the defined editor. If an editor is given499- (should be the full path to the executable but the regular operating500- system search path is used for finding the executable) it overrides501- the detected editor. Optionally, some environment variables can be502- used. If the editor is closed without changes, `None` is returned. In503- case a file is edited directly the return value is always `None` and504- `require_save` and `extension` are ignored.505-506- If the editor cannot be opened a :exc:`UsageError` is raised.507-508- Note for Windows: to simplify cross-platform usage, the newlines are509- automatically converted from POSIX to Windows and vice versa. As such,510- the message here will have ``\n`` as newline markers.511-512- :param text: the text to edit.513- :param editor: optionally the editor to use. Defaults to automatic514- detection.515- :param env: environment variables to forward to the editor.516- :param require_save: if this is true, then not saving in the editor517- will make the return value become `None`.518- :param extension: the extension to tell the editor about. This defaults519- to `.txt` but changing this might change syntax520- highlighting.521- :param filename: if provided it will edit this file instead of the522- provided text contents. It will not use a temporary523- file as an indirection in that case.524- """525- from ._termui_impl import Editor526- editor = Editor(editor=editor, env=env, require_save=require_save,527- extension=extension)528- if filename is None:529- return editor.edit(text)530- editor.edit_file(filename)531-532-533-def launch(url, wait=False, locate=False):534- """This function launches the given URL (or filename) in the default535- viewer application for this file type. If this is an executable, it536- might launch the executable in a new session. The return value is537- the exit code of the launched application. Usually, ``0`` indicates538- success.539-540- Examples::541-542- click.launch('https://click.palletsprojects.com/')543- click.launch('/my/downloaded/file', locate=True)544-545- .. versionadded:: 2.0546-547- :param url: URL or filename of the thing to launch.548- :param wait: waits for the program to stop.549- :param locate: if this is set to `True` then instead of launching the550- application associated with the URL it will attempt to551- launch a file manager with the file located. This552- might have weird effects if the URL does not point to553- the filesystem.554- """555- from ._termui_impl import open_url556- return open_url(url, wait=wait, locate=locate)557-558-559-# If this is provided, getchar() calls into this instead. This is used560-# for unittesting purposes.561-_getchar = None562-563-564-def getchar(echo=False):565- """Fetches a single character from the terminal and returns it. This566- will always return a unicode character and under certain rare567- circumstances this might return more than one character. The568- situations which more than one character is returned is when for569- whatever reason multiple characters end up in the terminal buffer or570- standard input was not actually a terminal.571-572- Note that this will always read from the terminal, even if something573- is piped into the standard input.574-575- Note for Windows: in rare cases when typing non-ASCII characters, this576- function might wait for a second character and then return both at once.577- This is because certain Unicode characters look like special-key markers.578-579- .. versionadded:: 2.0580-581- :param echo: if set to `True`, the character read will also show up on582- the terminal. The default is to not show it.583- """584- f = _getchar585- if f is None:586- from ._termui_impl import getchar as f587- return f(echo)588-589-590-def raw_terminal():591- from ._termui_impl import raw_terminal as f592- return f()593-594-595-def pause(info='Press any key to continue ...', err=False):596- """This command stops execution and waits for the user to press any597- key to continue. This is similar to the Windows batch "pause"598- command. If the program is not run through a terminal, this command599- will instead do nothing.600-601- .. versionadded:: 2.0602-603- .. versionadded:: 4.0604- Added the `err` parameter.605-606- :param info: the info string to print before pausing.607- :param err: if set to message goes to ``stderr`` instead of608- ``stdout``, the same as with echo.609- """610- if not isatty(sys.stdin) or not isatty(sys.stdout):611- return612- try:613- if info:614- echo(info, nl=False, err=err)615- try:616- getchar()617- except (KeyboardInterrupt, EOFError):618- pass619- finally:620- if info:621- echo(err=err)deleted:click/testing.py-377 removed
1-import os2-import sys3-import shutil4-import tempfile5-import contextlib6-import shlex7-8-from ._compat import iteritems, PY2, string_types9-10-11-# If someone wants to vendor click, we want to ensure the12-# correct package is discovered. Ideally we could use a13-# relative import here but unfortunately Python does not14-# support that.15-clickpkg = sys.modules[__name__.rsplit('.', 1)[0]]16-17-18-if PY2:19- from cStringIO import StringIO20-else:21- import io22- from ._compat import _find_binary_reader23-24-25-class EchoingStdin(object):26-27- def __init__(self, input, output):28- self._input = input29- self._output = output30-31- def __getattr__(self, x):32- return getattr(self._input, x)33-34- def _echo(self, rv):35- self._output.write(rv)36- return rv37-38- def read(self, n=-1):39- return self._echo(self._input.read(n))40-41- def readline(self, n=-1):42- return self._echo(self._input.readline(n))43-44- def readlines(self):45- return [self._echo(x) for x in self._input.readlines()]46-47- def __iter__(self):48- return iter(self._echo(x) for x in self._input)49-50- def __repr__(self):51- return repr(self._input)52-53-54-def make_input_stream(input, charset):55- # Is already an input stream.56- if hasattr(input, 'read'):57- if PY2:58- return input59- rv = _find_binary_reader(input)60- if rv is not None:61- return rv62- raise TypeError('Could not find binary reader for input stream.')63-64- if input is None:65- input = b''66- elif not isinstance(input, bytes):67- input = input.encode(charset)68- if PY2:69- return StringIO(input)70- return io.BytesIO(input)71-72-73-class Result(object):74- """Holds the captured result of an invoked CLI script."""75-76- def __init__(self, runner, stdout_bytes, stderr_bytes, exit_code,77- exception, exc_info=None):78- #: The runner that created the result79- self.runner = runner80- #: The standard output as bytes.81- self.stdout_bytes = stdout_bytes82- #: The standard error as bytes, or None if not available83- self.stderr_bytes = stderr_bytes84- #: The exit code as integer.85- self.exit_code = exit_code86- #: The exception that happened if one did.87- self.exception = exception88- #: The traceback89- self.exc_info = exc_info90-91- @property92- def output(self):93- """The (standard) output as unicode string."""94- return self.stdout95-96- @property97- def stdout(self):98- """The standard output as unicode string."""99- return self.stdout_bytes.decode(self.runner.charset, 'replace') \100- .replace('\r\n', '\n')101-102- @property103- def stderr(self):104- """The standard error as unicode string."""105- if self.stderr_bytes is None:106- raise ValueError("stderr not separately captured")107- return self.stderr_bytes.decode(self.runner.charset, 'replace') \108- .replace('\r\n', '\n')109-110-111- def __repr__(self):112- return '<%s %s>' % (113- type(self).__name__,114- self.exception and repr(self.exception) or 'okay',115- )116-117-118-class CliRunner(object):119- """The CLI runner provides functionality to invoke a Click command line120- script for unittesting purposes in a isolated environment. This only121- works in single-threaded systems without any concurrency as it changes the122- global interpreter state.123-124- :param charset: the character set for the input and output data. This is125- UTF-8 by default and should not be changed currently as126- the reporting to Click only works in Python 2 properly.127- :param env: a dictionary with environment variables for overriding.128- :param echo_stdin: if this is set to `True`, then reading from stdin writes129- to stdout. This is useful for showing examples in130- some circumstances. Note that regular prompts131- will automatically echo the input.132- :param mix_stderr: if this is set to `False`, then stdout and stderr are133- preserved as independent streams. This is useful for134- Unix-philosophy apps that have predictable stdout and135- noisy stderr, such that each may be measured136- independently137- """138-139- def __init__(self, charset=None, env=None, echo_stdin=False,140- mix_stderr=True):141- if charset is None:142- charset = 'utf-8'143- self.charset = charset144- self.env = env or {}145- self.echo_stdin = echo_stdin146- self.mix_stderr = mix_stderr147-148- def get_default_prog_name(self, cli):149- """Given a command object it will return the default program name150- for it. The default is the `name` attribute or ``"root"`` if not151- set.152- """153- return cli.name or 'root'154-155- def make_env(self, overrides=None):156- """Returns the environment overrides for invoking a script."""157- rv = dict(self.env)158- if overrides:159- rv.update(overrides)160- return rv161-162- @contextlib.contextmanager163- def isolation(self, input=None, env=None, color=False):164- """A context manager that sets up the isolation for invoking of a165- command line tool. This sets up stdin with the given input data166- and `os.environ` with the overrides from the given dictionary.167- This also rebinds some internals in Click to be mocked (like the168- prompt functionality).169-170- This is automatically done in the :meth:`invoke` method.171-172- .. versionadded:: 4.0173- The ``color`` parameter was added.174-175- :param input: the input stream to put into sys.stdin.176- :param env: the environment overrides as dictionary.177- :param color: whether the output should contain color codes. The178- application can still override this explicitly.179- """180- input = make_input_stream(input, self.charset)181-182- old_stdin = sys.stdin183- old_stdout = sys.stdout184- old_stderr = sys.stderr185- old_forced_width = clickpkg.formatting.FORCED_WIDTH186- clickpkg.formatting.FORCED_WIDTH = 80187-188- env = self.make_env(env)189-190- if PY2:191- bytes_output = StringIO()192- if self.echo_stdin:193- input = EchoingStdin(input, bytes_output)194- sys.stdout = bytes_output195- if not self.mix_stderr:196- bytes_error = StringIO()197- sys.stderr = bytes_error198- else:199- bytes_output = io.BytesIO()200- if self.echo_stdin:201- input = EchoingStdin(input, bytes_output)202- input = io.TextIOWrapper(input, encoding=self.charset)203- sys.stdout = io.TextIOWrapper(204- bytes_output, encoding=self.charset)205- if not self.mix_stderr:206- bytes_error = io.BytesIO()207- sys.stderr = io.TextIOWrapper(208- bytes_error, encoding=self.charset)209-210- if self.mix_stderr:211- sys.stderr = sys.stdout212-213- sys.stdin = input214-215- def visible_input(prompt=None):216- sys.stdout.write(prompt or '')217- val = input.readline().rstrip('\r\n')218- sys.stdout.write(val + '\n')219- sys.stdout.flush()220- return val221-222- def hidden_input(prompt=None):223- sys.stdout.write((prompt or '') + '\n')224- sys.stdout.flush()225- return input.readline().rstrip('\r\n')226-227- def _getchar(echo):228- char = sys.stdin.read(1)229- if echo:230- sys.stdout.write(char)231- sys.stdout.flush()232- return char233-234- default_color = color235-236- def should_strip_ansi(stream=None, color=None):237- if color is None:238- return not default_color239- return not color240-241- old_visible_prompt_func = clickpkg.termui.visible_prompt_func242- old_hidden_prompt_func = clickpkg.termui.hidden_prompt_func243- old__getchar_func = clickpkg.termui._getchar244- old_should_strip_ansi = clickpkg.utils.should_strip_ansi245- clickpkg.termui.visible_prompt_func = visible_input246- clickpkg.termui.hidden_prompt_func = hidden_input247- clickpkg.termui._getchar = _getchar248- clickpkg.utils.should_strip_ansi = should_strip_ansi249-250- old_env = {}251- try:252- for key, value in iteritems(env):253- old_env[key] = os.environ.get(key)254- if value is None:255- try:256- del os.environ[key]257- except Exception:258- pass259- else:260- os.environ[key] = value261- yield (bytes_output, not self.mix_stderr and bytes_error)262- finally:263- for key, value in iteritems(old_env):264- if value is None:265- try:266- del os.environ[key]267- except Exception:268- pass269- else:270- os.environ[key] = value271- sys.stdout = old_stdout272- sys.stderr = old_stderr273- sys.stdin = old_stdin274- clickpkg.termui.visible_prompt_func = old_visible_prompt_func275- clickpkg.termui.hidden_prompt_func = old_hidden_prompt_func276- clickpkg.termui._getchar = old__getchar_func277- clickpkg.utils.should_strip_ansi = old_should_strip_ansi278- clickpkg.formatting.FORCED_WIDTH = old_forced_width279-280- def invoke(self, cli, args=None, input=None, env=None,281- catch_exceptions=True, color=False, **extra):282- """Invokes a command in an isolated environment. The arguments are283- forwarded directly to the command line script, the `extra` keyword284- arguments are passed to the :meth:`~clickpkg.Command.main` function of285- the command.286-287- This returns a :class:`Result` object.288-289- .. versionadded:: 3.0290- The ``catch_exceptions`` parameter was added.291-292- .. versionchanged:: 3.0293- The result object now has an `exc_info` attribute with the294- traceback if available.295-296- .. versionadded:: 4.0297- The ``color`` parameter was added.298-299- :param cli: the command to invoke300- :param args: the arguments to invoke. It may be given as an iterable301- or a string. When given as string it will be interpreted302- as a Unix shell command. More details at303- :func:`shlex.split`.304- :param input: the input data for `sys.stdin`.305- :param env: the environment overrides.306- :param catch_exceptions: Whether to catch any other exceptions than307- ``SystemExit``.308- :param extra: the keyword arguments to pass to :meth:`main`.309- :param color: whether the output should contain color codes. The310- application can still override this explicitly.311- """312- exc_info = None313- with self.isolation(input=input, env=env, color=color) as outstreams:314- exception = None315- exit_code = 0316-317- if isinstance(args, string_types):318- args = shlex.split(args)319-320- try:321- prog_name = extra.pop("prog_name")322- except KeyError:323- prog_name = self.get_default_prog_name(cli)324-325- try:326- cli.main(args=args or (), prog_name=prog_name, **extra)327- except SystemExit as e:328- exc_info = sys.exc_info()329- exit_code = e.code330- if exit_code is None:331- exit_code = 0332-333- if exit_code != 0:334- exception = e335-336- if not isinstance(exit_code, int):337- sys.stdout.write(str(exit_code))338- sys.stdout.write('\n')339- exit_code = 1340-341- except Exception as e:342- if not catch_exceptions:343- raise344- exception = e345- exit_code = 1346- exc_info = sys.exc_info()347- finally:348- sys.stdout.flush()349- stdout = outstreams[0].getvalue()350- if self.mix_stderr:351- stderr = None352- else:353- stderr = outstreams[1].getvalue()354-355- return Result(runner=self,356- stdout_bytes=stdout,357- stderr_bytes=stderr,358- exit_code=exit_code,359- exception=exception,360- exc_info=exc_info)361-362- @contextlib.contextmanager363- def isolated_filesystem(self):364- """A context manager that creates a temporary folder and changes365- the current working directory to it for isolated filesystem tests.366- """367- cwd = os.getcwd()368- t = tempfile.mkdtemp()369- os.chdir(t)370- try:371- yield t372- finally:373- os.chdir(cwd)374- try:375- shutil.rmtree(t)376- except (OSError, IOError):377- passdeleted:click/types.py-679 removed
1-import os2-import stat3-from datetime import datetime4-5-from ._compat import open_stream, text_type, filename_to_ui, \6- get_filesystem_encoding, get_streerror, _get_argv_encoding, PY27-from .exceptions import BadParameter8-from .utils import safecall, LazyFile9-10-11-class ParamType(object):12- """Helper for converting values through types. The following is13- necessary for a valid type:14-15- * it needs a name16- * it needs to pass through None unchanged17- * it needs to convert from a string18- * it needs to convert its result type through unchanged19- (eg: needs to be idempotent)20- * it needs to be able to deal with param and context being `None`.21- This can be the case when the object is used with prompt22- inputs.23- """24- is_composite = False25-26- #: the descriptive name of this type27- name = None28-29- #: if a list of this type is expected and the value is pulled from a30- #: string environment variable, this is what splits it up. `None`31- #: means any whitespace. For all parameters the general rule is that32- #: whitespace splits them up. The exception are paths and files which33- #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on34- #: Windows).35- envvar_list_splitter = None36-37- def __call__(self, value, param=None, ctx=None):38- if value is not None:39- return self.convert(value, param, ctx)40-41- def get_metavar(self, param):42- """Returns the metavar default for this param if it provides one."""43-44- def get_missing_message(self, param):45- """Optionally might return extra information about a missing46- parameter.47-48- .. versionadded:: 2.049- """50-51- def convert(self, value, param, ctx):52- """Converts the value. This is not invoked for values that are53- `None` (the missing value).54- """55- return value56-57- def split_envvar_value(self, rv):58- """Given a value from an environment variable this splits it up59- into small chunks depending on the defined envvar list splitter.60-61- If the splitter is set to `None`, which means that whitespace splits,62- then leading and trailing whitespace is ignored. Otherwise, leading63- and trailing splitters usually lead to empty items being included.64- """65- return (rv or '').split(self.envvar_list_splitter)66-67- def fail(self, message, param=None, ctx=None):68- """Helper method to fail with an invalid value message."""69- raise BadParameter(message, ctx=ctx, param=param)70-71-72-class CompositeParamType(ParamType):73- is_composite = True74-75- @property76- def arity(self):77- raise NotImplementedError()78-79-80-class FuncParamType(ParamType):81-82- def __init__(self, func):83- self.name = func.__name__84- self.func = func85-86- def convert(self, value, param, ctx):87- try:88- return self.func(value)89- except ValueError:90- try:91- value = text_type(value)92- except UnicodeError:93- value = str(value).decode('utf-8', 'replace')94- self.fail(value, param, ctx)95-96-97-class UnprocessedParamType(ParamType):98- name = 'text'99-100- def convert(self, value, param, ctx):101- return value102-103- def __repr__(self):104- return 'UNPROCESSED'105-106-107-class StringParamType(ParamType):108- name = 'text'109-110- def convert(self, value, param, ctx):111- if isinstance(value, bytes):112- enc = _get_argv_encoding()113- try:114- value = value.decode(enc)115- except UnicodeError:116- fs_enc = get_filesystem_encoding()117- if fs_enc != enc:118- try:119- value = value.decode(fs_enc)120- except UnicodeError:121- value = value.decode('utf-8', 'replace')122- else:123- value = value.decode('utf-8', 'replace')124- return value125- return value126-127- def __repr__(self):128- return 'STRING'129-130-131-class Choice(ParamType):132- """The choice type allows a value to be checked against a fixed set133- of supported values. All of these values have to be strings.134-135- You should only pass a list or tuple of choices. Other iterables136- (like generators) may lead to surprising results.137-138- The resulting value will always be one of the originally passed choices139- regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``140- being specified.141-142- See :ref:`choice-opts` for an example.143-144- :param case_sensitive: Set to false to make choices case145- insensitive. Defaults to true.146- """147-148- name = 'choice'149-150- def __init__(self, choices, case_sensitive=True):151- self.choices = choices152- self.case_sensitive = case_sensitive153-154- def get_metavar(self, param):155- return '[%s]' % '|'.join(self.choices)156-157- def get_missing_message(self, param):158- return 'Choose from:\n\t%s.' % ',\n\t'.join(self.choices)159-160- def convert(self, value, param, ctx):161- # Match through normalization and case sensitivity162- # first do token_normalize_func, then lowercase163- # preserve original `value` to produce an accurate message in164- # `self.fail`165- normed_value = value166- normed_choices = {choice: choice for choice in self.choices}167-168- if ctx is not None and ctx.token_normalize_func is not None:169- normed_value = ctx.token_normalize_func(value)170- normed_choices = {171- ctx.token_normalize_func(normed_choice): original172- for normed_choice, original in normed_choices.items()173- }174-175- if not self.case_sensitive:176- if PY2:177- lower = str.lower178- else:179- lower = str.casefold180-181- normed_value = lower(normed_value)182- normed_choices = {183- lower(normed_choice): original184- for normed_choice, original in normed_choices.items()185- }186-187- if normed_value in normed_choices:188- return normed_choices[normed_value]189-190- self.fail('invalid choice: %s. (choose from %s)' %191- (value, ', '.join(self.choices)), param, ctx)192-193- def __repr__(self):194- return 'Choice(%r)' % list(self.choices)195-196-197-class DateTime(ParamType):198- """The DateTime type converts date strings into `datetime` objects.199-200- The format strings which are checked are configurable, but default to some201- common (non-timezone aware) ISO 8601 formats.202-203- When specifying *DateTime* formats, you should only pass a list or a tuple.204- Other iterables, like generators, may lead to surprising results.205-206- The format strings are processed using ``datetime.strptime``, and this207- consequently defines the format strings which are allowed.208-209- Parsing is tried using each format, in order, and the first format which210- parses successfully is used.211-212- :param formats: A list or tuple of date format strings, in the order in213- which they should be tried. Defaults to214- ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,215- ``'%Y-%m-%d %H:%M:%S'``.216- """217- name = 'datetime'218-219- def __init__(self, formats=None):220- self.formats = formats or [221- '%Y-%m-%d',222- '%Y-%m-%dT%H:%M:%S',223- '%Y-%m-%d %H:%M:%S'224- ]225-226- def get_metavar(self, param):227- return '[{}]'.format('|'.join(self.formats))228-229- def _try_to_convert_date(self, value, format):230- try:231- return datetime.strptime(value, format)232- except ValueError:233- return None234-235- def convert(self, value, param, ctx):236- # Exact match237- for format in self.formats:238- dtime = self._try_to_convert_date(value, format)239- if dtime:240- return dtime241-242- self.fail(243- 'invalid datetime format: {}. (choose from {})'.format(244- value, ', '.join(self.formats)))245-246- def __repr__(self):247- return 'DateTime'248-249-250-class IntParamType(ParamType):251- name = 'integer'252-253- def convert(self, value, param, ctx):254- try:255- return int(value)256- except (ValueError, UnicodeError):257- self.fail('%s is not a valid integer' % value, param, ctx)258-259- def __repr__(self):260- return 'INT'261-262-263-class IntRange(IntParamType):264- """A parameter that works similar to :data:`click.INT` but restricts265- the value to fit into a range. The default behavior is to fail if the266- value falls outside the range, but it can also be silently clamped267- between the two edges.268-269- See :ref:`ranges` for an example.270- """271- name = 'integer range'272-273- def __init__(self, min=None, max=None, clamp=False):274- self.min = min275- self.max = max276- self.clamp = clamp277-278- def convert(self, value, param, ctx):279- rv = IntParamType.convert(self, value, param, ctx)280- if self.clamp:281- if self.min is not None and rv < self.min:282- return self.min283- if self.max is not None and rv > self.max:284- return self.max285- if self.min is not None and rv < self.min or \286- self.max is not None and rv > self.max:287- if self.min is None:288- self.fail('%s is bigger than the maximum valid value '289- '%s.' % (rv, self.max), param, ctx)290- elif self.max is None:291- self.fail('%s is smaller than the minimum valid value '292- '%s.' % (rv, self.min), param, ctx)293- else:294- self.fail('%s is not in the valid range of %s to %s.'295- % (rv, self.min, self.max), param, ctx)296- return rv297-298- def __repr__(self):299- return 'IntRange(%r, %r)' % (self.min, self.max)300-301-302-class FloatParamType(ParamType):303- name = 'float'304-305- def convert(self, value, param, ctx):306- try:307- return float(value)308- except (UnicodeError, ValueError):309- self.fail('%s is not a valid floating point value' %310- value, param, ctx)311-312- def __repr__(self):313- return 'FLOAT'314-315-316-class FloatRange(FloatParamType):317- """A parameter that works similar to :data:`click.FLOAT` but restricts318- the value to fit into a range. The default behavior is to fail if the319- value falls outside the range, but it can also be silently clamped320- between the two edges.321-322- See :ref:`ranges` for an example.323- """324- name = 'float range'325-326- def __init__(self, min=None, max=None, clamp=False):327- self.min = min328- self.max = max329- self.clamp = clamp330-331- def convert(self, value, param, ctx):332- rv = FloatParamType.convert(self, value, param, ctx)333- if self.clamp:334- if self.min is not None and rv < self.min:335- return self.min336- if self.max is not None and rv > self.max:337- return self.max338- if self.min is not None and rv < self.min or \339- self.max is not None and rv > self.max:340- if self.min is None:341- self.fail('%s is bigger than the maximum valid value '342- '%s.' % (rv, self.max), param, ctx)343- elif self.max is None:344- self.fail('%s is smaller than the minimum valid value '345- '%s.' % (rv, self.min), param, ctx)346- else:347- self.fail('%s is not in the valid range of %s to %s.'348- % (rv, self.min, self.max), param, ctx)349- return rv350-351- def __repr__(self):352- return 'FloatRange(%r, %r)' % (self.min, self.max)353-354-355-class BoolParamType(ParamType):356- name = 'boolean'357-358- def convert(self, value, param, ctx):359- if isinstance(value, bool):360- return bool(value)361- value = value.lower()362- if value in ('true', 't', '1', 'yes', 'y'):363- return True364- elif value in ('false', 'f', '0', 'no', 'n'):365- return False366- self.fail('%s is not a valid boolean' % value, param, ctx)367-368- def __repr__(self):369- return 'BOOL'370-371-372-class UUIDParameterType(ParamType):373- name = 'uuid'374-375- def convert(self, value, param, ctx):376- import uuid377- try:378- if PY2 and isinstance(value, text_type):379- value = value.encode('ascii')380- return uuid.UUID(value)381- except (UnicodeError, ValueError):382- self.fail('%s is not a valid UUID value' % value, param, ctx)383-384- def __repr__(self):385- return 'UUID'386-387-388-class File(ParamType):389- """Declares a parameter to be a file for reading or writing. The file390- is automatically closed once the context tears down (after the command391- finished working).392-393- Files can be opened for reading or writing. The special value ``-``394- indicates stdin or stdout depending on the mode.395-396- By default, the file is opened for reading text data, but it can also be397- opened in binary mode or for writing. The encoding parameter can be used398- to force a specific encoding.399-400- The `lazy` flag controls if the file should be opened immediately or upon401- first IO. The default is to be non-lazy for standard input and output402- streams as well as files opened for reading, `lazy` otherwise. When opening a403- file lazily for reading, it is still opened temporarily for validation, but404- will not be held open until first IO. lazy is mainly useful when opening405- for writing to avoid creating the file until it is needed.406-407- Starting with Click 2.0, files can also be opened atomically in which408- case all writes go into a separate file in the same folder and upon409- completion the file will be moved over to the original location. This410- is useful if a file regularly read by other users is modified.411-412- See :ref:`file-args` for more information.413- """414- name = 'filename'415- envvar_list_splitter = os.path.pathsep416-417- def __init__(self, mode='r', encoding=None, errors='strict', lazy=None,418- atomic=False):419- self.mode = mode420- self.encoding = encoding421- self.errors = errors422- self.lazy = lazy423- self.atomic = atomic424-425- def resolve_lazy_flag(self, value):426- if self.lazy is not None:427- return self.lazy428- if value == '-':429- return False430- elif 'w' in self.mode:431- return True432- return False433-434- def convert(self, value, param, ctx):435- try:436- if hasattr(value, 'read') or hasattr(value, 'write'):437- return value438-439- lazy = self.resolve_lazy_flag(value)440-441- if lazy:442- f = LazyFile(value, self.mode, self.encoding, self.errors,443- atomic=self.atomic)444- if ctx is not None:445- ctx.call_on_close(f.close_intelligently)446- return f447-448- f, should_close = open_stream(value, self.mode,449- self.encoding, self.errors,450- atomic=self.atomic)451- # If a context is provided, we automatically close the file452- # at the end of the context execution (or flush out). If a453- # context does not exist, it's the caller's responsibility to454- # properly close the file. This for instance happens when the455- # type is used with prompts.456- if ctx is not None:457- if should_close:458- ctx.call_on_close(safecall(f.close))459- else:460- ctx.call_on_close(safecall(f.flush))461- return f462- except (IOError, OSError) as e:463- self.fail('Could not open file: %s: %s' % (464- filename_to_ui(value),465- get_streerror(e),466- ), param, ctx)467-468-469-class Path(ParamType):470- """The path type is similar to the :class:`File` type but it performs471- different checks. First of all, instead of returning an open file472- handle it returns just the filename. Secondly, it can perform various473- basic checks about what the file or directory should be.474-475- .. versionchanged:: 6.0476- `allow_dash` was added.477-478- :param exists: if set to true, the file or directory needs to exist for479- this value to be valid. If this is not required and a480- file does indeed not exist, then all further checks are481- silently skipped.482- :param file_okay: controls if a file is a possible value.483- :param dir_okay: controls if a directory is a possible value.484- :param writable: if true, a writable check is performed.485- :param readable: if true, a readable check is performed.486- :param resolve_path: if this is true, then the path is fully resolved487- before the value is passed onwards. This means488- that it's absolute and symlinks are resolved. It489- will not expand a tilde-prefix, as this is490- supposed to be done by the shell only.491- :param allow_dash: If this is set to `True`, a single dash to indicate492- standard streams is permitted.493- :param path_type: optionally a string type that should be used to494- represent the path. The default is `None` which495- means the return value will be either bytes or496- unicode depending on what makes most sense given the497- input data Click deals with.498- """499- envvar_list_splitter = os.path.pathsep500-501- def __init__(self, exists=False, file_okay=True, dir_okay=True,502- writable=False, readable=True, resolve_path=False,503- allow_dash=False, path_type=None):504- self.exists = exists505- self.file_okay = file_okay506- self.dir_okay = dir_okay507- self.writable = writable508- self.readable = readable509- self.resolve_path = resolve_path510- self.allow_dash = allow_dash511- self.type = path_type512-513- if self.file_okay and not self.dir_okay:514- self.name = 'file'515- self.path_type = 'File'516- elif self.dir_okay and not self.file_okay:517- self.name = 'directory'518- self.path_type = 'Directory'519- else:520- self.name = 'path'521- self.path_type = 'Path'522-523- def coerce_path_result(self, rv):524- if self.type is not None and not isinstance(rv, self.type):525- if self.type is text_type:526- rv = rv.decode(get_filesystem_encoding())527- else:528- rv = rv.encode(get_filesystem_encoding())529- return rv530-531- def convert(self, value, param, ctx):532- rv = value533-534- is_dash = self.file_okay and self.allow_dash and rv in (b'-', '-')535-536- if not is_dash:537- if self.resolve_path:538- rv = os.path.realpath(rv)539-540- try:541- st = os.stat(rv)542- except OSError:543- if not self.exists:544- return self.coerce_path_result(rv)545- self.fail('%s "%s" does not exist.' % (546- self.path_type,547- filename_to_ui(value)548- ), param, ctx)549-550- if not self.file_okay and stat.S_ISREG(st.st_mode):551- self.fail('%s "%s" is a file.' % (552- self.path_type,553- filename_to_ui(value)554- ), param, ctx)555- if not self.dir_okay and stat.S_ISDIR(st.st_mode):556- self.fail('%s "%s" is a directory.' % (557- self.path_type,558- filename_to_ui(value)559- ), param, ctx)560- if self.writable and not os.access(value, os.W_OK):561- self.fail('%s "%s" is not writable.' % (562- self.path_type,563- filename_to_ui(value)564- ), param, ctx)565- if self.readable and not os.access(value, os.R_OK):566- self.fail('%s "%s" is not readable.' % (567- self.path_type,568- filename_to_ui(value)569- ), param, ctx)570-571- return self.coerce_path_result(rv)572-573-574-class Tuple(CompositeParamType):575- """The default behavior of Click is to apply a type on a value directly.576- This works well in most cases, except for when `nargs` is set to a fixed577- count and different types should be used for different items. In this578- case the :class:`Tuple` type can be used. This type can only be used579- if `nargs` is set to a fixed number.580-581- For more information see :ref:`tuple-type`.582-583- This can be selected by using a Python tuple literal as a type.584-585- :param types: a list of types that should be used for the tuple items.586- """587-588- def __init__(self, types):589- self.types = [convert_type(ty) for ty in types]590-591- @property592- def name(self):593- return "<" + " ".join(ty.name for ty in self.types) + ">"594-595- @property596- def arity(self):597- return len(self.types)598-599- def convert(self, value, param, ctx):600- if len(value) != len(self.types):601- raise TypeError('It would appear that nargs is set to conflict '602- 'with the composite type arity.')603- return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))604-605-606-def convert_type(ty, default=None):607- """Converts a callable or python ty into the most appropriate param608- ty.609- """610- guessed_type = False611- if ty is None and default is not None:612- if isinstance(default, tuple):613- ty = tuple(map(type, default))614- else:615- ty = type(default)616- guessed_type = True617-618- if isinstance(ty, tuple):619- return Tuple(ty)620- if isinstance(ty, ParamType):621- return ty622- if ty is text_type or ty is str or ty is None:623- return STRING624- if ty is int:625- return INT626- # Booleans are only okay if not guessed. This is done because for627- # flags the default value is actually a bit of a lie in that it628- # indicates which of the flags is the one we want. See get_default()629- # for more information.630- if ty is bool and not guessed_type:631- return BOOL632- if ty is float:633- return FLOAT634- if guessed_type:635- return STRING636-637- # Catch a common mistake638- if __debug__:639- try:640- if issubclass(ty, ParamType):641- raise AssertionError('Attempted to use an uninstantiated '642- 'parameter type (%s).' % ty)643- except TypeError:644- pass645- return FuncParamType(ty)646-647-648-#: A dummy parameter type that just does nothing. From a user's649-#: perspective this appears to just be the same as `STRING` but internally650-#: no string conversion takes place. This is necessary to achieve the651-#: same bytes/unicode behavior on Python 2/3 in situations where you want652-#: to not convert argument types. This is usually useful when working653-#: with file paths as they can appear in bytes and unicode.654-#:655-#: For path related uses the :class:`Path` type is a better choice but656-#: there are situations where an unprocessed type is useful which is why657-#: it is is provided.658-#:659-#: .. versionadded:: 4.0660-UNPROCESSED = UnprocessedParamType()661-662-#: A unicode string parameter type which is the implicit default. This663-#: can also be selected by using ``str`` as type.664-STRING = StringParamType()665-666-#: An integer parameter. This can also be selected by using ``int`` as667-#: type.668-INT = IntParamType()669-670-#: A floating point value parameter. This can also be selected by using671-#: ``float`` as type.672-FLOAT = FloatParamType()673-674-#: A boolean parameter. This is the default for boolean flags. This can675-#: also be selected by using ``bool`` as a type.676-BOOL = BoolParamType()677-678-#: A UUID parameter.679-UUID = UUIDParameterType()deleted:click/utils.py-440 removed
1-import os2-import sys3-4-from .globals import resolve_color_default5-6-from ._compat import text_type, open_stream, get_filesystem_encoding, \7- get_streerror, string_types, PY2, binary_streams, text_streams, \8- filename_to_ui, auto_wrap_for_ansi, strip_ansi, should_strip_ansi, \9- _default_text_stdout, _default_text_stderr, is_bytes, WIN10-11-if not PY2:12- from ._compat import _find_binary_writer13-elif WIN:14- from ._winconsole import _get_windows_argv, \15- _hash_py_argv, _initial_argv_hash16-17-18-echo_native_types = string_types + (bytes, bytearray)19-20-21-def _posixify(name):22- return '-'.join(name.split()).lower()23-24-25-def safecall(func):26- """Wraps a function so that it swallows exceptions."""27- def wrapper(*args, **kwargs):28- try:29- return func(*args, **kwargs)30- except Exception:31- pass32- return wrapper33-34-35-def make_str(value):36- """Converts a value into a valid string."""37- if isinstance(value, bytes):38- try:39- return value.decode(get_filesystem_encoding())40- except UnicodeError:41- return value.decode('utf-8', 'replace')42- return text_type(value)43-44-45-def make_default_short_help(help, max_length=45):46- """Return a condensed version of help string."""47- words = help.split()48- total_length = 049- result = []50- done = False51-52- for word in words:53- if word[-1:] == '.':54- done = True55- new_length = result and 1 + len(word) or len(word)56- if total_length + new_length > max_length:57- result.append('...')58- done = True59- else:60- if result:61- result.append(' ')62- result.append(word)63- if done:64- break65- total_length += new_length66-67- return ''.join(result)68-69-70-class LazyFile(object):71- """A lazy file works like a regular file but it does not fully open72- the file but it does perform some basic checks early to see if the73- filename parameter does make sense. This is useful for safely opening74- files for writing.75- """76-77- def __init__(self, filename, mode='r', encoding=None, errors='strict',78- atomic=False):79- self.name = filename80- self.mode = mode81- self.encoding = encoding82- self.errors = errors83- self.atomic = atomic84-85- if filename == '-':86- self._f, self.should_close = open_stream(filename, mode,87- encoding, errors)88- else:89- if 'r' in mode:90- # Open and close the file in case we're opening it for91- # reading so that we can catch at least some errors in92- # some cases early.93- open(filename, mode).close()94- self._f = None95- self.should_close = True96-97- def __getattr__(self, name):98- return getattr(self.open(), name)99-100- def __repr__(self):101- if self._f is not None:102- return repr(self._f)103- return '<unopened file %r %s>' % (self.name, self.mode)104-105- def open(self):106- """Opens the file if it's not yet open. This call might fail with107- a :exc:`FileError`. Not handling this error will produce an error108- that Click shows.109- """110- if self._f is not None:111- return self._f112- try:113- rv, self.should_close = open_stream(self.name, self.mode,114- self.encoding,115- self.errors,116- atomic=self.atomic)117- except (IOError, OSError) as e:118- from .exceptions import FileError119- raise FileError(self.name, hint=get_streerror(e))120- self._f = rv121- return rv122-123- def close(self):124- """Closes the underlying file, no matter what."""125- if self._f is not None:126- self._f.close()127-128- def close_intelligently(self):129- """This function only closes the file if it was opened by the lazy130- file wrapper. For instance this will never close stdin.131- """132- if self.should_close:133- self.close()134-135- def __enter__(self):136- return self137-138- def __exit__(self, exc_type, exc_value, tb):139- self.close_intelligently()140-141- def __iter__(self):142- self.open()143- return iter(self._f)144-145-146-class KeepOpenFile(object):147-148- def __init__(self, file):149- self._file = file150-151- def __getattr__(self, name):152- return getattr(self._file, name)153-154- def __enter__(self):155- return self156-157- def __exit__(self, exc_type, exc_value, tb):158- pass159-160- def __repr__(self):161- return repr(self._file)162-163- def __iter__(self):164- return iter(self._file)165-166-167-def echo(message=None, file=None, nl=True, err=False, color=None):168- """Prints a message plus a newline to the given file or stdout. On169- first sight, this looks like the print function, but it has improved170- support for handling Unicode and binary data that does not fail no171- matter how badly configured the system is.172-173- Primarily it means that you can print binary data as well as Unicode174- data on both 2.x and 3.x to the given file in the most appropriate way175- possible. This is a very carefree function in that it will try its176- best to not fail. As of Click 6.0 this includes support for unicode177- output on the Windows console.178-179- In addition to that, if `colorama`_ is installed, the echo function will180- also support clever handling of ANSI codes. Essentially it will then181- do the following:182-183- - add transparent handling of ANSI color codes on Windows.184- - hide ANSI codes automatically if the destination file is not a185- terminal.186-187- .. _colorama: https://pypi.org/project/colorama/188-189- .. versionchanged:: 6.0190- As of Click 6.0 the echo function will properly support unicode191- output on the windows console. Not that click does not modify192- the interpreter in any way which means that `sys.stdout` or the193- print statement or function will still not provide unicode support.194-195- .. versionchanged:: 2.0196- Starting with version 2.0 of Click, the echo function will work197- with colorama if it's installed.198-199- .. versionadded:: 3.0200- The `err` parameter was added.201-202- .. versionchanged:: 4.0203- Added the `color` flag.204-205- :param message: the message to print206- :param file: the file to write to (defaults to ``stdout``)207- :param err: if set to true the file defaults to ``stderr`` instead of208- ``stdout``. This is faster and easier than calling209- :func:`get_text_stderr` yourself.210- :param nl: if set to `True` (the default) a newline is printed afterwards.211- :param color: controls if the terminal supports ANSI colors or not. The212- default is autodetection.213- """214- if file is None:215- if err:216- file = _default_text_stderr()217- else:218- file = _default_text_stdout()219-220- # Convert non bytes/text into the native string type.221- if message is not None and not isinstance(message, echo_native_types):222- message = text_type(message)223-224- if nl:225- message = message or u''226- if isinstance(message, text_type):227- message += u'\n'228- else:229- message += b'\n'230-231- # If there is a message, and we're in Python 3, and the value looks232- # like bytes, we manually need to find the binary stream and write the233- # message in there. This is done separately so that most stream234- # types will work as you would expect. Eg: you can write to StringIO235- # for other cases.236- if message and not PY2 and is_bytes(message):237- binary_file = _find_binary_writer(file)238- if binary_file is not None:239- file.flush()240- binary_file.write(message)241- binary_file.flush()242- return243-244- # ANSI-style support. If there is no message or we are dealing with245- # bytes nothing is happening. If we are connected to a file we want246- # to strip colors. If we are on windows we either wrap the stream247- # to strip the color or we use the colorama support to translate the248- # ansi codes to API calls.249- if message and not is_bytes(message):250- color = resolve_color_default(color)251- if should_strip_ansi(file, color):252- message = strip_ansi(message)253- elif WIN:254- if auto_wrap_for_ansi is not None:255- file = auto_wrap_for_ansi(file)256- elif not color:257- message = strip_ansi(message)258-259- if message:260- file.write(message)261- file.flush()262-263-264-def get_binary_stream(name):265- """Returns a system stream for byte processing. This essentially266- returns the stream from the sys module with the given name but it267- solves some compatibility issues between different Python versions.268- Primarily this function is necessary for getting binary streams on269- Python 3.270-271- :param name: the name of the stream to open. Valid names are ``'stdin'``,272- ``'stdout'`` and ``'stderr'``273- """274- opener = binary_streams.get(name)275- if opener is None:276- raise TypeError('Unknown standard stream %r' % name)277- return opener()278-279-280-def get_text_stream(name, encoding=None, errors='strict'):281- """Returns a system stream for text processing. This usually returns282- a wrapped stream around a binary stream returned from283- :func:`get_binary_stream` but it also can take shortcuts on Python 3284- for already correctly configured streams.285-286- :param name: the name of the stream to open. Valid names are ``'stdin'``,287- ``'stdout'`` and ``'stderr'``288- :param encoding: overrides the detected default encoding.289- :param errors: overrides the default error mode.290- """291- opener = text_streams.get(name)292- if opener is None:293- raise TypeError('Unknown standard stream %r' % name)294- return opener(encoding, errors)295-296-297-def open_file(filename, mode='r', encoding=None, errors='strict',298- lazy=False, atomic=False):299- """This is similar to how the :class:`File` works but for manual300- usage. Files are opened non lazy by default. This can open regular301- files as well as stdin/stdout if ``'-'`` is passed.302-303- If stdin/stdout is returned the stream is wrapped so that the context304- manager will not close the stream accidentally. This makes it possible305- to always use the function like this without having to worry to306- accidentally close a standard stream::307-308- with open_file(filename) as f:309- ...310-311- .. versionadded:: 3.0312-313- :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).314- :param mode: the mode in which to open the file.315- :param encoding: the encoding to use.316- :param errors: the error handling for this file.317- :param lazy: can be flipped to true to open the file lazily.318- :param atomic: in atomic mode writes go into a temporary file and it's319- moved on close.320- """321- if lazy:322- return LazyFile(filename, mode, encoding, errors, atomic=atomic)323- f, should_close = open_stream(filename, mode, encoding, errors,324- atomic=atomic)325- if not should_close:326- f = KeepOpenFile(f)327- return f328-329-330-def get_os_args():331- """This returns the argument part of sys.argv in the most appropriate332- form for processing. What this means is that this return value is in333- a format that works for Click to process but does not necessarily334- correspond well to what's actually standard for the interpreter.335-336- On most environments the return value is ``sys.argv[:1]`` unchanged.337- However if you are on Windows and running Python 2 the return value338- will actually be a list of unicode strings instead because the339- default behavior on that platform otherwise will not be able to340- carry all possible values that sys.argv can have.341-342- .. versionadded:: 6.0343- """344- # We can only extract the unicode argv if sys.argv has not been345- # changed since the startup of the application.346- if PY2 and WIN and _initial_argv_hash == _hash_py_argv():347- return _get_windows_argv()348- return sys.argv[1:]349-350-351-def format_filename(filename, shorten=False):352- """Formats a filename for user display. The main purpose of this353- function is to ensure that the filename can be displayed at all. This354- will decode the filename to unicode if necessary in a way that it will355- not fail. Optionally, it can shorten the filename to not include the356- full path to the filename.357-358- :param filename: formats a filename for UI display. This will also convert359- the filename into unicode without failing.360- :param shorten: this optionally shortens the filename to strip of the361- path that leads up to it.362- """363- if shorten:364- filename = os.path.basename(filename)365- return filename_to_ui(filename)366-367-368-def get_app_dir(app_name, roaming=True, force_posix=False):369- r"""Returns the config folder for the application. The default behavior370- is to return whatever is most appropriate for the operating system.371-372- To give you an idea, for an app called ``"Foo Bar"``, something like373- the following folders could be returned:374-375- Mac OS X:376- ``~/Library/Application Support/Foo Bar``377- Mac OS X (POSIX):378- ``~/.foo-bar``379- Unix:380- ``~/.config/foo-bar``381- Unix (POSIX):382- ``~/.foo-bar``383- Win XP (roaming):384- ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``385- Win XP (not roaming):386- ``C:\Documents and Settings\<user>\Application Data\Foo Bar``387- Win 7 (roaming):388- ``C:\Users\<user>\AppData\Roaming\Foo Bar``389- Win 7 (not roaming):390- ``C:\Users\<user>\AppData\Local\Foo Bar``391-392- .. versionadded:: 2.0393-394- :param app_name: the application name. This should be properly capitalized395- and can contain whitespace.396- :param roaming: controls if the folder should be roaming or not on Windows.397- Has no affect otherwise.398- :param force_posix: if this is set to `True` then on any POSIX system the399- folder will be stored in the home folder with a leading400- dot instead of the XDG config home or darwin's401- application support folder.402- """403- if WIN:404- key = roaming and 'APPDATA' or 'LOCALAPPDATA'405- folder = os.environ.get(key)406- if folder is None:407- folder = os.path.expanduser('~')408- return os.path.join(folder, app_name)409- if force_posix:410- return os.path.join(os.path.expanduser('~/.' + _posixify(app_name)))411- if sys.platform == 'darwin':412- return os.path.join(os.path.expanduser(413- '~/Library/Application Support'), app_name)414- return os.path.join(415- os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')),416- _posixify(app_name))417-418-419-class PacifyFlushWrapper(object):420- """This wrapper is used to catch and suppress BrokenPipeErrors resulting421- from ``.flush()`` being called on broken pipe during the shutdown/final-GC422- of the Python interpreter. Notably ``.flush()`` is always called on423- ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any424- other cleanup code, and the case where the underlying file is not a broken425- pipe, all calls and attributes are proxied.426- """427-428- def __init__(self, wrapped):429- self.wrapped = wrapped430-431- def flush(self):432- try:433- self.wrapped.flush()434- except IOError as e:435- import errno436- if e.errno != errno.EPIPE:437- raise438-439- def __getattr__(self, attr):440- return getattr(self.wrapped, attr)modified:docs/arguments.rst-1 removed
265 unmodified lines266 267 .. click:run::268 269 invoke(touch, ['-foo.txt', 'bar.txt'])270-modified:docs/conf.py+1 added-3 removed
45 unmodified lines46 html_show_sourcelink = False47 48 # LaTeX ----------------------------------------------------------------49 50-latex_documents = [51- (master_doc, f"Click-{version}.tex", html_title, author, "manual")52-]50+latex_documents = [(master_doc, f"Click-{version}.tex", html_title, author, "manual")]modified:examples/aliases/aliases.py+29 added-22 removed
1 import os2+3 import click4 5 try:5- import ConfigParser as configparser6-except ImportError:6 import configparser7+except ImportError:8+ import ConfigParser as configparser9 10 11 class Config(object):12 """The config in this example only holds aliases."""8 unmodified lines21 def read_config(self, filename):22 parser = configparser.RawConfigParser()23 parser.read([filename])24 try:24- self.aliases.update(parser.items('aliases'))25+ self.aliases.update(parser.items("aliases"))26 except configparser.NoSectionError:27 pass28 29 def write_config(self, filename):30 parser = configparser.RawConfigParser()30- parser.add_section('aliases')31+ parser.add_section("aliases")32 for key, value in self.aliases.items():32- parser.set('aliases', key, value)33- with open(filename, 'wb') as file:33+ parser.set("aliases", key, value)34+ with open(filename, "wb") as file:35 parser.write(file)36 37 38 pass_config = click.make_pass_decorator(Config, ensure=True)22 unmodified lines61 # Alternative option: if we did not find an explicit alias we62 # allow automatic abbreviation of the command. "status" for63 # instance will match "st". We only allow that however if64 # there is only one command.64- matches = [x for x in self.list_commands(ctx)65- if x.lower().startswith(cmd_name.lower())]65+ matches = [66+ x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower())67+ ]68 if not matches:69 return None70 elif len(matches) == 1:71 return click.Group.get_command(self, ctx, matches[0])70- ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))72+ ctx.fail("Too many matches: {}".format(", ".join(sorted(matches))))73 74 75 def read_config(ctx, param, value):76 """Callback that is used whenever --config is passed. We use this to2 unmodified lines79 available.80 """81 cfg = ctx.ensure_object(Config)82 if value is None:81- value = os.path.join(os.path.dirname(__file__), 'aliases.ini')83+ value = os.path.join(os.path.dirname(__file__), "aliases.ini")84 cfg.read_config(value)85 return value86 87 88 @click.command(cls=AliasedGroup)87-@click.option('--config', type=click.Path(exists=True, dir_okay=False),88- callback=read_config, expose_value=False,89- help='The config file to use instead of the default.')89+@click.option(90+ "--config",91+ type=click.Path(exists=True, dir_okay=False),92+ callback=read_config,93+ expose_value=False,94+ help="The config file to use instead of the default.",95+)96 def cli():97 """An example application that supports aliases."""98 99 100 @cli.command()101 def push():102 """Pushes changes."""97- click.echo('Push')103+ click.echo("Push")104 105 106 @cli.command()107 def pull():108 """Pulls changes."""103- click.echo('Pull')109+ click.echo("Pull")110 111 112 @cli.command()113 def clone():114 """Clones a repository."""109- click.echo('Clone')115+ click.echo("Clone")116 117 118 @cli.command()119 def commit():120 """Commits pending changes."""115- click.echo('Commit')121+ click.echo("Commit")122 123 124 @cli.command()125 @pass_config126 def status(config):127 """Shows the status."""122- click.echo('Status for %s' % config.path)128+ click.echo("Status for {}".format(config.path))129 130 131 @cli.command()132 @pass_config127-@click.argument("alias_", metavar='ALIAS', type=click.STRING)133+@click.argument("alias_", metavar="ALIAS", type=click.STRING)134 @click.argument("cmd", type=click.STRING)129-@click.option('--config_file', type=click.Path(exists=True, dir_okay=False),130- default="aliases.ini")135+@click.option(136+ "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini"137+)138 def alias(config, alias_, cmd, config_file):139 """Adds an alias to the specified configuration file."""140 config.add_alias(alias_, cmd)141 config.write_config(config_file)135- click.echo('Added %s as alias for %s' % (alias_, cmd))142+ click.echo("Added '{}' as alias for '{}'".format(alias_, cmd))modified:examples/aliases/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-aliases',5- version='1.0',6- py_modules=['aliases'],4+ name="click-example-aliases",5+ version="1.0",6+ py_modules=["aliases"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 aliases=aliases:cli14- ''',12+ """,13 )modified:examples/bashcompletion/bashcompletion.py+11 added-11 removed
1-import click1 import os2 3+import click4 5+6 @click.group()7 def cli():8 pass9 4 unmodified lines14 if incomplete in key:15 yield key16 17 17-@cli.command(help='A command to print environment variables')18+@cli.command(help="A command to print environment variables")19 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20 def cmd1(envvar):20- click.echo('Environment variable: %s' % envvar)21- click.echo('Value: %s' % os.environ[envvar])21+ click.echo("Environment variable: {}".format(envvar))22+ click.echo("Value: {}".format(os.environ[envvar]))23 24 24-@click.group(help='A group that holds a subcommand')25+@click.group(help="A group that holds a subcommand")26 def group():27 pass28 29 30 def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).32- users = [('bob', 'butcher'),33- ('alice', 'baker'),34- ('jerry', 'candlestick maker')]35- # Ths will allow completion matches based on matches within the description string too!33+ users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34+ # Ths will allow completion matches based on matches within the35+ # description string too!36 return [user for user in users if incomplete in user[0] or incomplete in user[1]]37 38 39-@group.command(help='Choose a user')39+@group.command(help="Choose a user")40 @click.argument("user", type=click.STRING, autocompletion=list_users)41 def subcmd(user):42- click.echo('Chosen user is %s' % user)42+ click.echo("Chosen user is {}".format(user))43 44 45 cli.add_command(group)modified:examples/bashcompletion/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-bashcompletion',5- version='1.0',6- py_modules=['bashcompletion'],4+ name="click-example-bashcompletion",5+ version="1.0",6+ py_modules=["bashcompletion"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 bashcompletion=bashcompletion:cli14- ''',12+ """,13 )modified:examples/colors/colors.py+27 added-11 removed
1 import click2 3 4-all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5- 'cyan', 'white', 'bright_black', 'bright_red', \6- 'bright_green', 'bright_yellow', 'bright_blue', \7- 'bright_magenta', 'bright_cyan', 'bright_white'4+all_colors = (5+ "black",6+ "red",7+ "green",8+ "yellow",9+ "blue",10+ "magenta",11+ "cyan",12+ "white",13+ "bright_black",14+ "bright_red",15+ "bright_green",16+ "bright_yellow",17+ "bright_blue",18+ "bright_magenta",19+ "bright_cyan",20+ "bright_white",21+)22 23 24 @click.command()25 def cli():3 unmodified lines29 30 Give it a try!31 """32 for color in all_colors:19- click.echo(click.style('I am colored %s' % color, fg=color))33+ click.echo(click.style("I am colored {}".format(color), fg=color))34 for color in all_colors:21- click.echo(click.style('I am colored %s and bold' % color,22- fg=color, bold=True))35+ click.echo(36+ click.style("I am colored {} and bold".format(color), fg=color, bold=True)37+ )38 for color in all_colors:24- click.echo(click.style('I am reverse colored %s' % color, fg=color,25- reverse=True))39+ click.echo(40+ click.style("I am reverse colored {}".format(color), fg=color, reverse=True)41+ )42 27- click.echo(click.style('I am blinking', blink=True))28- click.echo(click.style('I am underlined', underline=True))43+ click.echo(click.style("I am blinking", blink=True))44+ click.echo(click.style("I am underlined", underline=True))modified:examples/colors/setup.py+7 added-7 removed
1 from setuptools import setup2 3 setup(4- name='click-example-colors',5- version='1.0',6- py_modules=['colors'],4+ name="click-example-colors",5+ version="1.0",6+ py_modules=["colors"],7 include_package_data=True,8 install_requires=[9- 'click',9+ "click",10 # Colorama is only required for Windows.11- 'colorama',11+ "colorama",12 ],13- entry_points='''13+ entry_points="""14 [console_scripts]15 colors=colors:cli16- ''',16+ """,17 )modified:examples/complex/complex/commands/cmd_init.py+5 added-5 removed
1-import click1 from complex.cli import pass_environment2 3+import click4 5+5-@click.command('init', short_help='Initializes a repo.')6-@click.argument('path', required=False, type=click.Path(resolve_path=True))6+@click.command("init", short_help="Initializes a repo.")7+@click.argument("path", required=False, type=click.Path(resolve_path=True))8 @pass_environment9 def cli(ctx, path):10 """Initializes a repository."""11 if path is None:12 path = ctx.home12- ctx.log('Initialized the repository in %s',13- click.format_filename(path))13+ ctx.log("Initialized the repository in %s", click.format_filename(path))modified:examples/complex/complex/commands/cmd_status.py+5 added-4 removed
1-import click1 from complex.cli import pass_environment2 3+import click4 5-@click.command('status', short_help='Shows file changes.')5+6+@click.command("status", short_help="Shows file changes.")7 @pass_environment8 def cli(ctx):9 """Shows file changes in the current working directory."""9- ctx.log('Changed files: none')10- ctx.vlog('bla bla bla, debug info')10+ ctx.log("Changed files: none")11+ ctx.vlog("bla bla bla, debug info")modified:examples/complex/complex/cli.py+14 added-15 removed
1 import os2 import sys3+4 import click5 6 6-CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')7+CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8 9 10 class Environment(object):10-11 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14 9 unmodified lines24 self.log(msg, *args)25 26 27 pass_environment = click.make_pass_decorator(Environment, ensure=True)28-cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),29- 'commands'))28+cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))29 30 31 class ComplexCLI(click.MultiCommand):33-32 def list_commands(self, ctx):33 rv = []34 for filename in os.listdir(cmd_folder):37- if filename.endswith('.py') and \38- filename.startswith('cmd_'):35+ if filename.endswith(".py") and filename.startswith("cmd_"):36 rv.append(filename[4:-3])37 rv.sort()38 return rv39 40 def get_command(self, ctx, name):41 try:42 if sys.version_info[0] == 2:46- name = name.encode('ascii', 'replace')47- mod = __import__('complex.commands.cmd_' + name,48- None, None, ['cli'])43+ name = name.encode("ascii", "replace")44+ mod = __import__(45+ "complex.commands.cmd_{}".format(name), None, None, ["cli"]46+ )47 except ImportError:48 return49 return mod.cli50 51 52 @click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)55-@click.option('--home', type=click.Path(exists=True, file_okay=False,56- resolve_path=True),57- help='Changes the folder to operate on.')58-@click.option('-v', '--verbose', is_flag=True,59- help='Enables verbose mode.')53+@click.option(54+ "--home",55+ type=click.Path(exists=True, file_okay=False, resolve_path=True),56+ help="Changes the folder to operate on.",57+)58+@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")59 @pass_environment60 def cli(ctx, verbose, home):61 """A complex command line interface."""62 ctx.verbose = verbose2 unmodified linesmodified:examples/complex/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-complex',5- version='1.0',6- packages=['complex', 'complex.commands'],4+ name="click-example-complex",5+ version="1.0",6+ packages=["complex", "complex.commands"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 complex=complex.cli:cli14- ''',12+ """,13 )modified:examples/imagepipe/imagepipe.py+94 added-66 removed
1-import click1 from functools import update_wrapper3-from PIL import Image, ImageFilter, ImageEnhance2 3+from PIL import Image4+from PIL import ImageEnhance5+from PIL import ImageFilter6 7+import click8+9+10 @click.group(chain=True)11 def cli():12 """This script processes a bunch of images through pillow in a unix13 pipe. One commands feeds into the next.28 unmodified lines42 def processor(f):43 """Helper decorator to rewrite a function so that it returns another44 function from it.45 """46+47 def new_func(*args, **kwargs):48 def processor(stream):49 return f(stream, *args, **kwargs)50+51 return processor52+53 return update_wrapper(new_func, f)54 55 56 def generator(f):57 """Similar to the :func:`processor` but passes through old values58 unchanged and does not pass through the values as parameter.59 """60+61 @processor62 def new_func(stream, *args, **kwargs):63 for item in stream:64 yield item65 for item in f(*args, **kwargs):66 yield item67+68 return update_wrapper(new_func, f)69 70 71 def copy_filename(new, old):72 new.filename = old.filename73 return new74 75 67-@cli.command('open')68-@click.option('-i', '--image', 'images', type=click.Path(),69- multiple=True, help='The image file to open.')76+@cli.command("open")77+@click.option(78+ "-i",79+ "--image",80+ "images",81+ type=click.Path(),82+ multiple=True,83+ help="The image file to open.",84+)85 @generator86 def open_cmd(images):87 """Loads one or multiple images for processing. The input parameter88 can be specified multiple times to load more than one image.89 """90 for image in images:91 try:77- click.echo('Opening "%s"' % image)78- if image == '-':92+ click.echo("Opening '{}'".format(image))93+ if image == "-":94 img = Image.open(click.get_binary_stdin())80- img.filename = '-'95+ img.filename = "-"96 else:97 img = Image.open(image)98 yield img99 except Exception as e:85- click.echo('Could not open image "%s": %s' % (image, e), err=True)100+ click.echo("Could not open image '{}': {}".format(image, e), err=True)101 102 88-@cli.command('save')89-@click.option('--filename', default='processed-%04d.png', type=click.Path(),90- help='The format for the filename.',91- show_default=True)103+@cli.command("save")104+@click.option(105+ "--filename",106+ default="processed-{:04}.png",107+ type=click.Path(),108+ help="The format for the filename.",109+ show_default=True,110+)111 @processor112 def save_cmd(images, filename):113 """Saves all processed images to a series of files."""114 for idx, image in enumerate(images):115 try:97- fn = filename % (idx + 1)98- click.echo('Saving "%s" as "%s"' % (image.filename, fn))116+ fn = filename.format(idx + 1)117+ click.echo("Saving '{}' as '{}'".format(image.filename, fn))118 yield image.save(fn)119 except Exception as e:101- click.echo('Could not save image "%s": %s' %102- (image.filename, e), err=True)120+ click.echo(121+ "Could not save image '{}': {}".format(image.filename, e), err=True122+ )123 124 105-@cli.command('display')125+@cli.command("display")126 @processor127 def display_cmd(images):128 """Opens all images in an image viewer."""129 for image in images:110- click.echo('Displaying "%s"' % image.filename)130+ click.echo("Displaying '{}'".format(image.filename))131 image.show()132 yield image133 134 115-@cli.command('resize')116-@click.option('-w', '--width', type=int, help='The new width of the image.')117-@click.option('-h', '--height', type=int, help='The new height of the image.')135+@cli.command("resize")136+@click.option("-w", "--width", type=int, help="The new width of the image.")137+@click.option("-h", "--height", type=int, help="The new height of the image.")138 @processor139 def resize_cmd(images, width, height):140 """Resizes an image by fitting it into the box without changing141 the aspect ratio.142 """143 for image in images:144 w, h = (width or image.size[0], height or image.size[1])125- click.echo('Resizing "%s" to %dx%d' % (image.filename, w, h))145+ click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h))146 image.thumbnail((w, h))147 yield image148 149 130-@cli.command('crop')131-@click.option('-b', '--border', type=int, help='Crop the image from all '132- 'sides by this amount.')150+@cli.command("crop")151+@click.option(152+ "-b", "--border", type=int, help="Crop the image from all sides by this amount."153+)154 @processor155 def crop_cmd(images, border):156 """Crops an image from all edges."""157 for image in images:1 unmodified line159 160 if border is not None:161 for idx, val in enumerate(box):162 box[idx] = max(0, val - border)142- click.echo('Cropping "%s" by %dpx' % (image.filename, border))163+ click.echo("Cropping '{}' by {}px".format(image.filename, border))164 yield copy_filename(image.crop(box), image)165 else:166 yield image167 1 unmodified line169 def convert_rotation(ctx, param, value):170 if value is None:171 return172 value = value.lower()152- if value in ('90', 'r', 'right'):173+ if value in ("90", "r", "right"):174 return (Image.ROTATE_90, 90)154- if value in ('180', '-180'):175+ if value in ("180", "-180"):176 return (Image.ROTATE_180, 180)156- if value in ('-90', '270', 'l', 'left'):177+ if value in ("-90", "270", "l", "left"):178 return (Image.ROTATE_270, 270)158- raise click.BadParameter('invalid rotation "%s"' % value)179+ raise click.BadParameter("invalid rotation '{}'".format(value))180 181 182 def convert_flip(ctx, param, value):183 if value is None:184 return185 value = value.lower()165- if value in ('lr', 'leftright'):166- return (Image.FLIP_LEFT_RIGHT, 'left to right')167- if value in ('tb', 'topbottom', 'upsidedown', 'ud'):168- return (Image.FLIP_LEFT_RIGHT, 'top to bottom')169- raise click.BadParameter('invalid flip "%s"' % value)186+ if value in ("lr", "leftright"):187+ return (Image.FLIP_LEFT_RIGHT, "left to right")188+ if value in ("tb", "topbottom", "upsidedown", "ud"):189+ return (Image.FLIP_LEFT_RIGHT, "top to bottom")190+ raise click.BadParameter("invalid flip '{}'".format(value))191 192 172-@cli.command('transpose')173-@click.option('-r', '--rotate', callback=convert_rotation,174- help='Rotates the image (in degrees)')175-@click.option('-f', '--flip', callback=convert_flip,176- help='Flips the image [LR / TB]')193+@cli.command("transpose")194+@click.option(195+ "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"196+)197+@click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]")198 @processor199 def transpose_cmd(images, rotate, flip):200 """Transposes an image by either rotating or flipping it."""201 for image in images:202 if rotate is not None:203 mode, degrees = rotate183- click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees))204+ click.echo("Rotate '{}' by {}deg".format(image.filename, degrees))205 image = copy_filename(image.transpose(mode), image)206 if flip is not None:207 mode, direction = flip187- click.echo('Flip "%s" %s' % (image.filename, direction))208+ click.echo("Flip '{}' {}".format(image.filename, direction))209 image = copy_filename(image.transpose(mode), image)210 yield image211 212 192-@cli.command('blur')193-@click.option('-r', '--radius', default=2, show_default=True,194- help='The blur radius.')213+@cli.command("blur")214+@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")215 @processor216 def blur_cmd(images, radius):217 """Applies gaussian blur."""218 blur = ImageFilter.GaussianBlur(radius)219 for image in images:200- click.echo('Blurring "%s" by %dpx' % (image.filename, radius))220+ click.echo("Blurring '{}' by {}px".format(image.filename, radius))221 yield copy_filename(image.filter(blur), image)222 223 204-@cli.command('smoothen')205-@click.option('-i', '--iterations', default=1, show_default=True,206- help='How many iterations of the smoothen filter to run.')224+@cli.command("smoothen")225+@click.option(226+ "-i",227+ "--iterations",228+ default=1,229+ show_default=True,230+ help="How many iterations of the smoothen filter to run.",231+)232 @processor233 def smoothen_cmd(images, iterations):234 """Applies a smoothening filter."""235 for image in images:211- click.echo('Smoothening "%s" %d time%s' %212- (image.filename, iterations, iterations != 1 and 's' or '',))213- for x in xrange(iterations):236+ click.echo(237+ "Smoothening '{}' {} time{}".format(238+ image.filename, iterations, "s" if iterations != 1 else ""239+ )240+ )241+ for _ in range(iterations):242 image = copy_filename(image.filter(ImageFilter.BLUR), image)243 yield image244 245 218-@cli.command('emboss')246+@cli.command("emboss")247 @processor248 def emboss_cmd(images):249 """Embosses an image."""250 for image in images:223- click.echo('Embossing "%s"' % image.filename)251+ click.echo("Embossing '{}'".format(image.filename))252 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)253 254 227-@cli.command('sharpen')228-@click.option('-f', '--factor', default=2.0,229- help='Sharpens the image.', show_default=True)255+@cli.command("sharpen")256+@click.option(257+ "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True258+)259 @processor260 def sharpen_cmd(images, factor):261 """Sharpens an image."""262 for image in images:234- click.echo('Sharpen "%s" by %f' % (image.filename, factor))263+ click.echo("Sharpen '{}' by {}".format(image.filename, factor))264 enhancer = ImageEnhance.Sharpness(image)265 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)266 267 239-@cli.command('paste')240-@click.option('-l', '--left', default=0, help='Offset from left.')241-@click.option('-r', '--right', default=0, help='Offset from right.')268+@cli.command("paste")269+@click.option("-l", "--left", default=0, help="Offset from left.")270+@click.option("-r", "--right", default=0, help="Offset from right.")271 @processor272 def paste_cmd(images, left, right):273 """Pastes the second image on the first image and leaves the rest274 unchanged.6 unmodified lines281 if image is not None:282 yield image283 return284 256- click.echo('Paste "%s" on "%s"' %257- (to_paste.filename, image.filename))285+ click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename))286 mask = None259- if to_paste.mode == 'RGBA' or 'transparency' in to_paste.info:287+ if to_paste.mode == "RGBA" or "transparency" in to_paste.info:288 mask = to_paste289 image.paste(to_paste, (left, right), mask)262- image.filename += '+' + to_paste.filename290+ image.filename += "+{}".format(to_paste.filename)291 yield image292 293 for image in imageiter:294 yield imagemodified:examples/imagepipe/setup.py+6 added-9 removed
1 from setuptools import setup2 3 setup(4- name='click-example-imagepipe',5- version='1.0',6- py_modules=['imagepipe'],4+ name="click-example-imagepipe",5+ version="1.0",6+ py_modules=["imagepipe"],7 include_package_data=True,8- install_requires=[9- 'click',10- 'pillow',11- ],12- entry_points='''8+ install_requires=["click", "pillow"],9+ entry_points="""10 [console_scripts]11 imagepipe=imagepipe:cli15- ''',12+ """,13 )modified:examples/inout/inout.py+2 added-2 removed
1 import click2 3 4 @click.command()5-@click.argument('input', type=click.File('rb'), nargs=-1)6-@click.argument('output', type=click.File('wb'))5+@click.argument("input", type=click.File("rb"), nargs=-1)6+@click.argument("output", type=click.File("wb"))7 def cli(input, output):8 """This script works similar to the Unix `cat` command but it writes9 into a specific file (which could be the standard output as denoted by10 the ``-`` sign).20 unmodified linesmodified:examples/inout/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-inout',5- version='0.1',6- py_modules=['inout'],4+ name="click-example-inout",5+ version="0.1",6+ py_modules=["inout"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 inout=inout:cli14- ''',12+ """,13 )modified:examples/naval/naval.py+31 added-29 removed
15 unmodified lines16 def ship():17 """Manages ships."""18 19 20-@ship.command('new')21-@click.argument('name')20+@ship.command("new")21+@click.argument("name")22 def ship_new(name):23 """Creates a new ship."""24- click.echo('Created ship %s' % name)24+ click.echo("Created ship {}".format(name))25 26 27-@ship.command('move')28-@click.argument('ship')29-@click.argument('x', type=float)30-@click.argument('y', type=float)31-@click.option('--speed', metavar='KN', default=10,32- help='Speed in knots.')27+@ship.command("move")28+@click.argument("ship")29+@click.argument("x", type=float)30+@click.argument("y", type=float)31+@click.option("--speed", metavar="KN", default=10, help="Speed in knots.")32 def ship_move(ship, x, y, speed):33 """Moves SHIP to the new location X,Y."""35- click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed))34+ click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, speed))35 36 38-@ship.command('shoot')39-@click.argument('ship')40-@click.argument('x', type=float)41-@click.argument('y', type=float)37+@ship.command("shoot")38+@click.argument("ship")39+@click.argument("x", type=float)40+@click.argument("y", type=float)41 def ship_shoot(ship, x, y):42 """Makes SHIP fire to X,Y."""44- click.echo('Ship %s fires to %s,%s' % (ship, x, y))43+ click.echo("Ship {} fires to {},{}".format(ship, x, y))44 45 47-@cli.group('mine')46+@cli.group("mine")47 def mine():48 """Manages mines."""49 50 52-@mine.command('set')53-@click.argument('x', type=float)54-@click.argument('y', type=float)55-@click.option('ty', '--moored', flag_value='moored',56- default=True,57- help='Moored (anchored) mine. Default.')58-@click.option('ty', '--drifting', flag_value='drifting',59- help='Drifting mine.')51+@mine.command("set")52+@click.argument("x", type=float)53+@click.argument("y", type=float)54+@click.option(55+ "ty",56+ "--moored",57+ flag_value="moored",58+ default=True,59+ help="Moored (anchored) mine. Default.",60+)61+@click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.")62 def mine_set(x, y, ty):63 """Sets a mine at a specific coordinate."""62- click.echo('Set %s mine at %s,%s' % (ty, x, y))64+ click.echo("Set {} mine at {},{}".format(ty, x, y))65 66 65-@mine.command('remove')66-@click.argument('x', type=float)67-@click.argument('y', type=float)67+@mine.command("remove")68+@click.argument("x", type=float)69+@click.argument("y", type=float)70 def mine_remove(x, y):71 """Removes a mine at a specific coordinate."""70- click.echo('Removed mine at %s,%s' % (x, y))72+ click.echo("Removed mine at {},{}".format(x, y))modified:examples/naval/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-naval',5- version='2.0',6- py_modules=['naval'],4+ name="click-example-naval",5+ version="2.0",6+ py_modules=["naval"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 naval=naval:cli14- ''',12+ """,13 )modified:examples/repo/repo.py+66 added-51 removed
1 import os2-import sys2 import posixpath3+import sys4 5 import click6 7 8 class Repo(object):9-9 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False13 14 def set_config(self, key, value):15 self.config[key] = value16 if self.verbose:18- click.echo(' config[%s] = %s' % (key, value), file=sys.stderr)17+ click.echo(" config[{}] = {}".format(key, value), file=sys.stderr)18 19 def __repr__(self):21- return '<Repo %r>' % self.home20+ return "<Repo {}>".format(self.home)21 22 23 pass_repo = click.make_pass_decorator(Repo)24 25 26 @click.group()28-@click.option('--repo-home', envvar='REPO_HOME', default='.repo',29- metavar='PATH', help='Changes the repository folder location.')30-@click.option('--config', nargs=2, multiple=True,31- metavar='KEY VALUE', help='Overrides a config key/value pair.')32-@click.option('--verbose', '-v', is_flag=True,33- help='Enables verbose mode.')34-@click.version_option('1.0')27+@click.option(28+ "--repo-home",29+ envvar="REPO_HOME",30+ default=".repo",31+ metavar="PATH",32+ help="Changes the repository folder location.",33+)34+@click.option(35+ "--config",36+ nargs=2,37+ multiple=True,38+ metavar="KEY VALUE",39+ help="Overrides a config key/value pair.",40+)41+@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.")42+@click.version_option("1.0")43 @click.pass_context44 def cli(ctx, repo_home, config, verbose):45 """Repo is a command line tool that showcases how to build complex46 command line interfaces with Click.10 unmodified lines57 ctx.obj.set_config(key, value)58 59 60 @cli.command()53-@click.argument('src')54-@click.argument('dest', required=False)55-@click.option('--shallow/--deep', default=False,56- help='Makes a checkout shallow or deep. Deep by default.')57-@click.option('--rev', '-r', default='HEAD',58- help='Clone a specific revision instead of HEAD.')61+@click.argument("src")62+@click.argument("dest", required=False)63+@click.option(64+ "--shallow/--deep",65+ default=False,66+ help="Makes a checkout shallow or deep. Deep by default.",67+)68+@click.option(69+ "--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD."70+)71 @pass_repo72 def clone(repo, src, dest, shallow, rev):73 """Clones a repository.74 1 unmodified line76 is not provided this will automatically use the last path component77 of SRC and create that folder.78 """79 if dest is None:68- dest = posixpath.split(src)[-1] or '.'69- click.echo('Cloning repo %s to %s' % (src, os.path.abspath(dest)))80+ dest = posixpath.split(src)[-1] or "."81+ click.echo("Cloning repo {} to {}".format(src, os.path.abspath(dest)))82 repo.home = dest83 if shallow:72- click.echo('Making shallow checkout')73- click.echo('Checking out revision %s' % rev)84+ click.echo("Making shallow checkout")85+ click.echo("Checking out revision {}".format(rev))86 87 88 @cli.command()89 @click.confirmation_option()2 unmodified lines92 """Deletes a repository.93 94 This will throw away the current repository.95 """84- click.echo('Destroying repo %s' % repo.home)85- click.echo('Deleted!')96+ click.echo("Destroying repo {}".format(repo.home))97+ click.echo("Deleted!")98 99 100 @cli.command()89-@click.option('--username', prompt=True,90- help='The developer\'s shown username.')91-@click.option('--email', prompt='E-Mail',92- help='The developer\'s email address')93-@click.password_option(help='The login password.')101+@click.option("--username", prompt=True, help="The developer's shown username.")102+@click.option("--email", prompt="E-Mail", help="The developer's email address")103+@click.password_option(help="The login password.")104 @pass_repo105 def setuser(repo, username, email, password):106 """Sets the user credentials.107 108 This will override the current user config.109 """100- repo.set_config('username', username)101- repo.set_config('email', email)102- repo.set_config('password', '*' * len(password))103- click.echo('Changed credentials.')110+ repo.set_config("username", username)111+ repo.set_config("email", email)112+ repo.set_config("password", "*" * len(password))113+ click.echo("Changed credentials.")114 115 116 @cli.command()107-@click.option('--message', '-m', multiple=True,108- help='The commit message. If provided multiple times each '109- 'argument gets converted into a new line.')110-@click.argument('files', nargs=-1, type=click.Path())117+@click.option(118+ "--message",119+ "-m",120+ multiple=True,121+ help="The commit message. If provided multiple times each"122+ " argument gets converted into a new line.",123+)124+@click.argument("files", nargs=-1, type=click.Path())125 @pass_repo126 def commit(repo, files, message):127 """Commits outstanding changes.128 3 unmodified lines132 If a list of files is omitted, all changes reported by "repo status"133 will be committed.134 """135 if not message:122- marker = '# Files to be committed:'123- hint = ['', '', marker, '#']136+ marker = "# Files to be committed:"137+ hint = ["", "", marker, "#"]138 for file in files:125- hint.append('# U %s' % file)126- message = click.edit('\n'.join(hint))139+ hint.append("# U {}".format(file))140+ message = click.edit("\n".join(hint))141 if message is None:128- click.echo('Aborted!')142+ click.echo("Aborted!")143 return144 msg = message.split(marker)[0].rstrip()145 if not msg:132- click.echo('Aborted! Empty commit message')146+ click.echo("Aborted! Empty commit message")147 return148 else:135- msg = '\n'.join(message)136- click.echo('Files to be committed: %s' % (files,))137- click.echo('Commit message:\n' + msg)149+ msg = "\n".join(message)150+ click.echo("Files to be committed: {}".format(files))151+ click.echo("Commit message:\n{}".format(msg))152 153 140-@cli.command(short_help='Copies files.')141-@click.option('--force', is_flag=True,142- help='forcibly copy over an existing managed file')143-@click.argument('src', nargs=-1, type=click.Path())144-@click.argument('dst', type=click.Path())154+@cli.command(short_help="Copies files.")155+@click.option(156+ "--force", is_flag=True, help="forcibly copy over an existing managed file"157+)158+@click.argument("src", nargs=-1, type=click.Path())159+@click.argument("dst", type=click.Path())160 @pass_repo161 def copy(repo, src, dst, force):162 """Copies one or multiple files to a new location. This copies all163 files from SRC to DST.164 """165 for fn in src:151- click.echo('Copy from %s -> %s' % (fn, dst))166+ click.echo("Copy from {} -> {}".format(fn, dst))modified:examples/repo/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-repo',5- version='0.1',6- py_modules=['repo'],4+ name="click-example-repo",5+ version="0.1",6+ py_modules=["repo"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 repo=repo:cli14- ''',12+ """,13 )modified:examples/termui/setup.py+7 added-7 removed
1 from setuptools import setup2 3 setup(4- name='click-example-termui',5- version='1.0',6- py_modules=['termui'],4+ name="click-example-termui",5+ version="1.0",6+ py_modules=["termui"],7 include_package_data=True,8 install_requires=[9- 'click',9+ "click",10 # Colorama is only required for Windows.11- 'colorama',11+ "colorama",12 ],13- entry_points='''13+ entry_points="""14 [console_scripts]15 termui=termui:cli16- ''',16+ """,17 )modified:examples/termui/termui.py+71 added-57 removed
1 # coding: utf-82-import click2 import math4-import time3 import random4+import time5 7-try:8- range_type = xrange9-except NameError:10- range_type = range6+import click7 8 9 @click.group()10 def cli():3 unmodified lines14 15 @cli.command()16 def colordemo():17 """Demonstrates ANSI color support."""22- for color in 'red', 'green', 'blue':23- click.echo(click.style('I am colored %s' % color, fg=color))24- click.echo(click.style('I am background colored %s' % color, bg=color))18+ for color in "red", "green", "blue":19+ click.echo(click.style("I am colored {}".format(color), fg=color))20+ click.echo(click.style("I am background colored {}".format(color), bg=color))21 22 23 @cli.command()24 def pager():25 """Demonstrates using the pager."""26 lines = []31- for x in range_type(200):32- lines.append('%s. Hello World!' % click.style(str(x), fg='green'))33- click.echo_via_pager('\n'.join(lines))27+ for x in range(200):28+ lines.append("{}. Hello World!".format(click.style(str(x), fg="green")))29+ click.echo_via_pager("\n".join(lines))30 31 32 @cli.command()37-@click.option('--count', default=8000, type=click.IntRange(1, 100000),38- help='The number of items to process.')33+@click.option(34+ "--count",35+ default=8000,36+ type=click.IntRange(1, 100000),37+ help="The number of items to process.",38+)39 def progress(count):40 """Demonstrates the progress bar."""41- items = range_type(count)41+ items = range(count)42 43 def process_slowly(item):44 time.sleep(0.002 * random.random())45 1 unmodified line47 for item in items:48 if random.random() > 0.3:49 yield item50 51- with click.progressbar(items, label='Processing accounts',52- fill_char=click.style('#', fg='green')) as bar:51+ with click.progressbar(52+ items, label="Processing accounts", fill_char=click.style("#", fg="green")53+ ) as bar:54 for item in bar:55 process_slowly(item)56 57 def show_item(item):58 if item is not None:58- return 'Item #%d' % item59+ return "Item #{}".format(item)60 60- with click.progressbar(filter(items), label='Committing transaction',61- fill_char=click.style('#', fg='yellow'),62- item_show_func=show_item) as bar:61+ with click.progressbar(62+ filter(items),63+ label="Committing transaction",64+ fill_char=click.style("#", fg="yellow"),65+ item_show_func=show_item,66+ ) as bar:67 for item in bar:68 process_slowly(item)69 66- with click.progressbar(length=count, label='Counting',67- bar_template='%(label)s %(bar)s | %(info)s',68- fill_char=click.style(u'█', fg='cyan'),69- empty_char=' ') as bar:70+ with click.progressbar(71+ length=count,72+ label="Counting",73+ bar_template="%(label)s %(bar)s | %(info)s",74+ fill_char=click.style(u"█", fg="cyan"),75+ empty_char=" ",76+ ) as bar:77 for item in bar:78 process_slowly(item)79 73- with click.progressbar(length=count, width=0, show_percent=False,74- show_eta=False,75- fill_char=click.style('#', fg='magenta')) as bar:80+ with click.progressbar(81+ length=count,82+ width=0,83+ show_percent=False,84+ show_eta=False,85+ fill_char=click.style("#", fg="magenta"),86+ ) as bar:87 for item in bar:88 process_slowly(item)89 90 # 'Non-linear progress bar'80- steps = [math.exp( x * 1. / 20) - 1 for x in range(20)]91+ steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)]92 count = int(sum(steps))82- with click.progressbar(length=count, show_percent=False,83- label='Slowing progress bar',84- fill_char=click.style(u'█', fg='green')) as bar:93+ with click.progressbar(94+ length=count,95+ show_percent=False,96+ label="Slowing progress bar",97+ fill_char=click.style(u"█", fg="green"),98+ ) as bar:99 for item in steps:100 time.sleep(item)101 bar.update(item)102 103 104 @cli.command()91-@click.argument('url')105+@click.argument("url")106 def open(url):107 """Opens a file or URL In the default application."""108 click.launch(url)109 110 111 @cli.command()98-@click.argument('url')112+@click.argument("url")113 def locate(url):114 """Opens a file or URL In the default application."""115 click.launch(url, locate=True)116 117 118 @cli.command()119 def edit():120 """Opens an editor with some text in it."""107- MARKER = '# Everything below is ignored\n'108- message = click.edit('\n\n' + MARKER)121+ MARKER = "# Everything below is ignored\n"122+ message = click.edit("\n\n{}".format(MARKER))123 if message is not None:110- msg = message.split(MARKER, 1)[0].rstrip('\n')124+ msg = message.split(MARKER, 1)[0].rstrip("\n")125 if not msg:112- click.echo('Empty message!')126+ click.echo("Empty message!")127 else:114- click.echo('Message:\n' + msg)128+ click.echo("Message:\n{}".format(msg))129 else:116- click.echo('You did not enter anything!')130+ click.echo("You did not enter anything!")131 132 133 @cli.command()134 def clear():9 unmodified lines144 145 @cli.command()146 def menu():147 """Shows a simple menu."""134- menu = 'main'148+ menu = "main"149 while 1:136- if menu == 'main':137- click.echo('Main menu:')138- click.echo(' d: debug menu')139- click.echo(' q: quit')150+ if menu == "main":151+ click.echo("Main menu:")152+ click.echo(" d: debug menu")153+ click.echo(" q: quit")154 char = click.getchar()141- if char == 'd':142- menu = 'debug'143- elif char == 'q':144- menu = 'quit'155+ if char == "d":156+ menu = "debug"157+ elif char == "q":158+ menu = "quit"159 else:146- click.echo('Invalid input')147- elif menu == 'debug':148- click.echo('Debug menu')149- click.echo(' b: back')160+ click.echo("Invalid input")161+ elif menu == "debug":162+ click.echo("Debug menu")163+ click.echo(" b: back")164 char = click.getchar()151- if char == 'b':152- menu = 'main'165+ if char == "b":166+ menu = "main"167 else:154- click.echo('Invalid input')155- elif menu == 'quit':168+ click.echo("Invalid input")169+ elif menu == "quit":170 returnmodified:examples/validation/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-validation',5- version='1.0',6- py_modules=['validation'],4+ name="click-example-validation",5+ version="1.0",6+ py_modules=["validation"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click"],9+ entry_points="""10 [console_scripts]11 validation=validation:cli14- ''',12+ """,13 )modified:examples/validation/validation.py+23 added-15 removed
1 import click2+3 try:4 from urllib import parse as urlparse5 except ImportError:6 import urlparse7 8 9 def validate_count(ctx, param, value):10 if value < 0 or value % 2 != 0:10- raise click.BadParameter('Should be a positive, even integer.')11+ raise click.BadParameter("Should be a positive, even integer.")12 return value13 14 15 class URL(click.ParamType):15- name = 'url'16+ name = "url"17 18 def convert(self, value, param, ctx):19 if not isinstance(value, tuple):20 value = urlparse.urlparse(value)20- if value.scheme not in ('http', 'https'):21- self.fail('invalid URL scheme (%s). Only HTTP URLs are '22- 'allowed' % value.scheme, param, ctx)21+ if value.scheme not in ("http", "https"):22+ self.fail(23+ "invalid URL scheme ({}). Only HTTP URLs are"24+ " allowed".format(value.scheme),25+ param,26+ ctx,27+ )28 return value29 30 31 @click.command()27-@click.option('--count', default=2, callback=validate_count,28- help='A positive even number.')29-@click.option('--foo', help='A mysterious parameter.')30-@click.option('--url', help='A URL', type=URL())32+@click.option(33+ "--count", default=2, callback=validate_count, help="A positive even number."34+)35+@click.option("--foo", help="A mysterious parameter.")36+@click.option("--url", help="A URL", type=URL())37 @click.version_option()38 def cli(count, foo, url):39 """Validation.40 41 This example validates parameters in different ways. It does it42 through callbacks, through a custom type as well as by validating43 manually in the function.44 """39- if foo is not None and foo != 'wat':40- raise click.BadParameter('If a value is provided it needs to be the '41- 'value "wat".', param_hint=['--foo'])42- click.echo('count: %s' % count)43- click.echo('foo: %s' % foo)44- click.echo('url: %s' % repr(url))45+ if foo is not None and foo != "wat":46+ raise click.BadParameter(47+ 'If a value is provided it needs to be the value "wat".',48+ param_hint=["--foo"],49+ )50+ click.echo("count: {}".format(count))51+ click.echo("foo: {}".format(foo))52+ click.echo("url: {!r}".format(url))added:src/click/__init__.py+79 added
1+"""2+Click is a simple Python module inspired by the stdlib optparse to make3+writing command line scripts fun. Unlike other modules, it's based4+around a simple API that does not come with too much magic and is5+composable.6+"""7+from .core import Argument8+from .core import BaseCommand9+from .core import Command10+from .core import CommandCollection11+from .core import Context12+from .core import Group13+from .core import MultiCommand14+from .core import Option15+from .core import Parameter16+from .decorators import argument17+from .decorators import command18+from .decorators import confirmation_option19+from .decorators import group20+from .decorators import help_option21+from .decorators import make_pass_decorator22+from .decorators import option23+from .decorators import pass_context24+from .decorators import pass_obj25+from .decorators import password_option26+from .decorators import version_option27+from .exceptions import Abort28+from .exceptions import BadArgumentUsage29+from .exceptions import BadOptionUsage30+from .exceptions import BadParameter31+from .exceptions import ClickException32+from .exceptions import FileError33+from .exceptions import MissingParameter34+from .exceptions import NoSuchOption35+from .exceptions import UsageError36+from .formatting import HelpFormatter37+from .formatting import wrap_text38+from .globals import get_current_context39+from .parser import OptionParser40+from .termui import clear41+from .termui import confirm42+from .termui import echo_via_pager43+from .termui import edit44+from .termui import get_terminal_size45+from .termui import getchar46+from .termui import launch47+from .termui import pause48+from .termui import progressbar49+from .termui import prompt50+from .termui import secho51+from .termui import style52+from .termui import unstyle53+from .types import BOOL54+from .types import Choice55+from .types import DateTime56+from .types import File57+from .types import FLOAT58+from .types import FloatRange59+from .types import INT60+from .types import IntRange61+from .types import ParamType62+from .types import Path63+from .types import STRING64+from .types import Tuple65+from .types import UNPROCESSED66+from .types import UUID67+from .utils import echo68+from .utils import format_filename69+from .utils import get_app_dir70+from .utils import get_binary_stream71+from .utils import get_os_args72+from .utils import get_text_stream73+from .utils import open_file74+75+# Controls if click should emit the warning about the use of unicode76+# literals.77+disable_unicode_literals_warning = False78+79+__version__ = "7.1.dev"added:src/click/_bashcomplete.py+375 added
1+import copy2+import os3+import re4+5+from .core import Argument6+from .core import MultiCommand7+from .core import Option8+from .parser import split_arg_string9+from .types import Choice10+from .utils import echo11+12+try:13+ from collections import abc14+except ImportError:15+ import collections as abc16+17+WORDBREAK = "="18+19+# Note, only BASH version 4.4 and later have the nosort option.20+COMPLETION_SCRIPT_BASH = """21+%(complete_func)s() {22+ local IFS=$'\n'23+ COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\24+ COMP_CWORD=$COMP_CWORD \\25+ %(autocomplete_var)s=complete $1 ) )26+ return 027+}28+29+%(complete_func)setup() {30+ local COMPLETION_OPTIONS=""31+ local BASH_VERSION_ARR=(${BASH_VERSION//./ })32+ # Only BASH version 4.4 and later have the nosort option.33+ if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] \34+&& [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then35+ COMPLETION_OPTIONS="-o nosort"36+ fi37+38+ complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s39+}40+41+%(complete_func)setup42+"""43+44+COMPLETION_SCRIPT_ZSH = """45+#compdef %(script_names)s46+47+%(complete_func)s() {48+ local -a completions49+ local -a completions_with_descriptions50+ local -a response51+ (( ! $+commands[%(script_names)s] )) && return 152+53+ response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\54+ COMP_CWORD=$((CURRENT-1)) \\55+ %(autocomplete_var)s=\"complete_zsh\" \\56+ %(script_names)s )}")57+58+ for key descr in ${(kv)response}; do59+ if [[ "$descr" == "_" ]]; then60+ completions+=("$key")61+ else62+ completions_with_descriptions+=("$key":"$descr")63+ fi64+ done65+66+ if [ -n "$completions_with_descriptions" ]; then67+ _describe -V unsorted completions_with_descriptions -U68+ fi69+70+ if [ -n "$completions" ]; then71+ compadd -U -V unsorted -a completions72+ fi73+ compstate[insert]="automenu"74+}75+76+compdef %(complete_func)s %(script_names)s77+"""78+79+COMPLETION_SCRIPT_FISH = (80+ "complete --no-files --command %(script_names)s --arguments"81+ ' "(env %(autocomplete_var)s=complete_fish'82+ " COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t)"83+ ' %(script_names)s)"'84+)85+86+_completion_scripts = {87+ "bash": COMPLETION_SCRIPT_BASH,88+ "zsh": COMPLETION_SCRIPT_ZSH,89+ "fish": COMPLETION_SCRIPT_FISH,90+}91+92+_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")93+94+95+def get_completion_script(prog_name, complete_var, shell):96+ cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))97+ script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)98+ return (99+ script100+ % {101+ "complete_func": "_{}_completion".format(cf_name),102+ "script_names": prog_name,103+ "autocomplete_var": complete_var,104+ }105+ ).strip() + ";"106+107+108+def resolve_ctx(cli, prog_name, args):109+ """Parse into a hierarchy of contexts. Contexts are connected110+ through the parent variable.111+112+ :param cli: command definition113+ :param prog_name: the program that is running114+ :param args: full list of args115+ :return: the final context/command parsed116+ """117+ ctx = cli.make_context(prog_name, args, resilient_parsing=True)118+ args = ctx.protected_args + ctx.args119+ while args:120+ if isinstance(ctx.command, MultiCommand):121+ if not ctx.command.chain:122+ cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)123+ if cmd is None:124+ return ctx125+ ctx = cmd.make_context(126+ cmd_name, args, parent=ctx, resilient_parsing=True127+ )128+ args = ctx.protected_args + ctx.args129+ else:130+ # Walk chained subcommand contexts saving the last one.131+ while args:132+ cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)133+ if cmd is None:134+ return ctx135+ sub_ctx = cmd.make_context(136+ cmd_name,137+ args,138+ parent=ctx,139+ allow_extra_args=True,140+ allow_interspersed_args=False,141+ resilient_parsing=True,142+ )143+ args = sub_ctx.args144+ ctx = sub_ctx145+ args = sub_ctx.protected_args + sub_ctx.args146+ else:147+ break148+ return ctx149+150+151+def start_of_option(param_str):152+ """153+ :param param_str: param_str to check154+ :return: whether or not this is the start of an option declaration155+ (i.e. starts "-" or "--")156+ """157+ return param_str and param_str[:1] == "-"158+159+160+def is_incomplete_option(all_args, cmd_param):161+ """162+ :param all_args: the full original list of args supplied163+ :param cmd_param: the current command paramter164+ :return: whether or not the last option declaration (i.e. starts165+ "-" or "--") is incomplete and corresponds to this cmd_param. In166+ other words whether this cmd_param option can still accept167+ values168+ """169+ if not isinstance(cmd_param, Option):170+ return False171+ if cmd_param.is_flag:172+ return False173+ last_option = None174+ for index, arg_str in enumerate(175+ reversed([arg for arg in all_args if arg != WORDBREAK])176+ ):177+ if index + 1 > cmd_param.nargs:178+ break179+ if start_of_option(arg_str):180+ last_option = arg_str181+182+ return True if last_option and last_option in cmd_param.opts else False183+184+185+def is_incomplete_argument(current_params, cmd_param):186+ """187+ :param current_params: the current params and values for this188+ argument as already entered189+ :param cmd_param: the current command parameter190+ :return: whether or not the last argument is incomplete and191+ corresponds to this cmd_param. In other words whether or not the192+ this cmd_param argument can still accept values193+ """194+ if not isinstance(cmd_param, Argument):195+ return False196+ current_param_values = current_params[cmd_param.name]197+ if current_param_values is None:198+ return True199+ if cmd_param.nargs == -1:200+ return True201+ if (202+ isinstance(current_param_values, abc.Iterable)203+ and cmd_param.nargs > 1204+ and len(current_param_values) < cmd_param.nargs205+ ):206+ return True207+ return False208+209+210+def get_user_autocompletions(ctx, args, incomplete, cmd_param):211+ """212+ :param ctx: context associated with the parsed command213+ :param args: full list of args214+ :param incomplete: the incomplete text to autocomplete215+ :param cmd_param: command definition216+ :return: all the possible user-specified completions for the param217+ """218+ results = []219+ if isinstance(cmd_param.type, Choice):220+ # Choices don't support descriptions.221+ results = [222+ (c, None) for c in cmd_param.type.choices if str(c).startswith(incomplete)223+ ]224+ elif cmd_param.autocompletion is not None:225+ dynamic_completions = cmd_param.autocompletion(226+ ctx=ctx, args=args, incomplete=incomplete227+ )228+ results = [229+ c if isinstance(c, tuple) else (c, None) for c in dynamic_completions230+ ]231+ return results232+233+234+def get_visible_commands_starting_with(ctx, starts_with):235+ """236+ :param ctx: context associated with the parsed command237+ :starts_with: string that visible commands must start with.238+ :return: all visible (not hidden) commands that start with starts_with.239+ """240+ for c in ctx.command.list_commands(ctx):241+ if c.startswith(starts_with):242+ command = ctx.command.get_command(ctx, c)243+ if not command.hidden:244+ yield command245+246+247+def add_subcommand_completions(ctx, incomplete, completions_out):248+ # Add subcommand completions.249+ if isinstance(ctx.command, MultiCommand):250+ completions_out.extend(251+ [252+ (c.name, c.get_short_help_str())253+ for c in get_visible_commands_starting_with(ctx, incomplete)254+ ]255+ )256+257+ # Walk up the context list and add any other completion258+ # possibilities from chained commands259+ while ctx.parent is not None:260+ ctx = ctx.parent261+ if isinstance(ctx.command, MultiCommand) and ctx.command.chain:262+ remaining_commands = [263+ c264+ for c in get_visible_commands_starting_with(ctx, incomplete)265+ if c.name not in ctx.protected_args266+ ]267+ completions_out.extend(268+ [(c.name, c.get_short_help_str()) for c in remaining_commands]269+ )270+271+272+def get_choices(cli, prog_name, args, incomplete):273+ """274+ :param cli: command definition275+ :param prog_name: the program that is running276+ :param args: full list of args277+ :param incomplete: the incomplete text to autocomplete278+ :return: all the possible completions for the incomplete279+ """280+ all_args = copy.deepcopy(args)281+282+ ctx = resolve_ctx(cli, prog_name, args)283+ if ctx is None:284+ return []285+286+ has_double_dash = "--" in all_args287+288+ # In newer versions of bash long opts with '='s are partitioned, but289+ # it's easier to parse without the '='290+ if start_of_option(incomplete) and WORDBREAK in incomplete:291+ partition_incomplete = incomplete.partition(WORDBREAK)292+ all_args.append(partition_incomplete[0])293+ incomplete = partition_incomplete[2]294+ elif incomplete == WORDBREAK:295+ incomplete = ""296+297+ completions = []298+ if not has_double_dash and start_of_option(incomplete):299+ # completions for partial options300+ for param in ctx.command.params:301+ if isinstance(param, Option) and not param.hidden:302+ param_opts = [303+ param_opt304+ for param_opt in param.opts + param.secondary_opts305+ if param_opt not in all_args or param.multiple306+ ]307+ completions.extend(308+ [(o, param.help) for o in param_opts if o.startswith(incomplete)]309+ )310+ return completions311+ # completion for option values from user supplied values312+ for param in ctx.command.params:313+ if is_incomplete_option(all_args, param):314+ return get_user_autocompletions(ctx, all_args, incomplete, param)315+ # completion for argument values from user supplied values316+ for param in ctx.command.params:317+ if is_incomplete_argument(ctx.params, param):318+ return get_user_autocompletions(ctx, all_args, incomplete, param)319+320+ add_subcommand_completions(ctx, incomplete, completions)321+ # Sort before returning so that proper ordering can be enforced in custom types.322+ return sorted(completions)323+324+325+def do_complete(cli, prog_name, include_descriptions):326+ cwords = split_arg_string(os.environ["COMP_WORDS"])327+ cword = int(os.environ["COMP_CWORD"])328+ args = cwords[1:cword]329+ try:330+ incomplete = cwords[cword]331+ except IndexError:332+ incomplete = ""333+334+ for item in get_choices(cli, prog_name, args, incomplete):335+ echo(item[0])336+ if include_descriptions:337+ # ZSH has trouble dealing with empty array parameters when338+ # returned from commands, use '_' to indicate no description339+ # is present.340+ echo(item[1] if item[1] else "_")341+342+ return True343+344+345+def do_complete_fish(cli, prog_name):346+ cwords = split_arg_string(os.environ["COMP_WORDS"])347+ incomplete = os.environ["COMP_CWORD"]348+ args = cwords[1:]349+350+ for item in get_choices(cli, prog_name, args, incomplete):351+ if item[1]:352+ echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))353+ else:354+ echo(item[0])355+356+ return True357+358+359+def bashcomplete(cli, prog_name, complete_var, complete_instr):360+ if "_" in complete_instr:361+ command, shell = complete_instr.split("_", 1)362+ else:363+ command = complete_instr364+ shell = "bash"365+366+ if command == "source":367+ echo(get_completion_script(prog_name, complete_var, shell))368+ return True369+ elif command == "complete":370+ if shell == "fish":371+ return do_complete_fish(cli, prog_name)372+ elif shell in {"bash", "zsh"}:373+ return do_complete(cli, prog_name, shell == "zsh")374+375+ return Falseadded:src/click/_compat.py+790 added
1+# flake8: noqa2+import codecs3+import io4+import os5+import re6+import sys7+from weakref import WeakKeyDictionary8+9+PY2 = sys.version_info[0] == 210+CYGWIN = sys.platform.startswith("cygwin")11+MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)12+# Determine local App Engine environment, per Google's own suggestion13+APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(14+ "SERVER_SOFTWARE", ""15+)16+WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS217+DEFAULT_COLUMNS = 8018+19+20+_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")21+22+23+def get_filesystem_encoding():24+ return sys.getfilesystemencoding() or sys.getdefaultencoding()25+26+27+def _make_text_stream(28+ stream, encoding, errors, force_readable=False, force_writable=False29+):30+ if encoding is None:31+ encoding = get_best_encoding(stream)32+ if errors is None:33+ errors = "replace"34+ return _NonClosingTextIOWrapper(35+ stream,36+ encoding,37+ errors,38+ line_buffering=True,39+ force_readable=force_readable,40+ force_writable=force_writable,41+ )42+43+44+def is_ascii_encoding(encoding):45+ """Checks if a given encoding is ascii."""46+ try:47+ return codecs.lookup(encoding).name == "ascii"48+ except LookupError:49+ return False50+51+52+def get_best_encoding(stream):53+ """Returns the default stream encoding if not found."""54+ rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()55+ if is_ascii_encoding(rv):56+ return "utf-8"57+ return rv58+59+60+class _NonClosingTextIOWrapper(io.TextIOWrapper):61+ def __init__(62+ self,63+ stream,64+ encoding,65+ errors,66+ force_readable=False,67+ force_writable=False,68+ **extra69+ ):70+ self._stream = stream = _FixupStream(stream, force_readable, force_writable)71+ io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)72+73+ # The io module is a place where the Python 3 text behavior74+ # was forced upon Python 2, so we need to unbreak75+ # it to look like Python 2.76+ if PY2:77+78+ def write(self, x):79+ if isinstance(x, str) or is_bytes(x):80+ try:81+ self.flush()82+ except Exception:83+ pass84+ return self.buffer.write(str(x))85+ return io.TextIOWrapper.write(self, x)86+87+ def writelines(self, lines):88+ for line in lines:89+ self.write(line)90+91+ def __del__(self):92+ try:93+ self.detach()94+ except Exception:95+ pass96+97+ def isatty(self):98+ # https://bitbucket.org/pypy/pypy/issue/180399+ return self._stream.isatty()100+101+102+class _FixupStream(object):103+ """The new io interface needs more from streams than streams104+ traditionally implement. As such, this fix-up code is necessary in105+ some circumstances.106+107+ The forcing of readable and writable flags are there because some tools108+ put badly patched objects on sys (one such offender are certain version109+ of jupyter notebook).110+ """111+112+ def __init__(self, stream, force_readable=False, force_writable=False):113+ self._stream = stream114+ self._force_readable = force_readable115+ self._force_writable = force_writable116+117+ def __getattr__(self, name):118+ return getattr(self._stream, name)119+120+ def read1(self, size):121+ f = getattr(self._stream, "read1", None)122+ if f is not None:123+ return f(size)124+ # We only dispatch to readline instead of read in Python 2 as we125+ # do not want cause problems with the different implementation126+ # of line buffering.127+ if PY2:128+ return self._stream.readline(size)129+ return self._stream.read(size)130+131+ def readable(self):132+ if self._force_readable:133+ return True134+ x = getattr(self._stream, "readable", None)135+ if x is not None:136+ return x()137+ try:138+ self._stream.read(0)139+ except Exception:140+ return False141+ return True142+143+ def writable(self):144+ if self._force_writable:145+ return True146+ x = getattr(self._stream, "writable", None)147+ if x is not None:148+ return x()149+ try:150+ self._stream.write("")151+ except Exception:152+ try:153+ self._stream.write(b"")154+ except Exception:155+ return False156+ return True157+158+ def seekable(self):159+ x = getattr(self._stream, "seekable", None)160+ if x is not None:161+ return x()162+ try:163+ self._stream.seek(self._stream.tell())164+ except Exception:165+ return False166+ return True167+168+169+if PY2:170+ text_type = unicode171+ raw_input = raw_input172+ string_types = (str, unicode)173+ int_types = (int, long)174+ iteritems = lambda x: x.iteritems()175+ range_type = xrange176+177+ from pipes import quote as shlex_quote178+179+ def is_bytes(x):180+ return isinstance(x, (buffer, bytearray))181+182+ _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")183+184+ # For Windows, we need to force stdout/stdin/stderr to binary if it's185+ # fetched for that. This obviously is not the most correct way to do186+ # it as it changes global state. Unfortunately, there does not seem to187+ # be a clear better way to do it as just reopening the file in binary188+ # mode does not change anything.189+ #190+ # An option would be to do what Python 3 does and to open the file as191+ # binary only, patch it back to the system, and then use a wrapper192+ # stream that converts newlines. It's not quite clear what's the193+ # correct option here.194+ #195+ # This code also lives in _winconsole for the fallback to the console196+ # emulation stream.197+ #198+ # There are also Windows environments where the `msvcrt` module is not199+ # available (which is why we use try-catch instead of the WIN variable200+ # here), such as the Google App Engine development server on Windows. In201+ # those cases there is just nothing we can do.202+ def set_binary_mode(f):203+ return f204+205+ try:206+ import msvcrt207+ except ImportError:208+ pass209+ else:210+211+ def set_binary_mode(f):212+ try:213+ fileno = f.fileno()214+ except Exception:215+ pass216+ else:217+ msvcrt.setmode(fileno, os.O_BINARY)218+ return f219+220+ try:221+ import fcntl222+ except ImportError:223+ pass224+ else:225+226+ def set_binary_mode(f):227+ try:228+ fileno = f.fileno()229+ except Exception:230+ pass231+ else:232+ flags = fcntl.fcntl(fileno, fcntl.F_GETFL)233+ fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)234+ return f235+236+ def isidentifier(x):237+ return _identifier_re.search(x) is not None238+239+ def get_binary_stdin():240+ return set_binary_mode(sys.stdin)241+242+ def get_binary_stdout():243+ _wrap_std_stream("stdout")244+ return set_binary_mode(sys.stdout)245+246+ def get_binary_stderr():247+ _wrap_std_stream("stderr")248+ return set_binary_mode(sys.stderr)249+250+ def get_text_stdin(encoding=None, errors=None):251+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)252+ if rv is not None:253+ return rv254+ return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)255+256+ def get_text_stdout(encoding=None, errors=None):257+ _wrap_std_stream("stdout")258+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)259+ if rv is not None:260+ return rv261+ return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)262+263+ def get_text_stderr(encoding=None, errors=None):264+ _wrap_std_stream("stderr")265+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)266+ if rv is not None:267+ return rv268+ return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)269+270+ def filename_to_ui(value):271+ if isinstance(value, bytes):272+ value = value.decode(get_filesystem_encoding(), "replace")273+ return value274+275+276+else:277+ import io278+279+ text_type = str280+ raw_input = input281+ string_types = (str,)282+ int_types = (int,)283+ range_type = range284+ isidentifier = lambda x: x.isidentifier()285+ iteritems = lambda x: iter(x.items())286+287+ from shlex import quote as shlex_quote288+289+ def is_bytes(x):290+ return isinstance(x, (bytes, memoryview, bytearray))291+292+ def _is_binary_reader(stream, default=False):293+ try:294+ return isinstance(stream.read(0), bytes)295+ except Exception:296+ return default297+ # This happens in some cases where the stream was already298+ # closed. In this case, we assume the default.299+300+ def _is_binary_writer(stream, default=False):301+ try:302+ stream.write(b"")303+ except Exception:304+ try:305+ stream.write("")306+ return False307+ except Exception:308+ pass309+ return default310+ return True311+312+ def _find_binary_reader(stream):313+ # We need to figure out if the given stream is already binary.314+ # This can happen because the official docs recommend detaching315+ # the streams to get binary streams. Some code might do this, so316+ # we need to deal with this case explicitly.317+ if _is_binary_reader(stream, False):318+ return stream319+320+ buf = getattr(stream, "buffer", None)321+322+ # Same situation here; this time we assume that the buffer is323+ # actually binary in case it's closed.324+ if buf is not None and _is_binary_reader(buf, True):325+ return buf326+327+ def _find_binary_writer(stream):328+ # We need to figure out if the given stream is already binary.329+ # This can happen because the official docs recommend detatching330+ # the streams to get binary streams. Some code might do this, so331+ # we need to deal with this case explicitly.332+ if _is_binary_writer(stream, False):333+ return stream334+335+ buf = getattr(stream, "buffer", None)336+337+ # Same situation here; this time we assume that the buffer is338+ # actually binary in case it's closed.339+ if buf is not None and _is_binary_writer(buf, True):340+ return buf341+342+ def _stream_is_misconfigured(stream):343+ """A stream is misconfigured if its encoding is ASCII."""344+ # If the stream does not have an encoding set, we assume it's set345+ # to ASCII. This appears to happen in certain unittest346+ # environments. It's not quite clear what the correct behavior is347+ # but this at least will force Click to recover somehow.348+ return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")349+350+ def _is_compat_stream_attr(stream, attr, value):351+ """A stream attribute is compatible if it is equal to the352+ desired value or the desired value is unset and the attribute353+ has a value.354+ """355+ stream_value = getattr(stream, attr, None)356+ return stream_value == value or (value is None and stream_value is not None)357+358+ def _is_compatible_text_stream(stream, encoding, errors):359+ """Check if a stream's encoding and errors attributes are360+ compatible with the desired values.361+ """362+ return _is_compat_stream_attr(363+ stream, "encoding", encoding364+ ) and _is_compat_stream_attr(stream, "errors", errors)365+366+ def _force_correct_text_stream(367+ text_stream,368+ encoding,369+ errors,370+ is_binary,371+ find_binary,372+ force_readable=False,373+ force_writable=False,374+ ):375+ if is_binary(text_stream, False):376+ binary_reader = text_stream377+ else:378+ # If the stream looks compatible, and won't default to a379+ # misconfigured ascii encoding, return it as-is.380+ if _is_compatible_text_stream(text_stream, encoding, errors) and not (381+ encoding is None and _stream_is_misconfigured(text_stream)382+ ):383+ return text_stream384+385+ # Otherwise, get the underlying binary reader.386+ binary_reader = find_binary(text_stream)387+388+ # If that's not possible, silently use the original reader389+ # and get mojibake instead of exceptions.390+ if binary_reader is None:391+ return text_stream392+393+ # Default errors to replace instead of strict in order to get394+ # something that works.395+ if errors is None:396+ errors = "replace"397+398+ # Wrap the binary stream in a text stream with the correct399+ # encoding parameters.400+ return _make_text_stream(401+ binary_reader,402+ encoding,403+ errors,404+ force_readable=force_readable,405+ force_writable=force_writable,406+ )407+408+ def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):409+ return _force_correct_text_stream(410+ text_reader,411+ encoding,412+ errors,413+ _is_binary_reader,414+ _find_binary_reader,415+ force_readable=force_readable,416+ )417+418+ def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):419+ return _force_correct_text_stream(420+ text_writer,421+ encoding,422+ errors,423+ _is_binary_writer,424+ _find_binary_writer,425+ force_writable=force_writable,426+ )427+428+ def get_binary_stdin():429+ reader = _find_binary_reader(sys.stdin)430+ if reader is None:431+ raise RuntimeError("Was not able to determine binary stream for sys.stdin.")432+ return reader433+434+ def get_binary_stdout():435+ writer = _find_binary_writer(sys.stdout)436+ if writer is None:437+ raise RuntimeError(438+ "Was not able to determine binary stream for sys.stdout."439+ )440+ return writer441+442+ def get_binary_stderr():443+ writer = _find_binary_writer(sys.stderr)444+ if writer is None:445+ raise RuntimeError(446+ "Was not able to determine binary stream for sys.stderr."447+ )448+ return writer449+450+ def get_text_stdin(encoding=None, errors=None):451+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)452+ if rv is not None:453+ return rv454+ return _force_correct_text_reader(455+ sys.stdin, encoding, errors, force_readable=True456+ )457+458+ def get_text_stdout(encoding=None, errors=None):459+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)460+ if rv is not None:461+ return rv462+ return _force_correct_text_writer(463+ sys.stdout, encoding, errors, force_writable=True464+ )465+466+ def get_text_stderr(encoding=None, errors=None):467+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)468+ if rv is not None:469+ return rv470+ return _force_correct_text_writer(471+ sys.stderr, encoding, errors, force_writable=True472+ )473+474+ def filename_to_ui(value):475+ if isinstance(value, bytes):476+ value = value.decode(get_filesystem_encoding(), "replace")477+ else:478+ value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")479+ return value480+481+482+def get_streerror(e, default=None):483+ if hasattr(e, "strerror"):484+ msg = e.strerror485+ else:486+ if default is not None:487+ msg = default488+ else:489+ msg = str(e)490+ if isinstance(msg, bytes):491+ msg = msg.decode("utf-8", "replace")492+ return msg493+494+495+def _wrap_io_open(file, mode, encoding, errors):496+ """On Python 2, :func:`io.open` returns a text file wrapper that497+ requires passing ``unicode`` to ``write``. Need to open the file in498+ binary mode then wrap it in a subclass that can write ``str`` and499+ ``unicode``.500+501+ Also handles not passing ``encoding`` and ``errors`` in binary mode.502+ """503+ binary = "b" in mode504+505+ if binary:506+ kwargs = {}507+ else:508+ kwargs = {"encoding": encoding, "errors": errors}509+510+ if not PY2 or binary:511+ return io.open(file, mode, **kwargs)512+513+ f = io.open(file, "{}b".format(mode.replace("t", "")))514+ return _make_text_stream(f, **kwargs)515+516+517+def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):518+ binary = "b" in mode519+520+ # Standard streams first. These are simple because they don't need521+ # special handling for the atomic flag. It's entirely ignored.522+ if filename == "-":523+ if any(m in mode for m in ["w", "a", "x"]):524+ if binary:525+ return get_binary_stdout(), False526+ return get_text_stdout(encoding=encoding, errors=errors), False527+ if binary:528+ return get_binary_stdin(), False529+ return get_text_stdin(encoding=encoding, errors=errors), False530+531+ # Non-atomic writes directly go out through the regular open functions.532+ if not atomic:533+ return _wrap_io_open(filename, mode, encoding, errors), True534+535+ # Some usability stuff for atomic writes536+ if "a" in mode:537+ raise ValueError(538+ "Appending to an existing file is not supported, because that"539+ " would involve an expensive `copy`-operation to a temporary"540+ " file. Open the file in normal `w`-mode and copy explicitly"541+ " if that's what you're after."542+ )543+ if "x" in mode:544+ raise ValueError("Use the `overwrite`-parameter instead.")545+ if "w" not in mode:546+ raise ValueError("Atomic writes only make sense with `w`-mode.")547+548+ # Atomic writes are more complicated. They work by opening a file549+ # as a proxy in the same folder and then using the fdopen550+ # functionality to wrap it in a Python file. Then we wrap it in an551+ # atomic file that moves the file over on close.552+ import errno553+ import random554+555+ try:556+ perm = os.stat(filename).st_mode557+ except OSError:558+ perm = None559+560+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL561+562+ if binary:563+ flags |= getattr(os, "O_BINARY", 0)564+565+ while True:566+ tmp_filename = os.path.join(567+ os.path.dirname(filename),568+ ".__atomic-write{:08x}".format(random.randrange(1 << 32)),569+ )570+ try:571+ fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)572+ break573+ except OSError as e:574+ if e.errno == errno.EEXIST or (575+ os.name == "nt"576+ and e.errno == errno.EACCES577+ and os.path.isdir(e.filename)578+ and os.access(e.filename, os.W_OK)579+ ):580+ continue581+ raise582+583+ if perm is not None:584+ os.chmod(tmp_filename, perm) # in case perm includes bits in umask585+586+ f = _wrap_io_open(fd, mode, encoding, errors)587+ return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True588+589+590+# Used in a destructor call, needs extra protection from interpreter cleanup.591+if hasattr(os, "replace"):592+ _replace = os.replace593+ _can_replace = True594+else:595+ _replace = os.rename596+ _can_replace = not WIN597+598+599+class _AtomicFile(object):600+ def __init__(self, f, tmp_filename, real_filename):601+ self._f = f602+ self._tmp_filename = tmp_filename603+ self._real_filename = real_filename604+ self.closed = False605+606+ @property607+ def name(self):608+ return self._real_filename609+610+ def close(self, delete=False):611+ if self.closed:612+ return613+ self._f.close()614+ if not _can_replace:615+ try:616+ os.remove(self._real_filename)617+ except OSError:618+ pass619+ _replace(self._tmp_filename, self._real_filename)620+ self.closed = True621+622+ def __getattr__(self, name):623+ return getattr(self._f, name)624+625+ def __enter__(self):626+ return self627+628+ def __exit__(self, exc_type, exc_value, tb):629+ self.close(delete=exc_type is not None)630+631+ def __repr__(self):632+ return repr(self._f)633+634+635+auto_wrap_for_ansi = None636+colorama = None637+get_winterm_size = None638+639+640+def strip_ansi(value):641+ return _ansi_re.sub("", value)642+643+644+def _is_jupyter_kernel_output(stream):645+ if WIN:646+ # TODO: Couldn't test on Windows, should't try to support until647+ # someone tests the details wrt colorama.648+ return649+650+ while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):651+ stream = stream._stream652+653+ return stream.__class__.__module__.startswith("ipykernel.")654+655+656+def should_strip_ansi(stream=None, color=None):657+ if color is None:658+ if stream is None:659+ stream = sys.stdin660+ return not isatty(stream) and not _is_jupyter_kernel_output(stream)661+ return not color662+663+664+# If we're on Windows, we provide transparent integration through665+# colorama. This will make ANSI colors through the echo function666+# work automatically.667+if WIN:668+ # Windows has a smaller terminal669+ DEFAULT_COLUMNS = 79670+671+ from ._winconsole import _get_windows_console_stream, _wrap_std_stream672+673+ def _get_argv_encoding():674+ import locale675+676+ return locale.getpreferredencoding()677+678+ if PY2:679+680+ def raw_input(prompt=""):681+ sys.stderr.flush()682+ if prompt:683+ stdout = _default_text_stdout()684+ stdout.write(prompt)685+ stdin = _default_text_stdin()686+ return stdin.readline().rstrip("\r\n")687+688+ try:689+ import colorama690+ except ImportError:691+ pass692+ else:693+ _ansi_stream_wrappers = WeakKeyDictionary()694+695+ def auto_wrap_for_ansi(stream, color=None):696+ """This function wraps a stream so that calls through colorama697+ are issued to the win32 console API to recolor on demand. It698+ also ensures to reset the colors if a write call is interrupted699+ to not destroy the console afterwards.700+ """701+ try:702+ cached = _ansi_stream_wrappers.get(stream)703+ except Exception:704+ cached = None705+ if cached is not None:706+ return cached707+ strip = should_strip_ansi(stream, color)708+ ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)709+ rv = ansi_wrapper.stream710+ _write = rv.write711+712+ def _safe_write(s):713+ try:714+ return _write(s)715+ except:716+ ansi_wrapper.reset_all()717+ raise718+719+ rv.write = _safe_write720+ try:721+ _ansi_stream_wrappers[stream] = rv722+ except Exception:723+ pass724+ return rv725+726+ def get_winterm_size():727+ win = colorama.win32.GetConsoleScreenBufferInfo(728+ colorama.win32.STDOUT729+ ).srWindow730+ return win.Right - win.Left, win.Bottom - win.Top731+732+733+else:734+735+ def _get_argv_encoding():736+ return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()737+738+ _get_windows_console_stream = lambda *x: None739+ _wrap_std_stream = lambda *x: None740+741+742+def term_len(x):743+ return len(strip_ansi(x))744+745+746+def isatty(stream):747+ try:748+ return stream.isatty()749+ except Exception:750+ return False751+752+753+def _make_cached_stream_func(src_func, wrapper_func):754+ cache = WeakKeyDictionary()755+756+ def func():757+ stream = src_func()758+ try:759+ rv = cache.get(stream)760+ except Exception:761+ rv = None762+ if rv is not None:763+ return rv764+ rv = wrapper_func()765+ try:766+ stream = src_func() # In case wrapper_func() modified the stream767+ cache[stream] = rv768+ except Exception:769+ pass770+ return rv771+772+ return func773+774+775+_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)776+_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)777+_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)778+779+780+binary_streams = {781+ "stdin": get_binary_stdin,782+ "stdout": get_binary_stdout,783+ "stderr": get_binary_stderr,784+}785+786+text_streams = {787+ "stdin": get_text_stdin,788+ "stdout": get_text_stdout,789+ "stderr": get_text_stderr,790+}added:src/click/_termui_impl.py+661 added
1+# -*- coding: utf-8 -*-2+"""3+This module contains implementations for the termui module. To keep the4+import time of Click down, some infrequently used functionality is5+placed in this module and only imported as needed.6+"""7+import contextlib8+import math9+import os10+import sys11+import time12+13+from ._compat import _default_text_stdout14+from ._compat import CYGWIN15+from ._compat import get_best_encoding16+from ._compat import int_types17+from ._compat import isatty18+from ._compat import open_stream19+from ._compat import range_type20+from ._compat import shlex_quote21+from ._compat import strip_ansi22+from ._compat import term_len23+from ._compat import WIN24+from .exceptions import ClickException25+from .utils import echo26+27+if os.name == "nt":28+ BEFORE_BAR = "\r"29+ AFTER_BAR = "\n"30+else:31+ BEFORE_BAR = "\r\033[?25l"32+ AFTER_BAR = "\033[?25h\n"33+34+35+def _length_hint(obj):36+ """Returns the length hint of an object."""37+ try:38+ return len(obj)39+ except (AttributeError, TypeError):40+ try:41+ get_hint = type(obj).__length_hint__42+ except AttributeError:43+ return None44+ try:45+ hint = get_hint(obj)46+ except TypeError:47+ return None48+ if hint is NotImplemented or not isinstance(hint, int_types) or hint < 0:49+ return None50+ return hint51+52+53+class ProgressBar(object):54+ def __init__(55+ self,56+ iterable,57+ length=None,58+ fill_char="#",59+ empty_char=" ",60+ bar_template="%(bar)s",61+ info_sep=" ",62+ show_eta=True,63+ show_percent=None,64+ show_pos=False,65+ item_show_func=None,66+ label=None,67+ file=None,68+ color=None,69+ width=30,70+ ):71+ self.fill_char = fill_char72+ self.empty_char = empty_char73+ self.bar_template = bar_template74+ self.info_sep = info_sep75+ self.show_eta = show_eta76+ self.show_percent = show_percent77+ self.show_pos = show_pos78+ self.item_show_func = item_show_func79+ self.label = label or ""80+ if file is None:81+ file = _default_text_stdout()82+ self.file = file83+ self.color = color84+ self.width = width85+ self.autowidth = width == 086+87+ if length is None:88+ length = _length_hint(iterable)89+ if iterable is None:90+ if length is None:91+ raise TypeError("iterable or length is required")92+ iterable = range_type(length)93+ self.iter = iter(iterable)94+ self.length = length95+ self.length_known = length is not None96+ self.pos = 097+ self.avg = []98+ self.start = self.last_eta = time.time()99+ self.eta_known = False100+ self.finished = False101+ self.max_width = None102+ self.entered = False103+ self.current_item = None104+ self.is_hidden = not isatty(self.file)105+ self._last_line = None106+ self.short_limit = 0.5107+108+ def __enter__(self):109+ self.entered = True110+ self.render_progress()111+ return self112+113+ def __exit__(self, exc_type, exc_value, tb):114+ self.render_finish()115+116+ def __iter__(self):117+ if not self.entered:118+ raise RuntimeError("You need to use progress bars in a with block.")119+ self.render_progress()120+ return self.generator()121+122+ def __next__(self):123+ # Iteration is defined in terms of a generator function,124+ # returned by iter(self); use that to define next(). This works125+ # because `self.iter` is an iterable consumed by that generator,126+ # so it is re-entry safe. Calling `next(self.generator())`127+ # twice works and does "what you want".128+ return next(iter(self))129+130+ # Python 2 compat131+ next = __next__132+133+ def is_fast(self):134+ return time.time() - self.start <= self.short_limit135+136+ def render_finish(self):137+ if self.is_hidden or self.is_fast():138+ return139+ self.file.write(AFTER_BAR)140+ self.file.flush()141+142+ @property143+ def pct(self):144+ if self.finished:145+ return 1.0146+ return min(self.pos / (float(self.length) or 1), 1.0)147+148+ @property149+ def time_per_iteration(self):150+ if not self.avg:151+ return 0.0152+ return sum(self.avg) / float(len(self.avg))153+154+ @property155+ def eta(self):156+ if self.length_known and not self.finished:157+ return self.time_per_iteration * (self.length - self.pos)158+ return 0.0159+160+ def format_eta(self):161+ if self.eta_known:162+ t = int(self.eta)163+ seconds = t % 60164+ t //= 60165+ minutes = t % 60166+ t //= 60167+ hours = t % 24168+ t //= 24169+ if t > 0:170+ return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds)171+ else:172+ return "{:02}:{:02}:{:02}".format(hours, minutes, seconds)173+ return ""174+175+ def format_pos(self):176+ pos = str(self.pos)177+ if self.length_known:178+ pos += "/{}".format(self.length)179+ return pos180+181+ def format_pct(self):182+ return "{: 4}%".format(int(self.pct * 100))[1:]183+184+ def format_bar(self):185+ if self.length_known:186+ bar_length = int(self.pct * self.width)187+ bar = self.fill_char * bar_length188+ bar += self.empty_char * (self.width - bar_length)189+ elif self.finished:190+ bar = self.fill_char * self.width191+ else:192+ bar = list(self.empty_char * (self.width or 1))193+ if self.time_per_iteration != 0:194+ bar[195+ int(196+ (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)197+ * self.width198+ )199+ ] = self.fill_char200+ bar = "".join(bar)201+ return bar202+203+ def format_progress_line(self):204+ show_percent = self.show_percent205+206+ info_bits = []207+ if self.length_known and show_percent is None:208+ show_percent = not self.show_pos209+210+ if self.show_pos:211+ info_bits.append(self.format_pos())212+ if show_percent:213+ info_bits.append(self.format_pct())214+ if self.show_eta and self.eta_known and not self.finished:215+ info_bits.append(self.format_eta())216+ if self.item_show_func is not None:217+ item_info = self.item_show_func(self.current_item)218+ if item_info is not None:219+ info_bits.append(item_info)220+221+ return (222+ self.bar_template223+ % {224+ "label": self.label,225+ "bar": self.format_bar(),226+ "info": self.info_sep.join(info_bits),227+ }228+ ).rstrip()229+230+ def render_progress(self):231+ from .termui import get_terminal_size232+233+ if self.is_hidden:234+ return235+236+ buf = []237+ # Update width in case the terminal has been resized238+ if self.autowidth:239+ old_width = self.width240+ self.width = 0241+ clutter_length = term_len(self.format_progress_line())242+ new_width = max(0, get_terminal_size()[0] - clutter_length)243+ if new_width < old_width:244+ buf.append(BEFORE_BAR)245+ buf.append(" " * self.max_width)246+ self.max_width = new_width247+ self.width = new_width248+249+ clear_width = self.width250+ if self.max_width is not None:251+ clear_width = self.max_width252+253+ buf.append(BEFORE_BAR)254+ line = self.format_progress_line()255+ line_len = term_len(line)256+ if self.max_width is None or self.max_width < line_len:257+ self.max_width = line_len258+259+ buf.append(line)260+ buf.append(" " * (clear_width - line_len))261+ line = "".join(buf)262+ # Render the line only if it changed.263+264+ if line != self._last_line and not self.is_fast():265+ self._last_line = line266+ echo(line, file=self.file, color=self.color, nl=False)267+ self.file.flush()268+269+ def make_step(self, n_steps):270+ self.pos += n_steps271+ if self.length_known and self.pos >= self.length:272+ self.finished = True273+274+ if (time.time() - self.last_eta) < 1.0:275+ return276+277+ self.last_eta = time.time()278+279+ # self.avg is a rolling list of length <= 7 of steps where steps are280+ # defined as time elapsed divided by the total progress through281+ # self.length.282+ if self.pos:283+ step = (time.time() - self.start) / self.pos284+ else:285+ step = time.time() - self.start286+287+ self.avg = self.avg[-6:] + [step]288+289+ self.eta_known = self.length_known290+291+ def update(self, n_steps):292+ self.make_step(n_steps)293+ self.render_progress()294+295+ def finish(self):296+ self.eta_known = 0297+ self.current_item = None298+ self.finished = True299+300+ def generator(self):301+ """Return a generator which yields the items added to the bar302+ during construction, and updates the progress bar *after* the303+ yielded block returns.304+ """305+ # WARNING: the iterator interface for `ProgressBar` relies on306+ # this and only works because this is a simple generator which307+ # doesn't create or manage additional state. If this function308+ # changes, the impact should be evaluated both against309+ # `iter(bar)` and `next(bar)`. `next()` in particular may call310+ # `self.generator()` repeatedly, and this must remain safe in311+ # order for that interface to work.312+ if not self.entered:313+ raise RuntimeError("You need to use progress bars in a with block.")314+315+ if self.is_hidden:316+ for rv in self.iter:317+ yield rv318+ else:319+ for rv in self.iter:320+ self.current_item = rv321+ yield rv322+ self.update(1)323+ self.finish()324+ self.render_progress()325+326+327+def pager(generator, color=None):328+ """Decide what method to use for paging through text."""329+ stdout = _default_text_stdout()330+ if not isatty(sys.stdin) or not isatty(stdout):331+ return _nullpager(stdout, generator, color)332+ pager_cmd = (os.environ.get("PAGER", None) or "").strip()333+ if pager_cmd:334+ if WIN:335+ return _tempfilepager(generator, pager_cmd, color)336+ return _pipepager(generator, pager_cmd, color)337+ if os.environ.get("TERM") in ("dumb", "emacs"):338+ return _nullpager(stdout, generator, color)339+ if WIN or sys.platform.startswith("os2"):340+ return _tempfilepager(generator, "more <", color)341+ if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:342+ return _pipepager(generator, "less", color)343+344+ import tempfile345+346+ fd, filename = tempfile.mkstemp()347+ os.close(fd)348+ try:349+ if (350+ hasattr(os, "system")351+ and os.system("more {}".format(shlex_quote(filename))) == 0352+ ):353+ return _pipepager(generator, "more", color)354+ return _nullpager(stdout, generator, color)355+ finally:356+ os.unlink(filename)357+358+359+def _pipepager(generator, cmd, color):360+ """Page through text by feeding it to another program. Invoking a361+ pager through this might support colors.362+ """363+ import subprocess364+365+ env = dict(os.environ)366+367+ # If we're piping to less we might support colors under the368+ # condition that369+ cmd_detail = cmd.rsplit("/", 1)[-1].split()370+ if color is None and cmd_detail[0] == "less":371+ less_flags = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:]))372+ if not less_flags:373+ env["LESS"] = "-R"374+ color = True375+ elif "r" in less_flags or "R" in less_flags:376+ color = True377+378+ c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)379+ encoding = get_best_encoding(c.stdin)380+ try:381+ for text in generator:382+ if not color:383+ text = strip_ansi(text)384+385+ c.stdin.write(text.encode(encoding, "replace"))386+ except (IOError, KeyboardInterrupt):387+ pass388+ else:389+ c.stdin.close()390+391+ # Less doesn't respect ^C, but catches it for its own UI purposes (aborting392+ # search or other commands inside less).393+ #394+ # That means when the user hits ^C, the parent process (click) terminates,395+ # but less is still alive, paging the output and messing up the terminal.396+ #397+ # If the user wants to make the pager exit on ^C, they should set398+ # `LESS='-K'`. It's not our decision to make.399+ while True:400+ try:401+ c.wait()402+ except KeyboardInterrupt:403+ pass404+ else:405+ break406+407+408+def _tempfilepager(generator, cmd, color):409+ """Page through text by invoking a program on a temporary file."""410+ import tempfile411+412+ filename = tempfile.mktemp()413+ # TODO: This never terminates if the passed generator never terminates.414+ text = "".join(generator)415+ if not color:416+ text = strip_ansi(text)417+ encoding = get_best_encoding(sys.stdout)418+ with open_stream(filename, "wb")[0] as f:419+ f.write(text.encode(encoding))420+ try:421+ os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename)))422+ finally:423+ os.unlink(filename)424+425+426+def _nullpager(stream, generator, color):427+ """Simply print unformatted text. This is the ultimate fallback."""428+ for text in generator:429+ if not color:430+ text = strip_ansi(text)431+ stream.write(text)432+433+434+class Editor(object):435+ def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):436+ self.editor = editor437+ self.env = env438+ self.require_save = require_save439+ self.extension = extension440+441+ def get_editor(self):442+ if self.editor is not None:443+ return self.editor444+ for key in "VISUAL", "EDITOR":445+ rv = os.environ.get(key)446+ if rv:447+ return rv448+ if WIN:449+ return "notepad"450+ for editor in "sensible-editor", "vim", "nano":451+ if os.system("which {} >/dev/null 2>&1".format(editor)) == 0:452+ return editor453+ return "vi"454+455+ def edit_file(self, filename):456+ import subprocess457+458+ editor = self.get_editor()459+ if self.env:460+ environ = os.environ.copy()461+ environ.update(self.env)462+ else:463+ environ = None464+ try:465+ c = subprocess.Popen(466+ "{} {}".format(shlex_quote(editor), shlex_quote(filename)),467+ env=environ,468+ shell=True,469+ )470+ exit_code = c.wait()471+ if exit_code != 0:472+ raise ClickException("{}: Editing failed!".format(editor))473+ except OSError as e:474+ raise ClickException("{}: Editing failed: {}".format(editor, e))475+476+ def edit(self, text):477+ import tempfile478+479+ text = text or ""480+ if text and not text.endswith("\n"):481+ text += "\n"482+483+ fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)484+ try:485+ if WIN:486+ encoding = "utf-8-sig"487+ text = text.replace("\n", "\r\n")488+ else:489+ encoding = "utf-8"490+ text = text.encode(encoding)491+492+ f = os.fdopen(fd, "wb")493+ f.write(text)494+ f.close()495+ timestamp = os.path.getmtime(name)496+497+ self.edit_file(name)498+499+ if self.require_save and os.path.getmtime(name) == timestamp:500+ return None501+502+ f = open(name, "rb")503+ try:504+ rv = f.read()505+ finally:506+ f.close()507+ return rv.decode("utf-8-sig").replace("\r\n", "\n")508+ finally:509+ os.unlink(name)510+511+512+def open_url(url, wait=False, locate=False):513+ import subprocess514+515+ def _unquote_file(url):516+ try:517+ import urllib518+ except ImportError:519+ import urllib520+ if url.startswith("file://"):521+ url = urllib.unquote(url[7:])522+ return url523+524+ if sys.platform == "darwin":525+ args = ["open"]526+ if wait:527+ args.append("-W")528+ if locate:529+ args.append("-R")530+ args.append(_unquote_file(url))531+ null = open("/dev/null", "w")532+ try:533+ return subprocess.Popen(args, stderr=null).wait()534+ finally:535+ null.close()536+ elif WIN:537+ if locate:538+ url = _unquote_file(url)539+ args = "explorer /select,{}".format(shlex_quote(url))540+ else:541+ args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url))542+ return os.system(args)543+ elif CYGWIN:544+ if locate:545+ url = _unquote_file(url)546+ args = "cygstart {}".format(shlex_quote(os.path.dirname(url)))547+ else:548+ args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url))549+ return os.system(args)550+551+ try:552+ if locate:553+ url = os.path.dirname(_unquote_file(url)) or "."554+ else:555+ url = _unquote_file(url)556+ c = subprocess.Popen(["xdg-open", url])557+ if wait:558+ return c.wait()559+ return 0560+ except OSError:561+ if url.startswith(("http://", "https://")) and not locate and not wait:562+ import webbrowser563+564+ webbrowser.open(url)565+ return 0566+ return 1567+568+569+def _translate_ch_to_exc(ch):570+ if ch == u"\x03":571+ raise KeyboardInterrupt()572+ if ch == u"\x04" and not WIN: # Unix-like, Ctrl+D573+ raise EOFError()574+ if ch == u"\x1a" and WIN: # Windows, Ctrl+Z575+ raise EOFError()576+577+578+if WIN:579+ import msvcrt580+581+ @contextlib.contextmanager582+ def raw_terminal():583+ yield584+585+ def getchar(echo):586+ # The function `getch` will return a bytes object corresponding to587+ # the pressed character. Since Windows 10 build 1803, it will also588+ # return \x00 when called a second time after pressing a regular key.589+ #590+ # `getwch` does not share this probably-bugged behavior. Moreover, it591+ # returns a Unicode object by default, which is what we want.592+ #593+ # Either of these functions will return \x00 or \xe0 to indicate594+ # a special key, and you need to call the same function again to get595+ # the "rest" of the code. The fun part is that \u00e0 is596+ # "latin small letter a with grave", so if you type that on a French597+ # keyboard, you _also_ get a \xe0.598+ # E.g., consider the Up arrow. This returns \xe0 and then \x48. The599+ # resulting Unicode string reads as "a with grave" + "capital H".600+ # This is indistinguishable from when the user actually types601+ # "a with grave" and then "capital H".602+ #603+ # When \xe0 is returned, we assume it's part of a special-key sequence604+ # and call `getwch` again, but that means that when the user types605+ # the \u00e0 character, `getchar` doesn't return until a second606+ # character is typed.607+ # The alternative is returning immediately, but that would mess up608+ # cross-platform handling of arrow keys and others that start with609+ # \xe0. Another option is using `getch`, but then we can't reliably610+ # read non-ASCII characters, because return values of `getch` are611+ # limited to the current 8-bit codepage.612+ #613+ # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`614+ # is doing the right thing in more situations than with `getch`.615+ if echo:616+ func = msvcrt.getwche617+ else:618+ func = msvcrt.getwch619+620+ rv = func()621+ if rv in (u"\x00", u"\xe0"):622+ # \x00 and \xe0 are control characters that indicate special key,623+ # see above.624+ rv += func()625+ _translate_ch_to_exc(rv)626+ return rv627+628+629+else:630+ import tty631+ import termios632+633+ @contextlib.contextmanager634+ def raw_terminal():635+ if not isatty(sys.stdin):636+ f = open("/dev/tty")637+ fd = f.fileno()638+ else:639+ fd = sys.stdin.fileno()640+ f = None641+ try:642+ old_settings = termios.tcgetattr(fd)643+ try:644+ tty.setraw(fd)645+ yield fd646+ finally:647+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)648+ sys.stdout.flush()649+ if f is not None:650+ f.close()651+ except termios.error:652+ pass653+654+ def getchar(echo):655+ with raw_terminal() as fd:656+ ch = os.read(fd, 32)657+ ch = ch.decode(get_best_encoding(sys.stdin), "replace")658+ if echo and isatty(sys.stdout):659+ sys.stdout.write(ch)660+ _translate_ch_to_exc(ch)661+ return chadded:src/click/_textwrap.py+37 added
1+import textwrap2+from contextlib import contextmanager3+4+5+class TextWrapper(textwrap.TextWrapper):6+ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):7+ space_left = max(width - cur_len, 1)8+9+ if self.break_long_words:10+ last = reversed_chunks[-1]11+ cut = last[:space_left]12+ res = last[space_left:]13+ cur_line.append(cut)14+ reversed_chunks[-1] = res15+ elif not cur_line:16+ cur_line.append(reversed_chunks.pop())17+18+ @contextmanager19+ def extra_indent(self, indent):20+ old_initial_indent = self.initial_indent21+ old_subsequent_indent = self.subsequent_indent22+ self.initial_indent += indent23+ self.subsequent_indent += indent24+ try:25+ yield26+ finally:27+ self.initial_indent = old_initial_indent28+ self.subsequent_indent = old_subsequent_indent29+30+ def indent_only(self, text):31+ rv = []32+ for idx, line in enumerate(text.splitlines()):33+ indent = self.initial_indent34+ if idx > 0:35+ indent = self.subsequent_indent36+ rv.append(indent + line)37+ return "\n".join(rv)added:src/click/_unicodefun.py+131 added
1+import codecs2+import os3+import sys4+5+from ._compat import PY26+7+8+def _find_unicode_literals_frame():9+ import __future__10+11+ if not hasattr(sys, "_getframe"): # not all Python implementations have it12+ return 013+ frm = sys._getframe(1)14+ idx = 115+ while frm is not None:16+ if frm.f_globals.get("__name__", "").startswith("click."):17+ frm = frm.f_back18+ idx += 119+ elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:20+ return idx21+ else:22+ break23+ return 024+25+26+def _check_for_unicode_literals():27+ if not __debug__:28+ return29+30+ from . import disable_unicode_literals_warning31+32+ if not PY2 or disable_unicode_literals_warning:33+ return34+ bad_frame = _find_unicode_literals_frame()35+ if bad_frame <= 0:36+ return37+ from warnings import warn38+39+ warn(40+ Warning(41+ "Click detected the use of the unicode_literals __future__"42+ " import. This is heavily discouraged because it can"43+ " introduce subtle bugs in your code. You should instead"44+ ' use explicit u"" literals for your unicode strings. For'45+ " more information see"46+ " https://click.palletsprojects.com/python3/"47+ ),48+ stacklevel=bad_frame,49+ )50+51+52+def _verify_python3_env():53+ """Ensures that the environment is good for unicode on Python 3."""54+ if PY2:55+ return56+ try:57+ import locale58+59+ fs_enc = codecs.lookup(locale.getpreferredencoding()).name60+ except Exception:61+ fs_enc = "ascii"62+ if fs_enc != "ascii":63+ return64+65+ extra = ""66+ if os.name == "posix":67+ import subprocess68+69+ try:70+ rv = subprocess.Popen(71+ ["locale", "-a"], stdout=subprocess.PIPE, stderr=subprocess.PIPE72+ ).communicate()[0]73+ except OSError:74+ rv = b""75+ good_locales = set()76+ has_c_utf8 = False77+78+ # Make sure we're operating on text here.79+ if isinstance(rv, bytes):80+ rv = rv.decode("ascii", "replace")81+82+ for line in rv.splitlines():83+ locale = line.strip()84+ if locale.lower().endswith((".utf-8", ".utf8")):85+ good_locales.add(locale)86+ if locale.lower() in ("c.utf8", "c.utf-8"):87+ has_c_utf8 = True88+89+ extra += "\n\n"90+ if not good_locales:91+ extra += (92+ "Additional information: on this system no suitable"93+ " UTF-8 locales were discovered. This most likely"94+ " requires resolving by reconfiguring the locale"95+ " system."96+ )97+ elif has_c_utf8:98+ extra += (99+ "This system supports the C.UTF-8 locale which is"100+ " recommended. You might be able to resolve your issue"101+ " by exporting the following environment variables:\n\n"102+ " export LC_ALL=C.UTF-8\n"103+ " export LANG=C.UTF-8"104+ )105+ else:106+ extra += (107+ "This system lists a couple of UTF-8 supporting locales"108+ " that you can pick from. The following suitable"109+ " locales were discovered: {}".format(", ".join(sorted(good_locales)))110+ )111+112+ bad_locale = None113+ for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):114+ if locale and locale.lower().endswith((".utf-8", ".utf8")):115+ bad_locale = locale116+ if locale is not None:117+ break118+ if bad_locale is not None:119+ extra += (120+ "\n\nClick discovered that you exported a UTF-8 locale"121+ " but the locale system could not pick up from it"122+ " because it does not exist. The exported locale is"123+ " '{}' but it is not supported".format(bad_locale)124+ )125+126+ raise RuntimeError(127+ "Click will abort further execution because Python 3 was"128+ " configured to use ASCII as encoding for the environment."129+ " Consult https://click.palletsprojects.com/python3/ for"130+ " mitigation steps.{}".format(extra)131+ )added:src/click/_winconsole.py+370 added
1+# -*- coding: utf-8 -*-2+# This module is based on the excellent work by Adam Bartoš who3+# provided a lot of what went into the implementation here in4+# the discussion to issue1602 in the Python bug tracker.5+#6+# There are some general differences in regards to how this works7+# compared to the original patches as we do not need to patch8+# the entire interpreter but just work in our little world of9+# echo and prmopt.10+import ctypes11+import io12+import os13+import sys14+import time15+import zlib16+from ctypes import byref17+from ctypes import c_char18+from ctypes import c_char_p19+from ctypes import c_int20+from ctypes import c_ssize_t21+from ctypes import c_ulong22+from ctypes import c_void_p23+from ctypes import POINTER24+from ctypes import py_object25+from ctypes import windll26+from ctypes import WinError27+from ctypes import WINFUNCTYPE28+from ctypes.wintypes import DWORD29+from ctypes.wintypes import HANDLE30+from ctypes.wintypes import LPCWSTR31+from ctypes.wintypes import LPWSTR32+33+import msvcrt34+35+from ._compat import _NonClosingTextIOWrapper36+from ._compat import PY237+from ._compat import text_type38+39+try:40+ from ctypes import pythonapi41+42+ PyObject_GetBuffer = pythonapi.PyObject_GetBuffer43+ PyBuffer_Release = pythonapi.PyBuffer_Release44+except ImportError:45+ pythonapi = None46+47+48+c_ssize_p = POINTER(c_ssize_t)49+50+kernel32 = windll.kernel3251+GetStdHandle = kernel32.GetStdHandle52+ReadConsoleW = kernel32.ReadConsoleW53+WriteConsoleW = kernel32.WriteConsoleW54+GetConsoleMode = kernel32.GetConsoleMode55+GetLastError = kernel32.GetLastError56+GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))57+CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(58+ ("CommandLineToArgvW", windll.shell32)59+)60+LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(61+ ("LocalFree", windll.kernel32)62+)63+64+65+STDIN_HANDLE = GetStdHandle(-10)66+STDOUT_HANDLE = GetStdHandle(-11)67+STDERR_HANDLE = GetStdHandle(-12)68+69+70+PyBUF_SIMPLE = 071+PyBUF_WRITABLE = 172+73+ERROR_SUCCESS = 074+ERROR_NOT_ENOUGH_MEMORY = 875+ERROR_OPERATION_ABORTED = 99576+77+STDIN_FILENO = 078+STDOUT_FILENO = 179+STDERR_FILENO = 280+81+EOF = b"\x1a"82+MAX_BYTES_WRITTEN = 3276783+84+85+class Py_buffer(ctypes.Structure):86+ _fields_ = [87+ ("buf", c_void_p),88+ ("obj", py_object),89+ ("len", c_ssize_t),90+ ("itemsize", c_ssize_t),91+ ("readonly", c_int),92+ ("ndim", c_int),93+ ("format", c_char_p),94+ ("shape", c_ssize_p),95+ ("strides", c_ssize_p),96+ ("suboffsets", c_ssize_p),97+ ("internal", c_void_p),98+ ]99+100+ if PY2:101+ _fields_.insert(-1, ("smalltable", c_ssize_t * 2))102+103+104+# On PyPy we cannot get buffers so our ability to operate here is105+# serverly limited.106+if pythonapi is None:107+ get_buffer = None108+else:109+110+ def get_buffer(obj, writable=False):111+ buf = Py_buffer()112+ flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE113+ PyObject_GetBuffer(py_object(obj), byref(buf), flags)114+ try:115+ buffer_type = c_char * buf.len116+ return buffer_type.from_address(buf.buf)117+ finally:118+ PyBuffer_Release(byref(buf))119+120+121+class _WindowsConsoleRawIOBase(io.RawIOBase):122+ def __init__(self, handle):123+ self.handle = handle124+125+ def isatty(self):126+ io.RawIOBase.isatty(self)127+ return True128+129+130+class _WindowsConsoleReader(_WindowsConsoleRawIOBase):131+ def readable(self):132+ return True133+134+ def readinto(self, b):135+ bytes_to_be_read = len(b)136+ if not bytes_to_be_read:137+ return 0138+ elif bytes_to_be_read % 2:139+ raise ValueError(140+ "cannot read odd number of bytes from UTF-16-LE encoded console"141+ )142+143+ buffer = get_buffer(b, writable=True)144+ code_units_to_be_read = bytes_to_be_read // 2145+ code_units_read = c_ulong()146+147+ rv = ReadConsoleW(148+ HANDLE(self.handle),149+ buffer,150+ code_units_to_be_read,151+ byref(code_units_read),152+ None,153+ )154+ if GetLastError() == ERROR_OPERATION_ABORTED:155+ # wait for KeyboardInterrupt156+ time.sleep(0.1)157+ if not rv:158+ raise OSError("Windows error: {}".format(GetLastError()))159+160+ if buffer[0] == EOF:161+ return 0162+ return 2 * code_units_read.value163+164+165+class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):166+ def writable(self):167+ return True168+169+ @staticmethod170+ def _get_error_message(errno):171+ if errno == ERROR_SUCCESS:172+ return "ERROR_SUCCESS"173+ elif errno == ERROR_NOT_ENOUGH_MEMORY:174+ return "ERROR_NOT_ENOUGH_MEMORY"175+ return "Windows error {}".format(errno)176+177+ def write(self, b):178+ bytes_to_be_written = len(b)179+ buf = get_buffer(b)180+ code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2181+ code_units_written = c_ulong()182+183+ WriteConsoleW(184+ HANDLE(self.handle),185+ buf,186+ code_units_to_be_written,187+ byref(code_units_written),188+ None,189+ )190+ bytes_written = 2 * code_units_written.value191+192+ if bytes_written == 0 and bytes_to_be_written > 0:193+ raise OSError(self._get_error_message(GetLastError()))194+ return bytes_written195+196+197+class ConsoleStream(object):198+ def __init__(self, text_stream, byte_stream):199+ self._text_stream = text_stream200+ self.buffer = byte_stream201+202+ @property203+ def name(self):204+ return self.buffer.name205+206+ def write(self, x):207+ if isinstance(x, text_type):208+ return self._text_stream.write(x)209+ try:210+ self.flush()211+ except Exception:212+ pass213+ return self.buffer.write(x)214+215+ def writelines(self, lines):216+ for line in lines:217+ self.write(line)218+219+ def __getattr__(self, name):220+ return getattr(self._text_stream, name)221+222+ def isatty(self):223+ return self.buffer.isatty()224+225+ def __repr__(self):226+ return "<ConsoleStream name={!r} encoding={!r}>".format(227+ self.name, self.encoding228+ )229+230+231+class WindowsChunkedWriter(object):232+ """233+ Wraps a stream (such as stdout), acting as a transparent proxy for all234+ attribute access apart from method 'write()' which we wrap to write in235+ limited chunks due to a Windows limitation on binary console streams.236+ """237+238+ def __init__(self, wrapped):239+ # double-underscore everything to prevent clashes with names of240+ # attributes on the wrapped stream object.241+ self.__wrapped = wrapped242+243+ def __getattr__(self, name):244+ return getattr(self.__wrapped, name)245+246+ def write(self, text):247+ total_to_write = len(text)248+ written = 0249+250+ while written < total_to_write:251+ to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)252+ self.__wrapped.write(text[written : written + to_write])253+ written += to_write254+255+256+_wrapped_std_streams = set()257+258+259+def _wrap_std_stream(name):260+ # Python 2 & Windows 7 and below261+ if (262+ PY2263+ and sys.getwindowsversion()[:2] <= (6, 1)264+ and name not in _wrapped_std_streams265+ ):266+ setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))267+ _wrapped_std_streams.add(name)268+269+270+def _get_text_stdin(buffer_stream):271+ text_stream = _NonClosingTextIOWrapper(272+ io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),273+ "utf-16-le",274+ "strict",275+ line_buffering=True,276+ )277+ return ConsoleStream(text_stream, buffer_stream)278+279+280+def _get_text_stdout(buffer_stream):281+ text_stream = _NonClosingTextIOWrapper(282+ io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),283+ "utf-16-le",284+ "strict",285+ line_buffering=True,286+ )287+ return ConsoleStream(text_stream, buffer_stream)288+289+290+def _get_text_stderr(buffer_stream):291+ text_stream = _NonClosingTextIOWrapper(292+ io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),293+ "utf-16-le",294+ "strict",295+ line_buffering=True,296+ )297+ return ConsoleStream(text_stream, buffer_stream)298+299+300+if PY2:301+302+ def _hash_py_argv():303+ return zlib.crc32("\x00".join(sys.argv[1:]))304+305+ _initial_argv_hash = _hash_py_argv()306+307+ def _get_windows_argv():308+ argc = c_int(0)309+ argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))310+ if not argv_unicode:311+ raise WinError()312+ try:313+ argv = [argv_unicode[i] for i in range(0, argc.value)]314+ finally:315+ LocalFree(argv_unicode)316+ del argv_unicode317+318+ if not hasattr(sys, "frozen"):319+ argv = argv[1:]320+ while len(argv) > 0:321+ arg = argv[0]322+ if not arg.startswith("-") or arg == "-":323+ break324+ argv = argv[1:]325+ if arg.startswith(("-c", "-m")):326+ break327+328+ return argv[1:]329+330+331+_stream_factories = {332+ 0: _get_text_stdin,333+ 1: _get_text_stdout,334+ 2: _get_text_stderr,335+}336+337+338+def _is_console(f):339+ if not hasattr(f, "fileno"):340+ return False341+342+ try:343+ fileno = f.fileno()344+ except OSError:345+ return False346+347+ handle = msvcrt.get_osfhandle(fileno)348+ return bool(GetConsoleMode(handle, byref(DWORD())))349+350+351+def _get_windows_console_stream(f, encoding, errors):352+ if (353+ get_buffer is not None354+ and encoding in ("utf-16-le", None)355+ and errors in ("strict", None)356+ and _is_console(f)357+ ):358+ func = _stream_factories.get(f.fileno())359+ if func is not None:360+ if not PY2:361+ f = getattr(f, "buffer", None)362+ if f is None:363+ return None364+ else:365+ # If we are on Python 2 we need to set the stream that we366+ # deal with to binary mode as otherwise the exercise if a367+ # bit moot. The same problems apply as for368+ # get_binary_stdin and friends from _compat.369+ msvcrt.setmode(f.fileno(), os.O_BINARY)370+ return func(f)added:src/click/core.py+2033 added
1+import errno2+import inspect3+import os4+import sys5+from contextlib import contextmanager6+from functools import update_wrapper7+from itertools import repeat8+9+from ._compat import isidentifier10+from ._compat import iteritems11+from ._compat import PY212+from ._compat import string_types13+from ._unicodefun import _check_for_unicode_literals14+from ._unicodefun import _verify_python3_env15+from .exceptions import Abort16+from .exceptions import BadParameter17+from .exceptions import ClickException18+from .exceptions import Exit19+from .exceptions import MissingParameter20+from .exceptions import UsageError21+from .formatting import HelpFormatter22+from .formatting import join_options23+from .globals import pop_context24+from .globals import push_context25+from .parser import OptionParser26+from .parser import split_opt27+from .termui import confirm28+from .termui import prompt29+from .termui import style30+from .types import BOOL31+from .types import convert_type32+from .types import IntRange33+from .utils import echo34+from .utils import get_os_args35+from .utils import make_default_short_help36+from .utils import make_str37+from .utils import PacifyFlushWrapper38+39+_missing = object()40+41+SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."42+SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."43+44+DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45+DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."46+47+48+def _maybe_show_deprecated_notice(cmd):49+ if cmd.deprecated:50+ echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)51+52+53+def fast_exit(code):54+ """Exit without garbage collection, this speeds up exit by about 10ms for55+ things like bash completion.56+ """57+ sys.stdout.flush()58+ sys.stderr.flush()59+ os._exit(code)60+61+62+def _bashcomplete(cmd, prog_name, complete_var=None):63+ """Internal handler for the bash completion support."""64+ if complete_var is None:65+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())66+ complete_instr = os.environ.get(complete_var)67+ if not complete_instr:68+ return69+70+ from ._bashcomplete import bashcomplete71+72+ if bashcomplete(cmd, prog_name, complete_var, complete_instr):73+ fast_exit(1)74+75+76+def _check_multicommand(base_command, cmd_name, cmd, register=False):77+ if not base_command.chain or not isinstance(cmd, MultiCommand):78+ return79+ if register:80+ hint = (81+ "It is not possible to add multi commands as children to"82+ " another multi command that is in chain mode."83+ )84+ else:85+ hint = (86+ "Found a multi command as subcommand to a multi command"87+ " that is in chain mode. This is not supported."88+ )89+ raise RuntimeError(90+ "{}. Command '{}' is set to chain and '{}' was added as"91+ " subcommand but it in itself is a multi command. ('{}' is a {}"92+ " within a chained {} named '{}').".format(93+ hint,94+ base_command.name,95+ cmd_name,96+ cmd_name,97+ cmd.__class__.__name__,98+ base_command.__class__.__name__,99+ base_command.name,100+ )101+ )102+103+104+def batch(iterable, batch_size):105+ return list(zip(*repeat(iter(iterable), batch_size)))106+107+108+def invoke_param_callback(callback, ctx, param, value):109+ code = getattr(callback, "__code__", None)110+ args = getattr(code, "co_argcount", 3)111+112+ if args < 3:113+ # This will become a warning in Click 3.0:114+ from warnings import warn115+116+ warn(117+ Warning(118+ "Invoked legacy parameter callback '{}'. The new"119+ " signature for such callbacks starting with Click 2.0"120+ " is (ctx, param, value).".format(callback)121+ ),122+ stacklevel=3,123+ )124+ return callback(ctx, value)125+ return callback(ctx, param, value)126+127+128+@contextmanager129+def augment_usage_errors(ctx, param=None):130+ """Context manager that attaches extra information to exceptions."""131+ try:132+ yield133+ except BadParameter as e:134+ if e.ctx is None:135+ e.ctx = ctx136+ if param is not None and e.param is None:137+ e.param = param138+ raise139+ except UsageError as e:140+ if e.ctx is None:141+ e.ctx = ctx142+ raise143+144+145+def iter_params_for_processing(invocation_order, declaration_order):146+ """Given a sequence of parameters in the order as should be considered147+ for processing and an iterable of parameters that exist, this returns148+ a list in the correct order as they should be processed.149+ """150+151+ def sort_key(item):152+ try:153+ idx = invocation_order.index(item)154+ except ValueError:155+ idx = float("inf")156+ return (not item.is_eager, idx)157+158+ return sorted(declaration_order, key=sort_key)159+160+161+class Context(object):162+ """The context is a special internal object that holds state relevant163+ for the script execution at every single level. It's normally invisible164+ to commands unless they opt-in to getting access to it.165+166+ The context is useful as it can pass internal objects around and can167+ control special execution features such as reading data from168+ environment variables.169+170+ A context can be used as context manager in which case it will call171+ :meth:`close` on teardown.172+173+ .. versionadded:: 2.0174+ Added the `resilient_parsing`, `help_option_names`,175+ `token_normalize_func` parameters.176+177+ .. versionadded:: 3.0178+ Added the `allow_extra_args` and `allow_interspersed_args`179+ parameters.180+181+ .. versionadded:: 4.0182+ Added the `color`, `ignore_unknown_options`, and183+ `max_content_width` parameters.184+185+ .. versionadded:: 7.1186+ Added the `show_default` parameter.187+188+ :param command: the command class for this context.189+ :param parent: the parent context.190+ :param info_name: the info name for this invocation. Generally this191+ is the most descriptive name for the script or192+ command. For the toplevel script it is usually193+ the name of the script, for commands below it it's194+ the name of the script.195+ :param obj: an arbitrary object of user data.196+ :param auto_envvar_prefix: the prefix to use for automatic environment197+ variables. If this is `None` then reading198+ from environment variables is disabled. This199+ does not affect manually set environment200+ variables which are always read.201+ :param default_map: a dictionary (like object) with default values202+ for parameters.203+ :param terminal_width: the width of the terminal. The default is204+ inherit from parent context. If no context205+ defines the terminal width then auto206+ detection will be applied.207+ :param max_content_width: the maximum width for content rendered by208+ Click (this currently only affects help209+ pages). This defaults to 80 characters if210+ not overridden. In other words: even if the211+ terminal is larger than that, Click will not212+ format things wider than 80 characters by213+ default. In addition to that, formatters might214+ add some safety mapping on the right.215+ :param resilient_parsing: if this flag is enabled then Click will216+ parse without any interactivity or callback217+ invocation. Default values will also be218+ ignored. This is useful for implementing219+ things such as completion support.220+ :param allow_extra_args: if this is set to `True` then extra arguments221+ at the end will not raise an error and will be222+ kept on the context. The default is to inherit223+ from the command.224+ :param allow_interspersed_args: if this is set to `False` then options225+ and arguments cannot be mixed. The226+ default is to inherit from the command.227+ :param ignore_unknown_options: instructs click to ignore options it does228+ not know and keeps them for later229+ processing.230+ :param help_option_names: optionally a list of strings that define how231+ the default help parameter is named. The232+ default is ``['--help']``.233+ :param token_normalize_func: an optional function that is used to234+ normalize tokens (options, choices,235+ etc.). This for instance can be used to236+ implement case insensitive behavior.237+ :param color: controls if the terminal supports ANSI colors or not. The238+ default is autodetection. This is only needed if ANSI239+ codes are used in texts that Click prints which is by240+ default not the case. This for instance would affect241+ help output.242+ :param show_default: if True, shows defaults for all options.243+ Even if an option is later created with show_default=False,244+ this command-level setting overrides it.245+ """246+247+ def __init__(248+ self,249+ command,250+ parent=None,251+ info_name=None,252+ obj=None,253+ auto_envvar_prefix=None,254+ default_map=None,255+ terminal_width=None,256+ max_content_width=None,257+ resilient_parsing=False,258+ allow_extra_args=None,259+ allow_interspersed_args=None,260+ ignore_unknown_options=None,261+ help_option_names=None,262+ token_normalize_func=None,263+ color=None,264+ show_default=None,265+ ):266+ #: the parent context or `None` if none exists.267+ self.parent = parent268+ #: the :class:`Command` for this context.269+ self.command = command270+ #: the descriptive information name271+ self.info_name = info_name272+ #: the parsed parameters except if the value is hidden in which273+ #: case it's not remembered.274+ self.params = {}275+ #: the leftover arguments.276+ self.args = []277+ #: protected arguments. These are arguments that are prepended278+ #: to `args` when certain parsing scenarios are encountered but279+ #: must be never propagated to another arguments. This is used280+ #: to implement nested parsing.281+ self.protected_args = []282+ if obj is None and parent is not None:283+ obj = parent.obj284+ #: the user object stored.285+ self.obj = obj286+ self._meta = getattr(parent, "meta", {})287+288+ #: A dictionary (-like object) with defaults for parameters.289+ if (290+ default_map is None291+ and parent is not None292+ and parent.default_map is not None293+ ):294+ default_map = parent.default_map.get(info_name)295+ self.default_map = default_map296+297+ #: This flag indicates if a subcommand is going to be executed. A298+ #: group callback can use this information to figure out if it's299+ #: being executed directly or because the execution flow passes300+ #: onwards to a subcommand. By default it's None, but it can be301+ #: the name of the subcommand to execute.302+ #:303+ #: If chaining is enabled this will be set to ``'*'`` in case304+ #: any commands are executed. It is however not possible to305+ #: figure out which ones. If you require this knowledge you306+ #: should use a :func:`resultcallback`.307+ self.invoked_subcommand = None308+309+ if terminal_width is None and parent is not None:310+ terminal_width = parent.terminal_width311+ #: The width of the terminal (None is autodetection).312+ self.terminal_width = terminal_width313+314+ if max_content_width is None and parent is not None:315+ max_content_width = parent.max_content_width316+ #: The maximum width of formatted content (None implies a sensible317+ #: default which is 80 for most things).318+ self.max_content_width = max_content_width319+320+ if allow_extra_args is None:321+ allow_extra_args = command.allow_extra_args322+ #: Indicates if the context allows extra args or if it should323+ #: fail on parsing.324+ #:325+ #: .. versionadded:: 3.0326+ self.allow_extra_args = allow_extra_args327+328+ if allow_interspersed_args is None:329+ allow_interspersed_args = command.allow_interspersed_args330+ #: Indicates if the context allows mixing of arguments and331+ #: options or not.332+ #:333+ #: .. versionadded:: 3.0334+ self.allow_interspersed_args = allow_interspersed_args335+336+ if ignore_unknown_options is None:337+ ignore_unknown_options = command.ignore_unknown_options338+ #: Instructs click to ignore options that a command does not339+ #: understand and will store it on the context for later340+ #: processing. This is primarily useful for situations where you341+ #: want to call into external programs. Generally this pattern is342+ #: strongly discouraged because it's not possibly to losslessly343+ #: forward all arguments.344+ #:345+ #: .. versionadded:: 4.0346+ self.ignore_unknown_options = ignore_unknown_options347+348+ if help_option_names is None:349+ if parent is not None:350+ help_option_names = parent.help_option_names351+ else:352+ help_option_names = ["--help"]353+354+ #: The names for the help options.355+ self.help_option_names = help_option_names356+357+ if token_normalize_func is None and parent is not None:358+ token_normalize_func = parent.token_normalize_func359+360+ #: An optional normalization function for tokens. This is361+ #: options, choices, commands etc.362+ self.token_normalize_func = token_normalize_func363+364+ #: Indicates if resilient parsing is enabled. In that case Click365+ #: will do its best to not cause any failures and default values366+ #: will be ignored. Useful for completion.367+ self.resilient_parsing = resilient_parsing368+369+ # If there is no envvar prefix yet, but the parent has one and370+ # the command on this level has a name, we can expand the envvar371+ # prefix automatically.372+ if auto_envvar_prefix is None:373+ if (374+ parent is not None375+ and parent.auto_envvar_prefix is not None376+ and self.info_name is not None377+ ):378+ auto_envvar_prefix = "{}_{}".format(379+ parent.auto_envvar_prefix, self.info_name.upper()380+ )381+ else:382+ auto_envvar_prefix = auto_envvar_prefix.upper()383+ if auto_envvar_prefix is not None:384+ auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")385+ self.auto_envvar_prefix = auto_envvar_prefix386+387+ if color is None and parent is not None:388+ color = parent.color389+390+ #: Controls if styling output is wanted or not.391+ self.color = color392+393+ self.show_default = show_default394+395+ self._close_callbacks = []396+ self._depth = 0397+398+ def __enter__(self):399+ self._depth += 1400+ push_context(self)401+ return self402+403+ def __exit__(self, exc_type, exc_value, tb):404+ self._depth -= 1405+ if self._depth == 0:406+ self.close()407+ pop_context()408+409+ @contextmanager410+ def scope(self, cleanup=True):411+ """This helper method can be used with the context object to promote412+ it to the current thread local (see :func:`get_current_context`).413+ The default behavior of this is to invoke the cleanup functions which414+ can be disabled by setting `cleanup` to `False`. The cleanup415+ functions are typically used for things such as closing file handles.416+417+ If the cleanup is intended the context object can also be directly418+ used as a context manager.419+420+ Example usage::421+422+ with ctx.scope():423+ assert get_current_context() is ctx424+425+ This is equivalent::426+427+ with ctx:428+ assert get_current_context() is ctx429+430+ .. versionadded:: 5.0431+432+ :param cleanup: controls if the cleanup functions should be run or433+ not. The default is to run these functions. In434+ some situations the context only wants to be435+ temporarily pushed in which case this can be disabled.436+ Nested pushes automatically defer the cleanup.437+ """438+ if not cleanup:439+ self._depth += 1440+ try:441+ with self as rv:442+ yield rv443+ finally:444+ if not cleanup:445+ self._depth -= 1446+447+ @property448+ def meta(self):449+ """This is a dictionary which is shared with all the contexts450+ that are nested. It exists so that click utilities can store some451+ state here if they need to. It is however the responsibility of452+ that code to manage this dictionary well.453+454+ The keys are supposed to be unique dotted strings. For instance455+ module paths are a good choice for it. What is stored in there is456+ irrelevant for the operation of click. However what is important is457+ that code that places data here adheres to the general semantics of458+ the system.459+460+ Example usage::461+462+ LANG_KEY = f'{__name__}.lang'463+464+ def set_language(value):465+ ctx = get_current_context()466+ ctx.meta[LANG_KEY] = value467+468+ def get_language():469+ return get_current_context().meta.get(LANG_KEY, 'en_US')470+471+ .. versionadded:: 5.0472+ """473+ return self._meta474+475+ def make_formatter(self):476+ """Creates the formatter for the help and usage output."""477+ return HelpFormatter(478+ width=self.terminal_width, max_width=self.max_content_width479+ )480+481+ def call_on_close(self, f):482+ """This decorator remembers a function as callback that should be483+ executed when the context tears down. This is most useful to bind484+ resource handling to the script execution. For instance, file objects485+ opened by the :class:`File` type will register their close callbacks486+ here.487+488+ :param f: the function to execute on teardown.489+ """490+ self._close_callbacks.append(f)491+ return f492+493+ def close(self):494+ """Invokes all close callbacks."""495+ for cb in self._close_callbacks:496+ cb()497+ self._close_callbacks = []498+499+ @property500+ def command_path(self):501+ """The computed command path. This is used for the ``usage``502+ information on the help page. It's automatically created by503+ combining the info names of the chain of contexts to the root.504+ """505+ rv = ""506+ if self.info_name is not None:507+ rv = self.info_name508+ if self.parent is not None:509+ rv = "{} {}".format(self.parent.command_path, rv)510+ return rv.lstrip()511+512+ def find_root(self):513+ """Finds the outermost context."""514+ node = self515+ while node.parent is not None:516+ node = node.parent517+ return node518+519+ def find_object(self, object_type):520+ """Finds the closest object of a given type."""521+ node = self522+ while node is not None:523+ if isinstance(node.obj, object_type):524+ return node.obj525+ node = node.parent526+527+ def ensure_object(self, object_type):528+ """Like :meth:`find_object` but sets the innermost object to a529+ new instance of `object_type` if it does not exist.530+ """531+ rv = self.find_object(object_type)532+ if rv is None:533+ self.obj = rv = object_type()534+ return rv535+536+ def lookup_default(self, name):537+ """Looks up the default for a parameter name. This by default538+ looks into the :attr:`default_map` if available.539+ """540+ if self.default_map is not None:541+ rv = self.default_map.get(name)542+ if callable(rv):543+ rv = rv()544+ return rv545+546+ def fail(self, message):547+ """Aborts the execution of the program with a specific error548+ message.549+550+ :param message: the error message to fail with.551+ """552+ raise UsageError(message, self)553+554+ def abort(self):555+ """Aborts the script."""556+ raise Abort()557+558+ def exit(self, code=0):559+ """Exits the application with a given exit code."""560+ raise Exit(code)561+562+ def get_usage(self):563+ """Helper method to get formatted usage string for the current564+ context and command.565+ """566+ return self.command.get_usage(self)567+568+ def get_help(self):569+ """Helper method to get formatted help page for the current570+ context and command.571+ """572+ return self.command.get_help(self)573+574+ def invoke(*args, **kwargs): # noqa: B902575+ """Invokes a command callback in exactly the way it expects. There576+ are two ways to invoke this method:577+578+ 1. the first argument can be a callback and all other arguments and579+ keyword arguments are forwarded directly to the function.580+ 2. the first argument is a click command object. In that case all581+ arguments are forwarded as well but proper click parameters582+ (options and click arguments) must be keyword arguments and Click583+ will fill in defaults.584+585+ Note that before Click 3.2 keyword arguments were not properly filled586+ in against the intention of this code and no context was created. For587+ more information about this change and why it was done in a bugfix588+ release see :ref:`upgrade-to-3.2`.589+ """590+ self, callback = args[:2]591+ ctx = self592+593+ # It's also possible to invoke another command which might or594+ # might not have a callback. In that case we also fill595+ # in defaults and make a new context for this command.596+ if isinstance(callback, Command):597+ other_cmd = callback598+ callback = other_cmd.callback599+ ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)600+ if callback is None:601+ raise TypeError(602+ "The given command does not have a callback that can be invoked."603+ )604+605+ for param in other_cmd.params:606+ if param.name not in kwargs and param.expose_value:607+ kwargs[param.name] = param.get_default(ctx)608+609+ args = args[2:]610+ with augment_usage_errors(self):611+ with ctx:612+ return callback(*args, **kwargs)613+614+ def forward(*args, **kwargs): # noqa: B902615+ """Similar to :meth:`invoke` but fills in default keyword616+ arguments from the current context if the other command expects617+ it. This cannot invoke callbacks directly, only other commands.618+ """619+ self, cmd = args[:2]620+621+ # It's also possible to invoke another command which might or622+ # might not have a callback.623+ if not isinstance(cmd, Command):624+ raise TypeError("Callback is not a command.")625+626+ for param in self.params:627+ if param not in kwargs:628+ kwargs[param] = self.params[param]629+630+ return self.invoke(cmd, **kwargs)631+632+633+class BaseCommand(object):634+ """The base command implements the minimal API contract of commands.635+ Most code will never use this as it does not implement a lot of useful636+ functionality but it can act as the direct subclass of alternative637+ parsing methods that do not depend on the Click parser.638+639+ For instance, this can be used to bridge Click and other systems like640+ argparse or docopt.641+642+ Because base commands do not implement a lot of the API that other643+ parts of Click take for granted, they are not supported for all644+ operations. For instance, they cannot be used with the decorators645+ usually and they have no built-in callback system.646+647+ .. versionchanged:: 2.0648+ Added the `context_settings` parameter.649+650+ :param name: the name of the command to use unless a group overrides it.651+ :param context_settings: an optional dictionary with defaults that are652+ passed to the context object.653+ """654+655+ #: the default for the :attr:`Context.allow_extra_args` flag.656+ allow_extra_args = False657+ #: the default for the :attr:`Context.allow_interspersed_args` flag.658+ allow_interspersed_args = True659+ #: the default for the :attr:`Context.ignore_unknown_options` flag.660+ ignore_unknown_options = False661+662+ def __init__(self, name, context_settings=None):663+ #: the name the command thinks it has. Upon registering a command664+ #: on a :class:`Group` the group will default the command name665+ #: with this information. You should instead use the666+ #: :class:`Context`\'s :attr:`~Context.info_name` attribute.667+ self.name = name668+ if context_settings is None:669+ context_settings = {}670+ #: an optional dictionary with defaults passed to the context.671+ self.context_settings = context_settings672+673+ def __repr__(self):674+ return "<{} {}>".format(self.__class__.__name__, self.name)675+676+ def get_usage(self, ctx):677+ raise NotImplementedError("Base commands cannot get usage")678+679+ def get_help(self, ctx):680+ raise NotImplementedError("Base commands cannot get help")681+682+ def make_context(self, info_name, args, parent=None, **extra):683+ """This function when given an info name and arguments will kick684+ off the parsing and create a new :class:`Context`. It does not685+ invoke the actual command callback though.686+687+ :param info_name: the info name for this invokation. Generally this688+ is the most descriptive name for the script or689+ command. For the toplevel script it's usually690+ the name of the script, for commands below it it's691+ the name of the script.692+ :param args: the arguments to parse as list of strings.693+ :param parent: the parent context if available.694+ :param extra: extra keyword arguments forwarded to the context695+ constructor.696+ """697+ for key, value in iteritems(self.context_settings):698+ if key not in extra:699+ extra[key] = value700+ ctx = Context(self, info_name=info_name, parent=parent, **extra)701+ with ctx.scope(cleanup=False):702+ self.parse_args(ctx, args)703+ return ctx704+705+ def parse_args(self, ctx, args):706+ """Given a context and a list of arguments this creates the parser707+ and parses the arguments, then modifies the context as necessary.708+ This is automatically invoked by :meth:`make_context`.709+ """710+ raise NotImplementedError("Base commands do not know how to parse arguments.")711+712+ def invoke(self, ctx):713+ """Given a context, this invokes the command. The default714+ implementation is raising a not implemented error.715+ """716+ raise NotImplementedError("Base commands are not invokable by default")717+718+ def main(719+ self,720+ args=None,721+ prog_name=None,722+ complete_var=None,723+ standalone_mode=True,724+ **extra725+ ):726+ """This is the way to invoke a script with all the bells and727+ whistles as a command line application. This will always terminate728+ the application after a call. If this is not wanted, ``SystemExit``729+ needs to be caught.730+731+ This method is also available by directly calling the instance of732+ a :class:`Command`.733+734+ .. versionadded:: 3.0735+ Added the `standalone_mode` flag to control the standalone mode.736+737+ :param args: the arguments that should be used for parsing. If not738+ provided, ``sys.argv[1:]`` is used.739+ :param prog_name: the program name that should be used. By default740+ the program name is constructed by taking the file741+ name from ``sys.argv[0]``.742+ :param complete_var: the environment variable that controls the743+ bash completion support. The default is744+ ``"_<prog_name>_COMPLETE"`` with prog_name in745+ uppercase.746+ :param standalone_mode: the default behavior is to invoke the script747+ in standalone mode. Click will then748+ handle exceptions and convert them into749+ error messages and the function will never750+ return but shut down the interpreter. If751+ this is set to `False` they will be752+ propagated to the caller and the return753+ value of this function is the return value754+ of :meth:`invoke`.755+ :param extra: extra keyword arguments are forwarded to the context756+ constructor. See :class:`Context` for more information.757+ """758+ # If we are in Python 3, we will verify that the environment is759+ # sane at this point or reject further execution to avoid a760+ # broken script.761+ if not PY2:762+ _verify_python3_env()763+ else:764+ _check_for_unicode_literals()765+766+ if args is None:767+ args = get_os_args()768+ else:769+ args = list(args)770+771+ if prog_name is None:772+ prog_name = make_str(773+ os.path.basename(sys.argv[0] if sys.argv else __file__)774+ )775+776+ # Hook for the Bash completion. This only activates if the Bash777+ # completion is actually enabled, otherwise this is quite a fast778+ # noop.779+ _bashcomplete(self, prog_name, complete_var)780+781+ try:782+ try:783+ with self.make_context(prog_name, args, **extra) as ctx:784+ rv = self.invoke(ctx)785+ if not standalone_mode:786+ return rv787+ # it's not safe to `ctx.exit(rv)` here!788+ # note that `rv` may actually contain data like "1" which789+ # has obvious effects790+ # more subtle case: `rv=[None, None]` can come out of791+ # chained commands which all returned `None` -- so it's not792+ # even always obvious that `rv` indicates success/failure793+ # by its truthiness/falsiness794+ ctx.exit()795+ except (EOFError, KeyboardInterrupt):796+ echo(file=sys.stderr)797+ raise Abort()798+ except ClickException as e:799+ if not standalone_mode:800+ raise801+ e.show()802+ sys.exit(e.exit_code)803+ except IOError as e:804+ if e.errno == errno.EPIPE:805+ sys.stdout = PacifyFlushWrapper(sys.stdout)806+ sys.stderr = PacifyFlushWrapper(sys.stderr)807+ sys.exit(1)808+ else:809+ raise810+ except Exit as e:811+ if standalone_mode:812+ sys.exit(e.exit_code)813+ else:814+ # in non-standalone mode, return the exit code815+ # note that this is only reached if `self.invoke` above raises816+ # an Exit explicitly -- thus bypassing the check there which817+ # would return its result818+ # the results of non-standalone execution may therefore be819+ # somewhat ambiguous: if there are codepaths which lead to820+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to821+ # tell the difference between the two822+ return e.exit_code823+ except Abort:824+ if not standalone_mode:825+ raise826+ echo("Aborted!", file=sys.stderr)827+ sys.exit(1)828+829+ def __call__(self, *args, **kwargs):830+ """Alias for :meth:`main`."""831+ return self.main(*args, **kwargs)832+833+834+class Command(BaseCommand):835+ """Commands are the basic building block of command line interfaces in836+ Click. A basic command handles command line parsing and might dispatch837+ more parsing to commands nested below it.838+839+ .. versionchanged:: 2.0840+ Added the `context_settings` parameter.841+ .. versionchanged:: 7.1842+ Added the `no_args_is_help` parameter.843+844+ :param name: the name of the command to use unless a group overrides it.845+ :param context_settings: an optional dictionary with defaults that are846+ passed to the context object.847+ :param callback: the callback to invoke. This is optional.848+ :param params: the parameters to register with this command. This can849+ be either :class:`Option` or :class:`Argument` objects.850+ :param help: the help string to use for this command.851+ :param epilog: like the help string but it's printed at the end of the852+ help page after everything else.853+ :param short_help: the short help to use for this command. This is854+ shown on the command listing of the parent command.855+ :param add_help_option: by default each command registers a ``--help``856+ option. This can be disabled by this parameter.857+ :param no_args_is_help: this controls what happens if no arguments are858+ provided. This option is disabled by default.859+ If enabled this will add ``--help`` as argument860+ if no arguments are passed861+ :param hidden: hide this command from help outputs.862+863+ :param deprecated: issues a message indicating that864+ the command is deprecated.865+ """866+867+ def __init__(868+ self,869+ name,870+ context_settings=None,871+ callback=None,872+ params=None,873+ help=None,874+ epilog=None,875+ short_help=None,876+ options_metavar="[OPTIONS]",877+ add_help_option=True,878+ no_args_is_help=False,879+ hidden=False,880+ deprecated=False,881+ ):882+ BaseCommand.__init__(self, name, context_settings)883+ #: the callback to execute when the command fires. This might be884+ #: `None` in which case nothing happens.885+ self.callback = callback886+ #: the list of parameters for this command in the order they887+ #: should show up in the help page and execute. Eager parameters888+ #: will automatically be handled before non eager ones.889+ self.params = params or []890+ # if a form feed (page break) is found in the help text, truncate help891+ # text to the content preceding the first form feed892+ if help and "\f" in help:893+ help = help.split("\f", 1)[0]894+ self.help = help895+ self.epilog = epilog896+ self.options_metavar = options_metavar897+ self.short_help = short_help898+ self.add_help_option = add_help_option899+ self.no_args_is_help = no_args_is_help900+ self.hidden = hidden901+ self.deprecated = deprecated902+903+ def get_usage(self, ctx):904+ """Formats the usage line into a string and returns it.905+906+ Calls :meth:`format_usage` internally.907+ """908+ formatter = ctx.make_formatter()909+ self.format_usage(ctx, formatter)910+ return formatter.getvalue().rstrip("\n")911+912+ def get_params(self, ctx):913+ rv = self.params914+ help_option = self.get_help_option(ctx)915+ if help_option is not None:916+ rv = rv + [help_option]917+ return rv918+919+ def format_usage(self, ctx, formatter):920+ """Writes the usage line into the formatter.921+922+ This is a low-level method called by :meth:`get_usage`.923+ """924+ pieces = self.collect_usage_pieces(ctx)925+ formatter.write_usage(ctx.command_path, " ".join(pieces))926+927+ def collect_usage_pieces(self, ctx):928+ """Returns all the pieces that go into the usage line and returns929+ it as a list of strings.930+ """931+ rv = [self.options_metavar]932+ for param in self.get_params(ctx):933+ rv.extend(param.get_usage_pieces(ctx))934+ return rv935+936+ def get_help_option_names(self, ctx):937+ """Returns the names for the help option."""938+ all_names = set(ctx.help_option_names)939+ for param in self.params:940+ all_names.difference_update(param.opts)941+ all_names.difference_update(param.secondary_opts)942+ return all_names943+944+ def get_help_option(self, ctx):945+ """Returns the help option object."""946+ help_options = self.get_help_option_names(ctx)947+ if not help_options or not self.add_help_option:948+ return949+950+ def show_help(ctx, param, value):951+ if value and not ctx.resilient_parsing:952+ echo(ctx.get_help(), color=ctx.color)953+ ctx.exit()954+955+ return Option(956+ help_options,957+ is_flag=True,958+ is_eager=True,959+ expose_value=False,960+ callback=show_help,961+ help="Show this message and exit.",962+ )963+964+ def make_parser(self, ctx):965+ """Creates the underlying option parser for this command."""966+ parser = OptionParser(ctx)967+ for param in self.get_params(ctx):968+ param.add_to_parser(parser, ctx)969+ return parser970+971+ def get_help(self, ctx):972+ """Formats the help into a string and returns it.973+974+ Calls :meth:`format_help` internally.975+ """976+ formatter = ctx.make_formatter()977+ self.format_help(ctx, formatter)978+ return formatter.getvalue().rstrip("\n")979+980+ def get_short_help_str(self, limit=45):981+ """Gets short help for the command or makes it by shortening the982+ long help string.983+ """984+ return (985+ self.short_help986+ or self.help987+ and make_default_short_help(self.help, limit)988+ or ""989+ )990+991+ def format_help(self, ctx, formatter):992+ """Writes the help into the formatter if it exists.993+994+ This is a low-level method called by :meth:`get_help`.995+996+ This calls the following methods:997+998+ - :meth:`format_usage`999+ - :meth:`format_help_text`1000+ - :meth:`format_options`1001+ - :meth:`format_epilog`1002+ """1003+ self.format_usage(ctx, formatter)1004+ self.format_help_text(ctx, formatter)1005+ self.format_options(ctx, formatter)1006+ self.format_epilog(ctx, formatter)1007+1008+ def format_help_text(self, ctx, formatter):1009+ """Writes the help text to the formatter if it exists."""1010+ if self.help:1011+ formatter.write_paragraph()1012+ with formatter.indentation():1013+ help_text = self.help1014+ if self.deprecated:1015+ help_text += DEPRECATED_HELP_NOTICE1016+ formatter.write_text(help_text)1017+ elif self.deprecated:1018+ formatter.write_paragraph()1019+ with formatter.indentation():1020+ formatter.write_text(DEPRECATED_HELP_NOTICE)1021+1022+ def format_options(self, ctx, formatter):1023+ """Writes all the options into the formatter if they exist."""1024+ opts = []1025+ for param in self.get_params(ctx):1026+ rv = param.get_help_record(ctx)1027+ if rv is not None:1028+ opts.append(rv)1029+1030+ if opts:1031+ with formatter.section("Options"):1032+ formatter.write_dl(opts)1033+1034+ def format_epilog(self, ctx, formatter):1035+ """Writes the epilog into the formatter if it exists."""1036+ if self.epilog:1037+ formatter.write_paragraph()1038+ with formatter.indentation():1039+ formatter.write_text(self.epilog)1040+1041+ def parse_args(self, ctx, args):1042+ if not args and self.no_args_is_help and not ctx.resilient_parsing:1043+ echo(ctx.get_help(), color=ctx.color)1044+ ctx.exit()1045+1046+ parser = self.make_parser(ctx)1047+ opts, args, param_order = parser.parse_args(args=args)1048+1049+ for param in iter_params_for_processing(param_order, self.get_params(ctx)):1050+ value, args = param.handle_parse_result(ctx, opts, args)1051+1052+ if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1053+ ctx.fail(1054+ "Got unexpected extra argument{} ({})".format(1055+ "s" if len(args) != 1 else "", " ".join(map(make_str, args))1056+ )1057+ )1058+1059+ ctx.args = args1060+ return args1061+1062+ def invoke(self, ctx):1063+ """Given a context, this invokes the attached callback (if it exists)1064+ in the right way.1065+ """1066+ _maybe_show_deprecated_notice(self)1067+ if self.callback is not None:1068+ return ctx.invoke(self.callback, **ctx.params)1069+1070+1071+class MultiCommand(Command):1072+ """A multi command is the basic implementation of a command that1073+ dispatches to subcommands. The most common version is the1074+ :class:`Group`.1075+1076+ :param invoke_without_command: this controls how the multi command itself1077+ is invoked. By default it's only invoked1078+ if a subcommand is provided.1079+ :param no_args_is_help: this controls what happens if no arguments are1080+ provided. This option is enabled by default if1081+ `invoke_without_command` is disabled or disabled1082+ if it's enabled. If enabled this will add1083+ ``--help`` as argument if no arguments are1084+ passed.1085+ :param subcommand_metavar: the string that is used in the documentation1086+ to indicate the subcommand place.1087+ :param chain: if this is set to `True` chaining of multiple subcommands1088+ is enabled. This restricts the form of commands in that1089+ they cannot have optional arguments but it allows1090+ multiple commands to be chained together.1091+ :param result_callback: the result callback to attach to this multi1092+ command.1093+ """1094+1095+ allow_extra_args = True1096+ allow_interspersed_args = False1097+1098+ def __init__(1099+ self,1100+ name=None,1101+ invoke_without_command=False,1102+ no_args_is_help=None,1103+ subcommand_metavar=None,1104+ chain=False,1105+ result_callback=None,1106+ **attrs1107+ ):1108+ Command.__init__(self, name, **attrs)1109+ if no_args_is_help is None:1110+ no_args_is_help = not invoke_without_command1111+ self.no_args_is_help = no_args_is_help1112+ self.invoke_without_command = invoke_without_command1113+ if subcommand_metavar is None:1114+ if chain:1115+ subcommand_metavar = SUBCOMMANDS_METAVAR1116+ else:1117+ subcommand_metavar = SUBCOMMAND_METAVAR1118+ self.subcommand_metavar = subcommand_metavar1119+ self.chain = chain1120+ #: The result callback that is stored. This can be set or1121+ #: overridden with the :func:`resultcallback` decorator.1122+ self.result_callback = result_callback1123+1124+ if self.chain:1125+ for param in self.params:1126+ if isinstance(param, Argument) and not param.required:1127+ raise RuntimeError(1128+ "Multi commands in chain mode cannot have"1129+ " optional arguments."1130+ )1131+1132+ def collect_usage_pieces(self, ctx):1133+ rv = Command.collect_usage_pieces(self, ctx)1134+ rv.append(self.subcommand_metavar)1135+ return rv1136+1137+ def format_options(self, ctx, formatter):1138+ Command.format_options(self, ctx, formatter)1139+ self.format_commands(ctx, formatter)1140+1141+ def resultcallback(self, replace=False):1142+ """Adds a result callback to the chain command. By default if a1143+ result callback is already registered this will chain them but1144+ this can be disabled with the `replace` parameter. The result1145+ callback is invoked with the return value of the subcommand1146+ (or the list of return values from all subcommands if chaining1147+ is enabled) as well as the parameters as they would be passed1148+ to the main callback.1149+1150+ Example::1151+1152+ @click.group()1153+ @click.option('-i', '--input', default=23)1154+ def cli(input):1155+ return 421156+1157+ @cli.resultcallback()1158+ def process_result(result, input):1159+ return result + input1160+1161+ .. versionadded:: 3.01162+1163+ :param replace: if set to `True` an already existing result1164+ callback will be removed.1165+ """1166+1167+ def decorator(f):1168+ old_callback = self.result_callback1169+ if old_callback is None or replace:1170+ self.result_callback = f1171+ return f1172+1173+ def function(__value, *args, **kwargs):1174+ return f(old_callback(__value, *args, **kwargs), *args, **kwargs)1175+1176+ self.result_callback = rv = update_wrapper(function, f)1177+ return rv1178+1179+ return decorator1180+1181+ def format_commands(self, ctx, formatter):1182+ """Extra format methods for multi methods that adds all the commands1183+ after the options.1184+ """1185+ commands = []1186+ for subcommand in self.list_commands(ctx):1187+ cmd = self.get_command(ctx, subcommand)1188+ # What is this, the tool lied about a command. Ignore it1189+ if cmd is None:1190+ continue1191+ if cmd.hidden:1192+ continue1193+1194+ commands.append((subcommand, cmd))1195+1196+ # allow for 3 times the default spacing1197+ if len(commands):1198+ limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)1199+1200+ rows = []1201+ for subcommand, cmd in commands:1202+ help = cmd.get_short_help_str(limit)1203+ rows.append((subcommand, help))1204+1205+ if rows:1206+ with formatter.section("Commands"):1207+ formatter.write_dl(rows)1208+1209+ def parse_args(self, ctx, args):1210+ if not args and self.no_args_is_help and not ctx.resilient_parsing:1211+ echo(ctx.get_help(), color=ctx.color)1212+ ctx.exit()1213+1214+ rest = Command.parse_args(self, ctx, args)1215+ if self.chain:1216+ ctx.protected_args = rest1217+ ctx.args = []1218+ elif rest:1219+ ctx.protected_args, ctx.args = rest[:1], rest[1:]1220+1221+ return ctx.args1222+1223+ def invoke(self, ctx):1224+ def _process_result(value):1225+ if self.result_callback is not None:1226+ value = ctx.invoke(self.result_callback, value, **ctx.params)1227+ return value1228+1229+ if not ctx.protected_args:1230+ # If we are invoked without command the chain flag controls1231+ # how this happens. If we are not in chain mode, the return1232+ # value here is the return value of the command.1233+ # If however we are in chain mode, the return value is the1234+ # return value of the result processor invoked with an empty1235+ # list (which means that no subcommand actually was executed).1236+ if self.invoke_without_command:1237+ if not self.chain:1238+ return Command.invoke(self, ctx)1239+ with ctx:1240+ Command.invoke(self, ctx)1241+ return _process_result([])1242+ ctx.fail("Missing command.")1243+1244+ # Fetch args back out1245+ args = ctx.protected_args + ctx.args1246+ ctx.args = []1247+ ctx.protected_args = []1248+1249+ # If we're not in chain mode, we only allow the invocation of a1250+ # single command but we also inform the current context about the1251+ # name of the command to invoke.1252+ if not self.chain:1253+ # Make sure the context is entered so we do not clean up1254+ # resources until the result processor has worked.1255+ with ctx:1256+ cmd_name, cmd, args = self.resolve_command(ctx, args)1257+ ctx.invoked_subcommand = cmd_name1258+ Command.invoke(self, ctx)1259+ sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1260+ with sub_ctx:1261+ return _process_result(sub_ctx.command.invoke(sub_ctx))1262+1263+ # In chain mode we create the contexts step by step, but after the1264+ # base command has been invoked. Because at that point we do not1265+ # know the subcommands yet, the invoked subcommand attribute is1266+ # set to ``*`` to inform the command that subcommands are executed1267+ # but nothing else.1268+ with ctx:1269+ ctx.invoked_subcommand = "*" if args else None1270+ Command.invoke(self, ctx)1271+1272+ # Otherwise we make every single context and invoke them in a1273+ # chain. In that case the return value to the result processor1274+ # is the list of all invoked subcommand's results.1275+ contexts = []1276+ while args:1277+ cmd_name, cmd, args = self.resolve_command(ctx, args)1278+ sub_ctx = cmd.make_context(1279+ cmd_name,1280+ args,1281+ parent=ctx,1282+ allow_extra_args=True,1283+ allow_interspersed_args=False,1284+ )1285+ contexts.append(sub_ctx)1286+ args, sub_ctx.args = sub_ctx.args, []1287+1288+ rv = []1289+ for sub_ctx in contexts:1290+ with sub_ctx:1291+ rv.append(sub_ctx.command.invoke(sub_ctx))1292+ return _process_result(rv)1293+1294+ def resolve_command(self, ctx, args):1295+ cmd_name = make_str(args[0])1296+ original_cmd_name = cmd_name1297+1298+ # Get the command1299+ cmd = self.get_command(ctx, cmd_name)1300+1301+ # If we can't find the command but there is a normalization1302+ # function available, we try with that one.1303+ if cmd is None and ctx.token_normalize_func is not None:1304+ cmd_name = ctx.token_normalize_func(cmd_name)1305+ cmd = self.get_command(ctx, cmd_name)1306+1307+ # If we don't find the command we want to show an error message1308+ # to the user that it was not provided. However, there is1309+ # something else we should do: if the first argument looks like1310+ # an option we want to kick off parsing again for arguments to1311+ # resolve things like --help which now should go to the main1312+ # place.1313+ if cmd is None and not ctx.resilient_parsing:1314+ if split_opt(cmd_name)[0]:1315+ self.parse_args(ctx, ctx.args)1316+ ctx.fail("No such command '{}'.".format(original_cmd_name))1317+1318+ return cmd_name, cmd, args[1:]1319+1320+ def get_command(self, ctx, cmd_name):1321+ """Given a context and a command name, this returns a1322+ :class:`Command` object if it exists or returns `None`.1323+ """1324+ raise NotImplementedError()1325+1326+ def list_commands(self, ctx):1327+ """Returns a list of subcommand names in the order they should1328+ appear.1329+ """1330+ return []1331+1332+1333+class Group(MultiCommand):1334+ """A group allows a command to have subcommands attached. This is the1335+ most common way to implement nesting in Click.1336+1337+ :param commands: a dictionary of commands.1338+ """1339+1340+ def __init__(self, name=None, commands=None, **attrs):1341+ MultiCommand.__init__(self, name, **attrs)1342+ #: the registered subcommands by their exported names.1343+ self.commands = commands or {}1344+1345+ def add_command(self, cmd, name=None):1346+ """Registers another :class:`Command` with this group. If the name1347+ is not provided, the name of the command is used.1348+ """1349+ name = name or cmd.name1350+ if name is None:1351+ raise TypeError("Command has no name.")1352+ _check_multicommand(self, name, cmd, register=True)1353+ self.commands[name] = cmd1354+1355+ def command(self, *args, **kwargs):1356+ """A shortcut decorator for declaring and attaching a command to1357+ the group. This takes the same arguments as :func:`command` but1358+ immediately registers the created command with this instance by1359+ calling into :meth:`add_command`.1360+ """1361+ from .decorators import command1362+1363+ def decorator(f):1364+ cmd = command(*args, **kwargs)(f)1365+ self.add_command(cmd)1366+ return cmd1367+1368+ return decorator1369+1370+ def group(self, *args, **kwargs):1371+ """A shortcut decorator for declaring and attaching a group to1372+ the group. This takes the same arguments as :func:`group` but1373+ immediately registers the created command with this instance by1374+ calling into :meth:`add_command`.1375+ """1376+ from .decorators import group1377+1378+ def decorator(f):1379+ cmd = group(*args, **kwargs)(f)1380+ self.add_command(cmd)1381+ return cmd1382+1383+ return decorator1384+1385+ def get_command(self, ctx, cmd_name):1386+ return self.commands.get(cmd_name)1387+1388+ def list_commands(self, ctx):1389+ return sorted(self.commands)1390+1391+1392+class CommandCollection(MultiCommand):1393+ """A command collection is a multi command that merges multiple multi1394+ commands together into one. This is a straightforward implementation1395+ that accepts a list of different multi commands as sources and1396+ provides all the commands for each of them.1397+ """1398+1399+ def __init__(self, name=None, sources=None, **attrs):1400+ MultiCommand.__init__(self, name, **attrs)1401+ #: The list of registered multi commands.1402+ self.sources = sources or []1403+1404+ def add_source(self, multi_cmd):1405+ """Adds a new multi command to the chain dispatcher."""1406+ self.sources.append(multi_cmd)1407+1408+ def get_command(self, ctx, cmd_name):1409+ for source in self.sources:1410+ rv = source.get_command(ctx, cmd_name)1411+ if rv is not None:1412+ if self.chain:1413+ _check_multicommand(self, cmd_name, rv)1414+ return rv1415+1416+ def list_commands(self, ctx):1417+ rv = set()1418+ for source in self.sources:1419+ rv.update(source.list_commands(ctx))1420+ return sorted(rv)1421+1422+1423+class Parameter(object):1424+ r"""A parameter to a command comes in two versions: they are either1425+ :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1426+ not supported by design as some of the internals for parsing are1427+ intentionally not finalized.1428+1429+ Some settings are supported by both options and arguments.1430+1431+ :param param_decls: the parameter declarations for this option or1432+ argument. This is a list of flags or argument1433+ names.1434+ :param type: the type that should be used. Either a :class:`ParamType`1435+ or a Python type. The later is converted into the former1436+ automatically if supported.1437+ :param required: controls if this is optional or not.1438+ :param default: the default value if omitted. This can also be a callable,1439+ in which case it's invoked when the default is needed1440+ without any arguments.1441+ :param callback: a callback that should be executed after the parameter1442+ was matched. This is called as ``fn(ctx, param,1443+ value)`` and needs to return the value. Before Click1444+ 2.0, the signature was ``(ctx, value)``.1445+ :param nargs: the number of arguments to match. If not ``1`` the return1446+ value is a tuple instead of single value. The default for1447+ nargs is ``1`` (except if the type is a tuple, then it's1448+ the arity of the tuple).1449+ :param metavar: how the value is represented in the help page.1450+ :param expose_value: if this is `True` then the value is passed onwards1451+ to the command callback and stored on the context,1452+ otherwise it's skipped.1453+ :param is_eager: eager values are processed before non eager ones. This1454+ should not be set for arguments or it will inverse the1455+ order of processing.1456+ :param envvar: a string or list of strings that are environment variables1457+ that should be checked.1458+1459+ .. versionchanged:: 7.11460+ Empty environment variables are ignored rather than taking the1461+ empty string value. This makes it possible for scripts to clear1462+ variables if they can't unset them.1463+1464+ .. versionchanged:: 2.01465+ Changed signature for parameter callback to also be passed the1466+ parameter. The old callback format will still work, but it will1467+ raise a warning to give you a chance to migrate the code easier.1468+ """1469+ param_type_name = "parameter"1470+1471+ def __init__(1472+ self,1473+ param_decls=None,1474+ type=None,1475+ required=False,1476+ default=None,1477+ callback=None,1478+ nargs=None,1479+ metavar=None,1480+ expose_value=True,1481+ is_eager=False,1482+ envvar=None,1483+ autocompletion=None,1484+ ):1485+ self.name, self.opts, self.secondary_opts = self._parse_decls(1486+ param_decls or (), expose_value1487+ )1488+1489+ self.type = convert_type(type, default)1490+1491+ # Default nargs to what the type tells us if we have that1492+ # information available.1493+ if nargs is None:1494+ if self.type.is_composite:1495+ nargs = self.type.arity1496+ else:1497+ nargs = 11498+1499+ self.required = required1500+ self.callback = callback1501+ self.nargs = nargs1502+ self.multiple = False1503+ self.expose_value = expose_value1504+ self.default = default1505+ self.is_eager = is_eager1506+ self.metavar = metavar1507+ self.envvar = envvar1508+ self.autocompletion = autocompletion1509+1510+ def __repr__(self):1511+ return "<{} {}>".format(self.__class__.__name__, self.name)1512+1513+ @property1514+ def human_readable_name(self):1515+ """Returns the human readable name of this parameter. This is the1516+ same as the name for options, but the metavar for arguments.1517+ """1518+ return self.name1519+1520+ def make_metavar(self):1521+ if self.metavar is not None:1522+ return self.metavar1523+ metavar = self.type.get_metavar(self)1524+ if metavar is None:1525+ metavar = self.type.name.upper()1526+ if self.nargs != 1:1527+ metavar += "..."1528+ return metavar1529+1530+ def get_default(self, ctx):1531+ """Given a context variable this calculates the default value."""1532+ # Otherwise go with the regular default.1533+ if callable(self.default):1534+ rv = self.default()1535+ else:1536+ rv = self.default1537+ return self.type_cast_value(ctx, rv)1538+1539+ def add_to_parser(self, parser, ctx):1540+ pass1541+1542+ def consume_value(self, ctx, opts):1543+ value = opts.get(self.name)1544+ if value is None:1545+ value = self.value_from_envvar(ctx)1546+ if value is None:1547+ value = ctx.lookup_default(self.name)1548+ return value1549+1550+ def type_cast_value(self, ctx, value):1551+ """Given a value this runs it properly through the type system.1552+ This automatically handles things like `nargs` and `multiple` as1553+ well as composite types.1554+ """1555+ if self.type.is_composite:1556+ if self.nargs <= 1:1557+ raise TypeError(1558+ "Attempted to invoke composite type but nargs has"1559+ " been set to {}. This is not supported; nargs"1560+ " needs to be set to a fixed value > 1.".format(self.nargs)1561+ )1562+ if self.multiple:1563+ return tuple(self.type(x or (), self, ctx) for x in value or ())1564+ return self.type(value or (), self, ctx)1565+1566+ def _convert(value, level):1567+ if level == 0:1568+ return self.type(value, self, ctx)1569+ return tuple(_convert(x, level - 1) for x in value or ())1570+1571+ return _convert(value, (self.nargs != 1) + bool(self.multiple))1572+1573+ def process_value(self, ctx, value):1574+ """Given a value and context this runs the logic to convert the1575+ value as necessary.1576+ """1577+ # If the value we were given is None we do nothing. This way1578+ # code that calls this can easily figure out if something was1579+ # not provided. Otherwise it would be converted into an empty1580+ # tuple for multiple invocations which is inconvenient.1581+ if value is not None:1582+ return self.type_cast_value(ctx, value)1583+1584+ def value_is_missing(self, value):1585+ if value is None:1586+ return True1587+ if (self.nargs != 1 or self.multiple) and value == ():1588+ return True1589+ return False1590+1591+ def full_process_value(self, ctx, value):1592+ value = self.process_value(ctx, value)1593+1594+ if value is None and not ctx.resilient_parsing:1595+ value = self.get_default(ctx)1596+1597+ if self.required and self.value_is_missing(value):1598+ raise MissingParameter(ctx=ctx, param=self)1599+1600+ return value1601+1602+ def resolve_envvar_value(self, ctx):1603+ if self.envvar is None:1604+ return1605+ if isinstance(self.envvar, (tuple, list)):1606+ for envvar in self.envvar:1607+ rv = os.environ.get(envvar)1608+ if rv is not None:1609+ return rv1610+ else:1611+ rv = os.environ.get(self.envvar)1612+1613+ if rv != "":1614+ return rv1615+1616+ def value_from_envvar(self, ctx):1617+ rv = self.resolve_envvar_value(ctx)1618+ if rv is not None and self.nargs != 1:1619+ rv = self.type.split_envvar_value(rv)1620+ return rv1621+1622+ def handle_parse_result(self, ctx, opts, args):1623+ with augment_usage_errors(ctx, param=self):1624+ value = self.consume_value(ctx, opts)1625+ try:1626+ value = self.full_process_value(ctx, value)1627+ except Exception:1628+ if not ctx.resilient_parsing:1629+ raise1630+ value = None1631+ if self.callback is not None:1632+ try:1633+ value = invoke_param_callback(self.callback, ctx, self, value)1634+ except Exception:1635+ if not ctx.resilient_parsing:1636+ raise1637+1638+ if self.expose_value:1639+ ctx.params[self.name] = value1640+ return value, args1641+1642+ def get_help_record(self, ctx):1643+ pass1644+1645+ def get_usage_pieces(self, ctx):1646+ return []1647+1648+ def get_error_hint(self, ctx):1649+ """Get a stringified version of the param for use in error messages to1650+ indicate which param caused the error.1651+ """1652+ hint_list = self.opts or [self.human_readable_name]1653+ return " / ".join(repr(x) for x in hint_list)1654+1655+1656+class Option(Parameter):1657+ """Options are usually optional values on the command line and1658+ have some extra features that arguments don't have.1659+1660+ All other parameters are passed onwards to the parameter constructor.1661+1662+ :param show_default: controls if the default value should be shown on the1663+ help page. Normally, defaults are not shown. If this1664+ value is a string, it shows the string instead of the1665+ value. This is particularly useful for dynamic options.1666+ :param show_envvar: controls if an environment variable should be shown on1667+ the help page. Normally, environment variables1668+ are not shown.1669+ :param prompt: if set to `True` or a non empty string then the user will be1670+ prompted for input. If set to `True` the prompt will be the1671+ option name capitalized.1672+ :param confirmation_prompt: if set then the value will need to be confirmed1673+ if it was prompted for.1674+ :param hide_input: if this is `True` then the input on the prompt will be1675+ hidden from the user. This is useful for password1676+ input.1677+ :param is_flag: forces this option to act as a flag. The default is1678+ auto detection.1679+ :param flag_value: which value should be used for this flag if it's1680+ enabled. This is set to a boolean automatically if1681+ the option string contains a slash to mark two options.1682+ :param multiple: if this is set to `True` then the argument is accepted1683+ multiple times and recorded. This is similar to ``nargs``1684+ in how it works but supports arbitrary number of1685+ arguments.1686+ :param count: this flag makes an option increment an integer.1687+ :param allow_from_autoenv: if this is enabled then the value of this1688+ parameter will be pulled from an environment1689+ variable in case a prefix is defined on the1690+ context.1691+ :param help: the help string.1692+ :param hidden: hide this option from help outputs.1693+ """1694+1695+ param_type_name = "option"1696+1697+ def __init__(1698+ self,1699+ param_decls=None,1700+ show_default=False,1701+ prompt=False,1702+ confirmation_prompt=False,1703+ hide_input=False,1704+ is_flag=None,1705+ flag_value=None,1706+ multiple=False,1707+ count=False,1708+ allow_from_autoenv=True,1709+ type=None,1710+ help=None,1711+ hidden=False,1712+ show_choices=True,1713+ show_envvar=False,1714+ **attrs1715+ ):1716+ default_is_missing = attrs.get("default", _missing) is _missing1717+ Parameter.__init__(self, param_decls, type=type, **attrs)1718+1719+ if prompt is True:1720+ prompt_text = self.name.replace("_", " ").capitalize()1721+ elif prompt is False:1722+ prompt_text = None1723+ else:1724+ prompt_text = prompt1725+ self.prompt = prompt_text1726+ self.confirmation_prompt = confirmation_prompt1727+ self.hide_input = hide_input1728+ self.hidden = hidden1729+1730+ # Flags1731+ if is_flag is None:1732+ if flag_value is not None:1733+ is_flag = True1734+ else:1735+ is_flag = bool(self.secondary_opts)1736+ if is_flag and default_is_missing:1737+ self.default = False1738+ if flag_value is None:1739+ flag_value = not self.default1740+ self.is_flag = is_flag1741+ self.flag_value = flag_value1742+ if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:1743+ self.type = BOOL1744+ self.is_bool_flag = True1745+ else:1746+ self.is_bool_flag = False1747+1748+ # Counting1749+ self.count = count1750+ if count:1751+ if type is None:1752+ self.type = IntRange(min=0)1753+ if default_is_missing:1754+ self.default = 01755+1756+ self.multiple = multiple1757+ self.allow_from_autoenv = allow_from_autoenv1758+ self.help = help1759+ self.show_default = show_default1760+ self.show_choices = show_choices1761+ self.show_envvar = show_envvar1762+1763+ # Sanity check for stuff we don't support1764+ if __debug__:1765+ if self.nargs < 0:1766+ raise TypeError("Options cannot have nargs < 0")1767+ if self.prompt and self.is_flag and not self.is_bool_flag:1768+ raise TypeError("Cannot prompt for flags that are not bools.")1769+ if not self.is_bool_flag and self.secondary_opts:1770+ raise TypeError("Got secondary option for non boolean flag.")1771+ if self.is_bool_flag and self.hide_input and self.prompt is not None:1772+ raise TypeError("Hidden input does not work with boolean flag prompts.")1773+ if self.count:1774+ if self.multiple:1775+ raise TypeError(1776+ "Options cannot be multiple and count at the same time."1777+ )1778+ elif self.is_flag:1779+ raise TypeError(1780+ "Options cannot be count and flags at the same time."1781+ )1782+1783+ def _parse_decls(self, decls, expose_value):1784+ opts = []1785+ secondary_opts = []1786+ name = None1787+ possible_names = []1788+1789+ for decl in decls:1790+ if isidentifier(decl):1791+ if name is not None:1792+ raise TypeError("Name defined twice")1793+ name = decl1794+ else:1795+ split_char = ";" if decl[:1] == "/" else "/"1796+ if split_char in decl:1797+ first, second = decl.split(split_char, 1)1798+ first = first.rstrip()1799+ if first:1800+ possible_names.append(split_opt(first))1801+ opts.append(first)1802+ second = second.lstrip()1803+ if second:1804+ secondary_opts.append(second.lstrip())1805+ else:1806+ possible_names.append(split_opt(decl))1807+ opts.append(decl)1808+1809+ if name is None and possible_names:1810+ possible_names.sort(key=lambda x: -len(x[0])) # group long options first1811+ name = possible_names[0][1].replace("-", "_").lower()1812+ if not isidentifier(name):1813+ name = None1814+1815+ if name is None:1816+ if not expose_value:1817+ return None, opts, secondary_opts1818+ raise TypeError("Could not determine name for option")1819+1820+ if not opts and not secondary_opts:1821+ raise TypeError(1822+ "No options defined but a name was passed ({}). Did you"1823+ " mean to declare an argument instead of an option?".format(name)1824+ )1825+1826+ return name, opts, secondary_opts1827+1828+ def add_to_parser(self, parser, ctx):1829+ kwargs = {1830+ "dest": self.name,1831+ "nargs": self.nargs,1832+ "obj": self,1833+ }1834+1835+ if self.multiple:1836+ action = "append"1837+ elif self.count:1838+ action = "count"1839+ else:1840+ action = "store"1841+1842+ if self.is_flag:1843+ kwargs.pop("nargs", None)1844+ action_const = "{}_const".format(action)1845+ if self.is_bool_flag and self.secondary_opts:1846+ parser.add_option(self.opts, action=action_const, const=True, **kwargs)1847+ parser.add_option(1848+ self.secondary_opts, action=action_const, const=False, **kwargs1849+ )1850+ else:1851+ parser.add_option(1852+ self.opts, action=action_const, const=self.flag_value, **kwargs1853+ )1854+ else:1855+ kwargs["action"] = action1856+ parser.add_option(self.opts, **kwargs)1857+1858+ def get_help_record(self, ctx):1859+ if self.hidden:1860+ return1861+ any_prefix_is_slash = []1862+1863+ def _write_opts(opts):1864+ rv, any_slashes = join_options(opts)1865+ if any_slashes:1866+ any_prefix_is_slash[:] = [True]1867+ if not self.is_flag and not self.count:1868+ rv += " {}".format(self.make_metavar())1869+ return rv1870+1871+ rv = [_write_opts(self.opts)]1872+ if self.secondary_opts:1873+ rv.append(_write_opts(self.secondary_opts))1874+1875+ help = self.help or ""1876+ extra = []1877+ if self.show_envvar:1878+ envvar = self.envvar1879+ if envvar is None:1880+ if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1881+ envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1882+ if envvar is not None:1883+ extra.append(1884+ "env var: {}".format(1885+ ", ".join(str(d) for d in envvar)1886+ if isinstance(envvar, (list, tuple))1887+ else envvar1888+ )1889+ )1890+ if self.default is not None and (self.show_default or ctx.show_default):1891+ if isinstance(self.show_default, string_types):1892+ default_string = "({})".format(self.show_default)1893+ elif isinstance(self.default, (list, tuple)):1894+ default_string = ", ".join(str(d) for d in self.default)1895+ elif inspect.isfunction(self.default):1896+ default_string = "(dynamic)"1897+ else:1898+ default_string = self.default1899+ extra.append("default: {}".format(default_string))1900+1901+ if self.required:1902+ extra.append("required")1903+ if extra:1904+ help = "{}[{}]".format(1905+ "{} ".format(help) if help else "", "; ".join(extra)1906+ )1907+1908+ return ("; " if any_prefix_is_slash else " / ").join(rv), help1909+1910+ def get_default(self, ctx):1911+ # If we're a non boolean flag our default is more complex because1912+ # we need to look at all flags in the same group to figure out1913+ # if we're the the default one in which case we return the flag1914+ # value as default.1915+ if self.is_flag and not self.is_bool_flag:1916+ for param in ctx.command.params:1917+ if param.name == self.name and param.default:1918+ return param.flag_value1919+ return None1920+ return Parameter.get_default(self, ctx)1921+1922+ def prompt_for_value(self, ctx):1923+ """This is an alternative flow that can be activated in the full1924+ value processing if a value does not exist. It will prompt the1925+ user until a valid value exists and then returns the processed1926+ value as result.1927+ """1928+ # Calculate the default before prompting anything to be stable.1929+ default = self.get_default(ctx)1930+1931+ # If this is a prompt for a flag we need to handle this1932+ # differently.1933+ if self.is_bool_flag:1934+ return confirm(self.prompt, default)1935+1936+ return prompt(1937+ self.prompt,1938+ default=default,1939+ type=self.type,1940+ hide_input=self.hide_input,1941+ show_choices=self.show_choices,1942+ confirmation_prompt=self.confirmation_prompt,1943+ value_proc=lambda x: self.process_value(ctx, x),1944+ )1945+1946+ def resolve_envvar_value(self, ctx):1947+ rv = Parameter.resolve_envvar_value(self, ctx)1948+ if rv is not None:1949+ return rv1950+ if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1951+ envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1952+ return os.environ.get(envvar)1953+1954+ def value_from_envvar(self, ctx):1955+ rv = self.resolve_envvar_value(ctx)1956+ if rv is None:1957+ return None1958+ value_depth = (self.nargs != 1) + bool(self.multiple)1959+ if value_depth > 0 and rv is not None:1960+ rv = self.type.split_envvar_value(rv)1961+ if self.multiple and self.nargs != 1:1962+ rv = batch(rv, self.nargs)1963+ return rv1964+1965+ def full_process_value(self, ctx, value):1966+ if value is None and self.prompt is not None and not ctx.resilient_parsing:1967+ return self.prompt_for_value(ctx)1968+ return Parameter.full_process_value(self, ctx, value)1969+1970+1971+class Argument(Parameter):1972+ """Arguments are positional parameters to a command. They generally1973+ provide fewer features than options but can have infinite ``nargs``1974+ and are required by default.1975+1976+ All parameters are passed onwards to the parameter constructor.1977+ """1978+1979+ param_type_name = "argument"1980+1981+ def __init__(self, param_decls, required=None, **attrs):1982+ if required is None:1983+ if attrs.get("default") is not None:1984+ required = False1985+ else:1986+ required = attrs.get("nargs", 1) > 01987+ Parameter.__init__(self, param_decls, required=required, **attrs)1988+ if self.default is not None and self.nargs < 0:1989+ raise TypeError(1990+ "nargs=-1 in combination with a default value is not supported."1991+ )1992+1993+ @property1994+ def human_readable_name(self):1995+ if self.metavar is not None:1996+ return self.metavar1997+ return self.name.upper()1998+1999+ def make_metavar(self):2000+ if self.metavar is not None:2001+ return self.metavar2002+ var = self.type.get_metavar(self)2003+ if not var:2004+ var = self.name.upper()2005+ if not self.required:2006+ var = "[{}]".format(var)2007+ if self.nargs != 1:2008+ var += "..."2009+ return var2010+2011+ def _parse_decls(self, decls, expose_value):2012+ if not decls:2013+ if not expose_value:2014+ return None, [], []2015+ raise TypeError("Could not determine name for argument")2016+ if len(decls) == 1:2017+ name = arg = decls[0]2018+ name = name.replace("-", "_").lower()2019+ else:2020+ raise TypeError(2021+ "Arguments take exactly one parameter declaration, got"2022+ " {}".format(len(decls))2023+ )2024+ return name, [arg], []2025+2026+ def get_usage_pieces(self, ctx):2027+ return [self.make_metavar()]2028+2029+ def get_error_hint(self, ctx):2030+ return repr(self.make_metavar())2031+2032+ def add_to_parser(self, parser, ctx):2033+ parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)added:src/click/decorators.py+333 added
1+import inspect2+import sys3+from functools import update_wrapper4+5+from ._compat import iteritems6+from ._unicodefun import _check_for_unicode_literals7+from .core import Argument8+from .core import Command9+from .core import Group10+from .core import Option11+from .globals import get_current_context12+from .utils import echo13+14+15+def pass_context(f):16+ """Marks a callback as wanting to receive the current context17+ object as first argument.18+ """19+20+ def new_func(*args, **kwargs):21+ return f(get_current_context(), *args, **kwargs)22+23+ return update_wrapper(new_func, f)24+25+26+def pass_obj(f):27+ """Similar to :func:`pass_context`, but only pass the object on the28+ context onwards (:attr:`Context.obj`). This is useful if that object29+ represents the state of a nested system.30+ """31+32+ def new_func(*args, **kwargs):33+ return f(get_current_context().obj, *args, **kwargs)34+35+ return update_wrapper(new_func, f)36+37+38+def make_pass_decorator(object_type, ensure=False):39+ """Given an object type this creates a decorator that will work40+ similar to :func:`pass_obj` but instead of passing the object of the41+ current context, it will find the innermost context of type42+ :func:`object_type`.43+44+ This generates a decorator that works roughly like this::45+46+ from functools import update_wrapper47+48+ def decorator(f):49+ @pass_context50+ def new_func(ctx, *args, **kwargs):51+ obj = ctx.find_object(object_type)52+ return ctx.invoke(f, obj, *args, **kwargs)53+ return update_wrapper(new_func, f)54+ return decorator55+56+ :param object_type: the type of the object to pass.57+ :param ensure: if set to `True`, a new object will be created and58+ remembered on the context if it's not there yet.59+ """60+61+ def decorator(f):62+ def new_func(*args, **kwargs):63+ ctx = get_current_context()64+ if ensure:65+ obj = ctx.ensure_object(object_type)66+ else:67+ obj = ctx.find_object(object_type)68+ if obj is None:69+ raise RuntimeError(70+ "Managed to invoke callback without a context"71+ " object of type '{}' existing".format(object_type.__name__)72+ )73+ return ctx.invoke(f, obj, *args, **kwargs)74+75+ return update_wrapper(new_func, f)76+77+ return decorator78+79+80+def _make_command(f, name, attrs, cls):81+ if isinstance(f, Command):82+ raise TypeError("Attempted to convert a callback into a command twice.")83+ try:84+ params = f.__click_params__85+ params.reverse()86+ del f.__click_params__87+ except AttributeError:88+ params = []89+ help = attrs.get("help")90+ if help is None:91+ help = inspect.getdoc(f)92+ if isinstance(help, bytes):93+ help = help.decode("utf-8")94+ else:95+ help = inspect.cleandoc(help)96+ attrs["help"] = help97+ _check_for_unicode_literals()98+ return cls(99+ name=name or f.__name__.lower().replace("_", "-"),100+ callback=f,101+ params=params,102+ **attrs103+ )104+105+106+def command(name=None, cls=None, **attrs):107+ r"""Creates a new :class:`Command` and uses the decorated function as108+ callback. This will also automatically attach all decorated109+ :func:`option`\s and :func:`argument`\s as parameters to the command.110+111+ The name of the command defaults to the name of the function with112+ underscores replaced by dashes. If you want to change that, you can113+ pass the intended name as the first argument.114+115+ All keyword arguments are forwarded to the underlying command class.116+117+ Once decorated the function turns into a :class:`Command` instance118+ that can be invoked as a command line utility or be attached to a119+ command :class:`Group`.120+121+ :param name: the name of the command. This defaults to the function122+ name with underscores replaced by dashes.123+ :param cls: the command class to instantiate. This defaults to124+ :class:`Command`.125+ """126+ if cls is None:127+ cls = Command128+129+ def decorator(f):130+ cmd = _make_command(f, name, attrs, cls)131+ cmd.__doc__ = f.__doc__132+ return cmd133+134+ return decorator135+136+137+def group(name=None, **attrs):138+ """Creates a new :class:`Group` with a function as callback. This139+ works otherwise the same as :func:`command` just that the `cls`140+ parameter is set to :class:`Group`.141+ """142+ attrs.setdefault("cls", Group)143+ return command(name, **attrs)144+145+146+def _param_memo(f, param):147+ if isinstance(f, Command):148+ f.params.append(param)149+ else:150+ if not hasattr(f, "__click_params__"):151+ f.__click_params__ = []152+ f.__click_params__.append(param)153+154+155+def argument(*param_decls, **attrs):156+ """Attaches an argument to the command. All positional arguments are157+ passed as parameter declarations to :class:`Argument`; all keyword158+ arguments are forwarded unchanged (except ``cls``).159+ This is equivalent to creating an :class:`Argument` instance manually160+ and attaching it to the :attr:`Command.params` list.161+162+ :param cls: the argument class to instantiate. This defaults to163+ :class:`Argument`.164+ """165+166+ def decorator(f):167+ ArgumentClass = attrs.pop("cls", Argument)168+ _param_memo(f, ArgumentClass(param_decls, **attrs))169+ return f170+171+ return decorator172+173+174+def option(*param_decls, **attrs):175+ """Attaches an option to the command. All positional arguments are176+ passed as parameter declarations to :class:`Option`; all keyword177+ arguments are forwarded unchanged (except ``cls``).178+ This is equivalent to creating an :class:`Option` instance manually179+ and attaching it to the :attr:`Command.params` list.180+181+ :param cls: the option class to instantiate. This defaults to182+ :class:`Option`.183+ """184+185+ def decorator(f):186+ # Issue 926, copy attrs, so pre-defined options can re-use the same cls=187+ option_attrs = attrs.copy()188+189+ if "help" in option_attrs:190+ option_attrs["help"] = inspect.cleandoc(option_attrs["help"])191+ OptionClass = option_attrs.pop("cls", Option)192+ _param_memo(f, OptionClass(param_decls, **option_attrs))193+ return f194+195+ return decorator196+197+198+def confirmation_option(*param_decls, **attrs):199+ """Shortcut for confirmation prompts that can be ignored by passing200+ ``--yes`` as parameter.201+202+ This is equivalent to decorating a function with :func:`option` with203+ the following parameters::204+205+ def callback(ctx, param, value):206+ if not value:207+ ctx.abort()208+209+ @click.command()210+ @click.option('--yes', is_flag=True, callback=callback,211+ expose_value=False, prompt='Do you want to continue?')212+ def dropdb():213+ pass214+ """215+216+ def decorator(f):217+ def callback(ctx, param, value):218+ if not value:219+ ctx.abort()220+221+ attrs.setdefault("is_flag", True)222+ attrs.setdefault("callback", callback)223+ attrs.setdefault("expose_value", False)224+ attrs.setdefault("prompt", "Do you want to continue?")225+ attrs.setdefault("help", "Confirm the action without prompting.")226+ return option(*(param_decls or ("--yes",)), **attrs)(f)227+228+ return decorator229+230+231+def password_option(*param_decls, **attrs):232+ """Shortcut for password prompts.233+234+ This is equivalent to decorating a function with :func:`option` with235+ the following parameters::236+237+ @click.command()238+ @click.option('--password', prompt=True, confirmation_prompt=True,239+ hide_input=True)240+ def changeadmin(password):241+ pass242+ """243+244+ def decorator(f):245+ attrs.setdefault("prompt", True)246+ attrs.setdefault("confirmation_prompt", True)247+ attrs.setdefault("hide_input", True)248+ return option(*(param_decls or ("--password",)), **attrs)(f)249+250+ return decorator251+252+253+def version_option(version=None, *param_decls, **attrs):254+ """Adds a ``--version`` option which immediately ends the program255+ printing out the version number. This is implemented as an eager256+ option that prints the version and exits the program in the callback.257+258+ :param version: the version number to show. If not provided Click259+ attempts an auto discovery via setuptools.260+ :param prog_name: the name of the program (defaults to autodetection)261+ :param message: custom message to show instead of the default262+ (``'%(prog)s, version %(version)s'``)263+ :param others: everything else is forwarded to :func:`option`.264+ """265+ if version is None:266+ if hasattr(sys, "_getframe"):267+ module = sys._getframe(1).f_globals.get("__name__")268+ else:269+ module = ""270+271+ def decorator(f):272+ prog_name = attrs.pop("prog_name", None)273+ message = attrs.pop("message", "%(prog)s, version %(version)s")274+275+ def callback(ctx, param, value):276+ if not value or ctx.resilient_parsing:277+ return278+ prog = prog_name279+ if prog is None:280+ prog = ctx.find_root().info_name281+ ver = version282+ if ver is None:283+ try:284+ import pkg_resources285+ except ImportError:286+ pass287+ else:288+ for dist in pkg_resources.working_set:289+ scripts = dist.get_entry_map().get("console_scripts") or {}290+ for _, entry_point in iteritems(scripts):291+ if entry_point.module_name == module:292+ ver = dist.version293+ break294+ if ver is None:295+ raise RuntimeError("Could not determine version")296+ echo(message % {"prog": prog, "version": ver}, color=ctx.color)297+ ctx.exit()298+299+ attrs.setdefault("is_flag", True)300+ attrs.setdefault("expose_value", False)301+ attrs.setdefault("is_eager", True)302+ attrs.setdefault("help", "Show the version and exit.")303+ attrs["callback"] = callback304+ return option(*(param_decls or ("--version",)), **attrs)(f)305+306+ return decorator307+308+309+def help_option(*param_decls, **attrs):310+ """Adds a ``--help`` option which immediately ends the program311+ printing out the help page. This is usually unnecessary to add as312+ this is added by default to all commands unless suppressed.313+314+ Like :func:`version_option`, this is implemented as eager option that315+ prints in the callback and exits.316+317+ All arguments are forwarded to :func:`option`.318+ """319+320+ def decorator(f):321+ def callback(ctx, param, value):322+ if value and not ctx.resilient_parsing:323+ echo(ctx.get_help(), color=ctx.color)324+ ctx.exit()325+326+ attrs.setdefault("is_flag", True)327+ attrs.setdefault("expose_value", False)328+ attrs.setdefault("help", "Show this message and exit.")329+ attrs.setdefault("is_eager", True)330+ attrs["callback"] = callback331+ return option(*(param_decls or ("--help",)), **attrs)(f)332+333+ return decoratoradded:src/click/exceptions.py+253 added
1+from ._compat import filename_to_ui2+from ._compat import get_text_stderr3+from ._compat import PY24+from .utils import echo5+6+7+def _join_param_hints(param_hint):8+ if isinstance(param_hint, (tuple, list)):9+ return " / ".join(repr(x) for x in param_hint)10+ return param_hint11+12+13+class ClickException(Exception):14+ """An exception that Click can handle and show to the user."""15+16+ #: The exit code for this exception17+ exit_code = 118+19+ def __init__(self, message):20+ ctor_msg = message21+ if PY2:22+ if ctor_msg is not None:23+ ctor_msg = ctor_msg.encode("utf-8")24+ Exception.__init__(self, ctor_msg)25+ self.message = message26+27+ def format_message(self):28+ return self.message29+30+ def __str__(self):31+ return self.message32+33+ if PY2:34+ __unicode__ = __str__35+36+ def __str__(self):37+ return self.message.encode("utf-8")38+39+ def show(self, file=None):40+ if file is None:41+ file = get_text_stderr()42+ echo("Error: {}".format(self.format_message(), file=file))43+44+45+class UsageError(ClickException):46+ """An internal exception that signals a usage error. This typically47+ aborts any further handling.48+49+ :param message: the error message to display.50+ :param ctx: optionally the context that caused this error. Click will51+ fill in the context automatically in some situations.52+ """53+54+ exit_code = 255+56+ def __init__(self, message, ctx=None):57+ ClickException.__init__(self, message)58+ self.ctx = ctx59+ self.cmd = self.ctx.command if self.ctx else None60+61+ def show(self, file=None):62+ if file is None:63+ file = get_text_stderr()64+ color = None65+ hint = ""66+ if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67+ hint = "Try '{} {}' for help.\n".format(68+ self.ctx.command_path, self.ctx.help_option_names[0]69+ )70+ if self.ctx is not None:71+ color = self.ctx.color72+ echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)73+ echo("Error: {}".format(self.format_message()), file=file, color=color)74+75+76+class BadParameter(UsageError):77+ """An exception that formats out a standardized error message for a78+ bad parameter. This is useful when thrown from a callback or type as79+ Click will attach contextual information to it (for instance, which80+ parameter it is).81+82+ .. versionadded:: 2.083+84+ :param param: the parameter object that caused this error. This can85+ be left out, and Click will attach this info itself86+ if possible.87+ :param param_hint: a string that shows up as parameter name. This88+ can be used as alternative to `param` in cases89+ where custom validation should happen. If it is90+ a string it's used as such, if it's a list then91+ each item is quoted and separated.92+ """93+94+ def __init__(self, message, ctx=None, param=None, param_hint=None):95+ UsageError.__init__(self, message, ctx)96+ self.param = param97+ self.param_hint = param_hint98+99+ def format_message(self):100+ if self.param_hint is not None:101+ param_hint = self.param_hint102+ elif self.param is not None:103+ param_hint = self.param.get_error_hint(self.ctx)104+ else:105+ return "Invalid value: {}".format(self.message)106+ param_hint = _join_param_hints(param_hint)107+108+ return "Invalid value for {}: {}".format(param_hint, self.message)109+110+111+class MissingParameter(BadParameter):112+ """Raised if click required an option or argument but it was not113+ provided when invoking the script.114+115+ .. versionadded:: 4.0116+117+ :param param_type: a string that indicates the type of the parameter.118+ The default is to inherit the parameter type from119+ the given `param`. Valid values are ``'parameter'``,120+ ``'option'`` or ``'argument'``.121+ """122+123+ def __init__(124+ self, message=None, ctx=None, param=None, param_hint=None, param_type=None125+ ):126+ BadParameter.__init__(self, message, ctx, param, param_hint)127+ self.param_type = param_type128+129+ def format_message(self):130+ if self.param_hint is not None:131+ param_hint = self.param_hint132+ elif self.param is not None:133+ param_hint = self.param.get_error_hint(self.ctx)134+ else:135+ param_hint = None136+ param_hint = _join_param_hints(param_hint)137+138+ param_type = self.param_type139+ if param_type is None and self.param is not None:140+ param_type = self.param.param_type_name141+142+ msg = self.message143+ if self.param is not None:144+ msg_extra = self.param.type.get_missing_message(self.param)145+ if msg_extra:146+ if msg:147+ msg += ". {}".format(msg_extra)148+ else:149+ msg = msg_extra150+151+ return "Missing {}{}{}{}".format(152+ param_type,153+ " {}".format(param_hint) if param_hint else "",154+ ". " if msg else ".",155+ msg or "",156+ )157+158+ def __str__(self):159+ if self.message is None:160+ param_name = self.param.name if self.param else None161+ return "missing parameter: {}".format(param_name)162+ else:163+ return self.message164+165+ if PY2:166+ __unicode__ = __str__167+168+ def __str__(self):169+ return self.__unicode__().encode("utf-8")170+171+172+class NoSuchOption(UsageError):173+ """Raised if click attempted to handle an option that does not174+ exist.175+176+ .. versionadded:: 4.0177+ """178+179+ def __init__(self, option_name, message=None, possibilities=None, ctx=None):180+ if message is None:181+ message = "no such option: {}".format(option_name)182+ UsageError.__init__(self, message, ctx)183+ self.option_name = option_name184+ self.possibilities = possibilities185+186+ def format_message(self):187+ bits = [self.message]188+ if self.possibilities:189+ if len(self.possibilities) == 1:190+ bits.append("Did you mean {}?".format(self.possibilities[0]))191+ else:192+ possibilities = sorted(self.possibilities)193+ bits.append("(Possible options: {})".format(", ".join(possibilities)))194+ return " ".join(bits)195+196+197+class BadOptionUsage(UsageError):198+ """Raised if an option is generally supplied but the use of the option199+ was incorrect. This is for instance raised if the number of arguments200+ for an option is not correct.201+202+ .. versionadded:: 4.0203+204+ :param option_name: the name of the option being used incorrectly.205+ """206+207+ def __init__(self, option_name, message, ctx=None):208+ UsageError.__init__(self, message, ctx)209+ self.option_name = option_name210+211+212+class BadArgumentUsage(UsageError):213+ """Raised if an argument is generally supplied but the use of the argument214+ was incorrect. This is for instance raised if the number of values215+ for an argument is not correct.216+217+ .. versionadded:: 6.0218+ """219+220+ def __init__(self, message, ctx=None):221+ UsageError.__init__(self, message, ctx)222+223+224+class FileError(ClickException):225+ """Raised if a file cannot be opened."""226+227+ def __init__(self, filename, hint=None):228+ ui_filename = filename_to_ui(filename)229+ if hint is None:230+ hint = "unknown error"231+ ClickException.__init__(self, hint)232+ self.ui_filename = ui_filename233+ self.filename = filename234+235+ def format_message(self):236+ return "Could not open file {}: {}".format(self.ui_filename, self.message)237+238+239+class Abort(RuntimeError):240+ """An internal signalling exception that signals Click to abort."""241+242+243+class Exit(RuntimeError):244+ """An exception that indicates that the application should exit with some245+ status code.246+247+ :param code: the status code to exit with.248+ """249+250+ __slots__ = ("exit_code",)251+252+ def __init__(self, code=0):253+ self.exit_code = codeadded:src/click/formatting.py+283 added
1+from contextlib import contextmanager2+3+from ._compat import term_len4+from .parser import split_opt5+from .termui import get_terminal_size6+7+# Can force a width. This is used by the test system8+FORCED_WIDTH = None9+10+11+def measure_table(rows):12+ widths = {}13+ for row in rows:14+ for idx, col in enumerate(row):15+ widths[idx] = max(widths.get(idx, 0), term_len(col))16+ return tuple(y for x, y in sorted(widths.items()))17+18+19+def iter_rows(rows, col_count):20+ for row in rows:21+ row = tuple(row)22+ yield row + ("",) * (col_count - len(row))23+24+25+def wrap_text(26+ text, width=78, initial_indent="", subsequent_indent="", preserve_paragraphs=False27+):28+ """A helper function that intelligently wraps text. By default, it29+ assumes that it operates on a single paragraph of text but if the30+ `preserve_paragraphs` parameter is provided it will intelligently31+ handle paragraphs (defined by two empty lines).32+33+ If paragraphs are handled, a paragraph can be prefixed with an empty34+ line containing the ``\\b`` character (``\\x08``) to indicate that35+ no rewrapping should happen in that block.36+37+ :param text: the text that should be rewrapped.38+ :param width: the maximum width for the text.39+ :param initial_indent: the initial indent that should be placed on the40+ first line as a string.41+ :param subsequent_indent: the indent string that should be placed on42+ each consecutive line.43+ :param preserve_paragraphs: if this flag is set then the wrapping will44+ intelligently handle paragraphs.45+ """46+ from ._textwrap import TextWrapper47+48+ text = text.expandtabs()49+ wrapper = TextWrapper(50+ width,51+ initial_indent=initial_indent,52+ subsequent_indent=subsequent_indent,53+ replace_whitespace=False,54+ )55+ if not preserve_paragraphs:56+ return wrapper.fill(text)57+58+ p = []59+ buf = []60+ indent = None61+62+ def _flush_par():63+ if not buf:64+ return65+ if buf[0].strip() == "\b":66+ p.append((indent or 0, True, "\n".join(buf[1:])))67+ else:68+ p.append((indent or 0, False, " ".join(buf)))69+ del buf[:]70+71+ for line in text.splitlines():72+ if not line:73+ _flush_par()74+ indent = None75+ else:76+ if indent is None:77+ orig_len = term_len(line)78+ line = line.lstrip()79+ indent = orig_len - term_len(line)80+ buf.append(line)81+ _flush_par()82+83+ rv = []84+ for indent, raw, text in p:85+ with wrapper.extra_indent(" " * indent):86+ if raw:87+ rv.append(wrapper.indent_only(text))88+ else:89+ rv.append(wrapper.fill(text))90+91+ return "\n\n".join(rv)92+93+94+class HelpFormatter(object):95+ """This class helps with formatting text-based help pages. It's96+ usually just needed for very special internal cases, but it's also97+ exposed so that developers can write their own fancy outputs.98+99+ At present, it always writes into memory.100+101+ :param indent_increment: the additional increment for each level.102+ :param width: the width for the text. This defaults to the terminal103+ width clamped to a maximum of 78.104+ """105+106+ def __init__(self, indent_increment=2, width=None, max_width=None):107+ self.indent_increment = indent_increment108+ if max_width is None:109+ max_width = 80110+ if width is None:111+ width = FORCED_WIDTH112+ if width is None:113+ width = max(min(get_terminal_size()[0], max_width) - 2, 50)114+ self.width = width115+ self.current_indent = 0116+ self.buffer = []117+118+ def write(self, string):119+ """Writes a unicode string into the internal buffer."""120+ self.buffer.append(string)121+122+ def indent(self):123+ """Increases the indentation."""124+ self.current_indent += self.indent_increment125+126+ def dedent(self):127+ """Decreases the indentation."""128+ self.current_indent -= self.indent_increment129+130+ def write_usage(self, prog, args="", prefix="Usage: "):131+ """Writes a usage line into the buffer.132+133+ :param prog: the program name.134+ :param args: whitespace separated list of arguments.135+ :param prefix: the prefix for the first line.136+ """137+ usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)138+ text_width = self.width - self.current_indent139+140+ if text_width >= (term_len(usage_prefix) + 20):141+ # The arguments will fit to the right of the prefix.142+ indent = " " * term_len(usage_prefix)143+ self.write(144+ wrap_text(145+ args,146+ text_width,147+ initial_indent=usage_prefix,148+ subsequent_indent=indent,149+ )150+ )151+ else:152+ # The prefix is too long, put the arguments on the next line.153+ self.write(usage_prefix)154+ self.write("\n")155+ indent = " " * (max(self.current_indent, term_len(prefix)) + 4)156+ self.write(157+ wrap_text(158+ args, text_width, initial_indent=indent, subsequent_indent=indent159+ )160+ )161+162+ self.write("\n")163+164+ def write_heading(self, heading):165+ """Writes a heading into the buffer."""166+ self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))167+168+ def write_paragraph(self):169+ """Writes a paragraph into the buffer."""170+ if self.buffer:171+ self.write("\n")172+173+ def write_text(self, text):174+ """Writes re-indented text into the buffer. This rewraps and175+ preserves paragraphs.176+ """177+ text_width = max(self.width - self.current_indent, 11)178+ indent = " " * self.current_indent179+ self.write(180+ wrap_text(181+ text,182+ text_width,183+ initial_indent=indent,184+ subsequent_indent=indent,185+ preserve_paragraphs=True,186+ )187+ )188+ self.write("\n")189+190+ def write_dl(self, rows, col_max=30, col_spacing=2):191+ """Writes a definition list into the buffer. This is how options192+ and commands are usually formatted.193+194+ :param rows: a list of two item tuples for the terms and values.195+ :param col_max: the maximum width of the first column.196+ :param col_spacing: the number of spaces between the first and197+ second column.198+ """199+ rows = list(rows)200+ widths = measure_table(rows)201+ if len(widths) != 2:202+ raise TypeError("Expected two columns for definition list")203+204+ first_col = min(widths[0], col_max) + col_spacing205+206+ for first, second in iter_rows(rows, len(widths)):207+ self.write("{:>{w}}{}".format("", first, w=self.current_indent))208+ if not second:209+ self.write("\n")210+ continue211+ if term_len(first) <= first_col - col_spacing:212+ self.write(" " * (first_col - term_len(first)))213+ else:214+ self.write("\n")215+ self.write(" " * (first_col + self.current_indent))216+217+ text_width = max(self.width - first_col - 2, 10)218+ wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219+ lines = wrapped_text.splitlines()220+221+ if lines:222+ self.write("{}\n".format(lines[0]))223+224+ for line in lines[1:]:225+ self.write(226+ "{:>{w}}{}\n".format(227+ "", line, w=first_col + self.current_indent228+ )229+ )230+231+ if len(lines) > 1:232+ # separate long help from next option233+ self.write("\n")234+ else:235+ self.write("\n")236+237+ @contextmanager238+ def section(self, name):239+ """Helpful context manager that writes a paragraph, a heading,240+ and the indents.241+242+ :param name: the section name that is written as heading.243+ """244+ self.write_paragraph()245+ self.write_heading(name)246+ self.indent()247+ try:248+ yield249+ finally:250+ self.dedent()251+252+ @contextmanager253+ def indentation(self):254+ """A context manager that increases the indentation."""255+ self.indent()256+ try:257+ yield258+ finally:259+ self.dedent()260+261+ def getvalue(self):262+ """Returns the buffer contents."""263+ return "".join(self.buffer)264+265+266+def join_options(options):267+ """Given a list of option strings this joins them in the most appropriate268+ way and returns them in the form ``(formatted_string,269+ any_prefix_is_slash)`` where the second item in the tuple is a flag that270+ indicates if any of the option prefixes was a slash.271+ """272+ rv = []273+ any_prefix_is_slash = False274+ for opt in options:275+ prefix = split_opt(opt)[0]276+ if prefix == "/":277+ any_prefix_is_slash = True278+ rv.append((len(prefix), opt))279+280+ rv.sort(key=lambda x: x[0])281+282+ rv = ", ".join(x[1] for x in rv)283+ return rv, any_prefix_is_slashadded:src/click/globals.py+47 added
1+from threading import local2+3+_local = local()4+5+6+def get_current_context(silent=False):7+ """Returns the current click context. This can be used as a way to8+ access the current context object from anywhere. This is a more implicit9+ alternative to the :func:`pass_context` decorator. This function is10+ primarily useful for helpers such as :func:`echo` which might be11+ interested in changing its behavior based on the current context.12+13+ To push the current context, :meth:`Context.scope` can be used.14+15+ .. versionadded:: 5.016+17+ :param silent: if set to `True` the return value is `None` if no context18+ is available. The default behavior is to raise a19+ :exc:`RuntimeError`.20+ """21+ try:22+ return _local.stack[-1]23+ except (AttributeError, IndexError):24+ if not silent:25+ raise RuntimeError("There is no active click context.")26+27+28+def push_context(ctx):29+ """Pushes a new context to the current stack."""30+ _local.__dict__.setdefault("stack", []).append(ctx)31+32+33+def pop_context():34+ """Removes the top level from the stack."""35+ _local.stack.pop()36+37+38+def resolve_color_default(color=None):39+ """"Internal helper to get the default value of the color flag. If a40+ value is passed it's returned unchanged, otherwise it's looked up from41+ the current context.42+ """43+ if color is not None:44+ return color45+ ctx = get_current_context(silent=True)46+ if ctx is not None:47+ return ctx.coloradded:src/click/parser.py+428 added
1+# -*- coding: utf-8 -*-2+"""3+This module started out as largely a copy paste from the stdlib's4+optparse module with the features removed that we do not need from5+optparse because we implement them in Click on a higher level (for6+instance type handling, help formatting and a lot more).7+8+The plan is to remove more and more from here over time.9+10+The reason this is a different module and not optparse from the stdlib11+is that there are differences in 2.x and 3.x about the error messages12+generated and optparse in the stdlib uses gettext for no good reason13+and might cause us issues.14+15+Click uses parts of optparse written by Gregory P. Ward and maintained16+by the Python Software Foundation. This is limited to code in parser.py.17+18+Copyright 2001-2006 Gregory P. Ward. All rights reserved.19+Copyright 2002-2006 Python Software Foundation. All rights reserved.20+"""21+import re22+from collections import deque23+24+from .exceptions import BadArgumentUsage25+from .exceptions import BadOptionUsage26+from .exceptions import NoSuchOption27+from .exceptions import UsageError28+29+30+def _unpack_args(args, nargs_spec):31+ """Given an iterable of arguments and an iterable of nargs specifications,32+ it returns a tuple with all the unpacked arguments at the first index33+ and all remaining arguments as the second.34+35+ The nargs specification is the number of arguments that should be consumed36+ or `-1` to indicate that this position should eat up all the remainders.37+38+ Missing items are filled with `None`.39+ """40+ args = deque(args)41+ nargs_spec = deque(nargs_spec)42+ rv = []43+ spos = None44+45+ def _fetch(c):46+ try:47+ if spos is None:48+ return c.popleft()49+ else:50+ return c.pop()51+ except IndexError:52+ return None53+54+ while nargs_spec:55+ nargs = _fetch(nargs_spec)56+ if nargs == 1:57+ rv.append(_fetch(args))58+ elif nargs > 1:59+ x = [_fetch(args) for _ in range(nargs)]60+ # If we're reversed, we're pulling in the arguments in reverse,61+ # so we need to turn them around.62+ if spos is not None:63+ x.reverse()64+ rv.append(tuple(x))65+ elif nargs < 0:66+ if spos is not None:67+ raise TypeError("Cannot have two nargs < 0")68+ spos = len(rv)69+ rv.append(None)70+71+ # spos is the position of the wildcard (star). If it's not `None`,72+ # we fill it with the remainder.73+ if spos is not None:74+ rv[spos] = tuple(args)75+ args = []76+ rv[spos + 1 :] = reversed(rv[spos + 1 :])77+78+ return tuple(rv), list(args)79+80+81+def _error_opt_args(nargs, opt):82+ if nargs == 1:83+ raise BadOptionUsage(opt, "{} option requires an argument".format(opt))84+ raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs))85+86+87+def split_opt(opt):88+ first = opt[:1]89+ if first.isalnum():90+ return "", opt91+ if opt[1:2] == first:92+ return opt[:2], opt[2:]93+ return first, opt[1:]94+95+96+def normalize_opt(opt, ctx):97+ if ctx is None or ctx.token_normalize_func is None:98+ return opt99+ prefix, opt = split_opt(opt)100+ return prefix + ctx.token_normalize_func(opt)101+102+103+def split_arg_string(string):104+ """Given an argument string this attempts to split it into small parts."""105+ rv = []106+ for match in re.finditer(107+ r"('([^'\\]*(?:\\.[^'\\]*)*)'|\"([^\"\\]*(?:\\.[^\"\\]*)*)\"|\S+)\s*",108+ string,109+ re.S,110+ ):111+ arg = match.group().strip()112+ if arg[:1] == arg[-1:] and arg[:1] in "\"'":113+ arg = arg[1:-1].encode("ascii", "backslashreplace").decode("unicode-escape")114+ try:115+ arg = type(string)(arg)116+ except UnicodeError:117+ pass118+ rv.append(arg)119+ return rv120+121+122+class Option(object):123+ def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):124+ self._short_opts = []125+ self._long_opts = []126+ self.prefixes = set()127+128+ for opt in opts:129+ prefix, value = split_opt(opt)130+ if not prefix:131+ raise ValueError("Invalid start character for option ({})".format(opt))132+ self.prefixes.add(prefix[0])133+ if len(prefix) == 1 and len(value) == 1:134+ self._short_opts.append(opt)135+ else:136+ self._long_opts.append(opt)137+ self.prefixes.add(prefix)138+139+ if action is None:140+ action = "store"141+142+ self.dest = dest143+ self.action = action144+ self.nargs = nargs145+ self.const = const146+ self.obj = obj147+148+ @property149+ def takes_value(self):150+ return self.action in ("store", "append")151+152+ def process(self, value, state):153+ if self.action == "store":154+ state.opts[self.dest] = value155+ elif self.action == "store_const":156+ state.opts[self.dest] = self.const157+ elif self.action == "append":158+ state.opts.setdefault(self.dest, []).append(value)159+ elif self.action == "append_const":160+ state.opts.setdefault(self.dest, []).append(self.const)161+ elif self.action == "count":162+ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1163+ else:164+ raise ValueError("unknown action '{}'".format(self.action))165+ state.order.append(self.obj)166+167+168+class Argument(object):169+ def __init__(self, dest, nargs=1, obj=None):170+ self.dest = dest171+ self.nargs = nargs172+ self.obj = obj173+174+ def process(self, value, state):175+ if self.nargs > 1:176+ holes = sum(1 for x in value if x is None)177+ if holes == len(value):178+ value = None179+ elif holes != 0:180+ raise BadArgumentUsage(181+ "argument {} takes {} values".format(self.dest, self.nargs)182+ )183+ state.opts[self.dest] = value184+ state.order.append(self.obj)185+186+187+class ParsingState(object):188+ def __init__(self, rargs):189+ self.opts = {}190+ self.largs = []191+ self.rargs = rargs192+ self.order = []193+194+195+class OptionParser(object):196+ """The option parser is an internal class that is ultimately used to197+ parse options and arguments. It's modelled after optparse and brings198+ a similar but vastly simplified API. It should generally not be used199+ directly as the high level Click classes wrap it for you.200+201+ It's not nearly as extensible as optparse or argparse as it does not202+ implement features that are implemented on a higher level (such as203+ types or defaults).204+205+ :param ctx: optionally the :class:`~click.Context` where this parser206+ should go with.207+ """208+209+ def __init__(self, ctx=None):210+ #: The :class:`~click.Context` for this parser. This might be211+ #: `None` for some advanced use cases.212+ self.ctx = ctx213+ #: This controls how the parser deals with interspersed arguments.214+ #: If this is set to `False`, the parser will stop on the first215+ #: non-option. Click uses this to implement nested subcommands216+ #: safely.217+ self.allow_interspersed_args = True218+ #: This tells the parser how to deal with unknown options. By219+ #: default it will error out (which is sensible), but there is a220+ #: second mode where it will ignore it and continue processing221+ #: after shifting all the unknown options into the resulting args.222+ self.ignore_unknown_options = False223+ if ctx is not None:224+ self.allow_interspersed_args = ctx.allow_interspersed_args225+ self.ignore_unknown_options = ctx.ignore_unknown_options226+ self._short_opt = {}227+ self._long_opt = {}228+ self._opt_prefixes = {"-", "--"}229+ self._args = []230+231+ def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None):232+ """Adds a new option named `dest` to the parser. The destination233+ is not inferred (unlike with optparse) and needs to be explicitly234+ provided. Action can be any of ``store``, ``store_const``,235+ ``append``, ``appnd_const`` or ``count``.236+237+ The `obj` can be used to identify the option in the order list238+ that is returned from the parser.239+ """240+ if obj is None:241+ obj = dest242+ opts = [normalize_opt(opt, self.ctx) for opt in opts]243+ option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj)244+ self._opt_prefixes.update(option.prefixes)245+ for opt in option._short_opts:246+ self._short_opt[opt] = option247+ for opt in option._long_opts:248+ self._long_opt[opt] = option249+250+ def add_argument(self, dest, nargs=1, obj=None):251+ """Adds a positional argument named `dest` to the parser.252+253+ The `obj` can be used to identify the option in the order list254+ that is returned from the parser.255+ """256+ if obj is None:257+ obj = dest258+ self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))259+260+ def parse_args(self, args):261+ """Parses positional arguments and returns ``(values, args, order)``262+ for the parsed options and arguments as well as the leftover263+ arguments if there are any. The order is a list of objects as they264+ appear on the command line. If arguments appear multiple times they265+ will be memorized multiple times as well.266+ """267+ state = ParsingState(args)268+ try:269+ self._process_args_for_options(state)270+ self._process_args_for_args(state)271+ except UsageError:272+ if self.ctx is None or not self.ctx.resilient_parsing:273+ raise274+ return state.opts, state.largs, state.order275+276+ def _process_args_for_args(self, state):277+ pargs, args = _unpack_args(278+ state.largs + state.rargs, [x.nargs for x in self._args]279+ )280+281+ for idx, arg in enumerate(self._args):282+ arg.process(pargs[idx], state)283+284+ state.largs = args285+ state.rargs = []286+287+ def _process_args_for_options(self, state):288+ while state.rargs:289+ arg = state.rargs.pop(0)290+ arglen = len(arg)291+ # Double dashes always handled explicitly regardless of what292+ # prefixes are valid.293+ if arg == "--":294+ return295+ elif arg[:1] in self._opt_prefixes and arglen > 1:296+ self._process_opts(arg, state)297+ elif self.allow_interspersed_args:298+ state.largs.append(arg)299+ else:300+ state.rargs.insert(0, arg)301+ return302+303+ # Say this is the original argument list:304+ # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]305+ # ^306+ # (we are about to process arg(i)).307+ #308+ # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of309+ # [arg0, ..., arg(i-1)] (any options and their arguments will have310+ # been removed from largs).311+ #312+ # The while loop will usually consume 1 or more arguments per pass.313+ # If it consumes 1 (eg. arg is an option that takes no arguments),314+ # then after _process_arg() is done the situation is:315+ #316+ # largs = subset of [arg0, ..., arg(i)]317+ # rargs = [arg(i+1), ..., arg(N-1)]318+ #319+ # If allow_interspersed_args is false, largs will always be320+ # *empty* -- still a subset of [arg0, ..., arg(i-1)], but321+ # not a very interesting subset!322+323+ def _match_long_opt(self, opt, explicit_value, state):324+ if opt not in self._long_opt:325+ possibilities = [word for word in self._long_opt if word.startswith(opt)]326+ raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)327+328+ option = self._long_opt[opt]329+ if option.takes_value:330+ # At this point it's safe to modify rargs by injecting the331+ # explicit value, because no exception is raised in this332+ # branch. This means that the inserted value will be fully333+ # consumed.334+ if explicit_value is not None:335+ state.rargs.insert(0, explicit_value)336+337+ nargs = option.nargs338+ if len(state.rargs) < nargs:339+ _error_opt_args(nargs, opt)340+ elif nargs == 1:341+ value = state.rargs.pop(0)342+ else:343+ value = tuple(state.rargs[:nargs])344+ del state.rargs[:nargs]345+346+ elif explicit_value is not None:347+ raise BadOptionUsage(opt, "{} option does not take a value".format(opt))348+349+ else:350+ value = None351+352+ option.process(value, state)353+354+ def _match_short_opt(self, arg, state):355+ stop = False356+ i = 1357+ prefix = arg[0]358+ unknown_options = []359+360+ for ch in arg[1:]:361+ opt = normalize_opt(prefix + ch, self.ctx)362+ option = self._short_opt.get(opt)363+ i += 1364+365+ if not option:366+ if self.ignore_unknown_options:367+ unknown_options.append(ch)368+ continue369+ raise NoSuchOption(opt, ctx=self.ctx)370+ if option.takes_value:371+ # Any characters left in arg? Pretend they're the372+ # next arg, and stop consuming characters of arg.373+ if i < len(arg):374+ state.rargs.insert(0, arg[i:])375+ stop = True376+377+ nargs = option.nargs378+ if len(state.rargs) < nargs:379+ _error_opt_args(nargs, opt)380+ elif nargs == 1:381+ value = state.rargs.pop(0)382+ else:383+ value = tuple(state.rargs[:nargs])384+ del state.rargs[:nargs]385+386+ else:387+ value = None388+389+ option.process(value, state)390+391+ if stop:392+ break393+394+ # If we got any unknown options we re-combinate the string of the395+ # remaining options and re-attach the prefix, then report that396+ # to the state as new larg. This way there is basic combinatorics397+ # that can be achieved while still ignoring unknown arguments.398+ if self.ignore_unknown_options and unknown_options:399+ state.largs.append("{}{}".format(prefix, "".join(unknown_options)))400+401+ def _process_opts(self, arg, state):402+ explicit_value = None403+ # Long option handling happens in two parts. The first part is404+ # supporting explicitly attached values. In any case, we will try405+ # to long match the option first.406+ if "=" in arg:407+ long_opt, explicit_value = arg.split("=", 1)408+ else:409+ long_opt = arg410+ norm_long_opt = normalize_opt(long_opt, self.ctx)411+412+ # At this point we will match the (assumed) long option through413+ # the long option matching code. Note that this allows options414+ # like "-foo" to be matched as long options.415+ try:416+ self._match_long_opt(norm_long_opt, explicit_value, state)417+ except NoSuchOption:418+ # At this point the long option matching failed, and we need419+ # to try with short options. However there is a special rule420+ # which says, that if we have a two character options prefix421+ # (applies to "--foo" for instance), we do not dispatch to the422+ # short option code and will instead raise the no option423+ # error.424+ if arg[:2] not in self._opt_prefixes:425+ return self._match_short_opt(arg, state)426+ if not self.ignore_unknown_options:427+ raise428+ state.largs.append(arg)added:src/click/termui.py+681 added
1+import inspect2+import io3+import itertools4+import os5+import struct6+import sys7+8+from ._compat import DEFAULT_COLUMNS9+from ._compat import get_winterm_size10+from ._compat import isatty11+from ._compat import raw_input12+from ._compat import string_types13+from ._compat import strip_ansi14+from ._compat import text_type15+from ._compat import WIN16+from .exceptions import Abort17+from .exceptions import UsageError18+from .globals import resolve_color_default19+from .types import Choice20+from .types import convert_type21+from .types import Path22+from .utils import echo23+from .utils import LazyFile24+25+# The prompt functions to use. The doc tools currently override these26+# functions to customize how they work.27+visible_prompt_func = raw_input28+29+_ansi_colors = {30+ "black": 30,31+ "red": 31,32+ "green": 32,33+ "yellow": 33,34+ "blue": 34,35+ "magenta": 35,36+ "cyan": 36,37+ "white": 37,38+ "reset": 39,39+ "bright_black": 90,40+ "bright_red": 91,41+ "bright_green": 92,42+ "bright_yellow": 93,43+ "bright_blue": 94,44+ "bright_magenta": 95,45+ "bright_cyan": 96,46+ "bright_white": 97,47+}48+_ansi_reset_all = "\033[0m"49+50+51+def hidden_prompt_func(prompt):52+ import getpass53+54+ return getpass.getpass(prompt)55+56+57+def _build_prompt(58+ text, suffix, show_default=False, default=None, show_choices=True, type=None59+):60+ prompt = text61+ if type is not None and show_choices and isinstance(type, Choice):62+ prompt += " ({})".format(", ".join(map(str, type.choices)))63+ if default is not None and show_default:64+ prompt = "{} [{}]".format(prompt, _format_default(default))65+ return prompt + suffix66+67+68+def _format_default(default):69+ if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):70+ return default.name71+72+ return default73+74+75+def prompt(76+ text,77+ default=None,78+ hide_input=False,79+ confirmation_prompt=False,80+ type=None,81+ value_proc=None,82+ prompt_suffix=": ",83+ show_default=True,84+ err=False,85+ show_choices=True,86+):87+ """Prompts a user for input. This is a convenience function that can88+ be used to prompt a user for input later.89+90+ If the user aborts the input by sending a interrupt signal, this91+ function will catch it and raise a :exc:`Abort` exception.92+93+ .. versionadded:: 7.094+ Added the show_choices parameter.95+96+ .. versionadded:: 6.097+ Added unicode support for cmd.exe on Windows.98+99+ .. versionadded:: 4.0100+ Added the `err` parameter.101+102+ :param text: the text to show for the prompt.103+ :param default: the default value to use if no input happens. If this104+ is not given it will prompt until it's aborted.105+ :param hide_input: if this is set to true then the input value will106+ be hidden.107+ :param confirmation_prompt: asks for confirmation for the value.108+ :param type: the type to use to check the value against.109+ :param value_proc: if this parameter is provided it's a function that110+ is invoked instead of the type conversion to111+ convert a value.112+ :param prompt_suffix: a suffix that should be added to the prompt.113+ :param show_default: shows or hides the default value in the prompt.114+ :param err: if set to true the file defaults to ``stderr`` instead of115+ ``stdout``, the same as with echo.116+ :param show_choices: Show or hide choices if the passed type is a Choice.117+ For example if type is a Choice of either day or week,118+ show_choices is true and text is "Group by" then the119+ prompt will be "Group by (day, week): ".120+ """121+ result = None122+123+ def prompt_func(text):124+ f = hidden_prompt_func if hide_input else visible_prompt_func125+ try:126+ # Write the prompt separately so that we get nice127+ # coloring through colorama on Windows128+ echo(text, nl=False, err=err)129+ return f("")130+ except (KeyboardInterrupt, EOFError):131+ # getpass doesn't print a newline if the user aborts input with ^C.132+ # Allegedly this behavior is inherited from getpass(3).133+ # A doc bug has been filed at https://bugs.python.org/issue24711134+ if hide_input:135+ echo(None, err=err)136+ raise Abort()137+138+ if value_proc is None:139+ value_proc = convert_type(type, default)140+141+ prompt = _build_prompt(142+ text, prompt_suffix, show_default, default, show_choices, type143+ )144+145+ while 1:146+ while 1:147+ value = prompt_func(prompt)148+ if value:149+ break150+ elif default is not None:151+ if isinstance(value_proc, Path):152+ # validate Path default value(exists, dir_okay etc.)153+ value = default154+ break155+ return default156+ try:157+ result = value_proc(value)158+ except UsageError as e:159+ echo("Error: {}".format(e.message), err=err) # noqa: B306160+ continue161+ if not confirmation_prompt:162+ return result163+ while 1:164+ value2 = prompt_func("Repeat for confirmation: ")165+ if value2:166+ break167+ if value == value2:168+ return result169+ echo("Error: the two entered values do not match", err=err)170+171+172+def confirm(173+ text, default=False, abort=False, prompt_suffix=": ", show_default=True, err=False174+):175+ """Prompts for confirmation (yes/no question).176+177+ If the user aborts the input by sending a interrupt signal this178+ function will catch it and raise a :exc:`Abort` exception.179+180+ .. versionadded:: 4.0181+ Added the `err` parameter.182+183+ :param text: the question to ask.184+ :param default: the default for the prompt.185+ :param abort: if this is set to `True` a negative answer aborts the186+ exception by raising :exc:`Abort`.187+ :param prompt_suffix: a suffix that should be added to the prompt.188+ :param show_default: shows or hides the default value in the prompt.189+ :param err: if set to true the file defaults to ``stderr`` instead of190+ ``stdout``, the same as with echo.191+ """192+ prompt = _build_prompt(193+ text, prompt_suffix, show_default, "Y/n" if default else "y/N"194+ )195+ while 1:196+ try:197+ # Write the prompt separately so that we get nice198+ # coloring through colorama on Windows199+ echo(prompt, nl=False, err=err)200+ value = visible_prompt_func("").lower().strip()201+ except (KeyboardInterrupt, EOFError):202+ raise Abort()203+ if value in ("y", "yes"):204+ rv = True205+ elif value in ("n", "no"):206+ rv = False207+ elif value == "":208+ rv = default209+ else:210+ echo("Error: invalid input", err=err)211+ continue212+ break213+ if abort and not rv:214+ raise Abort()215+ return rv216+217+218+def get_terminal_size():219+ """Returns the current size of the terminal as tuple in the form220+ ``(width, height)`` in columns and rows.221+ """222+ # If shutil has get_terminal_size() (Python 3.3 and later) use that223+ if sys.version_info >= (3, 3):224+ import shutil225+226+ shutil_get_terminal_size = getattr(shutil, "get_terminal_size", None)227+ if shutil_get_terminal_size:228+ sz = shutil_get_terminal_size()229+ return sz.columns, sz.lines230+231+ # We provide a sensible default for get_winterm_size() when being invoked232+ # inside a subprocess. Without this, it would not provide a useful input.233+ if get_winterm_size is not None:234+ size = get_winterm_size()235+ if size == (0, 0):236+ return (79, 24)237+ else:238+ return size239+240+ def ioctl_gwinsz(fd):241+ try:242+ import fcntl243+ import termios244+245+ cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))246+ except Exception:247+ return248+ return cr249+250+ cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)251+ if not cr:252+ try:253+ fd = os.open(os.ctermid(), os.O_RDONLY)254+ try:255+ cr = ioctl_gwinsz(fd)256+ finally:257+ os.close(fd)258+ except Exception:259+ pass260+ if not cr or not cr[0] or not cr[1]:261+ cr = (os.environ.get("LINES", 25), os.environ.get("COLUMNS", DEFAULT_COLUMNS))262+ return int(cr[1]), int(cr[0])263+264+265+def echo_via_pager(text_or_generator, color=None):266+ """This function takes a text and shows it via an environment specific267+ pager on stdout.268+269+ .. versionchanged:: 3.0270+ Added the `color` flag.271+272+ :param text_or_generator: the text to page, or alternatively, a273+ generator emitting the text to page.274+ :param color: controls if the pager supports ANSI colors or not. The275+ default is autodetection.276+ """277+ color = resolve_color_default(color)278+279+ if inspect.isgeneratorfunction(text_or_generator):280+ i = text_or_generator()281+ elif isinstance(text_or_generator, string_types):282+ i = [text_or_generator]283+ else:284+ i = iter(text_or_generator)285+286+ # convert every element of i to a text type if necessary287+ text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i)288+289+ from ._termui_impl import pager290+291+ return pager(itertools.chain(text_generator, "\n"), color)292+293+294+def progressbar(295+ iterable=None,296+ length=None,297+ label=None,298+ show_eta=True,299+ show_percent=None,300+ show_pos=False,301+ item_show_func=None,302+ fill_char="#",303+ empty_char="-",304+ bar_template="%(label)s [%(bar)s] %(info)s",305+ info_sep=" ",306+ width=36,307+ file=None,308+ color=None,309+):310+ """This function creates an iterable context manager that can be used311+ to iterate over something while showing a progress bar. It will312+ either iterate over the `iterable` or `length` items (that are counted313+ up). While iteration happens, this function will print a rendered314+ progress bar to the given `file` (defaults to stdout) and will attempt315+ to calculate remaining time and more. By default, this progress bar316+ will not be rendered if the file is not a terminal.317+318+ The context manager creates the progress bar. When the context319+ manager is entered the progress bar is already created. With every320+ iteration over the progress bar, the iterable passed to the bar is321+ advanced and the bar is updated. When the context manager exits,322+ a newline is printed and the progress bar is finalized on screen.323+324+ Note: The progress bar is currently designed for use cases where the325+ total progress can be expected to take at least several seconds.326+ Because of this, the ProgressBar class object won't display327+ progress that is considered too fast, and progress where the time328+ between steps is less than a second.329+330+ No printing must happen or the progress bar will be unintentionally331+ destroyed.332+333+ Example usage::334+335+ with progressbar(items) as bar:336+ for item in bar:337+ do_something_with(item)338+339+ Alternatively, if no iterable is specified, one can manually update the340+ progress bar through the `update()` method instead of directly341+ iterating over the progress bar. The update method accepts the number342+ of steps to increment the bar with::343+344+ with progressbar(length=chunks.total_bytes) as bar:345+ for chunk in chunks:346+ process_chunk(chunk)347+ bar.update(chunks.bytes)348+349+ .. versionadded:: 2.0350+351+ .. versionadded:: 4.0352+ Added the `color` parameter. Added a `update` method to the353+ progressbar object.354+355+ :param iterable: an iterable to iterate over. If not provided the length356+ is required.357+ :param length: the number of items to iterate over. By default the358+ progressbar will attempt to ask the iterator about its359+ length, which might or might not work. If an iterable is360+ also provided this parameter can be used to override the361+ length. If an iterable is not provided the progress bar362+ will iterate over a range of that length.363+ :param label: the label to show next to the progress bar.364+ :param show_eta: enables or disables the estimated time display. This is365+ automatically disabled if the length cannot be366+ determined.367+ :param show_percent: enables or disables the percentage display. The368+ default is `True` if the iterable has a length or369+ `False` if not.370+ :param show_pos: enables or disables the absolute position display. The371+ default is `False`.372+ :param item_show_func: a function called with the current item which373+ can return a string to show the current item374+ next to the progress bar. Note that the current375+ item can be `None`!376+ :param fill_char: the character to use to show the filled part of the377+ progress bar.378+ :param empty_char: the character to use to show the non-filled part of379+ the progress bar.380+ :param bar_template: the format string to use as template for the bar.381+ The parameters in it are ``label`` for the label,382+ ``bar`` for the progress bar and ``info`` for the383+ info section.384+ :param info_sep: the separator between multiple info items (eta etc.)385+ :param width: the width of the progress bar in characters, 0 means full386+ terminal width387+ :param file: the file to write to. If this is not a terminal then388+ only the label is printed.389+ :param color: controls if the terminal supports ANSI colors or not. The390+ default is autodetection. This is only needed if ANSI391+ codes are included anywhere in the progress bar output392+ which is not the case by default.393+ """394+ from ._termui_impl import ProgressBar395+396+ color = resolve_color_default(color)397+ return ProgressBar(398+ iterable=iterable,399+ length=length,400+ show_eta=show_eta,401+ show_percent=show_percent,402+ show_pos=show_pos,403+ item_show_func=item_show_func,404+ fill_char=fill_char,405+ empty_char=empty_char,406+ bar_template=bar_template,407+ info_sep=info_sep,408+ file=file,409+ label=label,410+ width=width,411+ color=color,412+ )413+414+415+def clear():416+ """Clears the terminal screen. This will have the effect of clearing417+ the whole visible space of the terminal and moving the cursor to the418+ top left. This does not do anything if not connected to a terminal.419+420+ .. versionadded:: 2.0421+ """422+ if not isatty(sys.stdout):423+ return424+ # If we're on Windows and we don't have colorama available, then we425+ # clear the screen by shelling out. Otherwise we can use an escape426+ # sequence.427+ if WIN:428+ os.system("cls")429+ else:430+ sys.stdout.write("\033[2J\033[1;1H")431+432+433+def style(434+ text,435+ fg=None,436+ bg=None,437+ bold=None,438+ dim=None,439+ underline=None,440+ blink=None,441+ reverse=None,442+ reset=True,443+):444+ """Styles a text with ANSI styles and returns the new string. By445+ default the styling is self contained which means that at the end446+ of the string a reset code is issued. This can be prevented by447+ passing ``reset=False``.448+449+ Examples::450+451+ click.echo(click.style('Hello World!', fg='green'))452+ click.echo(click.style('ATTENTION!', blink=True))453+ click.echo(click.style('Some things', reverse=True, fg='cyan'))454+455+ Supported color names:456+457+ * ``black`` (might be a gray)458+ * ``red``459+ * ``green``460+ * ``yellow`` (might be an orange)461+ * ``blue``462+ * ``magenta``463+ * ``cyan``464+ * ``white`` (might be light gray)465+ * ``bright_black``466+ * ``bright_red``467+ * ``bright_green``468+ * ``bright_yellow``469+ * ``bright_blue``470+ * ``bright_magenta``471+ * ``bright_cyan``472+ * ``bright_white``473+ * ``reset`` (reset the color code only)474+475+ .. versionadded:: 2.0476+477+ .. versionadded:: 7.0478+ Added support for bright colors.479+480+ :param text: the string to style with ansi codes.481+ :param fg: if provided this will become the foreground color.482+ :param bg: if provided this will become the background color.483+ :param bold: if provided this will enable or disable bold mode.484+ :param dim: if provided this will enable or disable dim mode. This is485+ badly supported.486+ :param underline: if provided this will enable or disable underline.487+ :param blink: if provided this will enable or disable blinking.488+ :param reverse: if provided this will enable or disable inverse489+ rendering (foreground becomes background and the490+ other way round).491+ :param reset: by default a reset-all code is added at the end of the492+ string which means that styles do not carry over. This493+ can be disabled to compose styles.494+ """495+ bits = []496+ if fg:497+ try:498+ bits.append("\033[{}m".format(_ansi_colors[fg]))499+ except KeyError:500+ raise TypeError("Unknown color '{}'".format(fg))501+ if bg:502+ try:503+ bits.append("\033[{}m".format(_ansi_colors[bg] + 10))504+ except KeyError:505+ raise TypeError("Unknown color '{}'".format(bg))506+ if bold is not None:507+ bits.append("\033[{}m".format(1 if bold else 22))508+ if dim is not None:509+ bits.append("\033[{}m".format(2 if dim else 22))510+ if underline is not None:511+ bits.append("\033[{}m".format(4 if underline else 24))512+ if blink is not None:513+ bits.append("\033[{}m".format(5 if blink else 25))514+ if reverse is not None:515+ bits.append("\033[{}m".format(7 if reverse else 27))516+ bits.append(text)517+ if reset:518+ bits.append(_ansi_reset_all)519+ return "".join(bits)520+521+522+def unstyle(text):523+ """Removes ANSI styling information from a string. Usually it's not524+ necessary to use this function as Click's echo function will525+ automatically remove styling if necessary.526+527+ .. versionadded:: 2.0528+529+ :param text: the text to remove style information from.530+ """531+ return strip_ansi(text)532+533+534+def secho(message=None, file=None, nl=True, err=False, color=None, **styles):535+ """This function combines :func:`echo` and :func:`style` into one536+ call. As such the following two calls are the same::537+538+ click.secho('Hello World!', fg='green')539+ click.echo(click.style('Hello World!', fg='green'))540+541+ All keyword arguments are forwarded to the underlying functions542+ depending on which one they go with.543+544+ .. versionadded:: 2.0545+ """546+ if message is not None:547+ message = style(message, **styles)548+ return echo(message, file=file, nl=nl, err=err, color=color)549+550+551+def edit(552+ text=None, editor=None, env=None, require_save=True, extension=".txt", filename=None553+):554+ r"""Edits the given text in the defined editor. If an editor is given555+ (should be the full path to the executable but the regular operating556+ system search path is used for finding the executable) it overrides557+ the detected editor. Optionally, some environment variables can be558+ used. If the editor is closed without changes, `None` is returned. In559+ case a file is edited directly the return value is always `None` and560+ `require_save` and `extension` are ignored.561+562+ If the editor cannot be opened a :exc:`UsageError` is raised.563+564+ Note for Windows: to simplify cross-platform usage, the newlines are565+ automatically converted from POSIX to Windows and vice versa. As such,566+ the message here will have ``\n`` as newline markers.567+568+ :param text: the text to edit.569+ :param editor: optionally the editor to use. Defaults to automatic570+ detection.571+ :param env: environment variables to forward to the editor.572+ :param require_save: if this is true, then not saving in the editor573+ will make the return value become `None`.574+ :param extension: the extension to tell the editor about. This defaults575+ to `.txt` but changing this might change syntax576+ highlighting.577+ :param filename: if provided it will edit this file instead of the578+ provided text contents. It will not use a temporary579+ file as an indirection in that case.580+ """581+ from ._termui_impl import Editor582+583+ editor = Editor(584+ editor=editor, env=env, require_save=require_save, extension=extension585+ )586+ if filename is None:587+ return editor.edit(text)588+ editor.edit_file(filename)589+590+591+def launch(url, wait=False, locate=False):592+ """This function launches the given URL (or filename) in the default593+ viewer application for this file type. If this is an executable, it594+ might launch the executable in a new session. The return value is595+ the exit code of the launched application. Usually, ``0`` indicates596+ success.597+598+ Examples::599+600+ click.launch('https://click.palletsprojects.com/')601+ click.launch('/my/downloaded/file', locate=True)602+603+ .. versionadded:: 2.0604+605+ :param url: URL or filename of the thing to launch.606+ :param wait: waits for the program to stop.607+ :param locate: if this is set to `True` then instead of launching the608+ application associated with the URL it will attempt to609+ launch a file manager with the file located. This610+ might have weird effects if the URL does not point to611+ the filesystem.612+ """613+ from ._termui_impl import open_url614+615+ return open_url(url, wait=wait, locate=locate)616+617+618+# If this is provided, getchar() calls into this instead. This is used619+# for unittesting purposes.620+_getchar = None621+622+623+def getchar(echo=False):624+ """Fetches a single character from the terminal and returns it. This625+ will always return a unicode character and under certain rare626+ circumstances this might return more than one character. The627+ situations which more than one character is returned is when for628+ whatever reason multiple characters end up in the terminal buffer or629+ standard input was not actually a terminal.630+631+ Note that this will always read from the terminal, even if something632+ is piped into the standard input.633+634+ Note for Windows: in rare cases when typing non-ASCII characters, this635+ function might wait for a second character and then return both at once.636+ This is because certain Unicode characters look like special-key markers.637+638+ .. versionadded:: 2.0639+640+ :param echo: if set to `True`, the character read will also show up on641+ the terminal. The default is to not show it.642+ """643+ f = _getchar644+ if f is None:645+ from ._termui_impl import getchar as f646+ return f(echo)647+648+649+def raw_terminal():650+ from ._termui_impl import raw_terminal as f651+652+ return f()653+654+655+def pause(info="Press any key to continue ...", err=False):656+ """This command stops execution and waits for the user to press any657+ key to continue. This is similar to the Windows batch "pause"658+ command. If the program is not run through a terminal, this command659+ will instead do nothing.660+661+ .. versionadded:: 2.0662+663+ .. versionadded:: 4.0664+ Added the `err` parameter.665+666+ :param info: the info string to print before pausing.667+ :param err: if set to message goes to ``stderr`` instead of668+ ``stdout``, the same as with echo.669+ """670+ if not isatty(sys.stdin) or not isatty(sys.stdout):671+ return672+ try:673+ if info:674+ echo(info, nl=False, err=err)675+ try:676+ getchar()677+ except (KeyboardInterrupt, EOFError):678+ pass679+ finally:680+ if info:681+ echo(err=err)added:src/click/testing.py+382 added
1+import contextlib2+import os3+import shlex4+import shutil5+import sys6+import tempfile7+8+from . import formatting9+from . import termui10+from . import utils11+from ._compat import iteritems12+from ._compat import PY213+from ._compat import string_types14+15+16+if PY2:17+ from cStringIO import StringIO18+else:19+ import io20+ from ._compat import _find_binary_reader21+22+23+class EchoingStdin(object):24+ def __init__(self, input, output):25+ self._input = input26+ self._output = output27+28+ def __getattr__(self, x):29+ return getattr(self._input, x)30+31+ def _echo(self, rv):32+ self._output.write(rv)33+ return rv34+35+ def read(self, n=-1):36+ return self._echo(self._input.read(n))37+38+ def readline(self, n=-1):39+ return self._echo(self._input.readline(n))40+41+ def readlines(self):42+ return [self._echo(x) for x in self._input.readlines()]43+44+ def __iter__(self):45+ return iter(self._echo(x) for x in self._input)46+47+ def __repr__(self):48+ return repr(self._input)49+50+51+def make_input_stream(input, charset):52+ # Is already an input stream.53+ if hasattr(input, "read"):54+ if PY2:55+ return input56+ rv = _find_binary_reader(input)57+ if rv is not None:58+ return rv59+ raise TypeError("Could not find binary reader for input stream.")60+61+ if input is None:62+ input = b""63+ elif not isinstance(input, bytes):64+ input = input.encode(charset)65+ if PY2:66+ return StringIO(input)67+ return io.BytesIO(input)68+69+70+class Result(object):71+ """Holds the captured result of an invoked CLI script."""72+73+ def __init__(74+ self, runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None75+ ):76+ #: The runner that created the result77+ self.runner = runner78+ #: The standard output as bytes.79+ self.stdout_bytes = stdout_bytes80+ #: The standard error as bytes, or None if not available81+ self.stderr_bytes = stderr_bytes82+ #: The exit code as integer.83+ self.exit_code = exit_code84+ #: The exception that happened if one did.85+ self.exception = exception86+ #: The traceback87+ self.exc_info = exc_info88+89+ @property90+ def output(self):91+ """The (standard) output as unicode string."""92+ return self.stdout93+94+ @property95+ def stdout(self):96+ """The standard output as unicode string."""97+ return self.stdout_bytes.decode(self.runner.charset, "replace").replace(98+ "\r\n", "\n"99+ )100+101+ @property102+ def stderr(self):103+ """The standard error as unicode string."""104+ if self.stderr_bytes is None:105+ raise ValueError("stderr not separately captured")106+ return self.stderr_bytes.decode(self.runner.charset, "replace").replace(107+ "\r\n", "\n"108+ )109+110+ def __repr__(self):111+ return "<{} {}>".format(112+ type(self).__name__, repr(self.exception) if self.exception else "okay"113+ )114+115+116+class CliRunner(object):117+ """The CLI runner provides functionality to invoke a Click command line118+ script for unittesting purposes in a isolated environment. This only119+ works in single-threaded systems without any concurrency as it changes the120+ global interpreter state.121+122+ :param charset: the character set for the input and output data. This is123+ UTF-8 by default and should not be changed currently as124+ the reporting to Click only works in Python 2 properly.125+ :param env: a dictionary with environment variables for overriding.126+ :param echo_stdin: if this is set to `True`, then reading from stdin writes127+ to stdout. This is useful for showing examples in128+ some circumstances. Note that regular prompts129+ will automatically echo the input.130+ :param mix_stderr: if this is set to `False`, then stdout and stderr are131+ preserved as independent streams. This is useful for132+ Unix-philosophy apps that have predictable stdout and133+ noisy stderr, such that each may be measured134+ independently135+ """136+137+ def __init__(self, charset=None, env=None, echo_stdin=False, mix_stderr=True):138+ if charset is None:139+ charset = "utf-8"140+ self.charset = charset141+ self.env = env or {}142+ self.echo_stdin = echo_stdin143+ self.mix_stderr = mix_stderr144+145+ def get_default_prog_name(self, cli):146+ """Given a command object it will return the default program name147+ for it. The default is the `name` attribute or ``"root"`` if not148+ set.149+ """150+ return cli.name or "root"151+152+ def make_env(self, overrides=None):153+ """Returns the environment overrides for invoking a script."""154+ rv = dict(self.env)155+ if overrides:156+ rv.update(overrides)157+ return rv158+159+ @contextlib.contextmanager160+ def isolation(self, input=None, env=None, color=False):161+ """A context manager that sets up the isolation for invoking of a162+ command line tool. This sets up stdin with the given input data163+ and `os.environ` with the overrides from the given dictionary.164+ This also rebinds some internals in Click to be mocked (like the165+ prompt functionality).166+167+ This is automatically done in the :meth:`invoke` method.168+169+ .. versionadded:: 4.0170+ The ``color`` parameter was added.171+172+ :param input: the input stream to put into sys.stdin.173+ :param env: the environment overrides as dictionary.174+ :param color: whether the output should contain color codes. The175+ application can still override this explicitly.176+ """177+ input = make_input_stream(input, self.charset)178+179+ old_stdin = sys.stdin180+ old_stdout = sys.stdout181+ old_stderr = sys.stderr182+ old_forced_width = formatting.FORCED_WIDTH183+ formatting.FORCED_WIDTH = 80184+185+ env = self.make_env(env)186+187+ if PY2:188+ bytes_output = StringIO()189+ if self.echo_stdin:190+ input = EchoingStdin(input, bytes_output)191+ sys.stdout = bytes_output192+ if not self.mix_stderr:193+ bytes_error = StringIO()194+ sys.stderr = bytes_error195+ else:196+ bytes_output = io.BytesIO()197+ if self.echo_stdin:198+ input = EchoingStdin(input, bytes_output)199+ input = io.TextIOWrapper(input, encoding=self.charset)200+ sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)201+ if not self.mix_stderr:202+ bytes_error = io.BytesIO()203+ sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)204+205+ if self.mix_stderr:206+ sys.stderr = sys.stdout207+208+ sys.stdin = input209+210+ def visible_input(prompt=None):211+ sys.stdout.write(prompt or "")212+ val = input.readline().rstrip("\r\n")213+ sys.stdout.write("{}\n".format(val))214+ sys.stdout.flush()215+ return val216+217+ def hidden_input(prompt=None):218+ sys.stdout.write("{}\n".format(prompt or ""))219+ sys.stdout.flush()220+ return input.readline().rstrip("\r\n")221+222+ def _getchar(echo):223+ char = sys.stdin.read(1)224+ if echo:225+ sys.stdout.write(char)226+ sys.stdout.flush()227+ return char228+229+ default_color = color230+231+ def should_strip_ansi(stream=None, color=None):232+ if color is None:233+ return not default_color234+ return not color235+236+ old_visible_prompt_func = termui.visible_prompt_func237+ old_hidden_prompt_func = termui.hidden_prompt_func238+ old__getchar_func = termui._getchar239+ old_should_strip_ansi = utils.should_strip_ansi240+ termui.visible_prompt_func = visible_input241+ termui.hidden_prompt_func = hidden_input242+ termui._getchar = _getchar243+ utils.should_strip_ansi = should_strip_ansi244+245+ old_env = {}246+ try:247+ for key, value in iteritems(env):248+ old_env[key] = os.environ.get(key)249+ if value is None:250+ try:251+ del os.environ[key]252+ except Exception:253+ pass254+ else:255+ os.environ[key] = value256+ yield (bytes_output, not self.mix_stderr and bytes_error)257+ finally:258+ for key, value in iteritems(old_env):259+ if value is None:260+ try:261+ del os.environ[key]262+ except Exception:263+ pass264+ else:265+ os.environ[key] = value266+ sys.stdout = old_stdout267+ sys.stderr = old_stderr268+ sys.stdin = old_stdin269+ termui.visible_prompt_func = old_visible_prompt_func270+ termui.hidden_prompt_func = old_hidden_prompt_func271+ termui._getchar = old__getchar_func272+ utils.should_strip_ansi = old_should_strip_ansi273+ formatting.FORCED_WIDTH = old_forced_width274+275+ def invoke(276+ self,277+ cli,278+ args=None,279+ input=None,280+ env=None,281+ catch_exceptions=True,282+ color=False,283+ **extra284+ ):285+ """Invokes a command in an isolated environment. The arguments are286+ forwarded directly to the command line script, the `extra` keyword287+ arguments are passed to the :meth:`~clickpkg.Command.main` function of288+ the command.289+290+ This returns a :class:`Result` object.291+292+ .. versionadded:: 3.0293+ The ``catch_exceptions`` parameter was added.294+295+ .. versionchanged:: 3.0296+ The result object now has an `exc_info` attribute with the297+ traceback if available.298+299+ .. versionadded:: 4.0300+ The ``color`` parameter was added.301+302+ :param cli: the command to invoke303+ :param args: the arguments to invoke. It may be given as an iterable304+ or a string. When given as string it will be interpreted305+ as a Unix shell command. More details at306+ :func:`shlex.split`.307+ :param input: the input data for `sys.stdin`.308+ :param env: the environment overrides.309+ :param catch_exceptions: Whether to catch any other exceptions than310+ ``SystemExit``.311+ :param extra: the keyword arguments to pass to :meth:`main`.312+ :param color: whether the output should contain color codes. The313+ application can still override this explicitly.314+ """315+ exc_info = None316+ with self.isolation(input=input, env=env, color=color) as outstreams:317+ exception = None318+ exit_code = 0319+320+ if isinstance(args, string_types):321+ args = shlex.split(args)322+323+ try:324+ prog_name = extra.pop("prog_name")325+ except KeyError:326+ prog_name = self.get_default_prog_name(cli)327+328+ try:329+ cli.main(args=args or (), prog_name=prog_name, **extra)330+ except SystemExit as e:331+ exc_info = sys.exc_info()332+ exit_code = e.code333+ if exit_code is None:334+ exit_code = 0335+336+ if exit_code != 0:337+ exception = e338+339+ if not isinstance(exit_code, int):340+ sys.stdout.write(str(exit_code))341+ sys.stdout.write("\n")342+ exit_code = 1343+344+ except Exception as e:345+ if not catch_exceptions:346+ raise347+ exception = e348+ exit_code = 1349+ exc_info = sys.exc_info()350+ finally:351+ sys.stdout.flush()352+ stdout = outstreams[0].getvalue()353+ if self.mix_stderr:354+ stderr = None355+ else:356+ stderr = outstreams[1].getvalue()357+358+ return Result(359+ runner=self,360+ stdout_bytes=stdout,361+ stderr_bytes=stderr,362+ exit_code=exit_code,363+ exception=exception,364+ exc_info=exc_info,365+ )366+367+ @contextlib.contextmanager368+ def isolated_filesystem(self):369+ """A context manager that creates a temporary folder and changes370+ the current working directory to it for isolated filesystem tests.371+ """372+ cwd = os.getcwd()373+ t = tempfile.mkdtemp()374+ os.chdir(t)375+ try:376+ yield t377+ finally:378+ os.chdir(cwd)379+ try:380+ shutil.rmtree(t)381+ except (OSError, IOError): # noqa: B014382+ passadded:src/click/types.py+762 added
1+import os2+import stat3+from datetime import datetime4+5+from ._compat import _get_argv_encoding6+from ._compat import filename_to_ui7+from ._compat import get_filesystem_encoding8+from ._compat import get_streerror9+from ._compat import open_stream10+from ._compat import PY211+from ._compat import text_type12+from .exceptions import BadParameter13+from .utils import LazyFile14+from .utils import safecall15+16+17+class ParamType(object):18+ """Helper for converting values through types. The following is19+ necessary for a valid type:20+21+ * it needs a name22+ * it needs to pass through None unchanged23+ * it needs to convert from a string24+ * it needs to convert its result type through unchanged25+ (eg: needs to be idempotent)26+ * it needs to be able to deal with param and context being `None`.27+ This can be the case when the object is used with prompt28+ inputs.29+ """30+31+ is_composite = False32+33+ #: the descriptive name of this type34+ name = None35+36+ #: if a list of this type is expected and the value is pulled from a37+ #: string environment variable, this is what splits it up. `None`38+ #: means any whitespace. For all parameters the general rule is that39+ #: whitespace splits them up. The exception are paths and files which40+ #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on41+ #: Windows).42+ envvar_list_splitter = None43+44+ def __call__(self, value, param=None, ctx=None):45+ if value is not None:46+ return self.convert(value, param, ctx)47+48+ def get_metavar(self, param):49+ """Returns the metavar default for this param if it provides one."""50+51+ def get_missing_message(self, param):52+ """Optionally might return extra information about a missing53+ parameter.54+55+ .. versionadded:: 2.056+ """57+58+ def convert(self, value, param, ctx):59+ """Converts the value. This is not invoked for values that are60+ `None` (the missing value).61+ """62+ return value63+64+ def split_envvar_value(self, rv):65+ """Given a value from an environment variable this splits it up66+ into small chunks depending on the defined envvar list splitter.67+68+ If the splitter is set to `None`, which means that whitespace splits,69+ then leading and trailing whitespace is ignored. Otherwise, leading70+ and trailing splitters usually lead to empty items being included.71+ """72+ return (rv or "").split(self.envvar_list_splitter)73+74+ def fail(self, message, param=None, ctx=None):75+ """Helper method to fail with an invalid value message."""76+ raise BadParameter(message, ctx=ctx, param=param)77+78+79+class CompositeParamType(ParamType):80+ is_composite = True81+82+ @property83+ def arity(self):84+ raise NotImplementedError()85+86+87+class FuncParamType(ParamType):88+ def __init__(self, func):89+ self.name = func.__name__90+ self.func = func91+92+ def convert(self, value, param, ctx):93+ try:94+ return self.func(value)95+ except ValueError:96+ try:97+ value = text_type(value)98+ except UnicodeError:99+ value = str(value).decode("utf-8", "replace")100+ self.fail(value, param, ctx)101+102+103+class UnprocessedParamType(ParamType):104+ name = "text"105+106+ def convert(self, value, param, ctx):107+ return value108+109+ def __repr__(self):110+ return "UNPROCESSED"111+112+113+class StringParamType(ParamType):114+ name = "text"115+116+ def convert(self, value, param, ctx):117+ if isinstance(value, bytes):118+ enc = _get_argv_encoding()119+ try:120+ value = value.decode(enc)121+ except UnicodeError:122+ fs_enc = get_filesystem_encoding()123+ if fs_enc != enc:124+ try:125+ value = value.decode(fs_enc)126+ except UnicodeError:127+ value = value.decode("utf-8", "replace")128+ else:129+ value = value.decode("utf-8", "replace")130+ return value131+ return value132+133+ def __repr__(self):134+ return "STRING"135+136+137+class Choice(ParamType):138+ """The choice type allows a value to be checked against a fixed set139+ of supported values. All of these values have to be strings.140+141+ You should only pass a list or tuple of choices. Other iterables142+ (like generators) may lead to surprising results.143+144+ The resulting value will always be one of the originally passed choices145+ regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``146+ being specified.147+148+ See :ref:`choice-opts` for an example.149+150+ :param case_sensitive: Set to false to make choices case151+ insensitive. Defaults to true.152+ """153+154+ name = "choice"155+156+ def __init__(self, choices, case_sensitive=True):157+ self.choices = choices158+ self.case_sensitive = case_sensitive159+160+ def get_metavar(self, param):161+ return "[{}]".format("|".join(self.choices))162+163+ def get_missing_message(self, param):164+ return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))165+166+ def convert(self, value, param, ctx):167+ # Match through normalization and case sensitivity168+ # first do token_normalize_func, then lowercase169+ # preserve original `value` to produce an accurate message in170+ # `self.fail`171+ normed_value = value172+ normed_choices = {choice: choice for choice in self.choices}173+174+ if ctx is not None and ctx.token_normalize_func is not None:175+ normed_value = ctx.token_normalize_func(value)176+ normed_choices = {177+ ctx.token_normalize_func(normed_choice): original178+ for normed_choice, original in normed_choices.items()179+ }180+181+ if not self.case_sensitive:182+ if PY2:183+ lower = str.lower184+ else:185+ lower = str.casefold186+187+ normed_value = lower(normed_value)188+ normed_choices = {189+ lower(normed_choice): original190+ for normed_choice, original in normed_choices.items()191+ }192+193+ if normed_value in normed_choices:194+ return normed_choices[normed_value]195+196+ self.fail(197+ "invalid choice: {}. (choose from {})".format(198+ value, ", ".join(self.choices)199+ ),200+ param,201+ ctx,202+ )203+204+ def __repr__(self):205+ return "Choice('{}')".format(list(self.choices))206+207+208+class DateTime(ParamType):209+ """The DateTime type converts date strings into `datetime` objects.210+211+ The format strings which are checked are configurable, but default to some212+ common (non-timezone aware) ISO 8601 formats.213+214+ When specifying *DateTime* formats, you should only pass a list or a tuple.215+ Other iterables, like generators, may lead to surprising results.216+217+ The format strings are processed using ``datetime.strptime``, and this218+ consequently defines the format strings which are allowed.219+220+ Parsing is tried using each format, in order, and the first format which221+ parses successfully is used.222+223+ :param formats: A list or tuple of date format strings, in the order in224+ which they should be tried. Defaults to225+ ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,226+ ``'%Y-%m-%d %H:%M:%S'``.227+ """228+229+ name = "datetime"230+231+ def __init__(self, formats=None):232+ self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]233+234+ def get_metavar(self, param):235+ return "[{}]".format("|".join(self.formats))236+237+ def _try_to_convert_date(self, value, format):238+ try:239+ return datetime.strptime(value, format)240+ except ValueError:241+ return None242+243+ def convert(self, value, param, ctx):244+ # Exact match245+ for format in self.formats:246+ dtime = self._try_to_convert_date(value, format)247+ if dtime:248+ return dtime249+250+ self.fail(251+ "invalid datetime format: {}. (choose from {})".format(252+ value, ", ".join(self.formats)253+ )254+ )255+256+ def __repr__(self):257+ return "DateTime"258+259+260+class IntParamType(ParamType):261+ name = "integer"262+263+ def convert(self, value, param, ctx):264+ try:265+ return int(value)266+ except ValueError:267+ self.fail("{} is not a valid integer".format(value), param, ctx)268+269+ def __repr__(self):270+ return "INT"271+272+273+class IntRange(IntParamType):274+ """A parameter that works similar to :data:`click.INT` but restricts275+ the value to fit into a range. The default behavior is to fail if the276+ value falls outside the range, but it can also be silently clamped277+ between the two edges.278+279+ See :ref:`ranges` for an example.280+ """281+282+ name = "integer range"283+284+ def __init__(self, min=None, max=None, clamp=False):285+ self.min = min286+ self.max = max287+ self.clamp = clamp288+289+ def convert(self, value, param, ctx):290+ rv = IntParamType.convert(self, value, param, ctx)291+ if self.clamp:292+ if self.min is not None and rv < self.min:293+ return self.min294+ if self.max is not None and rv > self.max:295+ return self.max296+ if (297+ self.min is not None298+ and rv < self.min299+ or self.max is not None300+ and rv > self.max301+ ):302+ if self.min is None:303+ self.fail(304+ "{} is bigger than the maximum valid value {}.".format(305+ rv, self.max306+ ),307+ param,308+ ctx,309+ )310+ elif self.max is None:311+ self.fail(312+ "{} is smaller than the minimum valid value {}.".format(313+ rv, self.min314+ ),315+ param,316+ ctx,317+ )318+ else:319+ self.fail(320+ "{} is not in the valid range of {} to {}.".format(321+ rv, self.min, self.max322+ ),323+ param,324+ ctx,325+ )326+ return rv327+328+ def __repr__(self):329+ return "IntRange({}, {})".format(self.min, self.max)330+331+332+class FloatParamType(ParamType):333+ name = "float"334+335+ def convert(self, value, param, ctx):336+ try:337+ return float(value)338+ except ValueError:339+ self.fail(340+ "{} is not a valid floating point value".format(value), param, ctx341+ )342+343+ def __repr__(self):344+ return "FLOAT"345+346+347+class FloatRange(FloatParamType):348+ """A parameter that works similar to :data:`click.FLOAT` but restricts349+ the value to fit into a range. The default behavior is to fail if the350+ value falls outside the range, but it can also be silently clamped351+ between the two edges.352+353+ See :ref:`ranges` for an example.354+ """355+356+ name = "float range"357+358+ def __init__(self, min=None, max=None, clamp=False):359+ self.min = min360+ self.max = max361+ self.clamp = clamp362+363+ def convert(self, value, param, ctx):364+ rv = FloatParamType.convert(self, value, param, ctx)365+ if self.clamp:366+ if self.min is not None and rv < self.min:367+ return self.min368+ if self.max is not None and rv > self.max:369+ return self.max370+ if (371+ self.min is not None372+ and rv < self.min373+ or self.max is not None374+ and rv > self.max375+ ):376+ if self.min is None:377+ self.fail(378+ "{} is bigger than the maximum valid value {}.".format(379+ rv, self.max380+ ),381+ param,382+ ctx,383+ )384+ elif self.max is None:385+ self.fail(386+ "{} is smaller than the minimum valid value {}.".format(387+ rv, self.min388+ ),389+ param,390+ ctx,391+ )392+ else:393+ self.fail(394+ "{} is not in the valid range of {} to {}.".format(395+ rv, self.min, self.max396+ ),397+ param,398+ ctx,399+ )400+ return rv401+402+ def __repr__(self):403+ return "FloatRange({}, {})".format(self.min, self.max)404+405+406+class BoolParamType(ParamType):407+ name = "boolean"408+409+ def convert(self, value, param, ctx):410+ if isinstance(value, bool):411+ return bool(value)412+ value = value.lower()413+ if value in ("true", "t", "1", "yes", "y"):414+ return True415+ elif value in ("false", "f", "0", "no", "n"):416+ return False417+ self.fail("{} is not a valid boolean".format(value), param, ctx)418+419+ def __repr__(self):420+ return "BOOL"421+422+423+class UUIDParameterType(ParamType):424+ name = "uuid"425+426+ def convert(self, value, param, ctx):427+ import uuid428+429+ try:430+ if PY2 and isinstance(value, text_type):431+ value = value.encode("ascii")432+ return uuid.UUID(value)433+ except ValueError:434+ self.fail("{} is not a valid UUID value".format(value), param, ctx)435+436+ def __repr__(self):437+ return "UUID"438+439+440+class File(ParamType):441+ """Declares a parameter to be a file for reading or writing. The file442+ is automatically closed once the context tears down (after the command443+ finished working).444+445+ Files can be opened for reading or writing. The special value ``-``446+ indicates stdin or stdout depending on the mode.447+448+ By default, the file is opened for reading text data, but it can also be449+ opened in binary mode or for writing. The encoding parameter can be used450+ to force a specific encoding.451+452+ The `lazy` flag controls if the file should be opened immediately or upon453+ first IO. The default is to be non-lazy for standard input and output454+ streams as well as files opened for reading, `lazy` otherwise. When opening a455+ file lazily for reading, it is still opened temporarily for validation, but456+ will not be held open until first IO. lazy is mainly useful when opening457+ for writing to avoid creating the file until it is needed.458+459+ Starting with Click 2.0, files can also be opened atomically in which460+ case all writes go into a separate file in the same folder and upon461+ completion the file will be moved over to the original location. This462+ is useful if a file regularly read by other users is modified.463+464+ See :ref:`file-args` for more information.465+ """466+467+ name = "filename"468+ envvar_list_splitter = os.path.pathsep469+470+ def __init__(471+ self, mode="r", encoding=None, errors="strict", lazy=None, atomic=False472+ ):473+ self.mode = mode474+ self.encoding = encoding475+ self.errors = errors476+ self.lazy = lazy477+ self.atomic = atomic478+479+ def resolve_lazy_flag(self, value):480+ if self.lazy is not None:481+ return self.lazy482+ if value == "-":483+ return False484+ elif "w" in self.mode:485+ return True486+ return False487+488+ def convert(self, value, param, ctx):489+ try:490+ if hasattr(value, "read") or hasattr(value, "write"):491+ return value492+493+ lazy = self.resolve_lazy_flag(value)494+495+ if lazy:496+ f = LazyFile(497+ value, self.mode, self.encoding, self.errors, atomic=self.atomic498+ )499+ if ctx is not None:500+ ctx.call_on_close(f.close_intelligently)501+ return f502+503+ f, should_close = open_stream(504+ value, self.mode, self.encoding, self.errors, atomic=self.atomic505+ )506+ # If a context is provided, we automatically close the file507+ # at the end of the context execution (or flush out). If a508+ # context does not exist, it's the caller's responsibility to509+ # properly close the file. This for instance happens when the510+ # type is used with prompts.511+ if ctx is not None:512+ if should_close:513+ ctx.call_on_close(safecall(f.close))514+ else:515+ ctx.call_on_close(safecall(f.flush))516+ return f517+ except (IOError, OSError) as e: # noqa: B014518+ self.fail(519+ "Could not open file: {}: {}".format(520+ filename_to_ui(value), get_streerror(e)521+ ),522+ param,523+ ctx,524+ )525+526+527+class Path(ParamType):528+ """The path type is similar to the :class:`File` type but it performs529+ different checks. First of all, instead of returning an open file530+ handle it returns just the filename. Secondly, it can perform various531+ basic checks about what the file or directory should be.532+533+ .. versionchanged:: 6.0534+ `allow_dash` was added.535+536+ :param exists: if set to true, the file or directory needs to exist for537+ this value to be valid. If this is not required and a538+ file does indeed not exist, then all further checks are539+ silently skipped.540+ :param file_okay: controls if a file is a possible value.541+ :param dir_okay: controls if a directory is a possible value.542+ :param writable: if true, a writable check is performed.543+ :param readable: if true, a readable check is performed.544+ :param resolve_path: if this is true, then the path is fully resolved545+ before the value is passed onwards. This means546+ that it's absolute and symlinks are resolved. It547+ will not expand a tilde-prefix, as this is548+ supposed to be done by the shell only.549+ :param allow_dash: If this is set to `True`, a single dash to indicate550+ standard streams is permitted.551+ :param path_type: optionally a string type that should be used to552+ represent the path. The default is `None` which553+ means the return value will be either bytes or554+ unicode depending on what makes most sense given the555+ input data Click deals with.556+ """557+558+ envvar_list_splitter = os.path.pathsep559+560+ def __init__(561+ self,562+ exists=False,563+ file_okay=True,564+ dir_okay=True,565+ writable=False,566+ readable=True,567+ resolve_path=False,568+ allow_dash=False,569+ path_type=None,570+ ):571+ self.exists = exists572+ self.file_okay = file_okay573+ self.dir_okay = dir_okay574+ self.writable = writable575+ self.readable = readable576+ self.resolve_path = resolve_path577+ self.allow_dash = allow_dash578+ self.type = path_type579+580+ if self.file_okay and not self.dir_okay:581+ self.name = "file"582+ self.path_type = "File"583+ elif self.dir_okay and not self.file_okay:584+ self.name = "directory"585+ self.path_type = "Directory"586+ else:587+ self.name = "path"588+ self.path_type = "Path"589+590+ def coerce_path_result(self, rv):591+ if self.type is not None and not isinstance(rv, self.type):592+ if self.type is text_type:593+ rv = rv.decode(get_filesystem_encoding())594+ else:595+ rv = rv.encode(get_filesystem_encoding())596+ return rv597+598+ def convert(self, value, param, ctx):599+ rv = value600+601+ is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")602+603+ if not is_dash:604+ if self.resolve_path:605+ rv = os.path.realpath(rv)606+607+ try:608+ st = os.stat(rv)609+ except OSError:610+ if not self.exists:611+ return self.coerce_path_result(rv)612+ self.fail(613+ "{} '{}' does not exist.".format(614+ self.path_type, filename_to_ui(value)615+ ),616+ param,617+ ctx,618+ )619+620+ if not self.file_okay and stat.S_ISREG(st.st_mode):621+ self.fail(622+ "{} '{}' is a file.".format(self.path_type, filename_to_ui(value)),623+ param,624+ ctx,625+ )626+ if not self.dir_okay and stat.S_ISDIR(st.st_mode):627+ self.fail(628+ "{} '{}' is a directory.".format(629+ self.path_type, filename_to_ui(value)630+ ),631+ param,632+ ctx,633+ )634+ if self.writable and not os.access(value, os.W_OK):635+ self.fail(636+ "{} '{}' is not writable.".format(637+ self.path_type, filename_to_ui(value)638+ ),639+ param,640+ ctx,641+ )642+ if self.readable and not os.access(value, os.R_OK):643+ self.fail(644+ "{} '{}' is not readable.".format(645+ self.path_type, filename_to_ui(value)646+ ),647+ param,648+ ctx,649+ )650+651+ return self.coerce_path_result(rv)652+653+654+class Tuple(CompositeParamType):655+ """The default behavior of Click is to apply a type on a value directly.656+ This works well in most cases, except for when `nargs` is set to a fixed657+ count and different types should be used for different items. In this658+ case the :class:`Tuple` type can be used. This type can only be used659+ if `nargs` is set to a fixed number.660+661+ For more information see :ref:`tuple-type`.662+663+ This can be selected by using a Python tuple literal as a type.664+665+ :param types: a list of types that should be used for the tuple items.666+ """667+668+ def __init__(self, types):669+ self.types = [convert_type(ty) for ty in types]670+671+ @property672+ def name(self):673+ return "<{}>".format(" ".join(ty.name for ty in self.types))674+675+ @property676+ def arity(self):677+ return len(self.types)678+679+ def convert(self, value, param, ctx):680+ if len(value) != len(self.types):681+ raise TypeError(682+ "It would appear that nargs is set to conflict with the"683+ " composite type arity."684+ )685+ return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))686+687+688+def convert_type(ty, default=None):689+ """Converts a callable or python type into the most appropriate690+ param type.691+ """692+ guessed_type = False693+ if ty is None and default is not None:694+ if isinstance(default, tuple):695+ ty = tuple(map(type, default))696+ else:697+ ty = type(default)698+ guessed_type = True699+700+ if isinstance(ty, tuple):701+ return Tuple(ty)702+ if isinstance(ty, ParamType):703+ return ty704+ if ty is text_type or ty is str or ty is None:705+ return STRING706+ if ty is int:707+ return INT708+ # Booleans are only okay if not guessed. This is done because for709+ # flags the default value is actually a bit of a lie in that it710+ # indicates which of the flags is the one we want. See get_default()711+ # for more information.712+ if ty is bool and not guessed_type:713+ return BOOL714+ if ty is float:715+ return FLOAT716+ if guessed_type:717+ return STRING718+719+ # Catch a common mistake720+ if __debug__:721+ try:722+ if issubclass(ty, ParamType):723+ raise AssertionError(724+ "Attempted to use an uninstantiated parameter type ({}).".format(ty)725+ )726+ except TypeError:727+ pass728+ return FuncParamType(ty)729+730+731+#: A dummy parameter type that just does nothing. From a user's732+#: perspective this appears to just be the same as `STRING` but internally733+#: no string conversion takes place. This is necessary to achieve the734+#: same bytes/unicode behavior on Python 2/3 in situations where you want735+#: to not convert argument types. This is usually useful when working736+#: with file paths as they can appear in bytes and unicode.737+#:738+#: For path related uses the :class:`Path` type is a better choice but739+#: there are situations where an unprocessed type is useful which is why740+#: it is is provided.741+#:742+#: .. versionadded:: 4.0743+UNPROCESSED = UnprocessedParamType()744+745+#: A unicode string parameter type which is the implicit default. This746+#: can also be selected by using ``str`` as type.747+STRING = StringParamType()748+749+#: An integer parameter. This can also be selected by using ``int`` as750+#: type.751+INT = IntParamType()752+753+#: A floating point value parameter. This can also be selected by using754+#: ``float`` as type.755+FLOAT = FloatParamType()756+757+#: A boolean parameter. This is the default for boolean flags. This can758+#: also be selected by using ``bool`` as a type.759+BOOL = BoolParamType()760+761+#: A UUID parameter.762+UUID = UUIDParameterType()added:src/click/utils.py+455 added
1+import os2+import sys3+4+from ._compat import _default_text_stderr5+from ._compat import _default_text_stdout6+from ._compat import auto_wrap_for_ansi7+from ._compat import binary_streams8+from ._compat import filename_to_ui9+from ._compat import get_filesystem_encoding10+from ._compat import get_streerror11+from ._compat import is_bytes12+from ._compat import open_stream13+from ._compat import PY214+from ._compat import should_strip_ansi15+from ._compat import string_types16+from ._compat import strip_ansi17+from ._compat import text_streams18+from ._compat import text_type19+from ._compat import WIN20+from .globals import resolve_color_default21+22+if not PY2:23+ from ._compat import _find_binary_writer24+elif WIN:25+ from ._winconsole import _get_windows_argv26+ from ._winconsole import _hash_py_argv27+ from ._winconsole import _initial_argv_hash28+29+echo_native_types = string_types + (bytes, bytearray)30+31+32+def _posixify(name):33+ return "-".join(name.split()).lower()34+35+36+def safecall(func):37+ """Wraps a function so that it swallows exceptions."""38+39+ def wrapper(*args, **kwargs):40+ try:41+ return func(*args, **kwargs)42+ except Exception:43+ pass44+45+ return wrapper46+47+48+def make_str(value):49+ """Converts a value into a valid string."""50+ if isinstance(value, bytes):51+ try:52+ return value.decode(get_filesystem_encoding())53+ except UnicodeError:54+ return value.decode("utf-8", "replace")55+ return text_type(value)56+57+58+def make_default_short_help(help, max_length=45):59+ """Return a condensed version of help string."""60+ words = help.split()61+ total_length = 062+ result = []63+ done = False64+65+ for word in words:66+ if word[-1:] == ".":67+ done = True68+ new_length = 1 + len(word) if result else len(word)69+ if total_length + new_length > max_length:70+ result.append("...")71+ done = True72+ else:73+ if result:74+ result.append(" ")75+ result.append(word)76+ if done:77+ break78+ total_length += new_length79+80+ return "".join(result)81+82+83+class LazyFile(object):84+ """A lazy file works like a regular file but it does not fully open85+ the file but it does perform some basic checks early to see if the86+ filename parameter does make sense. This is useful for safely opening87+ files for writing.88+ """89+90+ def __init__(91+ self, filename, mode="r", encoding=None, errors="strict", atomic=False92+ ):93+ self.name = filename94+ self.mode = mode95+ self.encoding = encoding96+ self.errors = errors97+ self.atomic = atomic98+99+ if filename == "-":100+ self._f, self.should_close = open_stream(filename, mode, encoding, errors)101+ else:102+ if "r" in mode:103+ # Open and close the file in case we're opening it for104+ # reading so that we can catch at least some errors in105+ # some cases early.106+ open(filename, mode).close()107+ self._f = None108+ self.should_close = True109+110+ def __getattr__(self, name):111+ return getattr(self.open(), name)112+113+ def __repr__(self):114+ if self._f is not None:115+ return repr(self._f)116+ return "<unopened file '{}' {}>".format(self.name, self.mode)117+118+ def open(self):119+ """Opens the file if it's not yet open. This call might fail with120+ a :exc:`FileError`. Not handling this error will produce an error121+ that Click shows.122+ """123+ if self._f is not None:124+ return self._f125+ try:126+ rv, self.should_close = open_stream(127+ self.name, self.mode, self.encoding, self.errors, atomic=self.atomic128+ )129+ except (IOError, OSError) as e: # noqa: E402130+ from .exceptions import FileError131+132+ raise FileError(self.name, hint=get_streerror(e))133+ self._f = rv134+ return rv135+136+ def close(self):137+ """Closes the underlying file, no matter what."""138+ if self._f is not None:139+ self._f.close()140+141+ def close_intelligently(self):142+ """This function only closes the file if it was opened by the lazy143+ file wrapper. For instance this will never close stdin.144+ """145+ if self.should_close:146+ self.close()147+148+ def __enter__(self):149+ return self150+151+ def __exit__(self, exc_type, exc_value, tb):152+ self.close_intelligently()153+154+ def __iter__(self):155+ self.open()156+ return iter(self._f)157+158+159+class KeepOpenFile(object):160+ def __init__(self, file):161+ self._file = file162+163+ def __getattr__(self, name):164+ return getattr(self._file, name)165+166+ def __enter__(self):167+ return self168+169+ def __exit__(self, exc_type, exc_value, tb):170+ pass171+172+ def __repr__(self):173+ return repr(self._file)174+175+ def __iter__(self):176+ return iter(self._file)177+178+179+def echo(message=None, file=None, nl=True, err=False, color=None):180+ """Prints a message plus a newline to the given file or stdout. On181+ first sight, this looks like the print function, but it has improved182+ support for handling Unicode and binary data that does not fail no183+ matter how badly configured the system is.184+185+ Primarily it means that you can print binary data as well as Unicode186+ data on both 2.x and 3.x to the given file in the most appropriate way187+ possible. This is a very carefree function in that it will try its188+ best to not fail. As of Click 6.0 this includes support for unicode189+ output on the Windows console.190+191+ In addition to that, if `colorama`_ is installed, the echo function will192+ also support clever handling of ANSI codes. Essentially it will then193+ do the following:194+195+ - add transparent handling of ANSI color codes on Windows.196+ - hide ANSI codes automatically if the destination file is not a197+ terminal.198+199+ .. _colorama: https://pypi.org/project/colorama/200+201+ .. versionchanged:: 6.0202+ As of Click 6.0 the echo function will properly support unicode203+ output on the windows console. Not that click does not modify204+ the interpreter in any way which means that `sys.stdout` or the205+ print statement or function will still not provide unicode support.206+207+ .. versionchanged:: 2.0208+ Starting with version 2.0 of Click, the echo function will work209+ with colorama if it's installed.210+211+ .. versionadded:: 3.0212+ The `err` parameter was added.213+214+ .. versionchanged:: 4.0215+ Added the `color` flag.216+217+ :param message: the message to print218+ :param file: the file to write to (defaults to ``stdout``)219+ :param err: if set to true the file defaults to ``stderr`` instead of220+ ``stdout``. This is faster and easier than calling221+ :func:`get_text_stderr` yourself.222+ :param nl: if set to `True` (the default) a newline is printed afterwards.223+ :param color: controls if the terminal supports ANSI colors or not. The224+ default is autodetection.225+ """226+ if file is None:227+ if err:228+ file = _default_text_stderr()229+ else:230+ file = _default_text_stdout()231+232+ # Convert non bytes/text into the native string type.233+ if message is not None and not isinstance(message, echo_native_types):234+ message = text_type(message)235+236+ if nl:237+ message = message or u""238+ if isinstance(message, text_type):239+ message += u"\n"240+ else:241+ message += b"\n"242+243+ # If there is a message, and we're in Python 3, and the value looks244+ # like bytes, we manually need to find the binary stream and write the245+ # message in there. This is done separately so that most stream246+ # types will work as you would expect. Eg: you can write to StringIO247+ # for other cases.248+ if message and not PY2 and is_bytes(message):249+ binary_file = _find_binary_writer(file)250+ if binary_file is not None:251+ file.flush()252+ binary_file.write(message)253+ binary_file.flush()254+ return255+256+ # ANSI-style support. If there is no message or we are dealing with257+ # bytes nothing is happening. If we are connected to a file we want258+ # to strip colors. If we are on windows we either wrap the stream259+ # to strip the color or we use the colorama support to translate the260+ # ansi codes to API calls.261+ if message and not is_bytes(message):262+ color = resolve_color_default(color)263+ if should_strip_ansi(file, color):264+ message = strip_ansi(message)265+ elif WIN:266+ if auto_wrap_for_ansi is not None:267+ file = auto_wrap_for_ansi(file)268+ elif not color:269+ message = strip_ansi(message)270+271+ if message:272+ file.write(message)273+ file.flush()274+275+276+def get_binary_stream(name):277+ """Returns a system stream for byte processing. This essentially278+ returns the stream from the sys module with the given name but it279+ solves some compatibility issues between different Python versions.280+ Primarily this function is necessary for getting binary streams on281+ Python 3.282+283+ :param name: the name of the stream to open. Valid names are ``'stdin'``,284+ ``'stdout'`` and ``'stderr'``285+ """286+ opener = binary_streams.get(name)287+ if opener is None:288+ raise TypeError("Unknown standard stream '{}'".format(name))289+ return opener()290+291+292+def get_text_stream(name, encoding=None, errors="strict"):293+ """Returns a system stream for text processing. This usually returns294+ a wrapped stream around a binary stream returned from295+ :func:`get_binary_stream` but it also can take shortcuts on Python 3296+ for already correctly configured streams.297+298+ :param name: the name of the stream to open. Valid names are ``'stdin'``,299+ ``'stdout'`` and ``'stderr'``300+ :param encoding: overrides the detected default encoding.301+ :param errors: overrides the default error mode.302+ """303+ opener = text_streams.get(name)304+ if opener is None:305+ raise TypeError("Unknown standard stream '{}'".format(name))306+ return opener(encoding, errors)307+308+309+def open_file(310+ filename, mode="r", encoding=None, errors="strict", lazy=False, atomic=False311+):312+ """This is similar to how the :class:`File` works but for manual313+ usage. Files are opened non lazy by default. This can open regular314+ files as well as stdin/stdout if ``'-'`` is passed.315+316+ If stdin/stdout is returned the stream is wrapped so that the context317+ manager will not close the stream accidentally. This makes it possible318+ to always use the function like this without having to worry to319+ accidentally close a standard stream::320+321+ with open_file(filename) as f:322+ ...323+324+ .. versionadded:: 3.0325+326+ :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).327+ :param mode: the mode in which to open the file.328+ :param encoding: the encoding to use.329+ :param errors: the error handling for this file.330+ :param lazy: can be flipped to true to open the file lazily.331+ :param atomic: in atomic mode writes go into a temporary file and it's332+ moved on close.333+ """334+ if lazy:335+ return LazyFile(filename, mode, encoding, errors, atomic=atomic)336+ f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)337+ if not should_close:338+ f = KeepOpenFile(f)339+ return f340+341+342+def get_os_args():343+ """This returns the argument part of sys.argv in the most appropriate344+ form for processing. What this means is that this return value is in345+ a format that works for Click to process but does not necessarily346+ correspond well to what's actually standard for the interpreter.347+348+ On most environments the return value is ``sys.argv[:1]`` unchanged.349+ However if you are on Windows and running Python 2 the return value350+ will actually be a list of unicode strings instead because the351+ default behavior on that platform otherwise will not be able to352+ carry all possible values that sys.argv can have.353+354+ .. versionadded:: 6.0355+ """356+ # We can only extract the unicode argv if sys.argv has not been357+ # changed since the startup of the application.358+ if PY2 and WIN and _initial_argv_hash == _hash_py_argv():359+ return _get_windows_argv()360+ return sys.argv[1:]361+362+363+def format_filename(filename, shorten=False):364+ """Formats a filename for user display. The main purpose of this365+ function is to ensure that the filename can be displayed at all. This366+ will decode the filename to unicode if necessary in a way that it will367+ not fail. Optionally, it can shorten the filename to not include the368+ full path to the filename.369+370+ :param filename: formats a filename for UI display. This will also convert371+ the filename into unicode without failing.372+ :param shorten: this optionally shortens the filename to strip of the373+ path that leads up to it.374+ """375+ if shorten:376+ filename = os.path.basename(filename)377+ return filename_to_ui(filename)378+379+380+def get_app_dir(app_name, roaming=True, force_posix=False):381+ r"""Returns the config folder for the application. The default behavior382+ is to return whatever is most appropriate for the operating system.383+384+ To give you an idea, for an app called ``"Foo Bar"``, something like385+ the following folders could be returned:386+387+ Mac OS X:388+ ``~/Library/Application Support/Foo Bar``389+ Mac OS X (POSIX):390+ ``~/.foo-bar``391+ Unix:392+ ``~/.config/foo-bar``393+ Unix (POSIX):394+ ``~/.foo-bar``395+ Win XP (roaming):396+ ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``397+ Win XP (not roaming):398+ ``C:\Documents and Settings\<user>\Application Data\Foo Bar``399+ Win 7 (roaming):400+ ``C:\Users\<user>\AppData\Roaming\Foo Bar``401+ Win 7 (not roaming):402+ ``C:\Users\<user>\AppData\Local\Foo Bar``403+404+ .. versionadded:: 2.0405+406+ :param app_name: the application name. This should be properly capitalized407+ and can contain whitespace.408+ :param roaming: controls if the folder should be roaming or not on Windows.409+ Has no affect otherwise.410+ :param force_posix: if this is set to `True` then on any POSIX system the411+ folder will be stored in the home folder with a leading412+ dot instead of the XDG config home or darwin's413+ application support folder.414+ """415+ if WIN:416+ key = "APPDATA" if roaming else "LOCALAPPDATA"417+ folder = os.environ.get(key)418+ if folder is None:419+ folder = os.path.expanduser("~")420+ return os.path.join(folder, app_name)421+ if force_posix:422+ return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))423+ if sys.platform == "darwin":424+ return os.path.join(425+ os.path.expanduser("~/Library/Application Support"), app_name426+ )427+ return os.path.join(428+ os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),429+ _posixify(app_name),430+ )431+432+433+class PacifyFlushWrapper(object):434+ """This wrapper is used to catch and suppress BrokenPipeErrors resulting435+ from ``.flush()`` being called on broken pipe during the shutdown/final-GC436+ of the Python interpreter. Notably ``.flush()`` is always called on437+ ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any438+ other cleanup code, and the case where the underlying file is not a broken439+ pipe, all calls and attributes are proxied.440+ """441+442+ def __init__(self, wrapped):443+ self.wrapped = wrapped444+445+ def flush(self):446+ try:447+ self.wrapped.flush()448+ except IOError as e:449+ import errno450+451+ if e.errno != errno.EPIPE:452+ raise453+454+ def __getattr__(self, attr):455+ return getattr(self.wrapped, attr)modified:tests/conftest.py+3 added-3 removed
1-from click.testing import CliRunner2-1 import pytest2 3+from click.testing import CliRunner4 5+6-@pytest.fixture(scope='function')6+@pytest.fixture(scope="function")7 def runner(request):8 return CliRunner()modified:tests/test_arguments.py+116 added-129 removed
1 # -*- coding: utf-8 -*-2+import sys3+4 import pytest5+6 import click4-import sys5-from click._compat import PY2, text_type7+from click._compat import PY28+from click._compat import text_type9 10 11 def test_nargs_star(runner):12 @click.command()10- @click.argument('src', nargs=-1)11- @click.argument('dst')13+ @click.argument("src", nargs=-1)14+ @click.argument("dst")15 def copy(src, dst):13- click.echo('src=%s' % '|'.join(src))14- click.echo('dst=%s' % dst)16+ click.echo("src={}".format("|".join(src)))17+ click.echo("dst={}".format(dst))18 16- result = runner.invoke(copy, ['foo.txt', 'bar.txt', 'dir'])19+ result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])20 assert not result.exception18- assert result.output.splitlines() == [19- 'src=foo.txt|bar.txt',20- 'dst=dir',21- ]21+ assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]22 23 24 def test_nargs_default(runner):25- try:25+ with pytest.raises(TypeError, match="nargs=-1"):26+27 @click.command()27- @click.argument('src', nargs=-1, default=42)28+ @click.argument("src", nargs=-1, default=42)29 def copy(src):30 pass30- except TypeError as e:31- assert 'nargs=-1' in str(e)32- else:33- assert False31 32 33 def test_nargs_tup(runner):34 @click.command()38- @click.argument('name', nargs=1)39- @click.argument('point', nargs=2, type=click.INT)35+ @click.argument("name", nargs=1)36+ @click.argument("point", nargs=2, type=click.INT)37 def copy(name, point):41- click.echo('name=%s' % name)42- click.echo('point=%d/%d' % point)38+ click.echo("name={}".format(name))39+ click.echo("point={0[0]}/{0[1]}".format(point))40 44- result = runner.invoke(copy, ['peter', '1', '2'])41+ result = runner.invoke(copy, ["peter", "1", "2"])42 assert not result.exception46- assert result.output.splitlines() == [47- 'name=peter',48- 'point=1/2',49- ]43+ assert result.output.splitlines() == ["name=peter", "point=1/2"]44 45 46 def test_nargs_tup_composite(runner):47 variations = [3 unmodified lines51 dict(nargs=2, type=(str, int)),52 ]53 54 for opts in variations:55+56 @click.command()62- @click.argument('item', **opts)57+ @click.argument("item", **opts)58 def copy(item):64- click.echo('name=%s id=%d' % item)59+ click.echo("name={0[0]} id={0[1]:d}".format(item))60 66- result = runner.invoke(copy, ['peter', '1'])61+ result = runner.invoke(copy, ["peter", "1"])62 assert not result.exception68- assert result.output.splitlines() == [69- 'name=peter id=1',70- ]63+ assert result.output.splitlines() == ["name=peter id=1"]64 65 66 def test_nargs_err(runner):67 @click.command()75- @click.argument('x')68+ @click.argument("x")69 def copy(x):70 click.echo(x)71 79- result = runner.invoke(copy, ['foo'])72+ result = runner.invoke(copy, ["foo"])73 assert not result.exception81- assert result.output == 'foo\n'74+ assert result.output == "foo\n"75 83- result = runner.invoke(copy, ['foo', 'bar'])76+ result = runner.invoke(copy, ["foo", "bar"])77 assert result.exit_code == 285- assert 'Got unexpected extra argument (bar)' in result.output78+ assert "Got unexpected extra argument (bar)" in result.output79 80 81 def test_bytes_args(runner, monkeypatch):82 @click.command()90- @click.argument('arg')83+ @click.argument("arg")84 def from_bytes(arg):92- assert isinstance(arg, text_type), "UTF-8 encoded argument should be implicitly converted to Unicode"85+ assert isinstance(86+ arg, text_type87+ ), "UTF-8 encoded argument should be implicitly converted to Unicode"88 89 # Simulate empty locale environment variables90 if PY2:96- monkeypatch.setattr(sys.stdin, 'encoding', 'ANSI_X3.4-1968')97- monkeypatch.setattr(sys, 'getfilesystemencoding', lambda: 'ANSI_X3.4-1968')98- monkeypatch.setattr(sys, 'getdefaultencoding', lambda: 'ascii')91+ monkeypatch.setattr(sys.stdin, "encoding", "ANSI_X3.4-1968")92+ monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "ANSI_X3.4-1968")93+ monkeypatch.setattr(sys, "getdefaultencoding", lambda: "ascii")94 else:100- monkeypatch.setattr(sys.stdin, 'encoding', 'utf-8')101- monkeypatch.setattr(sys, 'getfilesystemencoding', lambda: 'utf-8')102- monkeypatch.setattr(sys, 'getdefaultencoding', lambda: 'utf-8')95+ monkeypatch.setattr(sys.stdin, "encoding", "utf-8")96+ monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")97+ monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")98 104- runner.invoke(from_bytes, [u'Something outside of ASCII range: 林'.encode('UTF-8')],105- catch_exceptions=False)99+ runner.invoke(100+ from_bytes,101+ [u"Something outside of ASCII range: 林".encode("UTF-8")],102+ catch_exceptions=False,103+ )104 105 106 def test_file_args(runner):107 @click.command()110- @click.argument('input', type=click.File('rb'))111- @click.argument('output', type=click.File('wb'))108+ @click.argument("input", type=click.File("rb"))109+ @click.argument("output", type=click.File("wb"))110 def inout(input, output):111 while True:112 chunk = input.read(1024)113 if not chunk:114 break115 output.write(chunk)116 117 with runner.isolated_filesystem():120- result = runner.invoke(inout, ['-', 'hello.txt'], input='Hey!')121- assert result.output == ''118+ result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")119+ assert result.output == ""120 assert result.exit_code == 0123- with open('hello.txt', 'rb') as f:124- assert f.read() == b'Hey!'121+ with open("hello.txt", "rb") as f:122+ assert f.read() == b"Hey!"123 126- result = runner.invoke(inout, ['hello.txt', '-'])127- assert result.output == 'Hey!'124+ result = runner.invoke(inout, ["hello.txt", "-"])125+ assert result.output == "Hey!"126 assert result.exit_code == 0127 128 129 def test_path_args(runner):130 @click.command()133- @click.argument('input', type=click.Path(dir_okay=False, allow_dash=True))131+ @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True))132 def foo(input):133 click.echo(input)134 137- result = runner.invoke(foo, ['-'])138- assert result.output == '-\n'135+ result = runner.invoke(foo, ["-"])136+ assert result.output == "-\n"137 assert result.exit_code == 0138 139 140 def test_file_atomics(runner):141 @click.command()144- @click.argument('output', type=click.File('wb', atomic=True))142+ @click.argument("output", type=click.File("wb", atomic=True))143 def inout(output):146- output.write(b'Foo bar baz\n')144+ output.write(b"Foo bar baz\n")145 output.flush()148- with open(output.name, 'rb') as f:146+ with open(output.name, "rb") as f:147 old_content = f.read()150- assert old_content == b'OLD\n'148+ assert old_content == b"OLD\n"149 150 with runner.isolated_filesystem():153- with open('foo.txt', 'wb') as f:154- f.write(b'OLD\n')155- result = runner.invoke(inout, ['foo.txt'], input='Hey!',156- catch_exceptions=False)157- assert result.output == ''151+ with open("foo.txt", "wb") as f:152+ f.write(b"OLD\n")153+ result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)154+ assert result.output == ""155 assert result.exit_code == 0159- with open('foo.txt', 'rb') as f:160- assert f.read() == b'Foo bar baz\n'156+ with open("foo.txt", "rb") as f:157+ assert f.read() == b"Foo bar baz\n"158 159 160 def test_stdout_default(runner):161 @click.command()165- @click.argument('output', type=click.File('w'), default='-')162+ @click.argument("output", type=click.File("w"), default="-")163 def inout(output):167- output.write('Foo bar baz\n')164+ output.write("Foo bar baz\n")165 output.flush()166 167 result = runner.invoke(inout, [])168 assert not result.exception172- assert result.output == 'Foo bar baz\n'169+ assert result.output == "Foo bar baz\n"170 171 172 def test_nargs_envvar(runner):173 @click.command()177- @click.option('--arg', nargs=2)174+ @click.option("--arg", nargs=2)175 def cmd(arg):179- click.echo('|'.join(arg))176+ click.echo("|".join(arg))177 181- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',182- env={'TEST_ARG': 'foo bar'})178+ result = runner.invoke(179+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}180+ )181 assert not result.exception184- assert result.output == 'foo|bar\n'182+ assert result.output == "foo|bar\n"183 184 @click.command()187- @click.option('--arg', envvar='X', nargs=2)185+ @click.option("--arg", envvar="X", nargs=2)186 def cmd(arg):189- click.echo('|'.join(arg))187+ click.echo("|".join(arg))188 191- result = runner.invoke(cmd, [], env={'X': 'foo bar'})189+ result = runner.invoke(cmd, [], env={"X": "foo bar"})190 assert not result.exception193- assert result.output == 'foo|bar\n'191+ assert result.output == "foo|bar\n"192 193 194 def test_empty_nargs(runner):195 @click.command()198- @click.argument('arg', nargs=-1)196+ @click.argument("arg", nargs=-1)197 def cmd(arg):200- click.echo('arg:' + '|'.join(arg))198+ click.echo("arg:{}".format("|".join(arg)))199 200 result = runner.invoke(cmd, [])201 assert result.exit_code == 0204- assert result.output == 'arg:\n'202+ assert result.output == "arg:\n"203 204 @click.command()207- @click.argument('arg', nargs=-1, required=True)205+ @click.argument("arg", nargs=-1, required=True)206 def cmd2(arg):209- click.echo('arg:' + '|'.join(arg))207+ click.echo("arg:{}".format("|".join(arg)))208 209 result = runner.invoke(cmd2, [])210 assert result.exit_code == 2213- assert 'Missing argument "ARG..."' in result.output211+ assert "Missing argument 'ARG...'" in result.output212 213 214 def test_missing_arg(runner):215 @click.command()218- @click.argument('arg')216+ @click.argument("arg")217 def cmd(arg):220- click.echo('arg:' + arg)218+ click.echo("arg:{}".format(arg))219 220 result = runner.invoke(cmd, [])221 assert result.exit_code == 2224- assert 'Missing argument "ARG".' in result.output222+ assert "Missing argument 'ARG'." in result.output223 224 225 def test_missing_argument_string_cast():226 ctx = click.Context(click.Command(""))5 unmodified lines232 233 234 def test_implicit_non_required(runner):235 @click.command()238- @click.argument('f', default='test')236+ @click.argument("f", default="test")237 def cli(f):238 click.echo(f)239 240 result = runner.invoke(cli, [])241 assert result.exit_code == 0244- assert result.output == 'test\n'242+ assert result.output == "test\n"243 244 245 def test_eat_options(runner):246 @click.command()249- @click.option('-f')250- @click.argument('files', nargs=-1)247+ @click.option("-f")248+ @click.argument("files", nargs=-1)249 def cmd(f, files):250 for filename in files:251 click.echo(filename)252 click.echo(f)253 256- result = runner.invoke(cmd, ['--', '-foo', 'bar'])257- assert result.output.splitlines() == [258- '-foo',259- 'bar',260- '',261- ]254+ result = runner.invoke(cmd, ["--", "-foo", "bar"])255+ assert result.output.splitlines() == ["-foo", "bar", ""]256 263- result = runner.invoke(cmd, ['-f', '-x', '--', '-foo', 'bar'])264- assert result.output.splitlines() == [265- '-foo',266- 'bar',267- '-x',268- ]257+ result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])258+ assert result.output.splitlines() == ["-foo", "bar", "-x"]259 260 261 def test_nargs_star_ordering(runner):262 @click.command()273- @click.argument('a', nargs=-1)274- @click.argument('b')275- @click.argument('c')263+ @click.argument("a", nargs=-1)264+ @click.argument("b")265+ @click.argument("c")266 def cmd(a, b, c):267 for arg in (a, b, c):268 click.echo(arg)269 280- result = runner.invoke(cmd, ['a', 'b', 'c'])281- assert result.output.splitlines() == [282- PY2 and "(u'a',)" or "('a',)",283- 'b',284- 'c',285- ]270+ result = runner.invoke(cmd, ["a", "b", "c"])271+ assert result.output.splitlines() == ["(u'a',)" if PY2 else "('a',)", "b", "c"]272 273 274 def test_nargs_specified_plus_star_ordering(runner):275 @click.command()290- @click.argument('a', nargs=-1)291- @click.argument('b')292- @click.argument('c', nargs=2)276+ @click.argument("a", nargs=-1)277+ @click.argument("b")278+ @click.argument("c", nargs=2)279 def cmd(a, b, c):280 for arg in (a, b, c):281 click.echo(arg)282 297- result = runner.invoke(cmd, ['a', 'b', 'c', 'd', 'e', 'f'])283+ result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])284 assert result.output.splitlines() == [299- PY2 and "(u'a', u'b', u'c')" or "('a', 'b', 'c')",300- 'd',301- PY2 and "(u'e', u'f')" or "('e', 'f')",285+ "(u'a', u'b', u'c')" if PY2 else "('a', 'b', 'c')",286+ "d",287+ "(u'e', u'f')" if PY2 else "('e', 'f')",288 ]289 290 291 def test_defaults_for_nargs(runner):292 @click.command()307- @click.argument('a', nargs=2, type=int, default=(1, 2))293+ @click.argument("a", nargs=2, type=int, default=(1, 2))294 def cmd(a):295 x, y = a296 click.echo(x + y)297 298 result = runner.invoke(cmd, [])313- assert result.output.strip() == '3'299+ assert result.output.strip() == "3"300 315- result = runner.invoke(cmd, ['3', '4'])316- assert result.output.strip() == '7'301+ result = runner.invoke(cmd, ["3", "4"])302+ assert result.output.strip() == "7"303 318- result = runner.invoke(cmd, ['3'])304+ result = runner.invoke(cmd, ["3"])305 assert result.exception is not None320- assert 'argument a takes 2 values' in result.output306+ assert "argument a takes 2 values" in result.output307 308 309 def test_multiple_param_decls_not_allowed(runner):310 with pytest.raises(TypeError):311+312 @click.command()326- @click.argument('x', click.Choice(['a', 'b']))313+ @click.argument("x", click.Choice(["a", "b"]))314 def copy(x):315 click.echo(x)modified:tests/test_bashcomplete.py+240 added-176 removed
1 # -*- coding: utf-8 -*-2-2 import pytest3 4 import click5 from click._bashcomplete import get_choices6 7 8 def choices_without_help(cli, args, incomplete):10- completions = get_choices(cli, 'dummy', args, incomplete)9+ completions = get_choices(cli, "dummy", args, incomplete)10 return [c[0] for c in completions]11 12 13 def choices_with_help(cli, args, incomplete):15- return list(get_choices(cli, 'dummy', args, incomplete))14+ return list(get_choices(cli, "dummy", args, incomplete))15 16 17 def test_single_command():18 @click.command()20- @click.option('--local-opt')19+ @click.option("--local-opt")20 def cli(local_opt):21 pass22 24- assert choices_without_help(cli, [], '-') == ['--local-opt']25- assert choices_without_help(cli, [], '') == []23+ assert choices_without_help(cli, [], "-") == ["--local-opt"]24+ assert choices_without_help(cli, [], "") == []25 26 27 def test_boolean_flag():28 @click.command()30- @click.option('--shout/--no-shout', default=False)29+ @click.option("--shout/--no-shout", default=False)30 def cli(local_opt):31 pass32 34- assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']33+ assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]34 35 36 def test_multi_value_option():37 @click.group()39- @click.option('--pos', nargs=2, type=float)38+ @click.option("--pos", nargs=2, type=float)39 def cli(local_opt):40 pass41 42 @cli.command()44- @click.option('--local-opt')43+ @click.option("--local-opt")44 def sub(local_opt):45 pass46 48- assert choices_without_help(cli, [], '-') == ['--pos']49- assert choices_without_help(cli, ['--pos'], '') == []50- assert choices_without_help(cli, ['--pos', '1.0'], '') == []51- assert choices_without_help(cli, ['--pos', '1.0', '1.0'], '') == ['sub']47+ assert choices_without_help(cli, [], "-") == ["--pos"]48+ assert choices_without_help(cli, ["--pos"], "") == []49+ assert choices_without_help(cli, ["--pos", "1.0"], "") == []50+ assert choices_without_help(cli, ["--pos", "1.0", "1.0"], "") == ["sub"]51 52 53 def test_multi_option():54 @click.command()56- @click.option('--message', '-m', multiple=True)55+ @click.option("--message", "-m", multiple=True)56 def cli(local_opt):57 pass58 60- assert choices_without_help(cli, [], '-') == ['--message', '-m']61- assert choices_without_help(cli, ['-m'], '') == []59+ assert choices_without_help(cli, [], "-") == ["--message", "-m"]60+ assert choices_without_help(cli, ["-m"], "") == []61 62 63 def test_small_chain():64 @click.group()66- @click.option('--global-opt')65+ @click.option("--global-opt")66 def cli(global_opt):67 pass68 69 @cli.command()71- @click.option('--local-opt')70+ @click.option("--local-opt")71 def sub(local_opt):72 pass73 75- assert choices_without_help(cli, [], '') == ['sub']76- assert choices_without_help(cli, [], '-') == ['--global-opt']77- assert choices_without_help(cli, ['sub'], '') == []78- assert choices_without_help(cli, ['sub'], '-') == ['--local-opt']74+ assert choices_without_help(cli, [], "") == ["sub"]75+ assert choices_without_help(cli, [], "-") == ["--global-opt"]76+ assert choices_without_help(cli, ["sub"], "") == []77+ assert choices_without_help(cli, ["sub"], "-") == ["--local-opt"]78 79 80 def test_long_chain():82- @click.group('cli')83- @click.option('--cli-opt')81+ @click.group("cli")82+ @click.option("--cli-opt")83 def cli(cli_opt):84 pass85 87- @cli.group('asub')88- @click.option('--asub-opt')86+ @cli.group("asub")87+ @click.option("--asub-opt")88 def asub(asub_opt):89 pass90 92- @asub.group('bsub')93- @click.option('--bsub-opt')91+ @asub.group("bsub")92+ @click.option("--bsub-opt")93 def bsub(bsub_opt):94 pass95 97- COLORS = ['red', 'green', 'blue']96+ COLORS = ["red", "green", "blue"]97+98 def get_colors(ctx, args, incomplete):99 for c in COLORS:100 if c.startswith(incomplete):101 yield c2 unmodified lines104 for c in COLORS:105 if incomplete in c:106 yield c107 108- CSUB_OPT_CHOICES = ['foo', 'bar']109- CSUB_CHOICES = ['bar', 'baz']110- @bsub.command('csub')111- @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))112- @click.option('--csub', type=click.Choice(CSUB_CHOICES))113- @click.option('--search-color', autocompletion=search_colors)114- @click.argument('color', autocompletion=get_colors)108+ CSUB_OPT_CHOICES = ["foo", "bar"]109+ CSUB_CHOICES = ["bar", "baz"]110+111+ @bsub.command("csub")112+ @click.option("--csub-opt", type=click.Choice(CSUB_OPT_CHOICES))113+ @click.option("--csub", type=click.Choice(CSUB_CHOICES))114+ @click.option("--search-color", autocompletion=search_colors)115+ @click.argument("color", autocompletion=get_colors)116 def csub(csub_opt, color):117 pass118 118- assert choices_without_help(cli, [], '-') == ['--cli-opt']119- assert choices_without_help(cli, [], '') == ['asub']120- assert choices_without_help(cli, ['asub'], '-') == ['--asub-opt']121- assert choices_without_help(cli, ['asub'], '') == ['bsub']122- assert choices_without_help(cli, ['asub', 'bsub'], '-') == ['--bsub-opt']123- assert choices_without_help(cli, ['asub', 'bsub'], '') == ['csub']124- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '-') == ['--csub-opt', '--csub', '--search-color']125- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub-opt'], '') == CSUB_OPT_CHOICES126- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '--csub') == ['--csub-opt', '--csub']127- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub'], '') == CSUB_CHOICES128- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub-opt'], 'f') == ['foo']129- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '') == COLORS130- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], 'b') == ['blue']131- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--search-color'], 'een') == ['green']119+ assert choices_without_help(cli, [], "-") == ["--cli-opt"]120+ assert choices_without_help(cli, [], "") == ["asub"]121+ assert choices_without_help(cli, ["asub"], "-") == ["--asub-opt"]122+ assert choices_without_help(cli, ["asub"], "") == ["bsub"]123+ assert choices_without_help(cli, ["asub", "bsub"], "-") == ["--bsub-opt"]124+ assert choices_without_help(cli, ["asub", "bsub"], "") == ["csub"]125+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "-") == [126+ "--csub-opt",127+ "--csub",128+ "--search-color",129+ ]130+ assert (131+ choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "")132+ == CSUB_OPT_CHOICES133+ )134+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "--csub") == [135+ "--csub-opt",136+ "--csub",137+ ]138+ assert (139+ choices_without_help(cli, ["asub", "bsub", "csub", "--csub"], "")140+ == CSUB_CHOICES141+ )142+ assert choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "f") == [143+ "foo"144+ ]145+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "") == COLORS146+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "b") == ["blue"]147+ assert choices_without_help(148+ cli, ["asub", "bsub", "csub", "--search-color"], "een"149+ ) == ["green"]150 151 152 def test_chaining():135- @click.group('cli', chain=True)136- @click.option('--cli-opt')137- @click.argument('arg', type=click.Choice(['cliarg1', 'cliarg2']))153+ @click.group("cli", chain=True)154+ @click.option("--cli-opt")155+ @click.argument("arg", type=click.Choice(["cliarg1", "cliarg2"]))156 def cli(cli_opt, arg):157 pass158 159 @cli.command()142- @click.option('--asub-opt')160+ @click.option("--asub-opt")161 def asub(asub_opt):162 pass163 146- @cli.command(help='bsub help')147- @click.option('--bsub-opt')148- @click.argument('arg', type=click.Choice(['arg1', 'arg2']))164+ @cli.command(help="bsub help")165+ @click.option("--bsub-opt")166+ @click.argument("arg", type=click.Choice(["arg1", "arg2"]))167 def bsub(bsub_opt, arg):168 pass169 170 @cli.command()153- @click.option('--csub-opt')154- @click.argument('arg', type=click.Choice(['carg1', 'carg2']), default='carg1')171+ @click.option("--csub-opt")172+ @click.argument("arg", type=click.Choice(["carg1", "carg2"]), default="carg1")173 def csub(csub_opt, arg):174 pass175 158- assert choices_without_help(cli, [], '-') == ['--cli-opt']159- assert choices_without_help(cli, [], '') == ['cliarg1', 'cliarg2']160- assert choices_without_help(cli, ['cliarg1', 'asub'], '-') == ['--asub-opt']161- assert choices_without_help(cli, ['cliarg1', 'asub'], '') == ['bsub', 'csub']162- assert choices_without_help(cli, ['cliarg1', 'bsub'], '') == ['arg1', 'arg2']163- assert choices_without_help(cli, ['cliarg1', 'asub', '--asub-opt'], '') == []164- assert choices_without_help(cli, ['cliarg1', 'asub', '--asub-opt', '5', 'bsub'], '-') == ['--bsub-opt']165- assert choices_without_help(cli, ['cliarg1', 'asub', 'bsub'], '-') == ['--bsub-opt']166- assert choices_without_help(cli, ['cliarg1', 'asub', 'csub'], '') == ['carg1', 'carg2']167- assert choices_without_help(cli, ['cliarg1', 'bsub', 'arg1', 'csub'], '') == ['carg1', 'carg2']168- assert choices_without_help(cli, ['cliarg1', 'asub', 'csub'], '-') == ['--csub-opt']169- assert choices_with_help(cli, ['cliarg1', 'asub'], 'b') == [('bsub', 'bsub help')]176+ assert choices_without_help(cli, [], "-") == ["--cli-opt"]177+ assert choices_without_help(cli, [], "") == ["cliarg1", "cliarg2"]178+ assert choices_without_help(cli, ["cliarg1", "asub"], "-") == ["--asub-opt"]179+ assert choices_without_help(cli, ["cliarg1", "asub"], "") == ["bsub", "csub"]180+ assert choices_without_help(cli, ["cliarg1", "bsub"], "") == ["arg1", "arg2"]181+ assert choices_without_help(cli, ["cliarg1", "asub", "--asub-opt"], "") == []182+ assert choices_without_help(183+ cli, ["cliarg1", "asub", "--asub-opt", "5", "bsub"], "-"184+ ) == ["--bsub-opt"]185+ assert choices_without_help(cli, ["cliarg1", "asub", "bsub"], "-") == ["--bsub-opt"]186+ assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "") == [187+ "carg1",188+ "carg2",189+ ]190+ assert choices_without_help(cli, ["cliarg1", "bsub", "arg1", "csub"], "") == [191+ "carg1",192+ "carg2",193+ ]194+ assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "-") == ["--csub-opt"]195+ assert choices_with_help(cli, ["cliarg1", "asub"], "b") == [("bsub", "bsub help")]196 197 198 def test_argument_choice():199 @click.command()174- @click.argument('arg1', required=True, type=click.Choice(['arg11', 'arg12']))175- @click.argument('arg2', type=click.Choice(['arg21', 'arg22']), default='arg21')176- @click.argument('arg3', type=click.Choice(['arg', 'argument']), default='arg')200+ @click.argument("arg1", required=True, type=click.Choice(["arg11", "arg12"]))201+ @click.argument("arg2", type=click.Choice(["arg21", "arg22"]), default="arg21")202+ @click.argument("arg3", type=click.Choice(["arg", "argument"]), default="arg")203 def cli():204 pass205 180- assert choices_without_help(cli, [], '') == ['arg11', 'arg12']181- assert choices_without_help(cli, [], 'arg') == ['arg11', 'arg12']182- assert choices_without_help(cli, ['arg11'], '') == ['arg21', 'arg22']183- assert choices_without_help(cli, ['arg12', 'arg21'], '') == ['arg', 'argument']184- assert choices_without_help(cli, ['arg12', 'arg21'], 'argu') == ['argument']206+ assert choices_without_help(cli, [], "") == ["arg11", "arg12"]207+ assert choices_without_help(cli, [], "arg") == ["arg11", "arg12"]208+ assert choices_without_help(cli, ["arg11"], "") == ["arg21", "arg22"]209+ assert choices_without_help(cli, ["arg12", "arg21"], "") == ["arg", "argument"]210+ assert choices_without_help(cli, ["arg12", "arg21"], "argu") == ["argument"]211 212 213 def test_option_choice():214 @click.command()189- @click.option('--opt1', type=click.Choice(['opt11', 'opt12']), help='opt1 help')190- @click.option('--opt2', type=click.Choice(['opt21', 'opt22']), default='opt21')191- @click.option('--opt3', type=click.Choice(['opt', 'option']))215+ @click.option("--opt1", type=click.Choice(["opt11", "opt12"]), help="opt1 help")216+ @click.option("--opt2", type=click.Choice(["opt21", "opt22"]), default="opt21")217+ @click.option("--opt3", type=click.Choice(["opt", "option"]))218 def cli():219 pass220 195- assert choices_with_help(cli, [], '-') == [('--opt1', 'opt1 help'),196- ('--opt2', None),197- ('--opt3', None)]198- assert choices_without_help(cli, [], '--opt') == ['--opt1', '--opt2', '--opt3']199- assert choices_without_help(cli, [], '--opt1=') == ['opt11', 'opt12']200- assert choices_without_help(cli, [], '--opt2=') == ['opt21', 'opt22']201- assert choices_without_help(cli, ['--opt2'], '=') == ['opt21', 'opt22']202- assert choices_without_help(cli, ['--opt2', '='], 'opt') == ['opt21', 'opt22']203- assert choices_without_help(cli, ['--opt1'], '') == ['opt11', 'opt12']204- assert choices_without_help(cli, ['--opt2'], '') == ['opt21', 'opt22']205- assert choices_without_help(cli, ['--opt1', 'opt11', '--opt2'], '') == ['opt21', 'opt22']206- assert choices_without_help(cli, ['--opt2', 'opt21'], '-') == ['--opt1', '--opt3']207- assert choices_without_help(cli, ['--opt1', 'opt11'], '-') == ['--opt2', '--opt3']208- assert choices_without_help(cli, ['--opt1'], 'opt') == ['opt11', 'opt12']209- assert choices_without_help(cli, ['--opt3'], 'opti') == ['option']221+ assert choices_with_help(cli, [], "-") == [222+ ("--opt1", "opt1 help"),223+ ("--opt2", None),224+ ("--opt3", None),225+ ]226+ assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2", "--opt3"]227+ assert choices_without_help(cli, [], "--opt1=") == ["opt11", "opt12"]228+ assert choices_without_help(cli, [], "--opt2=") == ["opt21", "opt22"]229+ assert choices_without_help(cli, ["--opt2"], "=") == ["opt21", "opt22"]230+ assert choices_without_help(cli, ["--opt2", "="], "opt") == ["opt21", "opt22"]231+ assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]232+ assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]233+ assert choices_without_help(cli, ["--opt1", "opt11", "--opt2"], "") == [234+ "opt21",235+ "opt22",236+ ]237+ assert choices_without_help(cli, ["--opt2", "opt21"], "-") == ["--opt1", "--opt3"]238+ assert choices_without_help(cli, ["--opt1", "opt11"], "-") == ["--opt2", "--opt3"]239+ assert choices_without_help(cli, ["--opt1"], "opt") == ["opt11", "opt12"]240+ assert choices_without_help(cli, ["--opt3"], "opti") == ["option"]241 211- assert choices_without_help(cli, ['--opt1', 'invalid_opt'], '-') == ['--opt2', '--opt3']242+ assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [243+ "--opt2",244+ "--opt3",245+ ]246 247 248 def test_option_and_arg_choice():249 @click.command()216- @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))217- @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))218- @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))250+ @click.option("--opt1", type=click.Choice(["opt11", "opt12"]))251+ @click.argument("arg1", required=False, type=click.Choice(["arg11", "arg12"]))252+ @click.option("--opt2", type=click.Choice(["opt21", "opt22"]))253 def cli():254 pass255 222- assert choices_without_help(cli, ['--opt1'], '') == ['opt11', 'opt12']223- assert choices_without_help(cli, [''], '--opt1=') == ['opt11', 'opt12']224- assert choices_without_help(cli, [], '') == ['arg11', 'arg12']225- assert choices_without_help(cli, ['--opt2'], '') == ['opt21', 'opt22']226- assert choices_without_help(cli, ['arg11'], '--opt') == ['--opt1', '--opt2']227- assert choices_without_help(cli, [], '--opt') == ['--opt1', '--opt2']256+ assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]257+ assert choices_without_help(cli, [""], "--opt1=") == ["opt11", "opt12"]258+ assert choices_without_help(cli, [], "") == ["arg11", "arg12"]259+ assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]260+ assert choices_without_help(cli, ["arg11"], "--opt") == ["--opt1", "--opt2"]261+ assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2"]262 263 264 def test_boolean_flag_choice():265 @click.command()232- @click.option('--shout/--no-shout', default=False)233- @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))266+ @click.option("--shout/--no-shout", default=False)267+ @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))268 def cli(local_opt):269 pass270 237- assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']238- assert choices_without_help(cli, ['--shout'], '') == ['arg1', 'arg2']271+ assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]272+ assert choices_without_help(cli, ["--shout"], "") == ["arg1", "arg2"]273 274 275 def test_multi_value_option_choice():276 @click.command()243- @click.option('--pos', nargs=2, type=click.Choice(['pos1', 'pos2']))244- @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))277+ @click.option("--pos", nargs=2, type=click.Choice(["pos1", "pos2"]))278+ @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))279 def cli(local_opt):280 pass281 248- assert choices_without_help(cli, ['--pos'], '') == ['pos1', 'pos2']249- assert choices_without_help(cli, ['--pos', 'pos1'], '') == ['pos1', 'pos2']250- assert choices_without_help(cli, ['--pos', 'pos1', 'pos2'], '') == ['arg1', 'arg2']251- assert choices_without_help(cli, ['--pos', 'pos1', 'pos2', 'arg1'], '') == []282+ assert choices_without_help(cli, ["--pos"], "") == ["pos1", "pos2"]283+ assert choices_without_help(cli, ["--pos", "pos1"], "") == ["pos1", "pos2"]284+ assert choices_without_help(cli, ["--pos", "pos1", "pos2"], "") == ["arg1", "arg2"]285+ assert choices_without_help(cli, ["--pos", "pos1", "pos2", "arg1"], "") == []286 287 288 def test_multi_option_choice():289 @click.command()256- @click.option('--message', '-m', multiple=True, type=click.Choice(['m1', 'm2']))257- @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))290+ @click.option("--message", "-m", multiple=True, type=click.Choice(["m1", "m2"]))291+ @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))292 def cli(local_opt):293 pass294 261- assert choices_without_help(cli, ['-m'], '') == ['m1', 'm2']262- assert choices_without_help(cli, ['-m', 'm1', '-m'], '') == ['m1', 'm2']263- assert choices_without_help(cli, ['-m', 'm1'], '') == ['arg1', 'arg2']295+ assert choices_without_help(cli, ["-m"], "") == ["m1", "m2"]296+ assert choices_without_help(cli, ["-m", "m1", "-m"], "") == ["m1", "m2"]297+ assert choices_without_help(cli, ["-m", "m1"], "") == ["arg1", "arg2"]298 299 300 def test_variadic_argument_choice():301 @click.command()268- @click.option('--opt', type=click.Choice(['opt1', 'opt2']))269- @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))302+ @click.option("--opt", type=click.Choice(["opt1", "opt2"]))303+ @click.argument("src", nargs=-1, type=click.Choice(["src1", "src2"]))304 def cli(local_opt):305 pass306 273- assert choices_without_help(cli, ['src1', 'src2'], '') == ['src1', 'src2']274- assert choices_without_help(cli, ['src1', 'src2'], '--o') == ['--opt']275- assert choices_without_help(cli, ['src1', 'src2', '--opt'], '') == ['opt1', 'opt2']276- assert choices_without_help(cli, ['src1', 'src2'], '') == ['src1', 'src2']307+ assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]308+ assert choices_without_help(cli, ["src1", "src2"], "--o") == ["--opt"]309+ assert choices_without_help(cli, ["src1", "src2", "--opt"], "") == ["opt1", "opt2"]310+ assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]311 312 313 def test_variadic_argument_complete():280-314 def _complete(ctx, args, incomplete):282- return ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz']315+ return ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]316 317 @click.group()318 def entrypoint():319 pass320 321 @click.command()289- @click.option('--opt', autocompletion=_complete)290- @click.argument('arg', nargs=-1)322+ @click.option("--opt", autocompletion=_complete)323+ @click.argument("arg", nargs=-1)324 def subcommand(opt, arg):325 pass326 327 entrypoint.add_command(subcommand)328 296- assert choices_without_help(entrypoint, ['subcommand', '--opt'], '') == _complete(0,0,0)297- assert choices_without_help(entrypoint, ['subcommand', 'whatever', '--opt'], '') == _complete(0,0,0)298- assert choices_without_help(entrypoint, ['subcommand', 'whatever', '--opt', 'abc'], '') == []329+ assert choices_without_help(entrypoint, ["subcommand", "--opt"], "") == _complete(330+ 0, 0, 0331+ )332+ assert choices_without_help(333+ entrypoint, ["subcommand", "whatever", "--opt"], ""334+ ) == _complete(0, 0, 0)335+ assert (336+ choices_without_help(entrypoint, ["subcommand", "whatever", "--opt", "abc"], "")337+ == []338+ )339 340 341 def test_long_chain_choice():342 @click.group()343 def cli():344 pass345 346 @cli.group()307- @click.option('--sub-opt', type=click.Choice(['subopt1', 'subopt2']))308- @click.argument('sub-arg', required=False, type=click.Choice(['subarg1', 'subarg2']))347+ @click.option("--sub-opt", type=click.Choice(["subopt1", "subopt2"]))348+ @click.argument(349+ "sub-arg", required=False, type=click.Choice(["subarg1", "subarg2"])350+ )351 def sub(sub_opt, sub_arg):352 pass353 312- @sub.command(short_help='bsub help')313- @click.option('--bsub-opt', type=click.Choice(['bsubopt1', 'bsubopt2']))314- @click.argument('bsub-arg1', required=False, type=click.Choice(['bsubarg1', 'bsubarg2']))315- @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))354+ @sub.command(short_help="bsub help")355+ @click.option("--bsub-opt", type=click.Choice(["bsubopt1", "bsubopt2"]))356+ @click.argument(357+ "bsub-arg1", required=False, type=click.Choice(["bsubarg1", "bsubarg2"])358+ )359+ @click.argument(360+ "bbsub-arg2", required=False, type=click.Choice(["bbsubarg1", "bbsubarg2"])361+ )362 def bsub(bsub_opt):363 pass364 319- @sub.group('csub')365+ @sub.group("csub")366 def csub():367 pass368 369 @csub.command()370 def dsub():371 pass372 327- assert choices_with_help(cli, ['sub', 'subarg1'], '') == [('bsub', 'bsub help'), ('csub', '')]328- assert choices_without_help(cli, ['sub'], '') == ['subarg1', 'subarg2']329- assert choices_without_help(cli, ['sub', '--sub-opt'], '') == ['subopt1', 'subopt2']330- assert choices_without_help(cli, ['sub', '--sub-opt', 'subopt1'], '') == \331- ['subarg1', 'subarg2']332- assert choices_without_help(cli,333- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-') == ['--bsub-opt']334- assert choices_without_help(cli,335- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '') == ['bsubarg1', 'bsubarg2']336- assert choices_without_help(cli,337- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '') == \338- ['bsubopt1', 'bsubopt2']339- assert choices_without_help(cli,340- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt', 'bsubopt1', 'bsubarg1'],341- '') == ['bbsubarg1', 'bbsubarg2']342- assert choices_without_help(cli,343- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'csub'],344- '') == ['dsub']373+ assert choices_with_help(cli, ["sub", "subarg1"], "") == [374+ ("bsub", "bsub help"),375+ ("csub", ""),376+ ]377+ assert choices_without_help(cli, ["sub"], "") == ["subarg1", "subarg2"]378+ assert choices_without_help(cli, ["sub", "--sub-opt"], "") == ["subopt1", "subopt2"]379+ assert choices_without_help(cli, ["sub", "--sub-opt", "subopt1"], "") == [380+ "subarg1",381+ "subarg2",382+ ]383+ assert choices_without_help(384+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], "-"385+ ) == ["--bsub-opt"]386+ assert choices_without_help(387+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], ""388+ ) == ["bsubarg1", "bsubarg2"]389+ assert choices_without_help(390+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub", "--bsub-opt"], ""391+ ) == ["bsubopt1", "bsubopt2"]392+ assert choices_without_help(393+ cli,394+ [395+ "sub",396+ "--sub-opt",397+ "subopt1",398+ "subarg1",399+ "bsub",400+ "--bsub-opt",401+ "bsubopt1",402+ "bsubarg1",403+ ],404+ "",405+ ) == ["bbsubarg1", "bbsubarg2"]406+ assert choices_without_help(407+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "csub"], ""408+ ) == ["dsub"]409 410 411 def test_chained_multi():412 @click.group()19 unmodified lines432 @csub.command()433 def esub():434 pass435 372- assert choices_without_help(cli, ['sub'], '') == ['bsub', 'csub']373- assert choices_without_help(cli, ['sub'], 'c') == ['csub']374- assert choices_without_help(cli, ['sub', 'csub'], '') == ['dsub', 'esub']375- assert choices_without_help(cli, ['sub', 'csub', 'dsub'], '') == ['esub']436+ assert choices_without_help(cli, ["sub"], "") == ["bsub", "csub"]437+ assert choices_without_help(cli, ["sub"], "c") == ["csub"]438+ assert choices_without_help(cli, ["sub", "csub"], "") == ["dsub", "esub"]439+ assert choices_without_help(cli, ["sub", "csub", "dsub"], "") == ["esub"]440 441 442 def test_hidden():443 @click.group()380- @click.option('--name', hidden=True)381- @click.option('--choices', type=click.Choice([1, 2]), hidden=True)444+ @click.option("--name", hidden=True)445+ @click.option("--choices", type=click.Choice([1, 2]), hidden=True)446 def cli(name):447 pass448 449 @cli.group(hidden=True)8 unmodified lines458 def asub():459 pass460 461 @cli.command(hidden=True)398- @click.option('--hname')462+ @click.option("--hname")463 def hsub():464 pass465 402- assert choices_without_help(cli, [], '--n') == []403- assert choices_without_help(cli, [], '--c') == []466+ assert choices_without_help(cli, [], "--n") == []467+ assert choices_without_help(cli, [], "--c") == []468 # If the user exactly types out the hidden param, complete its options.405- assert choices_without_help(cli, ['--choices'], '') == [1, 2]406- assert choices_without_help(cli, [], '') == ['asub']407- assert choices_without_help(cli, [], '') == ['asub']408- assert choices_without_help(cli, [], 'h') == []469+ assert choices_without_help(cli, ["--choices"], "") == [1, 2]470+ assert choices_without_help(cli, [], "") == ["asub"]471+ assert choices_without_help(cli, [], "") == ["asub"]472+ assert choices_without_help(cli, [], "h") == []473 # If the user exactly types out the hidden command, complete its subcommands.410- assert choices_without_help(cli, ['hgroup'], '') == ['hgroupsub']411- assert choices_without_help(cli, ['hsub'], '--h') == ['--hname']474+ assert choices_without_help(cli, ["hgroup"], "") == ["hgroupsub"]475+ assert choices_without_help(cli, ["hsub"], "--h") == ["--hname"]476 477 478 @pytest.mark.parametrize(479 ("args", "part", "expect"),21 unmodified linesmodified:tests/test_basic.py+216 added-210 removed
1 # -*- coding: utf-8 -*-2 import os3 import uuid4+5 import click6 7 8 def test_basic_functionality(runner):9 @click.command()10 def cli():11 """Hello World!"""11- click.echo('I EXECUTED')12+ click.echo("I EXECUTED")13 13- result = runner.invoke(cli, ['--help'])14+ result = runner.invoke(cli, ["--help"])15 assert not result.exception15- assert 'Hello World!' in result.output16- assert 'Show this message and exit.' in result.output16+ assert "Hello World!" in result.output17+ assert "Show this message and exit." in result.output18 assert result.exit_code == 018- assert 'I EXECUTED' not in result.output19+ assert "I EXECUTED" not in result.output20 21 result = runner.invoke(cli, [])22 assert not result.exception22- assert 'I EXECUTED' in result.output23+ assert "I EXECUTED" in result.output24 assert result.exit_code == 025 26 27 def test_repr():8 unmodified lines36 @group.command()37 def subcommand():38 pass39 39- assert repr(command) == '<Command command>'40- assert repr(group) == '<Group group>'41- assert repr(subcommand) == '<Command subcommand>'40+ assert repr(command) == "<Command command>"41+ assert repr(group) == "<Group group>"42+ assert repr(subcommand) == "<Command subcommand>"43 44 45 def test_return_values():46 @click.command()47 def cli():48 return 4249 49- with cli.make_context('foo', []) as ctx:50+ with cli.make_context("foo", []) as ctx:51 rv = cli.invoke(ctx)51- assert rv is 4252+ assert rv == 4253 54 55 def test_basic_group(runner):56 @click.group()57 def cli():58 """This is the root."""58- click.echo('ROOT EXECUTED')59+ click.echo("ROOT EXECUTED")60 61 @cli.command()62 def subcommand():63 """This is a subcommand."""63- click.echo('SUBCOMMAND EXECUTED')64+ click.echo("SUBCOMMAND EXECUTED")65 65- result = runner.invoke(cli, ['--help'])66+ result = runner.invoke(cli, ["--help"])67 assert not result.exception67- assert 'COMMAND [ARGS]...' in result.output68- assert 'This is the root' in result.output69- assert 'This is a subcommand.' in result.output68+ assert "COMMAND [ARGS]..." in result.output69+ assert "This is the root" in result.output70+ assert "This is a subcommand." in result.output71 assert result.exit_code == 071- assert 'ROOT EXECUTED' not in result.output72+ assert "ROOT EXECUTED" not in result.output73 73- result = runner.invoke(cli, ['subcommand'])74+ result = runner.invoke(cli, ["subcommand"])75 assert not result.exception76 assert result.exit_code == 076- assert 'ROOT EXECUTED' in result.output77- assert 'SUBCOMMAND EXECUTED' in result.output77+ assert "ROOT EXECUTED" in result.output78+ assert "SUBCOMMAND EXECUTED" in result.output79 80 81 def test_basic_option(runner):82 @click.command()82- @click.option('--foo', default='no value')83+ @click.option("--foo", default="no value")84 def cli(foo):84- click.echo('FOO:[%s]' % foo)85+ click.echo(u"FOO:[{}]".format(foo))86 87 result = runner.invoke(cli, [])88 assert not result.exception88- assert 'FOO:[no value]' in result.output89+ assert "FOO:[no value]" in result.output90 90- result = runner.invoke(cli, ['--foo=42'])91+ result = runner.invoke(cli, ["--foo=42"])92 assert not result.exception92- assert 'FOO:[42]' in result.output93+ assert "FOO:[42]" in result.output94 94- result = runner.invoke(cli, ['--foo'])95+ result = runner.invoke(cli, ["--foo"])96 assert result.exception96- assert '--foo option requires an argument' in result.output97+ assert "--foo option requires an argument" in result.output98 98- result = runner.invoke(cli, ['--foo='])99+ result = runner.invoke(cli, ["--foo="])100 assert not result.exception100- assert 'FOO:[]' in result.output101+ assert "FOO:[]" in result.output102 102- result = runner.invoke(cli, [u'--foo=\N{SNOWMAN}'])103+ result = runner.invoke(cli, [u"--foo=\N{SNOWMAN}"])104 assert not result.exception104- assert u'FOO:[\N{SNOWMAN}]' in result.output105+ assert u"FOO:[\N{SNOWMAN}]" in result.output106 107 108 def test_int_option(runner):109 @click.command()109- @click.option('--foo', default=42)110+ @click.option("--foo", default=42)111 def cli(foo):111- click.echo('FOO:[%s]' % (foo * 2))112+ click.echo("FOO:[{}]".format(foo * 2))113 114 result = runner.invoke(cli, [])115 assert not result.exception115- assert 'FOO:[84]' in result.output116+ assert "FOO:[84]" in result.output117 117- result = runner.invoke(cli, ['--foo=23'])118+ result = runner.invoke(cli, ["--foo=23"])119 assert not result.exception119- assert 'FOO:[46]' in result.output120+ assert "FOO:[46]" in result.output121 121- result = runner.invoke(cli, ['--foo=bar'])122+ result = runner.invoke(cli, ["--foo=bar"])123 assert result.exception123- assert 'Invalid value for "--foo": bar is not a valid integer' \124- in result.output124+ assert "Invalid value for '--foo': bar is not a valid integer" in result.output125 126 127 def test_uuid_option(runner):128 @click.command()129- @click.option('--u', default='ba122011-349f-423b-873b-9d6a79c688ab',130- type=click.UUID)129+ @click.option(130+ "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID131+ )132 def cli(u):133 assert type(u) is uuid.UUID133- click.echo('U:[%s]' % u)134+ click.echo("U:[{}]".format(u))135 136 result = runner.invoke(cli, [])137 assert not result.exception137- assert 'U:[ba122011-349f-423b-873b-9d6a79c688ab]' in result.output138+ assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output139 139- result = runner.invoke(cli, ['--u=821592c1-c50e-4971-9cd6-e89dc6832f86'])140+ result = runner.invoke(cli, ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"])141 assert not result.exception141- assert 'U:[821592c1-c50e-4971-9cd6-e89dc6832f86]' in result.output142+ assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output143 143- result = runner.invoke(cli, ['--u=bar'])144+ result = runner.invoke(cli, ["--u=bar"])145 assert result.exception145- assert 'Invalid value for "--u": bar is not a valid UUID value' \146- in result.output146+ assert "Invalid value for '--u': bar is not a valid UUID value" in result.output147 148 149 def test_float_option(runner):150 @click.command()151- @click.option('--foo', default=42, type=click.FLOAT)151+ @click.option("--foo", default=42, type=click.FLOAT)152 def cli(foo):153 assert type(foo) is float154- click.echo('FOO:[%s]' % foo)154+ click.echo("FOO:[{}]".format(foo))155 156 result = runner.invoke(cli, [])157 assert not result.exception158- assert 'FOO:[42.0]' in result.output158+ assert "FOO:[42.0]" in result.output159 160- result = runner.invoke(cli, ['--foo=23.5'])160+ result = runner.invoke(cli, ["--foo=23.5"])161 assert not result.exception162- assert 'FOO:[23.5]' in result.output162+ assert "FOO:[23.5]" in result.output163 164- result = runner.invoke(cli, ['--foo=bar'])164+ result = runner.invoke(cli, ["--foo=bar"])165 assert result.exception166- assert 'Invalid value for "--foo": bar is not a valid float' \167- in result.output166+ assert "Invalid value for '--foo': bar is not a valid float" in result.output167 168 169 def test_boolean_option(runner):170 for default in True, False:171+172 @click.command()173- @click.option('--with-foo/--without-foo', default=default)173+ @click.option("--with-foo/--without-foo", default=default)174 def cli(with_foo):175 click.echo(with_foo)176 177- result = runner.invoke(cli, ['--with-foo'])177+ result = runner.invoke(cli, ["--with-foo"])178 assert not result.exception179- assert result.output == 'True\n'180- result = runner.invoke(cli, ['--without-foo'])179+ assert result.output == "True\n"180+ result = runner.invoke(cli, ["--without-foo"])181 assert not result.exception182- assert result.output == 'False\n'182+ assert result.output == "False\n"183 result = runner.invoke(cli, [])184 assert not result.exception185- assert result.output == '%s\n' % default185+ assert result.output == "{}\n".format(default)186 187 for default in True, False:188+189 @click.command()189- @click.option('--flag', is_flag=True, default=default)190+ @click.option("--flag", is_flag=True, default=default)191 def cli(flag):192 click.echo(flag)193 193- result = runner.invoke(cli, ['--flag'])194+ result = runner.invoke(cli, ["--flag"])195 assert not result.exception195- assert result.output == '%s\n' % (not default)196+ assert result.output == "{}\n".format(not default)197 result = runner.invoke(cli, [])198 assert not result.exception198- assert result.output == '%s\n' % (default)199+ assert result.output == "{}\n".format(default)200 201 202 def test_boolean_conversion(runner):203 for default in True, False:204+205 @click.command()204- @click.option('--flag', default=default, type=bool)206+ @click.option("--flag", default=default, type=bool)207 def cli(flag):208 click.echo(flag)209 208- for value in 'true', 't', '1', 'yes', 'y':209- result = runner.invoke(cli, ['--flag', value])210+ for value in "true", "t", "1", "yes", "y":211+ result = runner.invoke(cli, ["--flag", value])212 assert not result.exception211- assert result.output == 'True\n'213+ assert result.output == "True\n"214 213- for value in 'false', 'f', '0', 'no', 'n':214- result = runner.invoke(cli, ['--flag', value])215+ for value in "false", "f", "0", "no", "n":216+ result = runner.invoke(cli, ["--flag", value])217 assert not result.exception216- assert result.output == 'False\n'218+ assert result.output == "False\n"219 220 result = runner.invoke(cli, [])221 assert not result.exception220- assert result.output == '%s\n' % default222+ assert result.output == "{}\n".format(default)223 224 225 def test_file_option(runner):226 @click.command()225- @click.option('--file', type=click.File('w'))227+ @click.option("--file", type=click.File("w"))228 def input(file):227- file.write('Hello World!\n')229+ file.write("Hello World!\n")230 231 @click.command()230- @click.option('--file', type=click.File('r'))232+ @click.option("--file", type=click.File("r"))233 def output(file):234 click.echo(file.read())235 236 with runner.isolated_filesystem():235- result_in = runner.invoke(input, ['--file=example.txt'])236- result_out = runner.invoke(output, ['--file=example.txt'])237+ result_in = runner.invoke(input, ["--file=example.txt"])238+ result_out = runner.invoke(output, ["--file=example.txt"])239 240 assert not result_in.exception239- assert result_in.output == ''241+ assert result_in.output == ""242 assert not result_out.exception241- assert result_out.output == 'Hello World!\n\n'243+ assert result_out.output == "Hello World!\n\n"244 245 246 def test_file_lazy_mode(runner):247 do_io = False248 249 @click.command()248- @click.option('--file', type=click.File('w'))250+ @click.option("--file", type=click.File("w"))251 def input(file):252 if do_io:251- file.write('Hello World!\n')253+ file.write("Hello World!\n")254 255 @click.command()254- @click.option('--file', type=click.File('r'))256+ @click.option("--file", type=click.File("r"))257 def output(file):258 pass259 260 with runner.isolated_filesystem():259- os.mkdir('example.txt')261+ os.mkdir("example.txt")262 263 do_io = True262- result_in = runner.invoke(input, ['--file=example.txt'])264+ result_in = runner.invoke(input, ["--file=example.txt"])265 assert result_in.exit_code == 1266 267 do_io = False266- result_in = runner.invoke(input, ['--file=example.txt'])268+ result_in = runner.invoke(input, ["--file=example.txt"])269 assert result_in.exit_code == 0270 269- result_out = runner.invoke(output, ['--file=example.txt'])271+ result_out = runner.invoke(output, ["--file=example.txt"])272 assert result_out.exception273 274 @click.command()273- @click.option('--file', type=click.File('w', lazy=False))275+ @click.option("--file", type=click.File("w", lazy=False))276 def input_non_lazy(file):275- file.write('Hello World!\n')277+ file.write("Hello World!\n")278 279 with runner.isolated_filesystem():278- os.mkdir('example.txt')279- result_in = runner.invoke(input_non_lazy, ['--file=example.txt'])280+ os.mkdir("example.txt")281+ result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])282 assert result_in.exit_code == 2281- assert 'Invalid value for "--file": Could not open file: example.txt' \283+ assert (284+ "Invalid value for '--file': Could not open file: example.txt"285 in result_in.output286+ )287 288 289 def test_path_option(runner):290 @click.command()287- @click.option('-O', type=click.Path(file_okay=False, exists=True,288- writable=True))291+ @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))292 def write_to_dir(o):290- with open(os.path.join(o, 'foo.txt'), 'wb') as f:291- f.write(b'meh\n')293+ with open(os.path.join(o, "foo.txt"), "wb") as f:294+ f.write(b"meh\n")295 296 with runner.isolated_filesystem():294- os.mkdir('test')297+ os.mkdir("test")298 296- result = runner.invoke(write_to_dir, ['-O', 'test'])299+ result = runner.invoke(write_to_dir, ["-O", "test"])300 assert not result.exception301 299- with open('test/foo.txt', 'rb') as f:300- assert f.read() == b'meh\n'302+ with open("test/foo.txt", "rb") as f:303+ assert f.read() == b"meh\n"304 302- result = runner.invoke(write_to_dir, ['-O', 'test/foo.txt'])303- assert 'Invalid value for "-O": Directory "test/foo.txt" is a file.' \304- in result.output305+ result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])306+ assert "is a file" in result.output307 308 @click.command()307- @click.option('-f', type=click.Path(exists=True))309+ @click.option("-f", type=click.Path(exists=True))310 def showtype(f):309- click.echo('is_file=%s' % os.path.isfile(f))310- click.echo('is_dir=%s' % os.path.isdir(f))311+ click.echo("is_file={}".format(os.path.isfile(f)))312+ click.echo("is_dir={}".format(os.path.isdir(f)))313 314 with runner.isolated_filesystem():313- result = runner.invoke(showtype, ['-f', 'xxx'])314- assert 'Error: Invalid value for "-f": Path "xxx" does not exist' \315- in result.output315+ result = runner.invoke(showtype, ["-f", "xxx"])316+ assert "does not exist" in result.output317 317- result = runner.invoke(showtype, ['-f', '.'])318- assert 'is_file=False' in result.output319- assert 'is_dir=True' in result.output318+ result = runner.invoke(showtype, ["-f", "."])319+ assert "is_file=False" in result.output320+ assert "is_dir=True" in result.output321 322 @click.command()322- @click.option('-f', type=click.Path())323+ @click.option("-f", type=click.Path())324 def exists(f):324- click.echo('exists=%s' % os.path.exists(f))325+ click.echo("exists={}".format(os.path.exists(f)))326 327 with runner.isolated_filesystem():327- result = runner.invoke(exists, ['-f', 'xxx'])328- assert 'exists=False' in result.output328+ result = runner.invoke(exists, ["-f", "xxx"])329+ assert "exists=False" in result.output330 330- result = runner.invoke(exists, ['-f', '.'])331- assert 'exists=True' in result.output331+ result = runner.invoke(exists, ["-f", "."])332+ assert "exists=True" in result.output333 334 335 def test_choice_option(runner):336 @click.command()336- @click.option('--method', type=click.Choice(['foo', 'bar', 'baz']))337+ @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))338 def cli(method):339 click.echo(method)340 340- result = runner.invoke(cli, ['--method=foo'])341+ result = runner.invoke(cli, ["--method=foo"])342 assert not result.exception342- assert result.output == 'foo\n'343+ assert result.output == "foo\n"344 344- result = runner.invoke(cli, ['--method=meh'])345+ result = runner.invoke(cli, ["--method=meh"])346 assert result.exit_code == 2346- assert 'Invalid value for "--method": invalid choice: meh. ' \347- '(choose from foo, bar, baz)' in result.output347+ assert (348+ "Invalid value for '--method': invalid choice: meh."349+ " (choose from foo, bar, baz)" in result.output350+ )351 349- result = runner.invoke(cli, ['--help'])350- assert '--method [foo|bar|baz]' in result.output352+ result = runner.invoke(cli, ["--help"])353+ assert "--method [foo|bar|baz]" in result.output354 355 356 def test_datetime_option_default(runner):354-357 @click.command()356- @click.option('--start_date', type=click.DateTime())358+ @click.option("--start_date", type=click.DateTime())359 def cli(start_date):358- click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))360+ click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))361 360- result = runner.invoke(cli, ['--start_date=2015-09-29'])362+ result = runner.invoke(cli, ["--start_date=2015-09-29"])363 assert not result.exception362- assert result.output == '2015-09-29T00:00:00\n'364+ assert result.output == "2015-09-29T00:00:00\n"365 364- result = runner.invoke(cli, ['--start_date=2015-09-29T09:11:22'])366+ result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])367 assert not result.exception366- assert result.output == '2015-09-29T09:11:22\n'368+ assert result.output == "2015-09-29T09:11:22\n"369 368- result = runner.invoke(cli, ['--start_date=2015-09'])370+ result = runner.invoke(cli, ["--start_date=2015-09"])371 assert result.exit_code == 2370- assert ('Invalid value for "--start_date": '371- 'invalid datetime format: 2015-09. '372- '(choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)'373- ) in result.output372+ assert (373+ "Invalid value for '--start_date':"374+ " invalid datetime format: 2015-09."375+ " (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"376+ ) in result.output377 375- result = runner.invoke(cli, ['--help'])376- assert '--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]' in result.output378+ result = runner.invoke(cli, ["--help"])379+ assert (380+ "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output381+ )382 383 384 def test_datetime_option_custom(runner):385 @click.command()381- @click.option('--start_date',382- type=click.DateTime(formats=['%A %B %d, %Y']))386+ @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))387 def cli(start_date):384- click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))388+ click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))389 386- result = runner.invoke(cli, ['--start_date=Wednesday June 05, 2010'])390+ result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])391 assert not result.exception388- assert result.output == '2010-06-05T00:00:00\n'392+ assert result.output == "2010-06-05T00:00:00\n"393 394 395 def test_int_range_option(runner):396 @click.command()393- @click.option('--x', type=click.IntRange(0, 5))397+ @click.option("--x", type=click.IntRange(0, 5))398 def cli(x):399 click.echo(x)400 397- result = runner.invoke(cli, ['--x=5'])401+ result = runner.invoke(cli, ["--x=5"])402 assert not result.exception399- assert result.output == '5\n'403+ assert result.output == "5\n"404 401- result = runner.invoke(cli, ['--x=6'])405+ result = runner.invoke(cli, ["--x=6"])406 assert result.exit_code == 2403- assert 'Invalid value for "--x": 6 is not in the valid range of 0 to 5.\n' \407+ assert (408+ "Invalid value for '--x': 6 is not in the valid range of 0 to 5.\n"409 in result.output410+ )411 412 @click.command()407- @click.option('--x', type=click.IntRange(0, 5, clamp=True))413+ @click.option("--x", type=click.IntRange(0, 5, clamp=True))414 def clamp(x):415 click.echo(x)416 411- result = runner.invoke(clamp, ['--x=5'])417+ result = runner.invoke(clamp, ["--x=5"])418 assert not result.exception413- assert result.output == '5\n'419+ assert result.output == "5\n"420 415- result = runner.invoke(clamp, ['--x=6'])421+ result = runner.invoke(clamp, ["--x=6"])422 assert not result.exception417- assert result.output == '5\n'423+ assert result.output == "5\n"424 419- result = runner.invoke(clamp, ['--x=-1'])425+ result = runner.invoke(clamp, ["--x=-1"])426 assert not result.exception421- assert result.output == '0\n'427+ assert result.output == "0\n"428 429 430 def test_float_range_option(runner):431 @click.command()426- @click.option('--x', type=click.FloatRange(0, 5))432+ @click.option("--x", type=click.FloatRange(0, 5))433 def cli(x):434 click.echo(x)435 430- result = runner.invoke(cli, ['--x=5.0'])436+ result = runner.invoke(cli, ["--x=5.0"])437 assert not result.exception432- assert result.output == '5.0\n'438+ assert result.output == "5.0\n"439 434- result = runner.invoke(cli, ['--x=6.0'])440+ result = runner.invoke(cli, ["--x=6.0"])441 assert result.exit_code == 2436- assert 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n' \442+ assert (443+ "Invalid value for '--x': 6.0 is not in the valid range of 0 to 5.\n"444 in result.output445+ )446 447 @click.command()440- @click.option('--x', type=click.FloatRange(0, 5, clamp=True))448+ @click.option("--x", type=click.FloatRange(0, 5, clamp=True))449 def clamp(x):450 click.echo(x)451 444- result = runner.invoke(clamp, ['--x=5.0'])452+ result = runner.invoke(clamp, ["--x=5.0"])453 assert not result.exception446- assert result.output == '5.0\n'454+ assert result.output == "5.0\n"455 448- result = runner.invoke(clamp, ['--x=6.0'])456+ result = runner.invoke(clamp, ["--x=6.0"])457 assert not result.exception450- assert result.output == '5\n'458+ assert result.output == "5\n"459 452- result = runner.invoke(clamp, ['--x=-1.0'])460+ result = runner.invoke(clamp, ["--x=-1.0"])461 assert not result.exception454- assert result.output == '0\n'462+ assert result.output == "0\n"463 464 465 def test_required_option(runner):466 @click.command()459- @click.option('--foo', required=True)467+ @click.option("--foo", required=True)468 def cli(foo):469 click.echo(foo)470 471 result = runner.invoke(cli, [])472 assert result.exit_code == 2465- assert 'Missing option "--foo"' in result.output473+ assert "Missing option '--foo'" in result.output474 475 476 def test_evaluation_order(runner):477 called = []2 unmodified lines480 called.append(value)481 return value482 483 @click.command()476- @click.option('--missing', default='missing',477- is_eager=False, callback=memo)478- @click.option('--eager-flag1', flag_value='eager1',479- is_eager=True, callback=memo)480- @click.option('--eager-flag2', flag_value='eager2',481- is_eager=True, callback=memo)482- @click.option('--eager-flag3', flag_value='eager3',483- is_eager=True, callback=memo)484- @click.option('--normal-flag1', flag_value='normal1',485- is_eager=False, callback=memo)486- @click.option('--normal-flag2', flag_value='normal2',487- is_eager=False, callback=memo)488- @click.option('--normal-flag3', flag_value='normal3',489- is_eager=False, callback=memo)484+ @click.option("--missing", default="missing", is_eager=False, callback=memo)485+ @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)486+ @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)487+ @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)488+ @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)489+ @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)490+ @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)491 def cli(**x):492 pass493 493- result = runner.invoke(cli, ['--eager-flag2',494- '--eager-flag1',495- '--normal-flag2',496- '--eager-flag3',497- '--normal-flag3',498- '--normal-flag3',499- '--normal-flag1',500- '--normal-flag1'])494+ result = runner.invoke(495+ cli,496+ [497+ "--eager-flag2",498+ "--eager-flag1",499+ "--normal-flag2",500+ "--eager-flag3",501+ "--normal-flag3",502+ "--normal-flag3",503+ "--normal-flag1",504+ "--normal-flag1",505+ ],506+ )507 assert not result.exception508 assert called == [503- 'eager2',504- 'eager1',505- 'eager3',506- 'normal2',507- 'normal3',508- 'normal1',509- 'missing',509+ "eager2",510+ "eager1",511+ "eager3",512+ "normal2",513+ "normal3",514+ "normal1",515+ "missing",516 ]517 518 519 def test_hidden_option(runner):520 @click.command()515- @click.option('--nope', hidden=True)521+ @click.option("--nope", hidden=True)522 def cli(nope):523 click.echo(nope)524 519- result = runner.invoke(cli, ['--help'])525+ result = runner.invoke(cli, ["--help"])526 assert result.exit_code == 0521- assert '--nope' not in result.output527+ assert "--nope" not in result.output528 529 530 def test_hidden_command(runner):531 @click.group()3 unmodified lines535 @cli.command(hidden=True)536 def nope():537 pass538 533- result = runner.invoke(cli, ['--help'])539+ result = runner.invoke(cli, ["--help"])540 assert result.exit_code == 0535- assert 'nope' not in result.output541+ assert "nope" not in result.output542 543 544 def test_hidden_group(runner):545 @click.group()7 unmodified lines553 @subgroup.command()554 def nope():555 pass556 551- result = runner.invoke(cli, ['--help'])557+ result = runner.invoke(cli, ["--help"])558 assert result.exit_code == 0553- assert 'subgroup' not in result.output554- assert 'nope' not in result.output559+ assert "subgroup" not in result.output560+ assert "nope" not in result.outputmodified:tests/test_chain.py+70 added-92 removed
1 import sys2-import click2+3 import pytest4 5+import click6 7+8 def debug():7- click.echo('%s=%s' % (8- sys._getframe(1).f_code.co_name,9- '|'.join(click.get_current_context().args),10- ))9+ click.echo(10+ "{}={}".format(11+ sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args)12+ )13+ )14 15 16 def test_basic_chaining(runner):17 @click.group(chain=True)18 def cli():19 pass20 18- @cli.command('sdist')21+ @cli.command("sdist")22 def sdist():20- click.echo('sdist called')23+ click.echo("sdist called")24 22- @cli.command('bdist')25+ @cli.command("bdist")26 def bdist():24- click.echo('bdist called')27+ click.echo("bdist called")28 26- result = runner.invoke(cli, ['bdist', 'sdist', 'bdist'])29+ result = runner.invoke(cli, ["bdist", "sdist", "bdist"])30 assert not result.exception31 assert result.output.splitlines() == [29- 'bdist called',30- 'sdist called',31- 'bdist called',32+ "bdist called",33+ "sdist called",34+ "bdist called",35 ]36 37 38 def test_chaining_help(runner):1 unmodified line40 def cli():41 """ROOT HELP"""42 pass43 41- @cli.command('sdist')44+ @cli.command("sdist")45 def sdist():46 """SDIST HELP"""44- click.echo('sdist called')47+ click.echo("sdist called")48 46- @cli.command('bdist')49+ @cli.command("bdist")50 def bdist():51 """BDIST HELP"""49- click.echo('bdist called')52+ click.echo("bdist called")53 51- result = runner.invoke(cli, ['--help'])54+ result = runner.invoke(cli, ["--help"])55 assert not result.exception53- assert 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' in result.output54- assert 'ROOT HELP' in result.output56+ assert "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." in result.output57+ assert "ROOT HELP" in result.output58 56- result = runner.invoke(cli, ['sdist', '--help'])59+ result = runner.invoke(cli, ["sdist", "--help"])60 assert not result.exception58- assert 'SDIST HELP' in result.output61+ assert "SDIST HELP" in result.output62 60- result = runner.invoke(cli, ['bdist', '--help'])63+ result = runner.invoke(cli, ["bdist", "--help"])64 assert not result.exception62- assert 'BDIST HELP' in result.output65+ assert "BDIST HELP" in result.output66 64- result = runner.invoke(cli, ['bdist', 'sdist', '--help'])67+ result = runner.invoke(cli, ["bdist", "sdist", "--help"])68 assert not result.exception66- assert 'SDIST HELP' in result.output69+ assert "SDIST HELP" in result.output70 71 72 def test_chaining_with_options(runner):73 @click.group(chain=True)74 def cli():75 pass76 74- @cli.command('sdist')75- @click.option('--format')77+ @cli.command("sdist")78+ @click.option("--format")79 def sdist(format):77- click.echo('sdist called %s' % format)80+ click.echo("sdist called {}".format(format))81 79- @cli.command('bdist')80- @click.option('--format')82+ @cli.command("bdist")83+ @click.option("--format")84 def bdist(format):82- click.echo('bdist called %s' % format)85+ click.echo("bdist called {}".format(format))86 84- result = runner.invoke(cli, ['bdist', '--format=1', 'sdist', '--format=2'])87+ result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"])88 assert not result.exception86- assert result.output.splitlines() == [87- 'bdist called 1',88- 'sdist called 2',89- ]89+ assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]90 91 92 def test_chaining_with_arguments(runner):93 @click.group(chain=True)94 def cli():95 pass96 97- @cli.command('sdist')98- @click.argument('format')97+ @cli.command("sdist")98+ @click.argument("format")99 def sdist(format):100- click.echo('sdist called %s' % format)100+ click.echo("sdist called {}".format(format))101 102- @cli.command('bdist')103- @click.argument('format')102+ @cli.command("bdist")103+ @click.argument("format")104 def bdist(format):105- click.echo('bdist called %s' % format)105+ click.echo("bdist called {}".format(format))106 107- result = runner.invoke(cli, ['bdist', '1', 'sdist', '2'])107+ result = runner.invoke(cli, ["bdist", "1", "sdist", "2"])108 assert not result.exception109- assert result.output.splitlines() == [110- 'bdist called 1',111- 'sdist called 2',112- ]109+ assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]110 111 112 def test_pipeline(runner):113 @click.group(chain=True, invoke_without_command=True)117- @click.option('-i', '--input', type=click.File('r'))114+ @click.option("-i", "--input", type=click.File("r"))115 def cli(input):116 pass117 118 @cli.resultcallback()119 def process_pipeline(processors, input):123- iterator = (x.rstrip('\r\n') for x in input)120+ iterator = (x.rstrip("\r\n") for x in input)121 for processor in processors:122 iterator = processor(iterator)123 for item in iterator:124 click.echo(item)125 129- @cli.command('uppercase')126+ @cli.command("uppercase")127 def make_uppercase():128 def processor(iterator):129 for line in iterator:130 yield line.upper()131+132 return processor133 136- @cli.command('strip')134+ @cli.command("strip")135 def make_strip():136 def processor(iterator):137 for line in iterator:138 yield line.strip()139+140 return processor141 143- result = runner.invoke(cli, ['-i', '-'], input='foo\nbar')142+ result = runner.invoke(cli, ["-i", "-"], input="foo\nbar")143 assert not result.exception145- assert result.output.splitlines() == [146- 'foo',147- 'bar',148- ]144+ assert result.output.splitlines() == ["foo", "bar"]145 150- result = runner.invoke(cli, ['-i', '-', 'strip'], input='foo \n bar')146+ result = runner.invoke(cli, ["-i", "-", "strip"], input="foo \n bar")147 assert not result.exception152- assert result.output.splitlines() == [153- 'foo',154- 'bar',155- ]148+ assert result.output.splitlines() == ["foo", "bar"]149 157- result = runner.invoke(cli, ['-i', '-', 'strip', 'uppercase'],158- input='foo \n bar')150+ result = runner.invoke(cli, ["-i", "-", "strip", "uppercase"], input="foo \n bar")151 assert not result.exception160- assert result.output.splitlines() == [161- 'FOO',162- 'BAR',163- ]152+ assert result.output.splitlines() == ["FOO", "BAR"]153 154 155 def test_args_and_chain(runner):156 @click.group(chain=True)11 unmodified lines168 @cli.command()169 def c():170 debug()171 183- result = runner.invoke(cli, ['a', 'b', 'c'])172+ result = runner.invoke(cli, ["a", "b", "c"])173 assert not result.exception185- assert result.output.splitlines() == [186- 'cli=',187- 'a=',188- 'b=',189- 'c=',190- ]174+ assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]175 176 177 def test_multicommand_arg_behavior(runner):178 with pytest.raises(RuntimeError):179+180 @click.group(chain=True)196- @click.argument('forbidden', required=False)181+ @click.argument("forbidden", required=False)182 def bad_cli():183 pass184 185 with pytest.raises(RuntimeError):186+187 @click.group(chain=True)202- @click.argument('forbidden', nargs=-1)188+ @click.argument("forbidden", nargs=-1)189 def bad_cli2():190 pass191 192 @click.group(chain=True)207- @click.argument('arg')193+ @click.argument("arg")194 def cli(arg):209- click.echo('cli:%s' % arg)195+ click.echo("cli:{}".format(arg))196 197 @cli.command()198 def a():213- click.echo('a')199+ click.echo("a")200 215- result = runner.invoke(cli, ['foo', 'a'])201+ result = runner.invoke(cli, ["foo", "a"])202 assert not result.exception217- assert result.output.splitlines() == [218- 'cli:foo',219- 'a',220- ]203+ assert result.output.splitlines() == ["cli:foo", "a"]204 205 206 @pytest.mark.xfail207 def test_multicommand_chaining(runner):16 unmodified lines224 @cli.command()225 def l1b():226 debug()227 245- result = runner.invoke(cli, ['l1a', 'l2a', 'l1b'])228+ result = runner.invoke(cli, ["l1a", "l2a", "l1b"])229 assert not result.exception247- assert result.output.splitlines() == [248- 'cli=',249- 'l1a=',250- 'l2a=',251- 'l1b=',252- ]230+ assert result.output.splitlines() == ["cli=", "l1a=", "l2a=", "l1b="]modified:tests/test_commands.py+90 added-82 removed
1 # -*- coding: utf-8 -*-2 import re3 4 import click5-import pytest5 6 7 def test_other_command_invoke(runner):8 @click.command()1 unmodified line10 def cli(ctx):11 return ctx.invoke(other_cmd, arg=42)12 13 @click.command()15- @click.argument('arg', type=click.INT)14+ @click.argument("arg", type=click.INT)15 def other_cmd(arg):16 click.echo(arg)17 18 result = runner.invoke(cli, [])19 assert not result.exception21- assert result.output == '42\n'20+ assert result.output == "42\n"21 22 23 def test_other_command_forward(runner):24 cli = click.Group()25 26 @cli.command()28- @click.option('--count', default=1)27+ @click.option("--count", default=1)28 def test(count):30- click.echo('Count: %d' % count)29+ click.echo("Count: {:d}".format(count))30 31 @cli.command()33- @click.option('--count', default=1)32+ @click.option("--count", default=1)33 @click.pass_context34 def dist(ctx, count):35 ctx.forward(test)36 ctx.invoke(test, count=42)37 39- result = runner.invoke(cli, ['dist'])38+ result = runner.invoke(cli, ["dist"])39 assert not result.exception41- assert result.output == 'Count: 1\nCount: 42\n'40+ assert result.output == "Count: 1\nCount: 42\n"41 42 43 def test_auto_shorthelp(runner):44 @click.group()12 unmodified lines57 def long():58 """This is a long text that is too long to show as short help59 and will be truncated instead."""60 62- result = runner.invoke(cli, ['--help'])63- assert re.search(64- r'Commands:\n\s+'65- r'long\s+This is a long text that is too long to show as short help\.\.\.\n\s+'66- r'short\s+This is a short text\.\n\s+'67- r'special-chars\s+Login and store the token in ~/.netrc\.\s*',68- result.output) is not None61+ result = runner.invoke(cli, ["--help"])62+ assert (63+ re.search(64+ r"Commands:\n\s+"65+ r"long\s+This is a long text that is too long to show as short help"66+ r"\.\.\.\n\s+"67+ r"short\s+This is a short text\.\n\s+"68+ r"special-chars\s+Login and store the token in ~/.netrc\.\s*",69+ result.output,70+ )71+ is not None72+ )73 74 75 def test_no_args_is_help(runner):76 @click.command(no_args_is_help=True)1 unmodified line78 pass79 80 result = runner.invoke(cli, [])81 assert result.exit_code == 078- assert 'Show this message and exit.' in result.output82+ assert "Show this message and exit." in result.output83 84 85 def test_default_maps(runner):86 @click.group()87 def cli():88 pass89 90 @cli.command()87- @click.option('--name', default='normal')91+ @click.option("--name", default="normal")92 def foo(name):93 click.echo(name)94 91- result = runner.invoke(cli, ['foo'], default_map={92- 'foo': {'name': 'changed'}93- })95+ result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})96 97 assert not result.exception96- assert result.output == 'changed\n'98+ assert result.output == "changed\n"99 100 101 def test_group_with_args(runner):102 @click.group()101- @click.argument('obj')103+ @click.argument("obj")104 def cli(obj):103- click.echo('obj=%s' % obj)105+ click.echo("obj={}".format(obj))106 107 @cli.command()108 def move():107- click.echo('move')109+ click.echo("move")110 111 result = runner.invoke(cli, [])112 assert result.exit_code == 0111- assert 'Show this message and exit.' in result.output113+ assert "Show this message and exit." in result.output114 113- result = runner.invoke(cli, ['obj1'])115+ result = runner.invoke(cli, ["obj1"])116 assert result.exit_code == 2115- assert 'Error: Missing command.' in result.output117+ assert "Error: Missing command." in result.output118 117- result = runner.invoke(cli, ['obj1', '--help'])119+ result = runner.invoke(cli, ["obj1", "--help"])120 assert result.exit_code == 0119- assert 'Show this message and exit.' in result.output121+ assert "Show this message and exit." in result.output122 121- result = runner.invoke(cli, ['obj1', 'move'])123+ result = runner.invoke(cli, ["obj1", "move"])124 assert result.exit_code == 0123- assert result.output == 'obj=obj1\nmove\n'125+ assert result.output == "obj=obj1\nmove\n"126 127 128 def test_base_command(runner):129 import optparse2 unmodified lines132 def cli():133 pass134 135 class OptParseCommand(click.BaseCommand):134-136 def __init__(self, name, parser, callback):137 click.BaseCommand.__init__(self, name)138 self.parser = parser139 self.callback = callback14 unmodified lines154 155 def invoke(self, ctx):156 ctx.invoke(self.callback, ctx.args, **ctx.params)157 157- parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')158- parser.add_option("-f", "--file", dest="filename",159- help="write report to FILE", metavar="FILE")160- parser.add_option("-q", "--quiet",161- action="store_false", dest="verbose", default=True,162- help="don't print status messages to stdout")158+ parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")159+ parser.add_option(160+ "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"161+ )162+ parser.add_option(163+ "-q",164+ "--quiet",165+ action="store_false",166+ dest="verbose",167+ default=True,168+ help="don't print status messages to stdout",169+ )170 171 def test_callback(args, filename, verbose):165- click.echo(' '.join(args))172+ click.echo(" ".join(args))173 click.echo(filename)174 click.echo(verbose)168- cli.add_command(OptParseCommand('test', parser, test_callback))175 170- result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',171- 'whatever.txt', 'whateverelse.txt'])176+ cli.add_command(OptParseCommand("test", parser, test_callback))177+178+ result = runner.invoke(179+ cli, ["test", "-f", "test.txt", "-q", "whatever.txt", "whateverelse.txt"]180+ )181 assert not result.exception182 assert result.output.splitlines() == [174- 'whatever.txt whateverelse.txt',175- 'test.txt',176- 'False',183+ "whatever.txt whateverelse.txt",184+ "test.txt",185+ "False",186 ]187 179- result = runner.invoke(cli, ['test', '--help'])188+ result = runner.invoke(cli, ["test", "--help"])189 assert not result.exception190 assert result.output.splitlines() == [182- 'Usage: foo test [OPTIONS]',183- '',184- 'Options:',185- ' -h, --help show this help message and exit',186- ' -f FILE, --file=FILE write report to FILE',187- ' -q, --quiet don\'t print status messages to stdout',191+ "Usage: foo test [OPTIONS]",192+ "",193+ "Options:",194+ " -h, --help show this help message and exit",195+ " -f FILE, --file=FILE write report to FILE",196+ " -q, --quiet don't print status messages to stdout",197 ]198 199 200 def test_object_propagation(runner):201 for chain in False, True:202+203 @click.group(chain=chain)194- @click.option('--debug/--no-debug', default=False)204+ @click.option("--debug/--no-debug", default=False)205 @click.pass_context206 def cli(ctx, debug):207 if ctx.obj is None:208 ctx.obj = {}199- ctx.obj['DEBUG'] = debug209+ ctx.obj["DEBUG"] = debug210 211 @cli.command()212 @click.pass_context213 def sync(ctx):204- click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))214+ click.echo("Debug is {}".format("on" if ctx.obj["DEBUG"] else "off"))215 206- result = runner.invoke(cli, ['sync'])216+ result = runner.invoke(cli, ["sync"])217 assert result.exception is None208- assert result.output == 'Debug is off\n'218+ assert result.output == "Debug is off\n"219 220 221 def test_other_command_invoke_with_defaults(runner):222 @click.command()1 unmodified line224 def cli(ctx):225 return ctx.invoke(other_cmd)226 227 @click.command()218- @click.option('--foo', type=click.INT, default=42)228+ @click.option("--foo", type=click.INT, default=42)229 @click.pass_context230 def other_cmd(ctx, foo):221- assert ctx.info_name == 'other-cmd'231+ assert ctx.info_name == "other-cmd"232 click.echo(foo)233 234 result = runner.invoke(cli, [])235 assert not result.exception226- assert result.output == '42\n'236+ assert result.output == "42\n"237 238 239 def test_invoked_subcommand(runner):240 @click.group(invoke_without_command=True)241 @click.pass_context242 def cli(ctx):243 if ctx.invoked_subcommand is None:234- click.echo('no subcommand, use default')244+ click.echo("no subcommand, use default")245 ctx.invoke(sync)246 else:237- click.echo('invoke subcommand')247+ click.echo("invoke subcommand")248 249 @cli.command()250 def sync():241- click.echo('in subcommand')251+ click.echo("in subcommand")252 243- result = runner.invoke(cli, ['sync'])253+ result = runner.invoke(cli, ["sync"])254 assert not result.exception245- assert result.output == 'invoke subcommand\nin subcommand\n'255+ assert result.output == "invoke subcommand\nin subcommand\n"256 257 result = runner.invoke(cli)258 assert not result.exception249- assert result.output == 'no subcommand, use default\nin subcommand\n'259+ assert result.output == "no subcommand, use default\nin subcommand\n"260 261 262 def test_unprocessed_options(runner):253- @click.command(context_settings=dict(254- ignore_unknown_options=True255- ))256- @click.argument('args', nargs=-1, type=click.UNPROCESSED)257- @click.option('--verbose', '-v', count=True)263+ @click.command(context_settings=dict(ignore_unknown_options=True))264+ @click.argument("args", nargs=-1, type=click.UNPROCESSED)265+ @click.option("--verbose", "-v", count=True)266 def cli(verbose, args):259- click.echo('Verbosity: %s' % verbose)260- click.echo('Args: %s' % '|'.join(args))267+ click.echo("Verbosity: {}".format(verbose))268+ click.echo("Args: {}".format("|".join(args)))269 262- result = runner.invoke(cli, ['-foo', '-vvvvx', '--muhaha', 'x', 'y', '-x'])270+ result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])271 assert not result.exception272 assert result.output.splitlines() == [265- 'Verbosity: 4',266- 'Args: -foo|-x|--muhaha|x|y|-x',273+ "Verbosity: 4",274+ "Args: -foo|-x|--muhaha|x|y|-x",275 ]276 277 278 def test_deprecated_in_help_messages(runner):1 unmodified line280 def cmd_with_help():281 """CLI HELP"""282 pass283 276- result = runner.invoke(cmd_with_help, ['--help'])277- assert '(DEPRECATED)' in result.output284+ result = runner.invoke(cmd_with_help, ["--help"])285+ assert "(DEPRECATED)" in result.output286 287 @click.command(deprecated=True)288 def cmd_without_help():289 pass290 283- result = runner.invoke(cmd_without_help, ['--help'])284- assert '(DEPRECATED)' in result.output291+ result = runner.invoke(cmd_without_help, ["--help"])292+ assert "(DEPRECATED)" in result.output293 294 295 def test_deprecated_in_invocation(runner):296 @click.command(deprecated=True)297 def deprecated_cmd():290- debug()298+ pass299 300 result = runner.invoke(deprecated_cmd)293- assert 'DeprecationWarning:' in result.output301+ assert "DeprecationWarning:" in result.outputmodified:tests/test_compat.py+17 added-13 removed
1-import click1 import pytest3-from click._compat import should_strip_ansi, WIN2 3+import click4+from click._compat import should_strip_ansi5+from click._compat import WIN6 7+8 def test_legacy_callbacks(runner):9 def legacy_callback(ctx, value):10 return value.upper()11 12 @click.command()11- @click.option('--foo', callback=legacy_callback)13+ @click.option("--foo", callback=legacy_callback)14 def cli(foo):15 click.echo(foo)16 15- with pytest.warns(Warning, match='Invoked legacy parameter callback'):16- result = runner.invoke(cli, ['--foo', 'wat'])17+ with pytest.warns(Warning, match="Invoked legacy parameter callback"):18+ result = runner.invoke(cli, ["--foo", "wat"])19 assert result.exit_code == 018- assert 'WAT' in result.output20+ assert "WAT" in result.output21 22 23 def test_bash_func_name():24 from click._bashcomplete import get_completion_script23- script = get_completion_script('foo-bar baz_blah', '_COMPLETE_VAR', 'bash').strip()24- assert script.startswith('_foo_barbaz_blah_completion()')25- assert '_COMPLETE_VAR=complete $1' in script25 26+ script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip()27+ assert script.startswith("_foo_barbaz_blah_completion()")28+ assert "_COMPLETE_VAR=complete $1" in script29 30+31 def test_zsh_func_name():32 from click._bashcomplete import get_completion_script30- script = get_completion_script('foo-bar', '_COMPLETE_VAR', 'zsh').strip()31- assert script.startswith('#compdef foo-bar')32- assert 'compdef _foo_bar_completion foo-bar;' in script33- assert '(( ! $+commands[foo-bar] )) && return 1' in script33 34+ script = get_completion_script("foo-bar", "_COMPLETE_VAR", "zsh").strip()35+ assert script.startswith("#compdef foo-bar")36+ assert "compdef _foo_bar_completion foo-bar;" in script37+ assert "(( ! $+commands[foo-bar] )) && return 1" in script38 39+40 @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")41 def test_is_jupyter_kernel_output():42 class JupyterKernelFakeStream(object):43 pass4 unmodified linesmodified:tests/test_context.py+40 added-35 removed
3 unmodified lines4 5 def test_ensure_context_objects(runner):6 class Foo(object):7 def __init__(self):8- self.title = 'default'8+ self.title = "default"9 10 pass_foo = click.make_pass_decorator(Foo, ensure=True)11 12 @click.group()5 unmodified lines18 @pass_foo19 def test(foo):20 click.echo(foo.title)21 22- result = runner.invoke(cli, ['test'])22+ result = runner.invoke(cli, ["test"])23 assert not result.exception24- assert result.output == 'default\n'24+ assert result.output == "default\n"25 26 27 def test_get_context_objects(runner):28 class Foo(object):29 def __init__(self):30- self.title = 'default'30+ self.title = "default"31 32 pass_foo = click.make_pass_decorator(Foo, ensure=True)33 34 @click.group()35 @click.pass_context36 def cli(ctx):37 ctx.obj = Foo()38- ctx.obj.title = 'test'38+ ctx.obj.title = "test"39 40 @cli.command()41 @pass_foo42 def test(foo):43 click.echo(foo.title)44 45- result = runner.invoke(cli, ['test'])45+ result = runner.invoke(cli, ["test"])46 assert not result.exception47- assert result.output == 'test\n'47+ assert result.output == "test\n"48 49 50 def test_get_context_objects_no_ensuring(runner):51 class Foo(object):52 def __init__(self):53- self.title = 'default'53+ self.title = "default"54 55 pass_foo = click.make_pass_decorator(Foo)56 57 @click.group()58 @click.pass_context59 def cli(ctx):60 ctx.obj = Foo()61- ctx.obj.title = 'test'61+ ctx.obj.title = "test"62 63 @cli.command()64 @pass_foo65 def test(foo):66 click.echo(foo.title)67 68- result = runner.invoke(cli, ['test'])68+ result = runner.invoke(cli, ["test"])69 assert not result.exception70- assert result.output == 'test\n'70+ assert result.output == "test\n"71 72 73 def test_get_context_objects_missing(runner):74 class Foo(object):10 unmodified lines85 @pass_foo86 def test(foo):87 click.echo(foo.title)88 89- result = runner.invoke(cli, ['test'])89+ result = runner.invoke(cli, ["test"])90 assert result.exception is not None91 assert isinstance(result.exception, RuntimeError)92- assert "Managed to invoke callback without a context object " \93- "of type 'Foo' existing" in str(result.exception)92+ assert (93+ "Managed to invoke callback without a context object of type"94+ " 'Foo' existing" in str(result.exception)95+ )96 97 98 def test_multi_enter(runner):99 called = []2 unmodified lines102 @click.pass_context103 def cli(ctx):104 def callback():105 called.append(True)106+107 ctx.call_on_close(callback)108 109 with ctx:110 pass8 unmodified lines119 @click.command()120 @click.pass_context121 def cli(ctx):122 assert click.get_current_context() is ctx120- ctx.obj = 'FOOBAR'121- assert click.get_current_context().obj == 'FOOBAR'123+ ctx.obj = "FOOBAR"124+ assert click.get_current_context().obj == "FOOBAR"125 126 assert click.get_current_context(silent=True) is None127 runner.invoke(cli, [], catch_exceptions=False)128 assert click.get_current_context(silent=True) is None129 130 131 def test_context_meta(runner):129- LANG_KEY = __name__ + '.lang'132+ LANG_KEY = "{}.lang".format(__name__)133 134 def set_language(value):135 click.get_current_context().meta[LANG_KEY] = value136 137 def get_language():135- return click.get_current_context().meta.get(LANG_KEY, 'en_US')138+ return click.get_current_context().meta.get(LANG_KEY, "en_US")139 140 @click.command()141 @click.pass_context142 def cli(ctx):140- assert get_language() == 'en_US'141- set_language('de_DE')142- assert get_language() == 'de_DE'143+ assert get_language() == "en_US"144+ set_language("de_DE")145+ assert get_language() == "de_DE"146 147 runner.invoke(cli, [], catch_exceptions=False)148 149 26 unmodified lines176 def test_pass_obj(runner):177 @click.group()178 @click.pass_context179 def cli(ctx):177- ctx.obj = 'test'180+ ctx.obj = "test"181 182 @cli.command()183 @click.pass_obj184 def test(obj):185 click.echo(obj)186 184- result = runner.invoke(cli, ['test'])187+ result = runner.invoke(cli, ["test"])188 assert not result.exception186- assert result.output == 'test\n'189+ assert result.output == "test\n"190 191 192 def test_close_before_pop(runner):193 called = []194 195 @click.command()196 @click.pass_context197 def cli(ctx):195- ctx.obj = 'test'198+ ctx.obj = "test"199 200 @ctx.call_on_close201 def foo():199- assert click.get_current_context().obj == 'test'202+ assert click.get_current_context().obj == "test"203 called.append(True)201- click.echo('aha!')204 205+ click.echo("aha!")206+207 result = runner.invoke(cli, [])208 assert not result.exception205- assert result.output == 'aha!\n'209+ assert result.output == "aha!\n"210 assert called == [True]211 212 213 def test_make_pass_decorator_args(runner):214 """215 Test to check that make_pass_decorator doesn't consume arguments based on216 invocation order.217 """218+219 class Foo(object):215- title = 'foocmd'220+ title = "foocmd"221 222 pass_foo = click.make_pass_decorator(Foo)223 224 @click.group()12 unmodified lines237 @click.pass_context238 def test2(ctx, foo):239 click.echo(foo.title)240 236- result = runner.invoke(cli, ['test1'])241+ result = runner.invoke(cli, ["test1"])242 assert not result.exception238- assert result.output == 'foocmd\n'243+ assert result.output == "foocmd\n"244 240- result = runner.invoke(cli, ['test2'])245+ result = runner.invoke(cli, ["test2"])246 assert not result.exception242- assert result.output == 'foocmd\n'247+ assert result.output == "foocmd\n"248 249 250 def test_exit_not_standalone():251 @click.command()252 @click.pass_context253 def cli(ctx):254 ctx.exit(1)255 251- assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 1256+ assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1257 258 @click.command()259 @click.pass_context260 def cli(ctx):261 ctx.exit(0)262 258- assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0263+ assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0modified:tests/test_defaults.py+10 added-16 removed
1 unmodified line2 3 4 def test_basic_defaults(runner):5 @click.command()6- @click.option('--foo', default=42, type=click.FLOAT)6+ @click.option("--foo", default=42, type=click.FLOAT)7 def cli(foo):8 assert type(foo) is float9- click.echo('FOO:[%s]' % foo)9+ click.echo("FOO:[{}]".format(foo))10 11 result = runner.invoke(cli, [])12 assert not result.exception13- assert 'FOO:[42.0]' in result.output13+ assert "FOO:[42.0]" in result.output14 15 16 def test_multiple_defaults(runner):17 @click.command()18- @click.option('--foo', default=[23, 42], type=click.FLOAT,19- multiple=True)18+ @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True)19 def cli(foo):20 for item in foo:21 assert type(item) is float22 click.echo(item)23 24 result = runner.invoke(cli, [])25 assert not result.exception27- assert result.output.splitlines() == [28- '23.0',29- '42.0',30- ]26+ assert result.output.splitlines() == ["23.0", "42.0"]27 28 29 def test_nargs_plus_multiple(runner):30 @click.command()35- @click.option('--arg', default=((1, 2), (3, 4)),36- nargs=2, multiple=True, type=click.INT)31+ @click.option(32+ "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT33+ )34 def cli(arg):35 for item in arg:39- click.echo('<%d|%d>' % item)36+ click.echo("<{0[0]:d}|{0[1]:d}>".format(item))37 38 result = runner.invoke(cli, [])39 assert not result.exception43- assert result.output.splitlines() == [44- '<1|2>',45- '<3|4>',46- ]40+ assert result.output.splitlines() == ["<1|2>", "<3|4>"]modified:tests/test_formatting.py+138 added-136 removed
23 unmodified lines24 And this is a paragraph25 that will be rewrapped again.26 """27 28- result = runner.invoke(cli, ['--help'], terminal_width=60)28+ result = runner.invoke(cli, ["--help"], terminal_width=60)29 assert not result.exception30 assert result.output.splitlines() == [31- 'Usage: cli [OPTIONS]',32- '',33- ' First paragraph.',34- '',35- ' This is a very long second paragraph and not correctly',36- ' wrapped but it will be rewrapped.',37- '',38- ' This is',39- ' a paragraph',40- ' without rewrapping.',41- '',42- ' 1',43- ' 2',44- ' 3',45- '',46- ' And this is a paragraph that will be rewrapped again.',47- '',48- 'Options:',49- ' --help Show this message and exit.',31+ "Usage: cli [OPTIONS]",32+ "",33+ " First paragraph.",34+ "",35+ " This is a very long second paragraph and not correctly",36+ " wrapped but it will be rewrapped.",37+ "",38+ " This is",39+ " a paragraph",40+ " without rewrapping.",41+ "",42+ " 1",43+ " 2",44+ " 3",45+ "",46+ " And this is a paragraph that will be rewrapped again.",47+ "",48+ "Options:",49+ " --help Show this message and exit.",50 ]51 52 53 def test_wrapping_long_options_strings(runner):7 unmodified lines61 """Second level62 """63 64 @a_very_long.command()65- @click.argument('first')66- @click.argument('second')67- @click.argument('third')68- @click.argument('fourth')69- @click.argument('fifth')70- @click.argument('sixth')65+ @click.argument("first")66+ @click.argument("second")67+ @click.argument("third")68+ @click.argument("fourth")69+ @click.argument("fifth")70+ @click.argument("sixth")71 def command():72 """A command.73 """74 75 # 54 is chosen as a length where the second line is one character76 # longer than the maximum length.77- result = runner.invoke(cli, ['a-very-long', 'command', '--help'],78- terminal_width=54)77+ result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54)78 assert not result.exception79 assert result.output.splitlines() == [81- 'Usage: cli a-very-long command [OPTIONS] FIRST SECOND',82- ' THIRD FOURTH FIFTH',83- ' SIXTH',84- '',85- ' A command.',86- '',87- 'Options:',88- ' --help Show this message and exit.',80+ "Usage: cli a-very-long command [OPTIONS] FIRST SECOND",81+ " THIRD FOURTH FIFTH",82+ " SIXTH",83+ "",84+ " A command.",85+ "",86+ "Options:",87+ " --help Show this message and exit.",88 ]89 90 91 def test_wrapping_long_command_name(runner):7 unmodified lines99 """Second level100 """101 102 @a_very_very_very_long.command()104- @click.argument('first')105- @click.argument('second')106- @click.argument('third')107- @click.argument('fourth')108- @click.argument('fifth')109- @click.argument('sixth')103+ @click.argument("first")104+ @click.argument("second")105+ @click.argument("third")106+ @click.argument("fourth")107+ @click.argument("fifth")108+ @click.argument("sixth")109 def command():110 """A command.111 """112 114- result = runner.invoke(cli, ['a-very-very-very-long', 'command', '--help'],115- terminal_width=54)113+ result = runner.invoke(114+ cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54115+ )116 assert not result.exception117 assert result.output.splitlines() == [118- 'Usage: cli a-very-very-very-long command ',119- ' [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH',120- ' SIXTH',121- '',122- ' A command.',123- '',124- 'Options:',125- ' --help Show this message and exit.',118+ "Usage: cli a-very-very-very-long command ",119+ " [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH",120+ " SIXTH",121+ "",122+ " A command.",123+ "",124+ "Options:",125+ " --help Show this message and exit.",126 ]127 128 129 def test_formatting_empty_help_lines(runner):2 unmodified lines132 """Top level command133 134 """135 136- result = runner.invoke(cli, ['--help'])136+ result = runner.invoke(cli, ["--help"])137 assert not result.exception138 assert result.output.splitlines() == [139- 'Usage: cli [OPTIONS]',140- '',141- ' Top level command',142- '',143- '',144- '',145- 'Options:',146- ' --help Show this message and exit.',139+ "Usage: cli [OPTIONS]",140+ "",141+ " Top level command",142+ "",143+ "",144+ "",145+ "Options:",146+ " --help Show this message and exit.",147 ]148 149 150 def test_formatting_usage_error(runner):151 @click.command()152- @click.argument('arg')152+ @click.argument("arg")153 def cmd(arg):154- click.echo('arg:' + arg)154+ click.echo("arg:{}".format(arg))155 156 result = runner.invoke(cmd, [])157 assert result.exit_code == 2158 assert result.output.splitlines() == [159- 'Usage: cmd [OPTIONS] ARG',160- 'Try "cmd --help" for help.',161- '',162- 'Error: Missing argument "ARG".'159+ "Usage: cmd [OPTIONS] ARG",160+ "Try 'cmd --help' for help.",161+ "",162+ "Error: Missing argument 'ARG'.",163 ]164 165 166 def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171+172 @click.command()172- @click.argument('arg', metavar='metavar')173+ @click.argument("arg", metavar="metavar")174 def cmd(arg):175 pass176 177 result = runner.invoke(cmd, [])178 assert result.exit_code == 2179 assert result.output.splitlines() == [179- 'Usage: cmd [OPTIONS] metavar',180- 'Try "cmd --help" for help.',181- '',182- 'Error: Missing argument "metavar".'180+ "Usage: cmd [OPTIONS] metavar",181+ "Try 'cmd --help' for help.",182+ "",183+ "Error: Missing argument 'metavar'.",184 ]185 186 187 def test_formatting_usage_error_metavar_bad_arg(runner):188 @click.command()188- @click.argument('arg', type=click.INT, metavar='metavar')189+ @click.argument("arg", type=click.INT, metavar="metavar")190 def cmd(arg):191 pass192 192- result = runner.invoke(cmd, ['3.14'])193+ result = runner.invoke(cmd, ["3.14"])194 assert result.exit_code == 2195 assert result.output.splitlines() == [195- 'Usage: cmd [OPTIONS] metavar',196- 'Try "cmd --help" for help.',197- '',198- 'Error: Invalid value for "metavar": 3.14 is not a valid integer'196+ "Usage: cmd [OPTIONS] metavar",197+ "Try 'cmd --help' for help.",198+ "",199+ "Error: Invalid value for 'metavar': 3.14 is not a valid integer",200 ]201 202 203 def test_formatting_usage_error_nested(runner):1 unmodified line205 def cmd():206 pass207 208 @cmd.command()208- @click.argument('bar')209+ @click.argument("bar")210 def foo(bar):210- click.echo('foo:' + bar)211+ click.echo("foo:{}".format(bar))212 212- result = runner.invoke(cmd, ['foo'])213+ result = runner.invoke(cmd, ["foo"])214 assert result.exit_code == 2215 assert result.output.splitlines() == [215- 'Usage: cmd foo [OPTIONS] BAR',216- 'Try "cmd foo --help" for help.',217- '',218- 'Error: Missing argument "BAR".'216+ "Usage: cmd foo [OPTIONS] BAR",217+ "Try 'cmd foo --help' for help.",218+ "",219+ "Error: Missing argument 'BAR'.",220 ]221 222 223 def test_formatting_usage_error_no_help(runner):224 @click.command(add_help_option=False)224- @click.argument('arg')225+ @click.argument("arg")226 def cmd(arg):226- click.echo('arg:' + arg)227+ click.echo("arg:{}".format(arg))228 229 result = runner.invoke(cmd, [])230 assert result.exit_code == 2231 assert result.output.splitlines() == [231- 'Usage: cmd [OPTIONS] ARG',232- '',233- 'Error: Missing argument "ARG".'232+ "Usage: cmd [OPTIONS] ARG",233+ "",234+ "Error: Missing argument 'ARG'.",235 ]236 237 238 def test_formatting_usage_custom_help(runner):238- @click.command(context_settings=dict(help_option_names=['--man']))239- @click.argument('arg')239+ @click.command(context_settings=dict(help_option_names=["--man"]))240+ @click.argument("arg")241 def cmd(arg):241- click.echo('arg:' + arg)242+ click.echo("arg:{}".format(arg))243 244 result = runner.invoke(cmd, [])245 assert result.exit_code == 2246 assert result.output.splitlines() == [246- 'Usage: cmd [OPTIONS] ARG',247- 'Try "cmd --man" for help.',248- '',249- 'Error: Missing argument "ARG".'247+ "Usage: cmd [OPTIONS] ARG",248+ "Try 'cmd --man' for help.",249+ "",250+ "Error: Missing argument 'ARG'.",251 ]252 253+254 def test_formatting_custom_type_metavar(runner):255 class MyType(click.ParamType):256 def get_metavar(self, param):257 return "MY_TYPE"3 unmodified lines261 @click.argument("param", type=MyType())262 def cmd(param):263 pass264 263- result = runner.invoke(cmd, '--help')265+ result = runner.invoke(cmd, "--help")266 assert not result.exception267 assert result.output.splitlines() == [266- 'Usage: foo [OPTIONS] MY_TYPE',267- '',268- 'Options:',269- ' --help Show this message and exit.'268+ "Usage: foo [OPTIONS] MY_TYPE",269+ "",270+ "Options:",271+ " --help Show this message and exit.",272 ]273 274 275 def test_truncating_docstring(runner):9 unmodified lines285 286 :param click.core.Context ctx: Click context.287 """288 287- result = runner.invoke(cli, ['--help'], terminal_width=60)289+ result = runner.invoke(cli, ["--help"], terminal_width=60)290 assert not result.exception291 assert result.output.splitlines() == [290- 'Usage: cli [OPTIONS]',291- '',292- ' First paragraph.',293- '',294- ' This is a very long second paragraph and not correctly',295- ' wrapped but it will be rewrapped.',296- '',297- 'Options:',298- ' --help Show this message and exit.',292+ "Usage: cli [OPTIONS]",293+ "",294+ " First paragraph.",295+ "",296+ " This is a very long second paragraph and not correctly",297+ " wrapped but it will be rewrapped.",298+ "",299+ "Options:",300+ " --help Show this message and exit.",301 ]302 303 304 def test_global_show_default(runner):1 unmodified line306 @click.option("-f", "in_file", default="out.txt", help="Output file name")307 def cli():308 pass309 308- result = runner.invoke(cli, ['--help'],)310+ result = runner.invoke(cli, ["--help"],)311 assert result.output.splitlines() == [310- 'Usage: cli [OPTIONS]',311- '',312- 'Options:',313- ' -f TEXT Output file name [default: out.txt]',314- ' --help Show this message and exit. [default: False]'312+ "Usage: cli [OPTIONS]",313+ "",314+ "Options:",315+ " -f TEXT Output file name [default: out.txt]",316+ " --help Show this message and exit. [default: False]",317 ]318 319 320 def test_formatting_usage_multiline_option_padding(runner):319- @click.command('foo')320- @click.option('--bar', help='This help message will be padded if it wraps.')321+ @click.command("foo")322+ @click.option("--bar", help="This help message will be padded if it wraps.")323 def cli():324 pass325 324- result = runner.invoke(cli, '--help', terminal_width=45)326+ result = runner.invoke(cli, "--help", terminal_width=45)327 assert not result.exception328 assert result.output.splitlines() == [327- 'Usage: foo [OPTIONS]',328- '',329- 'Options:',330- ' --bar TEXT This help message will be',331- ' padded if it wraps.',332- '',333- ' --help Show this message and exit.'329+ "Usage: foo [OPTIONS]",330+ "",331+ "Options:",332+ " --bar TEXT This help message will be",333+ " padded if it wraps.",334+ "",335+ " --help Show this message and exit.",336 ]337 338 339 def test_formatting_usage_no_option_padding(runner):338- @click.command('foo')339- @click.option('--bar', help='This help message will be padded if it wraps.')340+ @click.command("foo")341+ @click.option("--bar", help="This help message will be padded if it wraps.")342 def cli():343 pass344 343- result = runner.invoke(cli, '--help', terminal_width=80)345+ result = runner.invoke(cli, "--help", terminal_width=80)346 assert not result.exception347 assert result.output.splitlines() == [346- 'Usage: foo [OPTIONS]',347- '',348- 'Options:',349- ' --bar TEXT This help message will be padded if it wraps.',350- ' --help Show this message and exit.'348+ "Usage: foo [OPTIONS]",349+ "",350+ "Options:",351+ " --bar TEXT This help message will be padded if it wraps.",352+ " --help Show this message and exit.",353 ]modified:tests/test_imports.py+31 added-14 removed
1-import sys1 import json2 import subprocess3+import sys4 5 from click._compat import WIN6 7 8-IMPORT_TEST = b'''\8+IMPORT_TEST = b"""\9 try:10 import __builtin__ as builtins11 except ImportError:12 import builtins13 unmodified lines26 import click27 rv = list(found_imports)28 import json29 click.echo(json.dumps(rv))30-'''30+"""31 32-ALLOWED_IMPORTS = set([33- 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34- 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35- 'threading', 'colorama', 'errno', 'fcntl', 'datetime', 'pipes', 'shlex'36-])32+ALLOWED_IMPORTS = {33+ "weakref",34+ "os",35+ "struct",36+ "collections",37+ "sys",38+ "contextlib",39+ "functools",40+ "stat",41+ "re",42+ "codecs",43+ "inspect",44+ "itertools",45+ "io",46+ "threading",47+ "colorama",48+ "errno",49+ "fcntl",50+ "datetime",51+ "pipes",52+ "shlex",53+}54 55 if WIN:39- ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',40- 'zlib'])56+ ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])57 58 59 def test_light_imports():44- c = subprocess.Popen([sys.executable, '-'], stdin=subprocess.PIPE,45- stdout=subprocess.PIPE)60+ c = subprocess.Popen(61+ [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE62+ )63 rv = c.communicate(IMPORT_TEST)[0]64 65 if sys.version_info[0] != 2:49- rv = rv.decode('utf-8')66+ rv = rv.decode("utf-8")67 imported = json.loads(rv)68 69 for module in imported:53- if module == 'click' or module.startswith('click.'):70+ if module == "click" or module.startswith("click."):71 continue72 assert module in ALLOWED_IMPORTSmodified:tests/test_normalization.py+10 added-10 removed
4 unmodified lines5 6 7 def test_option_normalization(runner):8 @click.command(context_settings=CONTEXT_SETTINGS)9- @click.option('--foo')10- @click.option('-x')9+ @click.option("--foo")10+ @click.option("-x")11 def cli(foo, x):12 click.echo(foo)13 click.echo(x)14 15- result = runner.invoke(cli, ['--FOO', '42', '-X', 23])16- assert result.output == '42\n23\n'15+ result = runner.invoke(cli, ["--FOO", "42", "-X", 23])16+ assert result.output == "42\n23\n"17 18 19 def test_choice_normalization(runner):20 @click.command(context_settings=CONTEXT_SETTINGS)21- @click.option('--choice', type=click.Choice(['Foo', 'Bar']))21+ @click.option("--choice", type=click.Choice(["Foo", "Bar"]))22 def cli(choice):23 click.echo(choice)24 25- result = runner.invoke(cli, ['--CHOICE', 'FOO'])26- assert result.output == 'Foo\n'25+ result = runner.invoke(cli, ["--CHOICE", "FOO"])26+ assert result.output == "Foo\n"27 28 29 def test_command_normalization(runner):30 @click.group(context_settings=CONTEXT_SETTINGS)1 unmodified line32 pass33 34 @cli.command()35 def foo():36- click.echo('here!')36+ click.echo("here!")37 38- result = runner.invoke(cli, ['FOO'])39- assert result.output == 'here!\n'38+ result = runner.invoke(cli, ["FOO"])39+ assert result.output == "here!\n"modified:tests/test_options.py+213 added-211 removed
1 # -*- coding: utf-8 -*-2-import re2 import os4-import click3+import re4+5 import pytest6 7+import click8 from click._compat import text_type9 10 11 def test_prefixes(runner):12 @click.command()12- @click.option('++foo', is_flag=True, help='das foo')13- @click.option('--bar', is_flag=True, help='das bar')13+ @click.option("++foo", is_flag=True, help="das foo")14+ @click.option("--bar", is_flag=True, help="das bar")15 def cli(foo, bar):15- click.echo('foo=%s bar=%s' % (foo, bar))16+ click.echo("foo={} bar={}".format(foo, bar))17 17- result = runner.invoke(cli, ['++foo', '--bar'])18+ result = runner.invoke(cli, ["++foo", "--bar"])19 assert not result.exception19- assert result.output == 'foo=True bar=True\n'20+ assert result.output == "foo=True bar=True\n"21 21- result = runner.invoke(cli, ['--help'])22- assert re.search(r'\+\+foo\s+das foo', result.output) is not None23- assert re.search(r'--bar\s+das bar', result.output) is not None22+ result = runner.invoke(cli, ["--help"])23+ assert re.search(r"\+\+foo\s+das foo", result.output) is not None24+ assert re.search(r"--bar\s+das bar", result.output) is not None25 26 27 def test_invalid_option(runner):27- try:28+ with pytest.raises(TypeError, match="name was passed"):29+30 @click.command()29- @click.option('foo')31+ @click.option("foo")32 def cli(foo):33 pass32- except TypeError as e:33- assert 'No options defined but a name was passed (foo).' \34- in str(e)35- else:36- assert False, 'Expected a type error because of an invalid option.'34 35 36 def test_invalid_nargs(runner):40- try:37+ with pytest.raises(TypeError, match="nargs < 0"):38+39 @click.command()42- @click.option('--foo', nargs=-1)40+ @click.option("--foo", nargs=-1)41 def cli(foo):42 pass45- except TypeError as e:46- assert 'Options cannot have nargs < 0' in str(e)47- else:48- assert False, 'Expected a type error because of an invalid option.'43 44 45 def test_nargs_tup_composite_mult(runner):46 @click.command()53- @click.option('--item', type=(str, int), multiple=True)47+ @click.option("--item", type=(str, int), multiple=True)48 def copy(item):49 for item in item:56- click.echo('name=%s id=%d' % item)50+ click.echo("name={0[0]} id={0[1]:d}".format(item))51 58- result = runner.invoke(copy, ['--item', 'peter', '1', '--item', 'max', '2'])52+ result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])53 assert not result.exception60- assert result.output.splitlines() == [61- 'name=peter id=1',62- 'name=max id=2',63- ]54+ assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]55 56 57 def test_counting(runner):58 @click.command()68- @click.option('-v', count=True, help='Verbosity',69- type=click.IntRange(0, 3))59+ @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))60 def cli(v):71- click.echo('verbosity=%d' % v)61+ click.echo("verbosity={:d}".format(v))62 73- result = runner.invoke(cli, ['-vvv'])63+ result = runner.invoke(cli, ["-vvv"])64 assert not result.exception75- assert result.output == 'verbosity=3\n'65+ assert result.output == "verbosity=3\n"66 77- result = runner.invoke(cli, ['-vvvv'])67+ result = runner.invoke(cli, ["-vvvv"])68 assert result.exception79- assert 'Invalid value for "-v": 4 is not in the valid range of 0 to 3.' \69+ assert (70+ "Invalid value for '-v': 4 is not in the valid range of 0 to 3."71 in result.output72+ )73 74 result = runner.invoke(cli, [])75 assert not result.exception84- assert result.output == 'verbosity=0\n'76+ assert result.output == "verbosity=0\n"77 86- result = runner.invoke(cli, ['--help'])87- assert re.search(r'-v\s+Verbosity', result.output) is not None78+ result = runner.invoke(cli, ["--help"])79+ assert re.search(r"-v\s+Verbosity", result.output) is not None80 81 90-@pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])82+@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])83 def test_unknown_options(runner, unknown_flag):84 @click.command()85 def cli():86 pass87 88 result = runner.invoke(cli, [unknown_flag])89 assert result.exception98- assert 'no such option: {0}'.format(unknown_flag) in result.output90+ assert "no such option: {}".format(unknown_flag) in result.output91 92 93 def test_multiple_required(runner):94 @click.command()103- @click.option('-m', '--message', multiple=True, required=True)95+ @click.option("-m", "--message", multiple=True, required=True)96 def cli(message):105- click.echo('\n'.join(message))97+ click.echo("\n".join(message))98 107- result = runner.invoke(cli, ['-m', 'foo', '-mbar'])99+ result = runner.invoke(cli, ["-m", "foo", "-mbar"])100 assert not result.exception109- assert result.output == 'foo\nbar\n'101+ assert result.output == "foo\nbar\n"102 103 result = runner.invoke(cli, [])104 assert result.exception113- assert 'Error: Missing option "-m" / "--message".' in result.output105+ assert "Error: Missing option '-m' / '--message'." in result.output106 107 108 def test_empty_envvar(runner):109 @click.command()118- @click.option('--mypath', type=click.Path(exists=True), envvar='MYPATH')110+ @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")111 def cli(mypath):120- click.echo('mypath: %s' % mypath)112+ click.echo("mypath: {}".format(mypath))113 122- result = runner.invoke(cli, [], env={'MYPATH': ''})114+ result = runner.invoke(cli, [], env={"MYPATH": ""})115 assert result.exit_code == 0124- assert result.output == 'mypath: None\n'116+ assert result.output == "mypath: None\n"117 118 119 def test_multiple_envvar(runner):120 @click.command()129- @click.option('--arg', multiple=True)121+ @click.option("--arg", multiple=True)122 def cmd(arg):131- click.echo('|'.join(arg))123+ click.echo("|".join(arg))124 133- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',134- env={'TEST_ARG': 'foo bar baz'})125+ result = runner.invoke(126+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}127+ )128 assert not result.exception136- assert result.output == 'foo|bar|baz\n'129+ assert result.output == "foo|bar|baz\n"130 131 @click.command()139- @click.option('--arg', multiple=True, envvar='X')132+ @click.option("--arg", multiple=True, envvar="X")133 def cmd(arg):141- click.echo('|'.join(arg))134+ click.echo("|".join(arg))135 143- result = runner.invoke(cmd, [], env={'X': 'foo bar baz'})136+ result = runner.invoke(cmd, [], env={"X": "foo bar baz"})137 assert not result.exception145- assert result.output == 'foo|bar|baz\n'138+ assert result.output == "foo|bar|baz\n"139 140 @click.command()148- @click.option('--arg', multiple=True, type=click.Path())141+ @click.option("--arg", multiple=True, type=click.Path())142 def cmd(arg):150- click.echo('|'.join(arg))143+ click.echo("|".join(arg))144 152- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',153- env={'TEST_ARG': 'foo%sbar' % os.path.pathsep})145+ result = runner.invoke(146+ cmd,147+ [],148+ auto_envvar_prefix="TEST",149+ env={"TEST_ARG": "foo{}bar".format(os.path.pathsep)},150+ )151 assert not result.exception155- assert result.output == 'foo|bar\n'152+ assert result.output == "foo|bar\n"153 154 155 def test_multiple_default_help(runner):156 @click.command()160- @click.option('--arg1', multiple=True, default=('foo', 'bar'),161- show_default=True)162- @click.option('--arg2', multiple=True, default=(1, 2), type=int,163- show_default=True)157+ @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)158+ @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)159 def cmd(arg, arg2):160 pass161 167- result = runner.invoke(cmd, ['--help'])162+ result = runner.invoke(cmd, ["--help"])163 assert not result.exception169- assert 'foo, bar' in result.output170- assert '1, 2' in result.output164+ assert "foo, bar" in result.output165+ assert "1, 2" in result.output166 167 168 def test_multiple_default_type(runner):169 @click.command()175- @click.option('--arg1', multiple=True, default=('foo', 'bar'))176- @click.option('--arg2', multiple=True, default=(1, 'a'))170+ @click.option("--arg1", multiple=True, default=("foo", "bar"))171+ @click.option("--arg2", multiple=True, default=(1, "a"))172 def cmd(arg1, arg2):173 assert all(isinstance(e[0], text_type) for e in arg1)174 assert all(isinstance(e[1], text_type) for e in arg1)175 176 assert all(isinstance(e[0], int) for e in arg2)177 assert all(isinstance(e[1], text_type) for e in arg2)178 184- result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '185- 'two --arg2 4 four'.split())179+ result = runner.invoke(180+ cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()181+ )182 assert not result.exception183 184+185 def test_dynamic_default_help_unset(runner):186 @click.command()187+ @click.option(188+ "--username",190- @click.option('--username', prompt=True,191- default=lambda: os.environ.get('USER', ''),192- show_default=True)189+ prompt=True,190+ default=lambda: os.environ.get("USER", ""),191+ show_default=True,192+ )193 def cmd(username):194 print("Hello,", username)195 196- result = runner.invoke(cmd, ['--help'])196+ result = runner.invoke(cmd, ["--help"])197 assert result.exit_code == 0198- assert '--username' in result.output199- assert 'lambda' not in result.output200- assert '(dynamic)' in result.output198+ assert "--username" in result.output199+ assert "lambda" not in result.output200+ assert "(dynamic)" in result.output201 202+203 def test_dynamic_default_help_text(runner):204 @click.command()204- @click.option('--username', prompt=True,205- default=lambda: os.environ.get('USER', ''),206- show_default='current user')205+ @click.option(206+ "--username",207+ prompt=True,208+ default=lambda: os.environ.get("USER", ""),209+ show_default="current user",210+ )211 def cmd(username):212 print("Hello,", username)213 210- result = runner.invoke(cmd, ['--help'])214+ result = runner.invoke(cmd, ["--help"])215 assert result.exit_code == 0212- assert '--username' in result.output213- assert 'lambda' not in result.output214- assert '(current user)' in result.output216+ assert "--username" in result.output217+ assert "lambda" not in result.output218+ assert "(current user)" in result.output219 220 221 def test_toupper_envvar_prefix(runner):222 @click.command()219- @click.option('--arg')223+ @click.option("--arg")224 def cmd(arg):225 click.echo(arg)226 223- result = runner.invoke(cmd, [], auto_envvar_prefix='test',224- env={'TEST_ARG': 'foo'})227+ result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})228 assert not result.exception226- assert result.output == 'foo\n'229+ assert result.output == "foo\n"230 231 232 def test_nargs_envvar(runner):233 @click.command()231- @click.option('--arg', nargs=2)234+ @click.option("--arg", nargs=2)235 def cmd(arg):233- click.echo('|'.join(arg))236+ click.echo("|".join(arg))237 235- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',236- env={'TEST_ARG': 'foo bar'})238+ result = runner.invoke(239+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}240+ )241 assert not result.exception238- assert result.output == 'foo|bar\n'242+ assert result.output == "foo|bar\n"243 244 @click.command()241- @click.option('--arg', nargs=2, multiple=True)245+ @click.option("--arg", nargs=2, multiple=True)246 def cmd(arg):247 for item in arg:244- click.echo('|'.join(item))248+ click.echo("|".join(item))249 246- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',247- env={'TEST_ARG': 'x 1 y 2'})250+ result = runner.invoke(251+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}252+ )253 assert not result.exception249- assert result.output == 'x|1\ny|2\n'254+ assert result.output == "x|1\ny|2\n"255 256 257 def test_show_envvar(runner):258 @click.command()254- @click.option('--arg1', envvar='ARG1',255- show_envvar=True)259+ @click.option("--arg1", envvar="ARG1", show_envvar=True)260 def cmd(arg):261 pass262 259- result = runner.invoke(cmd, ['--help'])263+ result = runner.invoke(cmd, ["--help"])264 assert not result.exception261- assert 'ARG1' in result.output265+ assert "ARG1" in result.output266 267 268 def test_show_envvar_auto_prefix(runner):269 @click.command()266- @click.option('--arg1', show_envvar=True)270+ @click.option("--arg1", show_envvar=True)271 def cmd(arg):272 pass273 270- result = runner.invoke(cmd, ['--help'],271- auto_envvar_prefix='TEST')274+ result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")275 assert not result.exception273- assert 'TEST_ARG1' in result.output276+ assert "TEST_ARG1" in result.output277 278 279 def test_show_envvar_auto_prefix_dash_in_command(runner):280 @click.group()281 def cli():282 pass283 284 @cli.command()282- @click.option('--baz', show_envvar=True)285+ @click.option("--baz", show_envvar=True)286 def foo_bar(baz):287 pass288 286- result = runner.invoke(cli, ['foo-bar', '--help'],287- auto_envvar_prefix='TEST')289+ result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")290 assert not result.exception289- assert 'TEST_FOO_BAR_BAZ' in result.output291+ assert "TEST_FOO_BAR_BAZ" in result.output292 293 294 def test_custom_validation(runner):295 def validate_pos_int(ctx, param, value):296 if value < 0:295- raise click.BadParameter('Value needs to be positive')297+ raise click.BadParameter("Value needs to be positive")298 return value299 300 @click.command()299- @click.option('--foo', callback=validate_pos_int, default=1)301+ @click.option("--foo", callback=validate_pos_int, default=1)302 def cmd(foo):303 click.echo(foo)304 303- result = runner.invoke(cmd, ['--foo', '-1'])304- assert 'Invalid value for "--foo": Value needs to be positive' \305- in result.output305+ result = runner.invoke(cmd, ["--foo", "-1"])306+ assert "Invalid value for '--foo': Value needs to be positive" in result.output307 307- result = runner.invoke(cmd, ['--foo', '42'])308- assert result.output == '42\n'308+ result = runner.invoke(cmd, ["--foo", "42"])309+ assert result.output == "42\n"310 311 312 def test_winstyle_options(runner):313 @click.command()313- @click.option('/debug;/no-debug', help='Enables or disables debug mode.')314+ @click.option("/debug;/no-debug", help="Enables or disables debug mode.")315 def cmd(debug):316 click.echo(debug)317 317- result = runner.invoke(cmd, ['/debug'], help_option_names=['/?'])318- assert result.output == 'True\n'319- result = runner.invoke(cmd, ['/no-debug'], help_option_names=['/?'])320- assert result.output == 'False\n'321- result = runner.invoke(cmd, [], help_option_names=['/?'])322- assert result.output == 'False\n'323- result = runner.invoke(cmd, ['/?'], help_option_names=['/?'])324- assert '/debug; /no-debug Enables or disables debug mode.' in result.output325- assert '/? Show this message and exit.' in result.output318+ result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])319+ assert result.output == "True\n"320+ result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])321+ assert result.output == "False\n"322+ result = runner.invoke(cmd, [], help_option_names=["/?"])323+ assert result.output == "False\n"324+ result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])325+ assert "/debug; /no-debug Enables or disables debug mode." in result.output326+ assert "/? Show this message and exit." in result.output327 328 329 def test_legacy_options(runner):330 @click.command()330- @click.option('-whatever')331+ @click.option("-whatever")332 def cmd(whatever):333 click.echo(whatever)334 334- result = runner.invoke(cmd, ['-whatever', '42'])335- assert result.output == '42\n'336- result = runner.invoke(cmd, ['-whatever=23'])337- assert result.output == '23\n'335+ result = runner.invoke(cmd, ["-whatever", "42"])336+ assert result.output == "42\n"337+ result = runner.invoke(cmd, ["-whatever=23"])338+ assert result.output == "23\n"339 340 341 def test_missing_option_string_cast():342 ctx = click.Context(click.Command(""))343 344 with pytest.raises(click.MissingParameter) as excinfo:344- click.Option(['-a'], required=True).full_process_value(ctx, None)345+ click.Option(["-a"], required=True).full_process_value(ctx, None)346 347 assert str(excinfo.value) == "missing parameter: a"348 349 350 def test_missing_choice(runner):351 @click.command()351- @click.option('--foo', type=click.Choice(['foo', 'bar']),352- required=True)352+ @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)353 def cmd(foo):354 click.echo(foo)355 356 result = runner.invoke(cmd)357 assert result.exit_code == 2358- error, separator, choices = result.output.partition('Choose from')359- assert 'Error: Missing option "--foo". ' in error360- assert 'Choose from' in separator361- assert 'foo' in choices362- assert 'bar' in choices358+ error, separator, choices = result.output.partition("Choose from")359+ assert "Error: Missing option '--foo'. " in error360+ assert "Choose from" in separator361+ assert "foo" in choices362+ assert "bar" in choices363 364 365 def test_case_insensitive_choice(runner):366 @click.command()367- @click.option('--foo', type=click.Choice(368- ['Orange', 'Apple'], case_sensitive=False))367+ @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))368 def cmd(foo):369 click.echo(foo)370 372- result = runner.invoke(cmd, ['--foo', 'apple'])371+ result = runner.invoke(cmd, ["--foo", "apple"])372 assert result.exit_code == 0374- assert result.output == 'Apple\n'373+ assert result.output == "Apple\n"374 376- result = runner.invoke(cmd, ['--foo', 'oRANGe'])375+ result = runner.invoke(cmd, ["--foo", "oRANGe"])376 assert result.exit_code == 0378- assert result.output == 'Orange\n'377+ assert result.output == "Orange\n"378 380- result = runner.invoke(cmd, ['--foo', 'Apple'])379+ result = runner.invoke(cmd, ["--foo", "Apple"])380 assert result.exit_code == 0382- assert result.output == 'Apple\n'381+ assert result.output == "Apple\n"382 383 @click.command()385- @click.option('--foo', type=click.Choice(['Orange', 'Apple']))384+ @click.option("--foo", type=click.Choice(["Orange", "Apple"]))385 def cmd2(foo):386 click.echo(foo)387 389- result = runner.invoke(cmd2, ['--foo', 'apple'])388+ result = runner.invoke(cmd2, ["--foo", "apple"])389 assert result.exit_code == 2390 392- result = runner.invoke(cmd2, ['--foo', 'oRANGe'])391+ result = runner.invoke(cmd2, ["--foo", "oRANGe"])392 assert result.exit_code == 2393 395- result = runner.invoke(cmd2, ['--foo', 'Apple'])394+ result = runner.invoke(cmd2, ["--foo", "Apple"])395 assert result.exit_code == 0396 397 398 def test_case_insensitive_choice_returned_exactly(runner):399 @click.command()401- @click.option('--foo', type=click.Choice(402- ['Orange', 'Apple'], case_sensitive=False))400+ @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))401 def cmd(foo):402 click.echo(foo)403 406- result = runner.invoke(cmd, ['--foo', 'apple'])404+ result = runner.invoke(cmd, ["--foo", "apple"])405 assert result.exit_code == 0408- assert result.output == 'Apple\n'406+ assert result.output == "Apple\n"407 408 409 def test_option_help_preserve_paragraphs(runner):410 @click.command()1 unmodified line412 "-C",413 "--config",414 type=click.Path(),415 help="""Configuration file to use.418- 416+417 If not given, the environment variable CONFIG_FILE is consulted418 and used if set. If neither are given, a default configuration419 file is loaded.""",420 )421 def cmd(config):422 pass423 426- result = runner.invoke(cmd, ['--help'], )424+ result = runner.invoke(cmd, ["--help"],)425 assert result.exit_code == 0426 assert (427 " -C, --config PATH Configuration file to use.\n"428 "{i}\n"1 unmodified line430 "{i}consulted and used if set. If neither are given, a default\n"431 "{i}configuration file is loaded.".format(i=" " * 21)432 ) in result.output433 434+435 def test_argument_custom_class(runner):436 class CustomArgument(click.Argument):437 def get_default(self, ctx):439- '''a dumb override of a default value for testing'''440- return 'I am a default'438+ """a dumb override of a default value for testing"""439+ return "I am a default"440 441 @click.command()443- @click.argument('testarg', cls=CustomArgument, default='you wont see me')442+ @click.argument("testarg", cls=CustomArgument, default="you wont see me")443 def cmd(testarg):444 click.echo(testarg)445 446 result = runner.invoke(cmd)448- assert 'I am a default' in result.output449- assert 'you wont see me' not in result.output447+ assert "I am a default" in result.output448+ assert "you wont see me" not in result.output449 450 451 def test_option_custom_class(runner):452 class CustomOption(click.Option):453 def get_help_record(self, ctx):455- '''a dumb override of a help text for testing'''456- return ('--help', 'I am a help text')454+ """a dumb override of a help text for testing"""455+ return ("--help", "I am a help text")456 457 @click.command()459- @click.option('--testoption', cls=CustomOption, help='you wont see me')458+ @click.option("--testoption", cls=CustomOption, help="you wont see me")459 def cmd(testoption):460 click.echo(testoption)461 463- result = runner.invoke(cmd, ['--help'])464- assert 'I am a help text' in result.output465- assert 'you wont see me' not in result.output462+ result = runner.invoke(cmd, ["--help"])463+ assert "I am a help text" in result.output464+ assert "you wont see me" not in result.output465 466 467 def test_option_custom_class_reusable(runner):468 """Ensure we can reuse a custom class option. See Issue #926"""469 470 class CustomOption(click.Option):471 def get_help_record(self, ctx):473- '''a dumb override of a help text for testing'''474- return ('--help', 'I am a help text')472+ """a dumb override of a help text for testing"""473+ return ("--help", "I am a help text")474 475 # Assign to a variable to re-use the decorator.477- testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')476+ testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")477 478 @click.command()479 @testoption480 def cmd1(testoption):6 unmodified lines487 488 # Both of the commands should have the --help option now.489 for cmd in (cmd1, cmd2):490 492- result = runner.invoke(cmd, ['--help'])493- assert 'I am a help text' in result.output494- assert 'you wont see me' not in result.output491+ result = runner.invoke(cmd, ["--help"])492+ assert "I am a help text" in result.output493+ assert "you wont see me" not in result.output494 495 496 def test_bool_flag_with_type(runner):497 @click.command()499- @click.option('--shout/--no-shout', default=False, type=bool)498+ @click.option("--shout/--no-shout", default=False, type=bool)499 def cmd(shout):500 pass501 502 result = runner.invoke(cmd)1 unmodified line504 505 506 def test_aliases_for_flags(runner):507 @click.command()509- @click.option('--warnings/--no-warnings', ' /-W', default=True)508+ @click.option("--warnings/--no-warnings", " /-W", default=True)509 def cli(warnings):510 click.echo(warnings)511 513- result = runner.invoke(cli, ['--warnings'])514- assert result.output == 'True\n'515- result = runner.invoke(cli, ['--no-warnings'])516- assert result.output == 'False\n'517- result = runner.invoke(cli, ['-W'])518- assert result.output == 'False\n'512+ result = runner.invoke(cli, ["--warnings"])513+ assert result.output == "True\n"514+ result = runner.invoke(cli, ["--no-warnings"])515+ assert result.output == "False\n"516+ result = runner.invoke(cli, ["-W"])517+ assert result.output == "False\n"518 519 @click.command()521- @click.option('--warnings/--no-warnings', '-w', default=True)520+ @click.option("--warnings/--no-warnings", "-w", default=True)521 def cli_alt(warnings):522 click.echo(warnings)523 525- result = runner.invoke(cli_alt, ['--warnings'])526- assert result.output == 'True\n'527- result = runner.invoke(cli_alt, ['--no-warnings'])528- assert result.output == 'False\n'529- result = runner.invoke(cli_alt, ['-w'])530- assert result.output == 'True\n'524+ result = runner.invoke(cli_alt, ["--warnings"])525+ assert result.output == "True\n"526+ result = runner.invoke(cli_alt, ["--no-warnings"])527+ assert result.output == "False\n"528+ result = runner.invoke(cli_alt, ["-w"])529+ assert result.output == "True\n"530 532-@pytest.mark.parametrize('option_args,expected', [533- (['--aggressive', '--all', '-a'], 'aggressive'),534- (['--first', '--second', '--third', '-a', '-b', '-c'], 'first'),535- (['--apple', '--banana', '--cantaloupe', '-a', '-b', '-c'], 'apple'),536- (['--cantaloupe', '--banana', '--apple', '-c', '-b', '-a'], 'cantaloupe'),537- (['-a', '-b', '-c'], 'a'),538- (['-c', '-b', '-a'], 'c'),539- (['-a', '--apple', '-b', '--banana', '-c', '--cantaloupe'], 'apple'),540- (['-c', '-a', '--cantaloupe', '-b', '--banana', '--apple'], 'cantaloupe'),541- (['--from', '-f', '_from'], '_from'),542- (['--return', '-r', '_ret'], '_ret'),543-])544-def test_option_names(runner, option_args, expected):531 532+@pytest.mark.parametrize(533+ "option_args,expected",534+ [535+ (["--aggressive", "--all", "-a"], "aggressive"),536+ (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),537+ (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),538+ (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),539+ (["-a", "-b", "-c"], "a"),540+ (["-c", "-b", "-a"], "c"),541+ (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),542+ (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),543+ (["--from", "-f", "_from"], "_from"),544+ (["--return", "-r", "_ret"], "_ret"),545+ ],546+)547+def test_option_names(runner, option_args, expected):548 @click.command()549 @click.option(*option_args, is_flag=True)550 def cmd(**kwargs):551 click.echo(str(kwargs[expected]))552 553 assert cmd.params[0].name == expected554 555 for form in option_args:554- if form.startswith('-'):556+ if form.startswith("-"):557 result = runner.invoke(cmd, [form])556- assert result.output == 'True\n'558+ assert result.output == "True\n"modified:tests/test_termui.py+120 added-111 removed
1 # -*- coding: utf-8 -*-2-import pytest3-4-import click2 import time3 4+import pytest5+6 import click._termui_impl7 from click._compat import WIN8 9 17 unmodified lines27 28 29 def test_progressbar_strip_regression(runner, monkeypatch):30 fake_clock = FakeClock()32- label = ' padded line'31+ label = " padded line"32 33 @click.command()34 def cli():35 with _create_progress(label=label) as progress:37- for thing in progress:36+ for _ in progress:37 fake_clock.advance_time()38 40- monkeypatch.setattr(time, 'time', fake_clock.time)41- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)39+ monkeypatch.setattr(time, "time", fake_clock.time)40+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)41 assert label in runner.invoke(cli, []).output42 43 44 def test_progressbar_length_hint(runner, monkeypatch):18 unmodified lines63 fake_clock = FakeClock()64 65 @click.command()66 def cli():68- with click.progressbar(Hinted(10), label='test') as progress:69- for thing in progress:67+ with click.progressbar(Hinted(10), label="test") as progress:68+ for _ in progress:69 fake_clock.advance_time()70 72- monkeypatch.setattr(time, 'time', fake_clock.time)73- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)71+ monkeypatch.setattr(time, "time", fake_clock.time)72+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)73 result = runner.invoke(cli, [])74 assert result.exception is None75 76 77 def test_progressbar_hidden(runner, monkeypatch):78 fake_clock = FakeClock()80- label = 'whatever'79+ label = "whatever"80 81 @click.command()82 def cli():83 with _create_progress(label=label) as progress:85- for thing in progress:84+ for _ in progress:85 fake_clock.advance_time()86 88- monkeypatch.setattr(time, 'time', fake_clock.time)89- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)90- assert runner.invoke(cli, []).output == ''87+ monkeypatch.setattr(time, "time", fake_clock.time)88+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)89+ assert runner.invoke(cli, []).output == ""90 91 93-@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])92+@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])93 def test_progressbar_time_per_iteration(runner, avg, expected):94 with _create_progress(2, avg=avg) as progress:95 assert progress.time_per_iteration == expected96 97 99-@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])98+@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])99 def test_progressbar_eta(runner, finished, expected):100 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:101 assert progress.eta == expected102 103 105-@pytest.mark.parametrize('eta, expected',106- [(0, '00:00:00'), (30, '00:00:30'), (90, '00:01:30'), (900, '00:15:00'),107- (9000, '02:30:00'), (99999999999, '1157407d 09:46:39'), (None, '')])104+@pytest.mark.parametrize(105+ "eta, expected",106+ [107+ (0, "00:00:00"),108+ (30, "00:00:30"),109+ (90, "00:01:30"),110+ (900, "00:15:00"),111+ (9000, "02:30:00"),112+ (99999999999, "1157407d 09:46:39"),113+ (None, ""),114+ ],115+)116 def test_progressbar_format_eta(runner, eta, expected):117 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:118 assert progress.format_eta() == expected119 120 113-@pytest.mark.parametrize('pos, length', [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])121+@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])122 def test_progressbar_format_pos(runner, pos, length):123 with _create_progress(length, length_known=length != 0, pos=pos) as progress:124 result = progress.format_pos()125 if progress.length_known:118- assert result == '%s/%s' % (pos, length)126+ assert result == "{}/{}".format(pos, length)127 else:128 assert result == str(pos)129 130 123-@pytest.mark.parametrize('length, finished, pos, avg, expected',124- [(8, False, 7, 0, '#######-'),125- (0, True, 8, 0, '########'),126- (0, False, 8, 0, '--------'),127- (0, False, 5, 3, '#-------')128- ])131+@pytest.mark.parametrize(132+ "length, finished, pos, avg, expected",133+ [134+ (8, False, 7, 0, "#######-"),135+ (0, True, 8, 0, "########"),136+ (0, False, 8, 0, "--------"),137+ (0, False, 5, 3, "#-------"),138+ ],139+)140 def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):130- with _create_progress(length,131- length_known=length != 0,132- width=8,133- pos=pos,134- finished=finished,135- avg=[avg]) as progress:141+ with _create_progress(142+ length, length_known=length != 0, width=8, pos=pos, finished=finished, avg=[avg]143+ ) as progress:144 assert progress.format_bar() == expected145 146 139-@pytest.mark.parametrize('length, length_known, show_percent, show_pos, pos, expected',140- [(0, True, True, True, 0, ' [--------] 0/0 0%'),141- (0, True, False, True, 0, ' [--------] 0/0'),142- (0, True, False, False, 0, ' [--------]'),143- (0, False, False, False, 0, ' [--------]'),144- (8, True, True, True, 8, ' [########] 8/8 100%')145- ])146-def test_progressbar_format_progress_line(runner, length, length_known, show_percent, show_pos, pos, expected):147- with _create_progress(length,148- length_known,149- width=8,150- show_percent=show_percent,151- pos=pos,152- show_pos=show_pos) as progress:147+@pytest.mark.parametrize(148+ "length, length_known, show_percent, show_pos, pos, expected",149+ [150+ (0, True, True, True, 0, " [--------] 0/0 0%"),151+ (0, True, False, True, 0, " [--------] 0/0"),152+ (0, True, False, False, 0, " [--------]"),153+ (0, False, False, False, 0, " [--------]"),154+ (8, True, True, True, 8, " [########] 8/8 100%"),155+ ],156+)157+def test_progressbar_format_progress_line(158+ runner, length, length_known, show_percent, show_pos, pos, expected159+):160+ with _create_progress(161+ length,162+ length_known,163+ width=8,164+ show_percent=show_percent,165+ pos=pos,166+ show_pos=show_pos,167+ ) as progress:168 assert progress.format_progress_line() == expected169 170 156-@pytest.mark.parametrize('test_item', ['test', None])171+@pytest.mark.parametrize("test_item", ["test", None])172 def test_progressbar_format_progress_line_with_show_func(runner, test_item):158-173 def item_show_func(item):174 return item175 162- with _create_progress(item_show_func=item_show_func, current_item=test_item) as progress:176+ with _create_progress(177+ item_show_func=item_show_func, current_item=test_item178+ ) as progress:179 if test_item:180 assert progress.format_progress_line().endswith(test_item)181 else:182 assert progress.format_progress_line().endswith(progress.format_pct())183 184 185 def test_progressbar_init_exceptions(runner):170- try:186+ with pytest.raises(TypeError, match="iterable or length is required"):187 click.progressbar()172- except TypeError as e:173- assert str(e) == 'iterable or length is required'174- else:175- assert False, 'Expected an exception because unspecified arguments'188 189 190 def test_progressbar_iter_outside_with_exceptions(runner):179- try:191+ with pytest.raises(RuntimeError, match="with block"):192 progress = click.progressbar(length=2)193 iter(progress)182- except RuntimeError as e:183- assert str(e) == 'You need to use progress bars in a with block.'184- else:185- assert False, 'Expected an exception because of abort-related inputs.'194 195 196 def test_progressbar_is_iterator(runner, monkeypatch):197 fake_clock = FakeClock()198 199 @click.command()200 def cli():193- with click.progressbar(range(10), label='test') as progress:201+ with click.progressbar(range(10), label="test") as progress:202 while True:203 try:204 next(progress)205 fake_clock.advance_time()206 except StopIteration:207 break208 201- monkeypatch.setattr(time, 'time', fake_clock.time)202- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)209+ monkeypatch.setattr(time, "time", fake_clock.time)210+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)211 212 result = runner.invoke(cli, [])213 assert result.exception is None214 215 216 def test_choices_list_in_prompt(runner, monkeypatch):217 @click.command()210- @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),211- prompt=True)218+ @click.option(219+ "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True220+ )221 def cli_with_choices(g):222 pass223 224 @click.command()216- @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),217- prompt=True, show_choices=False)225+ @click.option(226+ "-g",227+ type=click.Choice(["none", "day", "week", "month"]),228+ prompt=True,229+ show_choices=False,230+ )231 def cli_without_choices(g):232 pass233 221- result = runner.invoke(cli_with_choices, [], input='none')222- assert '(none, day, week, month)' in result.output234+ result = runner.invoke(cli_with_choices, [], input="none")235+ assert "(none, day, week, month)" in result.output236 224- result = runner.invoke(cli_without_choices, [], input='none')225- assert '(none, day, week, month)' not in result.output237+ result = runner.invoke(cli_without_choices, [], input="none")238+ assert "(none, day, week, month)" not in result.output239 240 241 @pytest.mark.parametrize(229- "file_kwargs",230- [231- {"mode": "rt"},232- {"mode": "rb"},233- {"lazy": True},234- ]242+ "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]243 )244 def test_file_prompt_default_format(runner, file_kwargs):245 @click.command()246 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))7 unmodified lines254 def test_secho(runner):255 with runner.isolation() as outstreams:256 click.secho(None, nl=False)257 bytes = outstreams[0].getvalue()250- assert bytes == b''258+ assert bytes == b""259 260 261 def test_progressbar_yields_all_items(runner):262 with click.progressbar(range(3)) as progress:9 unmodified lines272 for _ in progress:273 fake_clock.advance_time()274 print("")275 268- monkeypatch.setattr(time, 'time', fake_clock.time)269- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)276+ monkeypatch.setattr(time, "time", fake_clock.time)277+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)278 output = runner.invoke(cli, []).output279 272- lines = [line for line in output.split('\n') if '[' in line]280+ lines = [line for line in output.split("\n") if "[" in line]281 274- assert ' 25% 00:00:03' in lines[0]275- assert ' 50% 00:00:02' in lines[1]276- assert ' 75% 00:00:01' in lines[2]277- assert '100% ' in lines[3]282+ assert " 25% 00:00:03" in lines[0]283+ assert " 50% 00:00:02" in lines[1]284+ assert " 75% 00:00:01" in lines[2]285+ assert "100% " in lines[3]286 287 280-@pytest.mark.parametrize(281- 'key_char', (u'h', u'H', u'é', u'À', u' ', u'字', u'àH', u'àR')282-)283-@pytest.mark.parametrize('echo', [True, False])284-@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')288+@pytest.mark.parametrize("key_char", (u"h", u"H", u"é", u"À", u" ", u"字", u"àH", u"àR"))289+@pytest.mark.parametrize("echo", [True, False])290+@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")291 def test_getchar_windows(runner, monkeypatch, key_char, echo):286- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwche', lambda: key_char)287- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)288- monkeypatch.setattr(click.termui, '_getchar', None)292+ monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)293+ monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)294+ monkeypatch.setattr(click.termui, "_getchar", None)295 assert click.getchar(echo) == key_char296 297 292-@pytest.mark.parametrize('special_key_char, key_char', [(u'\x00', 'a'), (u'\x00', 'b'), (u'\xe0', 'c')])293-@pytest.mark.skipif(not WIN, reason='Tests special character inputs using the msvcrt module.')298+@pytest.mark.parametrize(299+ "special_key_char, key_char", [(u"\x00", "a"), (u"\x00", "b"), (u"\xe0", "c")]300+)301+@pytest.mark.skipif(302+ not WIN, reason="Tests special character inputs using the msvcrt module."303+)304 def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):305 ordered_inputs = [key_char, special_key_char]296- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: ordered_inputs.pop())297- monkeypatch.setattr(click.termui, '_getchar', None)306+ monkeypatch.setattr(307+ click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()308+ )309+ monkeypatch.setattr(click.termui, "_getchar", None)310 assert click.getchar() == special_key_char + key_char311 312 301-@pytest.mark.parametrize('key_char', [u'\x03', u'\x1a'])302-@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')303-def test_getchar_windows_exceptions(runner, monkeypatch, key_char):304- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)305- monkeypatch.setattr(click.termui, '_getchar', None)306- try:313+@pytest.mark.parametrize(314+ ("key_char", "exc"), [(u"\x03", KeyboardInterrupt), (u"\x1a", EOFError)],315+)316+@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")317+def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):318+ monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)319+ monkeypatch.setattr(click.termui, "_getchar", None)320+321+ with pytest.raises(exc):322 click.getchar()308- except KeyboardInterrupt:309- assert key_char == u'\x03'310- except EOFError:311- assert key_char == u'\x1a'312- else:313- assert False, 'Expected an exception because of abort-specific inputs.'modified:tests/test_testing.py+70 added-68 removed
1 import os2 import sys3 4 import pytest5-import click5 6+import click7+from click._compat import PY28+from click._compat import WIN9 from click.testing import CliRunner10 9-from click._compat import PY2, WIN10-11 # Use the most reasonable io that users would use for the python version.12 if PY2:13 from cStringIO import StringIO as ReasonableBytesIO14 else:2 unmodified lines17 18 def test_runner():19 @click.command()20 def test():21- i = click.get_binary_stream('stdin')22- o = click.get_binary_stream('stdout')21+ i = click.get_binary_stream("stdin")22+ o = click.get_binary_stream("stdout")23 while 1:24 chunk = i.read(4096)25 if not chunk:26 break27 o.write(chunk)28 o.flush()29 30 runner = CliRunner()31- result = runner.invoke(test, input='Hello World!\n')31+ result = runner.invoke(test, input="Hello World!\n")32 assert not result.exception33- assert result.output == 'Hello World!\n'33+ assert result.output == "Hello World!\n"34 35 runner = CliRunner(echo_stdin=True)36- result = runner.invoke(test, input='Hello World!\n')36+ result = runner.invoke(test, input="Hello World!\n")37 assert not result.exception38- assert result.output == 'Hello World!\nHello World!\n'38+ assert result.output == "Hello World!\nHello World!\n"39 40 41 def test_runner_with_stream():42 @click.command()43 def test():44- i = click.get_binary_stream('stdin')45- o = click.get_binary_stream('stdout')44+ i = click.get_binary_stream("stdin")45+ o = click.get_binary_stream("stdout")46 while 1:47 chunk = i.read(4096)48 if not chunk:49 break50 o.write(chunk)51 o.flush()52 53 runner = CliRunner()54- result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))54+ result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))55 assert not result.exception56- assert result.output == 'Hello World!\n'56+ assert result.output == "Hello World!\n"57 58 runner = CliRunner(echo_stdin=True)59- result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))59+ result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))60 assert not result.exception61- assert result.output == 'Hello World!\nHello World!\n'61+ assert result.output == "Hello World!\nHello World!\n"62 63 64 def test_prompts():65 @click.command()66- @click.option('--foo', prompt=True)66+ @click.option("--foo", prompt=True)67 def test(foo):68- click.echo('foo=%s' % foo)68+ click.echo("foo={}".format(foo))69 70 runner = CliRunner()71- result = runner.invoke(test, input='wau wau\n')71+ result = runner.invoke(test, input="wau wau\n")72 assert not result.exception73- assert result.output == 'Foo: wau wau\nfoo=wau wau\n'73+ assert result.output == "Foo: wau wau\nfoo=wau wau\n"74 75 @click.command()76- @click.option('--foo', prompt=True, hide_input=True)76+ @click.option("--foo", prompt=True, hide_input=True)77 def test(foo):78- click.echo('foo=%s' % foo)78+ click.echo("foo={}".format(foo))79 80 runner = CliRunner()81- result = runner.invoke(test, input='wau wau\n')81+ result = runner.invoke(test, input="wau wau\n")82 assert not result.exception83- assert result.output == 'Foo: \nfoo=wau wau\n'83+ assert result.output == "Foo: \nfoo=wau wau\n"84 85 86 def test_getchar():87 @click.command()88 def continue_it():89 click.echo(click.getchar())90 91 runner = CliRunner()92- result = runner.invoke(continue_it, input='y')92+ result = runner.invoke(continue_it, input="y")93 assert not result.exception94- assert result.output == 'y\n'94+ assert result.output == "y\n"95 96 97 def test_catch_exceptions():98 class CustomError(Exception):18 unmodified lines117 result = runner.invoke(cli)118 assert result.exit_code == 1119 120 121-@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')121+@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")122 def test_with_color():123 @click.command()124 def cli():125- click.secho('hello world', fg='blue')125+ click.secho("hello world", fg="blue")126 127 runner = CliRunner()128 129 result = runner.invoke(cli)130- assert result.output == 'hello world\n'130+ assert result.output == "hello world\n"131 assert not result.exception132 133 result = runner.invoke(cli, color=True)134- assert result.output == click.style('hello world', fg='blue') + '\n'134+ assert result.output == "{}\n".format(click.style("hello world", fg="blue"))135 assert not result.exception136 137 138 def test_with_color_but_pause_not_blocking():3 unmodified lines142 143 runner = CliRunner()144 result = runner.invoke(cli, color=True)145 assert not result.exception146- assert result.output == ''146+ assert result.output == ""147 148 149 def test_exit_code_and_output_from_sys_exit():150 # See issue #362151 @click.command()152 def cli_string():153- click.echo('hello world')154- sys.exit('error')153+ click.echo("hello world")154+ sys.exit("error")155 156 @click.command()157 @click.pass_context158 def cli_string_ctx_exit(ctx):159- click.echo('hello world')160- ctx.exit('error')159+ click.echo("hello world")160+ ctx.exit("error")161 162 @click.command()163 def cli_int():164- click.echo('hello world')164+ click.echo("hello world")165 sys.exit(1)166 167 @click.command()168 @click.pass_context169 def cli_int_ctx_exit(ctx):170- click.echo('hello world')170+ click.echo("hello world")171 ctx.exit(1)172 173 @click.command()174 def cli_float():175- click.echo('hello world')175+ click.echo("hello world")176 sys.exit(1.0)177 178 @click.command()179 @click.pass_context180 def cli_float_ctx_exit(ctx):181- click.echo('hello world')181+ click.echo("hello world")182 ctx.exit(1.0)183 184 @click.command()185 def cli_no_error():186- click.echo('hello world')186+ click.echo("hello world")187 188 runner = CliRunner()189 190 result = runner.invoke(cli_string)191 assert result.exit_code == 1192- assert result.output == 'hello world\nerror\n'192+ assert result.output == "hello world\nerror\n"193 194 result = runner.invoke(cli_string_ctx_exit)195 assert result.exit_code == 1196- assert result.output == 'hello world\nerror\n'196+ assert result.output == "hello world\nerror\n"197 198 result = runner.invoke(cli_int)199 assert result.exit_code == 1200- assert result.output == 'hello world\n'200+ assert result.output == "hello world\n"201 202 result = runner.invoke(cli_int_ctx_exit)203 assert result.exit_code == 1204- assert result.output == 'hello world\n'204+ assert result.output == "hello world\n"205 206 result = runner.invoke(cli_float)207 assert result.exit_code == 1208- assert result.output == 'hello world\n1.0\n'208+ assert result.output == "hello world\n1.0\n"209 210 result = runner.invoke(cli_float_ctx_exit)211 assert result.exit_code == 1212- assert result.output == 'hello world\n1.0\n'212+ assert result.output == "hello world\n1.0\n"213 214 result = runner.invoke(cli_no_error)215 assert result.exit_code == 0216- assert result.output == 'hello world\n'216+ assert result.output == "hello world\n"217 218 219 def test_env():220 @click.command()221 def cli_env():222- click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])222+ click.echo("ENV={}".format(os.environ["TEST_CLICK_ENV"]))223 224 runner = CliRunner()225 226 env_orig = dict(os.environ)227 env = dict(env_orig)228- assert 'TEST_CLICK_ENV' not in env229- env['TEST_CLICK_ENV'] = 'some_value'228+ assert "TEST_CLICK_ENV" not in env229+ env["TEST_CLICK_ENV"] = "some_value"230 result = runner.invoke(cli_env, env=env)231 assert result.exit_code == 0232- assert result.output == 'ENV=some_value\n'232+ assert result.output == "ENV=some_value\n"233 234 assert os.environ == env_orig235 236 6 unmodified lines243 runner = CliRunner(mix_stderr=False)244 245 result = runner.invoke(cli_stderr)246 247- assert result.output == 'stdout\n'248- assert result.stdout == 'stdout\n'249- assert result.stderr == 'stderr\n'247+ assert result.output == "stdout\n"248+ assert result.stdout == "stdout\n"249+ assert result.stderr == "stderr\n"250 251 runner_mix = CliRunner(mix_stderr=True)252 result_mix = runner_mix.invoke(cli_stderr)253 254- assert result_mix.output == 'stdout\nstderr\n'255- assert result_mix.stdout == 'stdout\nstderr\n'254+ assert result_mix.output == "stdout\nstderr\n"255+ assert result_mix.stdout == "stdout\nstderr\n"256 257 with pytest.raises(ValueError):258 result_mix.stderr259 4 unmodified lines264 runner = CliRunner(mix_stderr=False)265 266 result = runner.invoke(cli_empty_stderr)267 268- assert result.output == 'stdout\n'269- assert result.stdout == 'stdout\n'270- assert result.stderr == ''268+ assert result.output == "stdout\n"269+ assert result.stdout == "stdout\n"270+ assert result.stderr == ""271 272 273-@pytest.mark.parametrize('args, expected_output', [274- (None, 'bar\n'),275- ([], 'bar\n'),276- ('', 'bar\n'),277- (['--foo', 'one two'], 'one two\n'),278- ('--foo "one two"', 'one two\n'),279-])273+@pytest.mark.parametrize(274+ "args, expected_output",275+ [276+ (None, "bar\n"),277+ ([], "bar\n"),278+ ("", "bar\n"),279+ (["--foo", "one two"], "one two\n"),280+ ('--foo "one two"', "one two\n"),281+ ],282+)283 def test_args(args, expected_output):281-284 @click.command()283- @click.option('--foo', default='bar')285+ @click.option("--foo", default="bar")286 def cli_args(foo):287 click.echo(foo)288 289 runner = CliRunner()9 unmodified lines299 300 runner = CliRunner()301 result = runner.invoke(cli, prog_name="foobar")302 assert not result.exception301- assert result.output == 'ok\n'303+ assert result.output == "ok\n"modified:tests/test_utils.py+139 added-143 removed
2 unmodified lines3 import sys4 5 import pytest6 7-import click8-import click.utils7 import click._termui_impl8+import click.utils10-from click._compat import WIN, PY29+from click._compat import WIN10 11 12 def test_echo(runner):13 with runner.isolation() as outstreams:15- click.echo(u'\N{SNOWMAN}')16- click.echo(b'\x44\x44')14+ click.echo(u"\N{SNOWMAN}")15+ click.echo(b"\x44\x44")16 click.echo(42, nl=False)18- click.echo(b'a', nl=False)19- click.echo('\x1b[31mx\x1b[39m', nl=False)20- bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')21- assert bytes == b'\xe2\x98\x83\nDD\n42ax'17+ click.echo(b"a", nl=False)18+ click.echo("\x1b[31mx\x1b[39m", nl=False)19+ bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")20+ assert bytes == b"\xe2\x98\x83\nDD\n42ax"21 22 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 324 if sys.version_info[0] == 2:25 import StringIO26+27 sys.stdout = x = StringIO.StringIO()28 try:29- click.echo('\xf6')29+ click.echo("\xf6")30 finally:31 sys.stdout = sys.__stdout__32- assert x.getvalue() == '\xf6\n'32+ assert x.getvalue() == "\xf6\n"33 34 # And in any case, if wrapped, we expect bytes to survive.35 @click.command()36 def cli():37- click.echo(b'\xf6')37+ click.echo(b"\xf6")38+39 result = runner.invoke(cli, [])39- assert result.stdout_bytes == b'\xf6\n'40+ assert result.stdout_bytes == b"\xf6\n"41 42 # Ensure we do not strip for bytes.43 with runner.isolation() as outstreams:43- click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)44- assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'44+ click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)45+ assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"46 47 48 def test_echo_custom_file():49 import io50+51 f = io.StringIO()50- click.echo(u'hello', file=f)51- assert f.getvalue() == u'hello\n'52+ click.echo(u"hello", file=f)53+ assert f.getvalue() == u"hello\n"54 55 56 @pytest.mark.parametrize(57 ("styles", "ref"),24 unmodified lines82 assert click.style("x y", **styles) == ref83 assert click.unstyle(ref) == "x y"84 85 84-@pytest.mark.parametrize(85- ("text", "expect"),86- [87- ("\x1b[?25lx y\x1b[?25h", "x y"),88- ]89-)86+@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])87 def test_unstyle_other_ansi(text, expect):88 assert click.unstyle(text) == expect89 90 94-91 def test_filename_formatting():96- assert click.format_filename(b'foo.txt') == 'foo.txt'97- assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'98- assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'99- assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt'92+ assert click.format_filename(b"foo.txt") == "foo.txt"93+ assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"94+ assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"95+ assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt"96 97 # filesystem encoding on windows permits this.98 if not WIN:103- assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \104- == u'foo\ufffd.txt'99+ assert (100+ click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"101+ )102 103 104 def test_prompts(runner):105 @click.command()106 def test():110- if click.confirm('Foo'):111- click.echo('yes!')107+ if click.confirm("Foo"):108+ click.echo("yes!")109 else:113- click.echo('no :(')110+ click.echo("no :(")111 115- result = runner.invoke(test, input='y\n')112+ result = runner.invoke(test, input="y\n")113 assert not result.exception117- assert result.output == 'Foo [y/N]: y\nyes!\n'114+ assert result.output == "Foo [y/N]: y\nyes!\n"115 119- result = runner.invoke(test, input='\n')116+ result = runner.invoke(test, input="\n")117 assert not result.exception121- assert result.output == 'Foo [y/N]: \nno :(\n'118+ assert result.output == "Foo [y/N]: \nno :(\n"119 123- result = runner.invoke(test, input='n\n')120+ result = runner.invoke(test, input="n\n")121 assert not result.exception125- assert result.output == 'Foo [y/N]: n\nno :(\n'122+ assert result.output == "Foo [y/N]: n\nno :(\n"123 124 @click.command()125 def test_no():129- if click.confirm('Foo', default=True):130- click.echo('yes!')126+ if click.confirm("Foo", default=True):127+ click.echo("yes!")128 else:132- click.echo('no :(')129+ click.echo("no :(")130 134- result = runner.invoke(test_no, input='y\n')131+ result = runner.invoke(test_no, input="y\n")132 assert not result.exception136- assert result.output == 'Foo [Y/n]: y\nyes!\n'133+ assert result.output == "Foo [Y/n]: y\nyes!\n"134 138- result = runner.invoke(test_no, input='\n')135+ result = runner.invoke(test_no, input="\n")136 assert not result.exception140- assert result.output == 'Foo [Y/n]: \nyes!\n'137+ assert result.output == "Foo [Y/n]: \nyes!\n"138 142- result = runner.invoke(test_no, input='n\n')139+ result = runner.invoke(test_no, input="n\n")140 assert not result.exception144- assert result.output == 'Foo [Y/n]: n\nno :(\n'141+ assert result.output == "Foo [Y/n]: n\nno :(\n"142 143 147-@pytest.mark.skipif(WIN, reason='Different behavior on windows.')144+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")145 def test_prompts_abort(monkeypatch, capsys):146 def f(_):147 raise KeyboardInterrupt()148 152- monkeypatch.setattr('click.termui.hidden_prompt_func', f)149+ monkeypatch.setattr("click.termui.hidden_prompt_func", f)150 151 try:155- click.prompt('Password', hide_input=True)152+ click.prompt("Password", hide_input=True)153 except click.Abort:157- click.echo('Screw you.')154+ click.echo("Screw you.")155 156 out, err = capsys.readouterr()160- assert out == 'Password: \nScrew you.\n'157+ assert out == "Password: \nScrew you.\n"158 159 160 def _test_gen_func():164- yield 'a'165- yield 'b'166- yield 'c'167- yield 'abc'161+ yield "a"162+ yield "b"163+ yield "c"164+ yield "abc"165 166 170-@pytest.mark.skipif(WIN, reason='Different behavior on windows.')171-@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])172-@pytest.mark.parametrize('test', [173- # We need lambda here, because pytest will174- # reuse the parameters, and then the generators175- # are already used and will not yield anymore176- ('just text\n', lambda: 'just text'),177- ('iterable\n', lambda: ["itera", "ble"]),178- ('abcabc\n', lambda: _test_gen_func),179- ('abcabc\n', lambda: _test_gen_func()),180- ('012345\n', lambda: (c for c in range(6))),181-])167+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")168+@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])169+@pytest.mark.parametrize(170+ "test",171+ [172+ # We need lambda here, because pytest will173+ # reuse the parameters, and then the generators174+ # are already used and will not yield anymore175+ ("just text\n", lambda: "just text"),176+ ("iterable\n", lambda: ["itera", "ble"]),177+ ("abcabc\n", lambda: _test_gen_func),178+ ("abcabc\n", lambda: _test_gen_func()),179+ ("012345\n", lambda: (c for c in range(6))),180+ ],181+)182 def test_echo_via_pager(monkeypatch, capfd, cat, test):183- monkeypatch.setitem(os.environ, 'PAGER', cat)184- monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)183+ monkeypatch.setitem(os.environ, "PAGER", cat)184+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)185 186 expected_output = test[0]187 test_input = test[1]()188 2 unmodified lines191 out, err = capfd.readouterr()192 assert out == expected_output193 194 195-@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')195+@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")196 def test_echo_color_flag(monkeypatch, capfd):197 isatty = True198- monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)198+ monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)199 200- text = 'foo'201- styled_text = click.style(text, fg='red')202- assert styled_text == '\x1b[31mfoo\x1b[0m'200+ text = "foo"201+ styled_text = click.style(text, fg="red")202+ assert styled_text == "\x1b[31mfoo\x1b[0m"203 204 click.echo(styled_text, color=False)205 out, err = capfd.readouterr()206- assert out == text + '\n'206+ assert out == "{}\n".format(text)207 208 click.echo(styled_text, color=True)209 out, err = capfd.readouterr()210- assert out == styled_text + '\n'210+ assert out == "{}\n".format(styled_text)211 212 isatty = True213 click.echo(styled_text)214 out, err = capfd.readouterr()215- assert out == styled_text + '\n'215+ assert out == "{}\n".format(styled_text)216 217 isatty = False218 click.echo(styled_text)219 out, err = capfd.readouterr()220- assert out == text + '\n'220+ assert out == "{}\n".format(text)221 222 223-@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')223+@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")224 def test_echo_writing_to_standard_error(capfd, monkeypatch):225 def emulate_input(text):226 """Emulate keyboard input."""227 if sys.version_info[0] == 2:228 from StringIO import StringIO229 else:230 from io import StringIO231- monkeypatch.setattr(sys, 'stdin', StringIO(text))231+ monkeypatch.setattr(sys, "stdin", StringIO(text))232 233- click.echo('Echo to standard output')233+ click.echo("Echo to standard output")234 out, err = capfd.readouterr()235- assert out == 'Echo to standard output\n'236- assert err == ''235+ assert out == "Echo to standard output\n"236+ assert err == ""237 238- click.echo('Echo to standard error', err=True)238+ click.echo("Echo to standard error", err=True)239 out, err = capfd.readouterr()240- assert out == ''241- assert err == 'Echo to standard error\n'240+ assert out == ""241+ assert err == "Echo to standard error\n"242 243- emulate_input('asdlkj\n')244- click.prompt('Prompt to stdin')243+ emulate_input("asdlkj\n")244+ click.prompt("Prompt to stdin")245 out, err = capfd.readouterr()246- assert out == 'Prompt to stdin: '247- assert err == ''246+ assert out == "Prompt to stdin: "247+ assert err == ""248 249- emulate_input('asdlkj\n')250- click.prompt('Prompt to stderr', err=True)249+ emulate_input("asdlkj\n")250+ click.prompt("Prompt to stderr", err=True)251 out, err = capfd.readouterr()252- assert out == ''253- assert err == 'Prompt to stderr: '252+ assert out == ""253+ assert err == "Prompt to stderr: "254 255- emulate_input('y\n')256- click.confirm('Prompt to stdin')255+ emulate_input("y\n")256+ click.confirm("Prompt to stdin")257 out, err = capfd.readouterr()258- assert out == 'Prompt to stdin [y/N]: '259- assert err == ''258+ assert out == "Prompt to stdin [y/N]: "259+ assert err == ""260 261- emulate_input('y\n')262- click.confirm('Prompt to stderr', err=True)261+ emulate_input("y\n")262+ click.confirm("Prompt to stderr", err=True)263 out, err = capfd.readouterr()264- assert out == ''265- assert err == 'Prompt to stderr [y/N]: '264+ assert out == ""265+ assert err == "Prompt to stderr [y/N]: "266 267- monkeypatch.setattr(click.termui, 'isatty', lambda x: True)268- monkeypatch.setattr(click.termui, 'getchar', lambda: ' ')267+ monkeypatch.setattr(click.termui, "isatty", lambda x: True)268+ monkeypatch.setattr(click.termui, "getchar", lambda: " ")269 270- click.pause('Pause to stdout')270+ click.pause("Pause to stdout")271 out, err = capfd.readouterr()272- assert out == 'Pause to stdout\n'273- assert err == ''272+ assert out == "Pause to stdout\n"273+ assert err == ""274 275- click.pause('Pause to stderr', err=True)275+ click.pause("Pause to stderr", err=True)276 out, err = capfd.readouterr()277- assert out == ''278- assert err == 'Pause to stderr\n'277+ assert out == ""278+ assert err == "Pause to stderr\n"279 280 281 def test_open_file(runner):282 @click.command()283- @click.argument('filename')283+ @click.argument("filename")284 def cli(filename):285 with click.open_file(filename) as f:286 click.echo(f.read())287 288- click.echo('meep')288+ click.echo("meep")289 290 with runner.isolated_filesystem():291- with open('hello.txt', 'w') as f:292- f.write('Cool stuff')291+ with open("hello.txt", "w") as f:292+ f.write("Cool stuff")293 294- result = runner.invoke(cli, ['hello.txt'])294+ result = runner.invoke(cli, ["hello.txt"])295 assert result.exception is None296- assert result.output == 'Cool stuff\nmeep\n'296+ assert result.output == "Cool stuff\nmeep\n"297 298- result = runner.invoke(cli, ['-'], input='foobar')298+ result = runner.invoke(cli, ["-"], input="foobar")299 assert result.exception is None300- assert result.output == 'foobar\nmeep\n'300+ assert result.output == "foobar\nmeep\n"301 302 303 def test_open_file_ignore_errors_stdin(runner):304 @click.command()32 unmodified lines337 with click.open_file("test.bin", errors="ignore") as f:338 f.read()339 340 341-@pytest.mark.skipif(WIN, reason='os.chmod() is not fully supported on Windows.')342-@pytest.mark.parametrize('permissions', [343- 0o400,344- 0o444,345- 0o600,346- 0o644,347- ])341+@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")342+@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])343 def test_open_file_atomic_permissions_existing_file(runner, permissions):344 with runner.isolated_filesystem():350- with open('existing.txt', 'w') as f:351- f.write('content')352- os.chmod('existing.txt', permissions)345+ with open("existing.txt", "w") as f:346+ f.write("content")347+ os.chmod("existing.txt", permissions)348 349 @click.command()355- @click.argument('filename')350+ @click.argument("filename")351 def cli(filename):357- click.open_file(filename, 'w', atomic=True).close()352+ click.open_file(filename, "w", atomic=True).close()353 359- result = runner.invoke(cli, ['existing.txt'])354+ result = runner.invoke(cli, ["existing.txt"])355 assert result.exception is None361- assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions356+ assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions357 358 364-@pytest.mark.skipif(WIN, reason='os.stat() is not fully supported on Windows.')359+@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")360 def test_open_file_atomic_permissions_new_file(runner):361 with runner.isolated_filesystem():362+363 @click.command()368- @click.argument('filename')364+ @click.argument("filename")365 def cli(filename):370- click.open_file(filename, 'w', atomic=True).close()366+ click.open_file(filename, "w", atomic=True).close()367 368 # Create a test file to get the expected permissions for new files369 # according to the current umask.374- with open('test.txt', 'w'):370+ with open("test.txt", "w"):371 pass376- permissions = stat.S_IMODE(os.stat('test.txt').st_mode)372+ permissions = stat.S_IMODE(os.stat("test.txt").st_mode)373 378- result = runner.invoke(cli, ['new.txt'])374+ result = runner.invoke(cli, ["new.txt"])375 assert result.exception is None380- assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions376+ assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions377 378 379 def test_iter_keepopenfile(tmpdir):380 expected = list(map(str, range(10)))385- p = tmpdir.mkdir('testdir').join('testfile')381+ p = tmpdir.mkdir("testdir").join("testfile")382 p.write("\n".join(expected))383 with p.open() as f:384 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):385 assert e_line == a_line.strip()386 387 388 def test_iter_lazyfile(tmpdir):389 expected = list(map(str, range(10)))394- p = tmpdir.mkdir('testdir').join('testfile')390+ p = tmpdir.mkdir("testdir").join("testfile")391 p.write("\n".join(expected))392 with p.open() as f:393 with click.utils.LazyFile(f.name) as lf:394 for e_line, a_line in zip(expected, lf):1 unmodified linemodified:.azure-pipelines.yml+3 added-15 removed
28 unmodified lines29 vmImage: windows-latest30 python.version: '2.7'31 Docs:32 TOXENV: docs33+ Style:34+ TOXENV: style35 36 pool:37 vmImage: $(vmImage)38 5 unmodified lines44 45 - script: pip --disable-pip-version-check install -U tox46 displayName: Install tox47 46- - script: tox -s false -- --junit-xml=test-results.xml48+ - script: tox49 displayName: Run tox48-49- - task: PublishTestResults@250- inputs:51- testResultsFiles: test-results.xml52- testRunTitle: $(Agent.JobName)53- condition: eq(variables['hasTestResults'], 'true')54- displayName: Publish test results55-56- - task: PublishCodeCoverageResults@157- inputs:58- codeCoverageTool: Cobertura59- summaryFileLocation: coverage.xml60- condition: eq(variables['hasTestResults'], 'true')61- displayName: Publish coverage resultsadded:.pre-commit-config.yaml+27 added
1+repos:2+ - repo: https://github.com/asottile/pyupgrade3+ rev: v2.1.04+ hooks:5+ - id: pyupgrade6+ - repo: https://github.com/asottile/reorder_python_imports7+ rev: v2.0.08+ hooks:9+ - id: reorder-python-imports10+ args: ["--application-directories", "src"]11+ - repo: https://github.com/ambv/black12+ rev: 19.10b013+ hooks:14+ - id: black15+ - repo: https://gitlab.com/pycqa/flake816+ rev: 3.7.917+ hooks:18+ - id: flake819+ additional_dependencies:20+ - flake8-bugbear21+ - flake8-implicit-str-concat22+ - repo: https://github.com/pre-commit/pre-commit-hooks23+ rev: v2.5.024+ hooks:25+ - id: check-byte-order-marker26+ - id: trailing-whitespace27+ - id: end-of-file-fixermodified:CONTRIBUTING.rst+1 added-1 removed
9 unmodified lines10 Please, don't use the issue tracker for this. Check whether the11 ``#pocoo`` IRC channel on Freenode can help with your issue. If your problem12 is not strictly Click-specific, ``#python`` on Freenode is generally more13 active. Also try searching or asking on `Stack Overflow`_ with the14-``python-click`` tag. 14+``python-click`` tag.15 16 .. _Stack Overflow: https://stackoverflow.com/questions/tagged/python-click?sort=votes17 18 Reporting issues48 unmodified linesmodified:README.rst+2 added-3 removed
36 unmodified lines37 import click38 39 @click.command()40 @click.option("--count", default=1, help="Number of greetings.")41- @click.option("--name", prompt="Your name",42- help="The person to greet.")41+ @click.option("--name", prompt="Your name", help="The person to greet.")42 def hello(count, name):43 """Simple program that greets NAME for a total of COUNT times."""44 for _ in range(count):46- click.echo("Hello, %s!" % name)45+ click.echo(f"Hello, {name}!")46 47 if __name__ == '__main__':48 hello()49 30 unmodified linesmodified:setup.cfg+24 added-1 removed
10 unmodified lines11 12 [coverage:run]13 branch = True14 source =15- click15+ src16 tests17 18 [coverage:paths]19 source =20 click21 */site-packages22+23+[flake8]24+# B = bugbear25+# E = pycodestyle errors26+# F = flake8 pyflakes27+# W = pycodestyle warnings28+# B9 = bugbear opinions,29+# ISC = implicit str concat30+select = B, E, F, W, B9, ISC31+ignore =32+ # slice notation whitespace, invalid33+ E20334+ # line length, handled by bugbear B95035+ E50136+ # bare except, handled by bugbear B00137+ E72238+ # bin op line break, invalid39+ W50340+# up to 88 allowed by bugbear B95041+max-line-length = 8042+per-file-ignores =43+ # __init__ module exports names44+ src/click/__init__.py: F401modified:setup.py+6 added-3 removed
1 import io2 import re3+4+from setuptools import find_packages5 from setuptools import setup6 7 with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()9 8-with io.open("click/__init__.py", "rt", encoding="utf8") as f:9- version = re.search(r"__version__ = '(.*?)'", f.read()).group(1)10+with io.open("src/click/__init__.py", "rt", encoding="utf8") as f:11+ version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)12 13 setup(14 name="click",15 version=version,7 unmodified lines23 maintainer="Pallets",24 maintainer_email="contact@palletsprojects.com",25 description="Composable command line interface toolkit",26 long_description=readme,25- packages=["click"],27+ packages=find_packages("src"),28+ package_dir={"": "src"},29 include_package_data=True,30 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",31 classifiers=[32 "Development Status :: 5 - Production/Stable",8 unmodified linesmodified:tox.ini+6 added
1 [tox]2 envlist =3 py{38,37,36,35,27,py3,py}4+ style5 docs6 skip_missing_interpreters = true7 8 [testenv]1 unmodified line10 pytest11 colorama12 commands = pytest --tb=short --basetemp={envtmpdir} {posargs}13 14+[testenv:style]15+deps = pre-commit16+skip_install = true17+commands = pre-commit run --all-files --show-diff-on-failure18+19 [testenv:docs]20 deps = -r docs/requirements.txt21 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html