move to src directory
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 3d1dcc2 · Browse files · 35 files·+7646 added−7643 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
35 files+7646 added−7643 removed
- other:+7646 added−7643 removed
Provenance
- Commit
079f91a- Tree
ca0eb69- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
3d1dcc2
35 files changed+7646 added−7643 removed
deleted: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)added:src/click/__init__.py+91 added
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'added:src/click/_bashcomplete.py+334 added
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 Falseadded:src/click/_compat.py+774 added
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+}added:src/click/_termui_impl.py+632 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+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 chadded:src/click/_textwrap.py+38 added
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)added:src/click/_unicodefun.py+125 added
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+ )added:src/click/_winconsole.py+330 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+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)added:src/click/core.py+1901 added
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, groupadded:src/click/decorators.py+311 added
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, Optionadded:src/click/exceptions.py+248 added
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 = codeadded:src/click/formatting.py+262 added
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_slashadded:src/click/globals.py+48 added
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.coloradded:src/click/parser.py+430 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+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)added:src/click/termui.py+621 added
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)added:src/click/testing.py+377 added
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+ passadded:src/click/types.py+679 added
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()added:src/click/utils.py+440 added
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:setup.py+5 added-2 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: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",8 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 lines