Skip to content
Myr

Merge branch '7.x'

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 · parents 8f36eab, 38ba2e6 · Browse files · 82 files+10277 added−9618 removed
This commit

State

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

Diff stats

82 files+10277 added−9618 removed

  • tests:+1554 added−1473 removed
  • other:+8723 added−8145 removed

82 files+10277 added−9618 removed

modified:.github/ISSUE_TEMPLATE.md+1 added-1 removed
deleted:click/__init__.py-91 removed
1# -*- coding: utf-8 -*-2"""3Click is a simple Python module inspired by the stdlib optparse to make4writing command line scripts fun. Unlike other modules, it's based5around a simple API that does not come with too much magic and is6composable.7"""89# Core classes10from .core import Context, BaseCommand, Command, MultiCommand, Group, \11 CommandCollection, Parameter, Option, Argument, ParameterSource1213# Globals14from .globals import get_current_context1516# Decorators17from .decorators import pass_context, pass_obj, make_pass_decorator, \18 command, group, argument, option, confirmation_option, \19 password_option, version_option, help_option2021# Types22from .types import ParamType, File, Path, Choice, IntRange, Tuple, \23 DateTime, STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED, FloatRange2425# Utilities26from .utils import echo, get_binary_stream, get_text_stream, open_file, \27 format_filename, get_app_dir, get_os_args2829# Terminal functions30from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \31 progressbar, clear, style, unstyle, secho, edit, launch, getchar, \32 pause3334# Exceptions35from .exceptions import ClickException, UsageError, BadParameter, \36 FileError, Abort, NoSuchOption, BadOptionUsage, BadArgumentUsage, \37 MissingParameter3839# Formatting40from .formatting import HelpFormatter, wrap_text4142# Parsing43from .parser import OptionParser444546__all__ = [47 # Core classes48 'Context', 'BaseCommand', 'Command', 'MultiCommand', 'Group',49 'CommandCollection', 'Parameter', 'Option', 'Argument',5051 # Globals52 'get_current_context',5354 # Decorators55 'pass_context', 'pass_obj', 'make_pass_decorator', 'command', 'group',56 'argument', 'option', 'confirmation_option', 'password_option',57 'version_option', 'help_option',5859 # Types60 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple',61 'DateTime', 'STRING', 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',62 'FloatRange',6364 # Utilities65 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',66 'format_filename', 'get_app_dir', 'get_os_args',6768 # Terminal functions69 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',70 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit', 'launch',71 'getchar', 'pause',7273 # Exceptions74 'ClickException', 'UsageError', 'BadParameter', 'FileError',75 'Abort', 'NoSuchOption', 'BadOptionUsage', 'BadArgumentUsage',76 'MissingParameter',7778 # Formatting79 'HelpFormatter', 'wrap_text',8081 # Parsing82 'OptionParser',83]848586# Controls if click should emit the warning about the use of unicode87# literals.88disable_unicode_literals_warning = False899091__version__ = '8.0.dev'
deleted:click/_bashcomplete.py-334 removed
1import copy2import os3import re45from .utils import echo6from .parser import split_arg_string7from .core import MultiCommand, Option, Argument8from .types import Choice910try:11 from collections import abc12except ImportError:13 import collections as abc1415WORDBREAK = '='1617# Note, only BASH version 4.4 and later have the nosort option.18COMPLETION_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}2627%(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 fi3435 complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s36}3738%(complete_func)setup39'''4041COMPLETION_SCRIPT_ZSH = '''42#compdef %(script_names)s4344%(complete_func)s() {45 local -a completions46 local -a completions_with_descriptions47 local -a response48 (( ! $+commands[%(script_names)s] )) && return 14950 response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\51 COMP_CWORD=$((CURRENT-1)) \\52 %(autocomplete_var)s=\"complete_zsh\" \\53 %(script_names)s )}")5455 for key descr in ${(kv)response}; do56 if [[ "$descr" == "_" ]]; then57 completions+=("$key")58 else59 completions_with_descriptions+=("$key":"$descr")60 fi61 done6263 if [ -n "$completions_with_descriptions" ]; then64 _describe -V unsorted completions_with_descriptions -U65 fi6667 if [ -n "$completions" ]; then68 compadd -U -V unsorted -a completions69 fi70 compstate[insert]="automenu"71}7273compdef %(complete_func)s %(script_names)s74'''7576COMPLETION_SCRIPT_FISH = '''77complete --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'''7980_completion_scripts = {81 "bash": COMPLETION_SCRIPT_BASH,82 "zsh": COMPLETION_SCRIPT_ZSH,83 "fish": COMPLETION_SCRIPT_FISH,84}8586_invalid_ident_char_re = re.compile(r'[^a-zA-Z0-9_]')878889def 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() + ';'979899def 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 ctx134135136def 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] == '-'142143144def 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 parameter148 :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_str162163 return True if last_option and last_option in cmd_param.opts else False164165166def 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 False184185186def 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 results206207208def 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 command219220221def 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)])226227 # 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])234235236def 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)245246 ctx = resolve_ctx(cli, prog_name, args)247 if ctx is None:248 return []249250 has_double_dash = "--" in all_args251252 # 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 = ''260261 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)278279 add_subcommand_completions(ctx, incomplete, completions)280 # Sort before returning so that proper ordering can be enforced in custom types.281 return sorted(completions)282283284def 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 = ''292293 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 '_')300301 return True302303304def 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:]308309 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])314315 return True316317318def 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"324325 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")333334 return False
deleted:click/_compat.py-773 removed
1import re2import io3import os4import sys5import codecs6from weakref import WeakKeyDictionary789PY2 = sys.version_info[0] == 210CYGWIN = sys.platform.startswith('cygwin')11MSYS2 = sys.platform.startswith('win') and ('GCC' in sys.version)12# Determine local App Engine environment, per Google's own suggestion13APP_ENGINE = ('APPENGINE_RUNTIME' in os.environ and14 'Development/' in os.environ.get('SERVER_SOFTWARE', ''))15WIN = sys.platform.startswith('win') and not APP_ENGINE and not MSYS216DEFAULT_COLUMNS = 80171819_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")202122def get_filesystem_encoding():23 return sys.getfilesystemencoding() or sys.getdefaultencoding()242526def _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)363738def 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 False444546def 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 rv525354class _NonClosingTextIOWrapper(io.TextIOWrapper):5556 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)6162 # 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)7475 def writelines(self, lines):76 for line in lines:77 self.write(line)7879 def __del__(self):80 try:81 self.detach()82 except Exception:83 pass8485 def isatty(self):86 # https://bitbucket.org/pypy/pypy/issue/180387 return self._stream.isatty()888990class _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.9495 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 """99100 def __init__(self, stream, force_readable=False, force_writable=False):101 self._stream = stream102 self._force_readable = force_readable103 self._force_writable = force_writable104105 def __getattr__(self, name):106 return getattr(self._stream, name)107108 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)118119 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 True130131 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 True145146 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 True155156157if 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 = xrange164165 from pipes import quote as shlex_quote166167 def is_bytes(x):168 return isinstance(x, (buffer, bytearray))169170 _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')171172 # 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 f192193 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 f206207 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 f221222 def isidentifier(x):223 return _identifier_re.search(x) is not None224225 def get_binary_stdin():226 return set_binary_mode(sys.stdin)227228 def get_binary_stdout():229 _wrap_std_stream('stdout')230 return set_binary_mode(sys.stdout)231232 def get_binary_stderr():233 _wrap_std_stream('stderr')234 return set_binary_mode(sys.stderr)235236 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)242243 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)250251 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)258259 def filename_to_ui(value):260 if isinstance(value, bytes):261 value = value.decode(get_filesystem_encoding(), 'replace')262 return value263else:264 text_type = str265 raw_input = input266 string_types = (str,)267 int_types = (int,)268 range_type = range269 isidentifier = lambda x: x.isidentifier()270 iteritems = lambda x: iter(x.items())271272 from shlex import quote as shlex_quote273274 def is_bytes(x):275 return isinstance(x, (bytes, memoryview, bytearray))276277 def _is_binary_reader(stream, default=False):278 try:279 return isinstance(stream.read(0), bytes)280 except Exception:281 return default282 # This happens in some cases where the stream was already283 # closed. In this case, we assume the default.284285 def _is_binary_writer(stream, default=False):286 try:287 stream.write(b'')288 except Exception:289 try:290 stream.write('')291 return False292 except Exception:293 pass294 return default295 return True296297 def _find_binary_reader(stream):298 # We need to figure out if the given stream is already binary.299 # This can happen because the official docs recommend detaching300 # the streams to get binary streams. Some code might do this, so301 # we need to deal with this case explicitly.302 if _is_binary_reader(stream, False):303 return stream304305 buf = getattr(stream, 'buffer', None)306307 # Same situation here; this time we assume that the buffer is308 # actually binary in case it's closed.309 if buf is not None and _is_binary_reader(buf, True):310 return buf311312 def _find_binary_writer(stream):313 # We need to figure out if the given stream is already binary.314 # This can happen because the official docs recommend detaching315 # the streams to get binary streams. Some code might do this, so316 # we need to deal with this case explicitly.317 if _is_binary_writer(stream, False):318 return stream319320 buf = getattr(stream, 'buffer', None)321322 # Same situation here; this time we assume that the buffer is323 # actually binary in case it's closed.324 if buf is not None and _is_binary_writer(buf, True):325 return buf326327 def _stream_is_misconfigured(stream):328 """A stream is misconfigured if its encoding is ASCII."""329 # If the stream does not have an encoding set, we assume it's set330 # to ASCII. This appears to happen in certain unittest331 # environments. It's not quite clear what the correct behavior is332 # but this at least will force Click to recover somehow.333 return is_ascii_encoding(getattr(stream, 'encoding', None) or 'ascii')334335 def _is_compat_stream_attr(stream, attr, value):336 """A stream attribute is compatible if it is equal to the337 desired value or the desired value is unset and the attribute338 has a value.339 """340 stream_value = getattr(stream, attr, None)341 return stream_value == value or (value is None and stream_value is not None)342343 def _is_compatible_text_stream(stream, encoding, errors):344 """Check if a stream's encoding and errors attributes are345 compatible with the desired values.346 """347 return (348 _is_compat_stream_attr(stream, "encoding", encoding)349 and _is_compat_stream_attr(stream, "errors", errors)350 )351352 def _force_correct_text_stream(353 text_stream,354 encoding,355 errors,356 is_binary,357 find_binary,358 force_readable=False,359 force_writable=False,360 ):361 if is_binary(text_stream, False):362 binary_reader = text_stream363 else:364 # If the stream looks compatible, and won't default to a365 # misconfigured ascii encoding, return it as-is.366 if (367 _is_compatible_text_stream(text_stream, encoding, errors)368 and not (369 encoding is None370 and _stream_is_misconfigured(text_stream)371 )372 ):373 return text_stream374375 # Otherwise, get the underlying binary reader.376 binary_reader = find_binary(text_stream)377378 # If that's not possible, silently use the original reader379 # and get mojibake instead of exceptions.380 if binary_reader is None:381 return text_stream382383 # Default errors to replace instead of strict in order to get384 # something that works.385 if errors is None:386 errors = "replace"387388 # Wrap the binary stream in a text stream with the correct389 # encoding parameters.390 return _make_text_stream(391 binary_reader,392 encoding,393 errors,394 force_readable=force_readable,395 force_writable=force_writable,396 )397398 def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):399 return _force_correct_text_stream(400 text_reader,401 encoding,402 errors,403 _is_binary_reader,404 _find_binary_reader,405 force_readable=force_readable,406 )407408 def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):409 return _force_correct_text_stream(410 text_writer,411 encoding,412 errors,413 _is_binary_writer,414 _find_binary_writer,415 force_writable=force_writable,416 )417418 def get_binary_stdin():419 reader = _find_binary_reader(sys.stdin)420 if reader is None:421 raise RuntimeError('Was not able to determine binary '422 'stream for sys.stdin.')423 return reader424425 def get_binary_stdout():426 writer = _find_binary_writer(sys.stdout)427 if writer is None:428 raise RuntimeError('Was not able to determine binary '429 'stream for sys.stdout.')430 return writer431432 def get_binary_stderr():433 writer = _find_binary_writer(sys.stderr)434 if writer is None:435 raise RuntimeError('Was not able to determine binary '436 'stream for sys.stderr.')437 return writer438439 def get_text_stdin(encoding=None, errors=None):440 rv = _get_windows_console_stream(sys.stdin, encoding, errors)441 if rv is not None:442 return rv443 return _force_correct_text_reader(sys.stdin, encoding, errors,444 force_readable=True)445446 def get_text_stdout(encoding=None, errors=None):447 rv = _get_windows_console_stream(sys.stdout, encoding, errors)448 if rv is not None:449 return rv450 return _force_correct_text_writer(sys.stdout, encoding, errors,451 force_writable=True)452453 def get_text_stderr(encoding=None, errors=None):454 rv = _get_windows_console_stream(sys.stderr, encoding, errors)455 if rv is not None:456 return rv457 return _force_correct_text_writer(sys.stderr, encoding, errors,458 force_writable=True)459460 def filename_to_ui(value):461 if isinstance(value, bytes):462 value = value.decode(get_filesystem_encoding(), 'replace')463 else:464 value = value.encode('utf-8', 'surrogateescape') \465 .decode('utf-8', 'replace')466 return value467468469def get_streerror(e, default=None):470 if hasattr(e, 'strerror'):471 msg = e.strerror472 else:473 if default is not None:474 msg = default475 else:476 msg = str(e)477 if isinstance(msg, bytes):478 msg = msg.decode('utf-8', 'replace')479 return msg480481482def _wrap_io_open(file, mode, encoding, errors):483 """On Python 2, :func:`io.open` returns a text file wrapper that484 requires passing ``unicode`` to ``write``. Need to open the file in485 binary mode then wrap it in a subclass that can write ``str`` and486 ``unicode``.487488 Also handles not passing ``encoding`` and ``errors`` in binary mode.489 """490 binary = "b" in mode491492 if binary:493 kwargs = {}494 else:495 kwargs = {"encoding": encoding, "errors": errors}496497 if not PY2 or binary:498 return io.open(file, mode, **kwargs)499500 f = io.open(file, "b" + mode.replace("t", ""))501 return _make_text_stream(f, **kwargs)502503504def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):505 binary = "b" in mode506507 # Standard streams first. These are simple because they don't need508 # special handling for the atomic flag. It's entirely ignored.509 if filename == '-':510 if any(m in mode for m in ['w', 'a', 'x']):511 if binary:512 return get_binary_stdout(), False513 return get_text_stdout(encoding=encoding, errors=errors), False514 if binary:515 return get_binary_stdin(), False516 return get_text_stdin(encoding=encoding, errors=errors), False517518 # Non-atomic writes directly go out through the regular open functions.519 if not atomic:520 return _wrap_io_open(filename, mode, encoding, errors), True521522 # Some usability stuff for atomic writes523 if 'a' in mode:524 raise ValueError(525 'Appending to an existing file is not supported, because that '526 'would involve an expensive `copy`-operation to a temporary '527 'file. Open the file in normal `w`-mode and copy explicitly '528 'if that\'s what you\'re after.'529 )530 if 'x' in mode:531 raise ValueError('Use the `overwrite`-parameter instead.')532 if 'w' not in mode:533 raise ValueError('Atomic writes only make sense with `w`-mode.')534535 # Atomic writes are more complicated. They work by opening a file536 # as a proxy in the same folder and then using the fdopen537 # functionality to wrap it in a Python file. Then we wrap it in an538 # atomic file that moves the file over on close.539 import errno540 import random541542 try:543 perm = os.stat(filename).st_mode544 except OSError:545 perm = None546547 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL548549 if binary:550 flags |= getattr(os, 'O_BINARY', 0)551552 while True:553 tmp_filename = os.path.join(554 os.path.dirname(filename),555 '.__atomic-write%08x' % (random.randrange(1 << 32),),556 )557 try:558 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)559 break560 except OSError as e:561 if e.errno == errno.EEXIST or (562 os.name == "nt"563 and e.errno == errno.EACCES564 and os.path.isdir(e.filename)565 and os.access(e.filename, os.W_OK)566 ):567 continue568 raise569570 if perm is not None:571 os.chmod(tmp_filename, perm) # in case perm includes bits in umask572573 f = _wrap_io_open(fd, mode, encoding, errors)574 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True575576577# Used in a destructor call, needs extra protection from interpreter cleanup.578if hasattr(os, 'replace'):579 _replace = os.replace580 _can_replace = True581else:582 _replace = os.rename583 _can_replace = not WIN584585586class _AtomicFile(object):587588 def __init__(self, f, tmp_filename, real_filename):589 self._f = f590 self._tmp_filename = tmp_filename591 self._real_filename = real_filename592 self.closed = False593594 @property595 def name(self):596 return self._real_filename597598 def close(self, delete=False):599 if self.closed:600 return601 self._f.close()602 if not _can_replace:603 try:604 os.remove(self._real_filename)605 except OSError:606 pass607 _replace(self._tmp_filename, self._real_filename)608 self.closed = True609610 def __getattr__(self, name):611 return getattr(self._f, name)612613 def __enter__(self):614 return self615616 def __exit__(self, exc_type, exc_value, tb):617 self.close(delete=exc_type is not None)618619 def __repr__(self):620 return repr(self._f)621622623auto_wrap_for_ansi = None624colorama = None625get_winterm_size = None626627628def strip_ansi(value):629 return _ansi_re.sub('', value)630631632def _is_jupyter_kernel_output(stream):633 if WIN:634 # TODO: Couldn't test on Windows, should't try to support until635 # someone tests the details wrt colorama.636 return637638 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):639 stream = stream._stream640641 return stream.__class__.__module__.startswith("ipykernel.")642643644def should_strip_ansi(stream=None, color=None):645 if color is None:646 if stream is None:647 stream = sys.stdin648 return not isatty(stream) and not _is_jupyter_kernel_output(stream)649 return not color650651652# If we're on Windows, we provide transparent integration through653# colorama. This will make ANSI colors through the echo function654# work automatically.655if WIN:656 # Windows has a smaller terminal657 DEFAULT_COLUMNS = 79658659 from ._winconsole import _get_windows_console_stream, _wrap_std_stream660661 def _get_argv_encoding():662 import locale663 return locale.getpreferredencoding()664665 if PY2:666 def raw_input(prompt=''):667 sys.stderr.flush()668 if prompt:669 stdout = _default_text_stdout()670 stdout.write(prompt)671 stdin = _default_text_stdin()672 return stdin.readline().rstrip('\r\n')673674 try:675 import colorama676 except ImportError:677 pass678 else:679 _ansi_stream_wrappers = WeakKeyDictionary()680681 def auto_wrap_for_ansi(stream, color=None):682 """This function wraps a stream so that calls through colorama683 are issued to the win32 console API to recolor on demand. It684 also ensures to reset the colors if a write call is interrupted685 to not destroy the console afterwards.686 """687 try:688 cached = _ansi_stream_wrappers.get(stream)689 except Exception:690 cached = None691 if cached is not None:692 return cached693 strip = should_strip_ansi(stream, color)694 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)695 rv = ansi_wrapper.stream696 _write = rv.write697698 def _safe_write(s):699 try:700 return _write(s)701 except:702 ansi_wrapper.reset_all()703 raise704705 rv.write = _safe_write706 try:707 _ansi_stream_wrappers[stream] = rv708 except Exception:709 pass710 return rv711712 def get_winterm_size():713 win = colorama.win32.GetConsoleScreenBufferInfo(714 colorama.win32.STDOUT).srWindow715 return win.Right - win.Left, win.Bottom - win.Top716else:717 def _get_argv_encoding():718 return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()719720 _get_windows_console_stream = lambda *x: None721 _wrap_std_stream = lambda *x: None722723724def term_len(x):725 return len(strip_ansi(x))726727728def isatty(stream):729 try:730 return stream.isatty()731 except Exception:732 return False733734735def _make_cached_stream_func(src_func, wrapper_func):736 cache = WeakKeyDictionary()737 def func():738 stream = src_func()739 try:740 rv = cache.get(stream)741 except Exception:742 rv = None743 if rv is not None:744 return rv745 rv = wrapper_func()746 try:747 stream = src_func() # In case wrapper_func() modified the stream748 cache[stream] = rv749 except Exception:750 pass751 return rv752 return func753754755_default_text_stdin = _make_cached_stream_func(756 lambda: sys.stdin, get_text_stdin)757_default_text_stdout = _make_cached_stream_func(758 lambda: sys.stdout, get_text_stdout)759_default_text_stderr = _make_cached_stream_func(760 lambda: sys.stderr, get_text_stderr)761762763binary_streams = {764 'stdin': get_binary_stdin,765 'stdout': get_binary_stdout,766 'stderr': get_binary_stderr,767}768769text_streams = {770 'stdin': get_text_stdin,771 'stdout': get_text_stdout,772 'stderr': get_text_stderr,773}
deleted:click/_termui_impl.py-651 removed
1# -*- coding: utf-8 -*-2"""3This module contains implementations for the termui module. To keep the4import time of Click down, some infrequently used functionality is5placed in this module and only imported as needed.6"""78import os9import sys10import time11import math12import contextlib13from ._compat import _default_text_stdout, range_type, isatty, \14 open_stream, shlex_quote, strip_ansi, term_len, get_best_encoding, WIN, \15 int_types, CYGWIN16from .utils import echo17from .exceptions import ClickException181920if os.name == 'nt':21 BEFORE_BAR = '\r'22 AFTER_BAR = '\n'23else:24 BEFORE_BAR = '\r\033[?25l'25 AFTER_BAR = '\033[?25h\n'262728def _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 hint464748class ProgressBar(object):4950 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 == 06970 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.59091 def __enter__(self):92 self.entered = True93 self.render_progress()94 return self9596 def __exit__(self, exc_type, exc_value, tb):97 self.render_finish()9899 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()104105 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))112113 # Python 2 compat114 next = __next__115116 def is_fast(self):117 return time.time() - self.start <= self.short_limit118119 def render_finish(self):120 if self.is_hidden or self.is_fast():121 return122 self.file.write(AFTER_BAR)123 self.file.flush()124125 @property126 def pct(self):127 if self.finished:128 return 1.0129 return min(self.pos / (float(self.length) or 1), 1.0)130131 @property132 def time_per_iteration(self):133 if not self.avg:134 return 0.0135 return sum(self.avg) / float(len(self.avg))136137 @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.0142143 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 ''158159 def format_pos(self):160 pos = str(self.pos)161 if self.length_known:162 pos += '/%s' % self.length163 return pos164165 def format_pct(self):166 return ('% 4d%%' % int(self.pct * 100))[1:]167168 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 bar182183 def format_progress_line(self):184 show_percent = self.show_percent185186 info_bits = []187 if self.length_known and show_percent is None:188 show_percent = not self.show_pos189190 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)200201 return (self.bar_template % {202 'label': self.label,203 'bar': self.format_bar(),204 'info': self.info_sep.join(info_bits)205 }).rstrip()206207 def render_progress(self):208 from .termui import get_terminal_size209210 if self.is_hidden:211 return212213 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_width225226 clear_width = self.width227 if self.max_width is not None:228 clear_width = self.max_width229230 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_len235236 buf.append(line)237 buf.append(' ' * (clear_width - line_len))238 line = ''.join(buf)239 # Render the line only if it changed.240241 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()245246 def make_step(self, n_steps):247 self.pos += n_steps248 if self.length_known and self.pos >= self.length:249 self.finished = True250251 if (time.time() - self.last_eta) < 1.0:252 return253254 self.last_eta = time.time()255256 # 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.start263264 self.avg = self.avg[-6:] + [step]265266 self.eta_known = self.length_known267268 def update(self, n_steps, current_item=None):269 """Update the progress bar by advancing a specified number of270 steps, and optionally set the ``current_item`` for this new271 position.272273 :param n_steps: Number of steps to advance.274 :param current_item: Optional item to set as ``current_item``275 for the updated position.276277 .. versionadded:: 8.0278 Added the ``current_item`` optional parameter.279 """280 self.make_step(n_steps)281 if current_item is not None:282 self.current_item = current_item283 self.render_progress()284285 def finish(self):286 self.eta_known = 0287 self.current_item = None288 self.finished = True289290 def generator(self):291 """Return a generator which yields the items added to the bar292 during construction, and updates the progress bar *after* the293 yielded block returns.294 """295 # WARNING: the iterator interface for `ProgressBar` relies on296 # this and only works because this is a simple generator which297 # doesn't create or manage additional state. If this function298 # changes, the impact should be evaluated both against299 # `iter(bar)` and `next(bar)`. `next()` in particular may call300 # `self.generator()` repeatedly, and this must remain safe in301 # order for that interface to work.302 if not self.entered:303 raise RuntimeError('You need to use progress bars in a with block.')304305 if self.is_hidden:306 for rv in self.iter:307 yield rv308 else:309 for rv in self.iter:310 self.current_item = rv311 yield rv312 self.update(1)313 self.finish()314 self.render_progress()315316317def pager(generator, color=None):318 """Decide what method to use for paging through text."""319 stdout = _default_text_stdout()320 if not isatty(sys.stdin) or not isatty(stdout):321 return _nullpager(stdout, generator, color)322 pager_cmd = (os.environ.get('PAGER', None) or '').strip()323 if pager_cmd:324 if WIN:325 return _tempfilepager(generator, pager_cmd, color)326 return _pipepager(generator, pager_cmd, color)327 if os.environ.get('TERM') in ('dumb', 'emacs'):328 return _nullpager(stdout, generator, color)329 if WIN or sys.platform.startswith('os2'):330 return _tempfilepager(generator, 'more <', color)331 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:332 return _pipepager(generator, 'less', color)333334 import tempfile335 fd, filename = tempfile.mkstemp()336 os.close(fd)337 try:338 if hasattr(os, 'system') and os.system("more %s" % shlex_quote(filename)) == 0:339 return _pipepager(generator, 'more', color)340 return _nullpager(stdout, generator, color)341 finally:342 os.unlink(filename)343344345def _pipepager(generator, cmd, color):346 """Page through text by feeding it to another program. Invoking a347 pager through this might support colors.348 """349 import subprocess350 env = dict(os.environ)351352 # If we're piping to less we might support colors under the353 # condition that354 cmd_detail = cmd.rsplit('/', 1)[-1].split()355 if color is None and cmd_detail[0] == 'less':356 less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])357 if not less_flags:358 env['LESS'] = '-R'359 color = True360 elif 'r' in less_flags or 'R' in less_flags:361 color = True362363 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,364 env=env)365 encoding = get_best_encoding(c.stdin)366 try:367 for text in generator:368 if not color:369 text = strip_ansi(text)370371 c.stdin.write(text.encode(encoding, 'replace'))372 except (IOError, KeyboardInterrupt):373 pass374 else:375 c.stdin.close()376377 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting378 # search or other commands inside less).379 #380 # That means when the user hits ^C, the parent process (click) terminates,381 # but less is still alive, paging the output and messing up the terminal.382 #383 # If the user wants to make the pager exit on ^C, they should set384 # `LESS='-K'`. It's not our decision to make.385 while True:386 try:387 c.wait()388 except KeyboardInterrupt:389 pass390 else:391 break392393394def _tempfilepager(generator, cmd, color):395 """Page through text by invoking a program on a temporary file."""396 import tempfile397 filename = tempfile.mktemp()398 # TODO: This never terminates if the passed generator never terminates.399 text = "".join(generator)400 if not color:401 text = strip_ansi(text)402 encoding = get_best_encoding(sys.stdout)403 with open_stream(filename, 'wb')[0] as f:404 f.write(text.encode(encoding))405 try:406 os.system("%s %s" % (shlex_quote(cmd), shlex_quote(filename)))407 finally:408 os.unlink(filename)409410411def _nullpager(stream, generator, color):412 """Simply print unformatted text. This is the ultimate fallback."""413 for text in generator:414 if not color:415 text = strip_ansi(text)416 stream.write(text)417418419class Editor(object):420421 def __init__(self, editor=None, env=None, require_save=True,422 extension='.txt'):423 self.editor = editor424 self.env = env425 self.require_save = require_save426 self.extension = extension427428 def get_editor(self):429 if self.editor is not None:430 return self.editor431 for key in 'VISUAL', 'EDITOR':432 rv = os.environ.get(key)433 if rv:434 return rv435 if WIN:436 return 'notepad'437 for editor in 'sensible-editor', 'vim', 'nano':438 if os.system('which %s >/dev/null 2>&1' % editor) == 0:439 return editor440 return 'vi'441442 def edit_file(self, filename):443 import subprocess444 editor = self.get_editor()445 if self.env:446 environ = os.environ.copy()447 environ.update(self.env)448 else:449 environ = None450 try:451 c = subprocess.Popen(452 "%s %s" % (shlex_quote(editor), shlex_quote(filename)),453 env=environ,454 shell=True455 )456 exit_code = c.wait()457 if exit_code != 0:458 raise ClickException('%s: Editing failed!' % editor)459 except OSError as e:460 raise ClickException('%s: Editing failed: %s' % (editor, e))461462 def edit(self, text):463 import tempfile464465 text = text or ''466 binary_data = type(text) in [bytes, bytearray]467468 if not binary_data and text and not text.endswith('\n'):469 text += '\n'470471 fd, name = tempfile.mkstemp(prefix='editor-', suffix=self.extension)472 try:473 if not binary_data:474 if WIN:475 encoding = 'utf-8-sig'476 text = text.replace('\n', '\r\n')477 else:478 encoding = 'utf-8'479 text = text.encode(encoding)480481 f = os.fdopen(fd, 'wb')482 f.write(text)483 f.close()484 timestamp = os.path.getmtime(name)485486 self.edit_file(name)487488 if self.require_save \489 and os.path.getmtime(name) == timestamp:490 return None491492 f = open(name, 'rb')493 try:494 rv = f.read()495 finally:496 f.close()497 if binary_data:498 return rv499 else:500 return rv.decode('utf-8-sig').replace('\r\n', '\n')501 finally:502 os.unlink(name)503504505def open_url(url, wait=False, locate=False):506 import subprocess507508 def _unquote_file(url):509 try:510 import urllib511 except ImportError:512 import urllib513 if url.startswith('file://'):514 url = urllib.unquote(url[7:])515 return url516517 if sys.platform == 'darwin':518 args = ['open']519 if wait:520 args.append('-W')521 if locate:522 args.append('-R')523 args.append(_unquote_file(url))524 null = open('/dev/null', 'w')525 try:526 return subprocess.Popen(args, stderr=null).wait()527 finally:528 null.close()529 elif WIN:530 if locate:531 url = _unquote_file(url)532 args = "explorer /select,%s" % (shlex_quote(url),)533 else:534 args = 'start %s "" %s' % ("/WAIT" if wait else "", shlex_quote(url))535 return os.system(args)536 elif CYGWIN:537 if locate:538 url = _unquote_file(url)539 args = "cygstart %s" % (shlex_quote(os.path.dirname(url)),)540 else:541 args = "cygstart %s %s" % ("-w" if wait else "", shlex_quote(url))542 return os.system(args)543544 try:545 if locate:546 url = os.path.dirname(_unquote_file(url)) or '.'547 else:548 url = _unquote_file(url)549 c = subprocess.Popen(['xdg-open', url])550 if wait:551 return c.wait()552 return 0553 except OSError:554 if url.startswith(('http://', 'https://')) and not locate and not wait:555 import webbrowser556 webbrowser.open(url)557 return 0558 return 1559560561def _translate_ch_to_exc(ch):562 if ch == u'\x03':563 raise KeyboardInterrupt()564 if ch == u'\x04' and not WIN: # Unix-like, Ctrl+D565 raise EOFError()566 if ch == u'\x1a' and WIN: # Windows, Ctrl+Z567 raise EOFError()568569570if WIN:571 import msvcrt572573 @contextlib.contextmanager574 def raw_terminal():575 yield576577 def getchar(echo):578 # The function `getch` will return a bytes object corresponding to579 # the pressed character. Since Windows 10 build 1803, it will also580 # return \x00 when called a second time after pressing a regular key.581 #582 # `getwch` does not share this probably-bugged behavior. Moreover, it583 # returns a Unicode object by default, which is what we want.584 #585 # Either of these functions will return \x00 or \xe0 to indicate586 # a special key, and you need to call the same function again to get587 # the "rest" of the code. The fun part is that \u00e0 is588 # "latin small letter a with grave", so if you type that on a French589 # keyboard, you _also_ get a \xe0.590 # E.g., consider the Up arrow. This returns \xe0 and then \x48. The591 # resulting Unicode string reads as "a with grave" + "capital H".592 # This is indistinguishable from when the user actually types593 # "a with grave" and then "capital H".594 #595 # When \xe0 is returned, we assume it's part of a special-key sequence596 # and call `getwch` again, but that means that when the user types597 # the \u00e0 character, `getchar` doesn't return until a second598 # character is typed.599 # The alternative is returning immediately, but that would mess up600 # cross-platform handling of arrow keys and others that start with601 # \xe0. Another option is using `getch`, but then we can't reliably602 # read non-ASCII characters, because return values of `getch` are603 # limited to the current 8-bit codepage.604 #605 # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`606 # is doing the right thing in more situations than with `getch`.607 if echo:608 func = msvcrt.getwche609 else:610 func = msvcrt.getwch611612 rv = func()613 if rv in (u'\x00', u'\xe0'):614 # \x00 and \xe0 are control characters that indicate special key,615 # see above.616 rv += func()617 _translate_ch_to_exc(rv)618 return rv619else:620 import tty621 import termios622623 @contextlib.contextmanager624 def raw_terminal():625 if not isatty(sys.stdin):626 f = open('/dev/tty')627 fd = f.fileno()628 else:629 fd = sys.stdin.fileno()630 f = None631 try:632 old_settings = termios.tcgetattr(fd)633 try:634 tty.setraw(fd)635 yield fd636 finally:637 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)638 sys.stdout.flush()639 if f is not None:640 f.close()641 except termios.error:642 pass643644 def getchar(echo):645 with raw_terminal() as fd:646 ch = os.read(fd, 32)647 ch = ch.decode(get_best_encoding(sys.stdin), 'replace')648 if echo and isatty(sys.stdout):649 sys.stdout.write(ch)650 _translate_ch_to_exc(ch)651 return ch
deleted:click/_textwrap.py-38 removed
1import textwrap2from contextlib import contextmanager345class TextWrapper(textwrap.TextWrapper):67 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):8 space_left = max(width - cur_len, 1)910 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())1819 @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_indent3031 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
1import os2import sys3import codecs45from ._compat import PY2678# 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.12click = sys.modules[__name__.rsplit('.', 1)[0]]131415def _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 0303132def _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)484950def _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 return6162 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 = False7273 # Make sure we're operating on text here.74 if isinstance(rv, bytes):75 rv = rv.decode('ascii', 'replace')7677 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 = True8384 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))105106 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_locale119120 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 prompt.1011import io12import os13import sys14import zlib15import time16import ctypes17import msvcrt18from ._compat import _NonClosingTextIOWrapper, text_type, PY219from 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 WinError22try:23 from ctypes import pythonapi24 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer25 PyBuffer_Release = pythonapi.PyBuffer_Release26except ImportError:27 pythonapi = None28from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE293031c_ssize_p = POINTER(c_ssize_t)3233kernel32 = windll.kernel3234GetStdHandle = kernel32.GetStdHandle35ReadConsoleW = kernel32.ReadConsoleW36WriteConsoleW = kernel32.WriteConsoleW37GetConsoleMode = kernel32.GetConsoleMode38GetLastError = kernel32.GetLastError39GetCommandLineW = WINFUNCTYPE(LPWSTR)(40 ('GetCommandLineW', windll.kernel32))41CommandLineToArgvW = WINFUNCTYPE(42 POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(43 ('CommandLineToArgvW', windll.shell32))44LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(45 ('LocalFree', windll.kernel32))464748STDIN_HANDLE = GetStdHandle(-10)49STDOUT_HANDLE = GetStdHandle(-11)50STDERR_HANDLE = GetStdHandle(-12)515253PyBUF_SIMPLE = 054PyBUF_WRITABLE = 15556ERROR_SUCCESS = 057ERROR_NOT_ENOUGH_MEMORY = 858ERROR_OPERATION_ABORTED = 9955960STDIN_FILENO = 061STDOUT_FILENO = 162STDERR_FILENO = 26364EOF = b'\x1a'65MAX_BYTES_WRITTEN = 32767666768class 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 ]8283 if PY2:84 _fields_.insert(-1, ('smalltable', c_ssize_t * 2))858687# On PyPy we cannot get buffers so our ability to operate here is88# severely limited.89if pythonapi is None:90 get_buffer = None91else: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))101102103class _WindowsConsoleRawIOBase(io.RawIOBase):104105 def __init__(self, handle):106 self.handle = handle107108 def isatty(self):109 io.RawIOBase.isatty(self)110 return True111112113class _WindowsConsoleReader(_WindowsConsoleRawIOBase):114115 def readable(self):116 return True117118 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')125126 buffer = get_buffer(b, writable=True)127 code_units_to_be_read = bytes_to_be_read // 2128 code_units_read = c_ulong()129130 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())137138 if buffer[0] == EOF:139 return 0140 return 2 * code_units_read.value141142143class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):144145 def writable(self):146 return True147148 @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' % errno155156 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()162163 WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,164 byref(code_units_written), None)165 bytes_written = 2 * code_units_written.value166167 if bytes_written == 0 and bytes_to_be_written > 0:168 raise OSError(self._get_error_message(GetLastError()))169 return bytes_written170171172class ConsoleStream(object):173174 def __init__(self, text_stream, byte_stream):175 self._text_stream = text_stream176 self.buffer = byte_stream177178 @property179 def name(self):180 return self.buffer.name181182 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)190191 def writelines(self, lines):192 for line in lines:193 self.write(line)194195 def __getattr__(self, name):196 return getattr(self._text_stream, name)197198 def isatty(self):199 return self.buffer.isatty()200201 def __repr__(self):202 return '<ConsoleStream name=%r encoding=%r>' % (203 self.name,204 self.encoding,205 )206207208class 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 = wrapped218219 def __getattr__(self, name):220 return getattr(self.__wrapped, name)221222 def write(self, text):223 total_to_write = len(text)224 written = 0225226 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_write230231232_wrapped_std_streams = set()233234235def _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)240241242def _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)247248249def _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)254255256def _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)261262263if PY2:264 def _hash_py_argv():265 return zlib.crc32('\x00'.join(sys.argv[1:]))266267 _initial_argv_hash = _hash_py_argv()268269 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_unicode279280 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 break289290 return argv[1:]291292293_stream_factories = {294 0: _get_text_stdin,295 1: _get_text_stdout,296 2: _get_text_stderr,297}298299300def _is_console(f):301 if not hasattr(f, 'fileno'):302 return False303304 try:305 fileno = f.fileno()306 except OSError:307 return False308309 handle = msvcrt.get_osfhandle(fileno)310 return bool(GetConsoleMode(handle, byref(DWORD())))311312313def _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-1973 removed
1import errno2import inspect3import os4import sys5from contextlib import contextmanager6from itertools import repeat7from functools import update_wrapper89from .types import convert_type, IntRange, BOOL10from .utils import PacifyFlushWrapper, make_str, make_default_short_help, \11 echo, get_os_args12from .exceptions import ClickException, UsageError, BadParameter, Abort, \13 MissingParameter, Exit14from .termui import prompt, confirm, style15from .formatting import HelpFormatter, join_options16from .parser import OptionParser, split_opt17from .globals import push_context, pop_context1819from ._compat import PY2, isidentifier, iteritems, string_types20from ._unicodefun import _check_for_unicode_literals, _verify_python3_env212223_missing = object()242526SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'27SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'2829DEPRECATED_HELP_NOTICE = ' (DEPRECATED)'30DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \31 'The command %(name)s is deprecated.'323334def _maybe_show_deprecated_notice(cmd):35 if cmd.deprecated:36 echo(style(DEPRECATED_INVOKE_NOTICE % {'name': cmd.name}, fg='red'), err=True)373839def 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)464748def _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 return5556 from ._bashcomplete import bashcomplete57 if bashcomplete(cmd, prog_name, complete_var, complete_instr):58 fast_exit(1)596061def _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))787980def batch(iterable, batch_size):81 return list(zip(*repeat(iter(iterable), batch_size)))828384def invoke_param_callback(callback, ctx, param, value):85 code = getattr(callback, '__code__', None)86 args = getattr(code, 'co_argcount', 3)8788 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)979899@contextmanager100def 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 raise116117118def 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)129130 return sorted(declaration_order, key=sort_key)131132class ParameterSource(object):133 """This is an enum that indicates the source of a command line parameter.134135 The enum has one of the following values: COMMANDLINE,136 ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the137 default value in the decorator was used. This class should be138 converted to an enum when Python 2 support is dropped.139 """140141 COMMANDLINE = "COMMANDLINE"142 ENVIRONMENT = "ENVIRONMENT"143 DEFAULT = "DEFAULT"144 DEFAULT_MAP = "DEFAULT_MAP"145 146 VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP}147 148 @classmethod149 def validate(cls, value):150 """Validate that the specified value is a valid enum.151152 This method will raise a ValueError if the value is153 not a valid enum.154155 :param value: the string value to verify156 """157 if value not in cls.VALUES:158 raise ValueError("Invalid ParameterSource value: '{}'. Valid "159 "values are: {}".format(value, ",".join(cls.VALUES)))160161162class Context(object):163 """The context is a special internal object that holds state relevant164 for the script execution at every single level. It's normally invisible165 to commands unless they opt-in to getting access to it.166167 The context is useful as it can pass internal objects around and can168 control special execution features such as reading data from169 environment variables.170171 A context can be used as context manager in which case it will call172 :meth:`close` on teardown.173174 .. versionadded:: 2.0175 Added the `resilient_parsing`, `help_option_names`,176 `token_normalize_func` parameters.177178 .. versionadded:: 3.0179 Added the `allow_extra_args` and `allow_interspersed_args`180 parameters.181182 .. versionadded:: 4.0183 Added the `color`, `ignore_unknown_options`, and184 `max_content_width` parameters.185186 .. versionadded:: 7.1187 Added the `show_default` parameter.188189 :param command: the command class for this context.190 :param parent: the parent context.191 :param info_name: the info name for this invocation. Generally this192 is the most descriptive name for the script or193 command. For the toplevel script it is usually194 the name of the script, for commands below it it's195 the name of the script.196 :param obj: an arbitrary object of user data.197 :param auto_envvar_prefix: the prefix to use for automatic environment198 variables. If this is `None` then reading199 from environment variables is disabled. This200 does not affect manually set environment201 variables which are always read.202 :param default_map: a dictionary (like object) with default values203 for parameters.204 :param terminal_width: the width of the terminal. The default is205 inherit from parent context. If no context206 defines the terminal width then auto207 detection will be applied.208 :param max_content_width: the maximum width for content rendered by209 Click (this currently only affects help210 pages). This defaults to 80 characters if211 not overridden. In other words: even if the212 terminal is larger than that, Click will not213 format things wider than 80 characters by214 default. In addition to that, formatters might215 add some safety mapping on the right.216 :param resilient_parsing: if this flag is enabled then Click will217 parse without any interactivity or callback218 invocation. Default values will also be219 ignored. This is useful for implementing220 things such as completion support.221 :param allow_extra_args: if this is set to `True` then extra arguments222 at the end will not raise an error and will be223 kept on the context. The default is to inherit224 from the command.225 :param allow_interspersed_args: if this is set to `False` then options226 and arguments cannot be mixed. The227 default is to inherit from the command.228 :param ignore_unknown_options: instructs click to ignore options it does229 not know and keeps them for later230 processing.231 :param help_option_names: optionally a list of strings that define how232 the default help parameter is named. The233 default is ``['--help']``.234 :param token_normalize_func: an optional function that is used to235 normalize tokens (options, choices,236 etc.). This for instance can be used to237 implement case insensitive behavior.238 :param color: controls if the terminal supports ANSI colors or not. The239 default is autodetection. This is only needed if ANSI240 codes are used in texts that Click prints which is by241 default not the case. This for instance would affect242 help output.243 :param show_default: if True, shows defaults for all options.244 Even if an option is later created with show_default=False,245 this command-level setting overrides it.246 """247248 def __init__(self, command, parent=None, info_name=None, obj=None,249 auto_envvar_prefix=None, default_map=None,250 terminal_width=None, max_content_width=None,251 resilient_parsing=False, allow_extra_args=None,252 allow_interspersed_args=None,253 ignore_unknown_options=None, help_option_names=None,254 token_normalize_func=None, color=None, show_default=None):255 #: the parent context or `None` if none exists.256 self.parent = parent257 #: the :class:`Command` for this context.258 self.command = command259 #: the descriptive information name260 self.info_name = info_name261 #: the parsed parameters except if the value is hidden in which262 #: case it's not remembered.263 self.params = {}264 #: the leftover arguments.265 self.args = []266 #: protected arguments. These are arguments that are prepended267 #: to `args` when certain parsing scenarios are encountered but268 #: must be never propagated to another arguments. This is used269 #: to implement nested parsing.270 self.protected_args = []271 if obj is None and parent is not None:272 obj = parent.obj273 #: the user object stored.274 self.obj = obj275 self._meta = getattr(parent, 'meta', {})276277 #: A dictionary (-like object) with defaults for parameters.278 if default_map is None \279 and parent is not None \280 and parent.default_map is not None:281 default_map = parent.default_map.get(info_name)282 self.default_map = default_map283284 #: This flag indicates if a subcommand is going to be executed. A285 #: group callback can use this information to figure out if it's286 #: being executed directly or because the execution flow passes287 #: onwards to a subcommand. By default it's None, but it can be288 #: the name of the subcommand to execute.289 #:290 #: If chaining is enabled this will be set to ``'*'`` in case291 #: any commands are executed. It is however not possible to292 #: figure out which ones. If you require this knowledge you293 #: should use a :func:`resultcallback`.294 self.invoked_subcommand = None295296 if terminal_width is None and parent is not None:297 terminal_width = parent.terminal_width298 #: The width of the terminal (None is autodetection).299 self.terminal_width = terminal_width300301 if max_content_width is None and parent is not None:302 max_content_width = parent.max_content_width303 #: The maximum width of formatted content (None implies a sensible304 #: default which is 80 for most things).305 self.max_content_width = max_content_width306307 if allow_extra_args is None:308 allow_extra_args = command.allow_extra_args309 #: Indicates if the context allows extra args or if it should310 #: fail on parsing.311 #:312 #: .. versionadded:: 3.0313 self.allow_extra_args = allow_extra_args314315 if allow_interspersed_args is None:316 allow_interspersed_args = command.allow_interspersed_args317 #: Indicates if the context allows mixing of arguments and318 #: options or not.319 #:320 #: .. versionadded:: 3.0321 self.allow_interspersed_args = allow_interspersed_args322323 if ignore_unknown_options is None:324 ignore_unknown_options = command.ignore_unknown_options325 #: Instructs click to ignore options that a command does not326 #: understand and will store it on the context for later327 #: processing. This is primarily useful for situations where you328 #: want to call into external programs. Generally this pattern is329 #: strongly discouraged because it's not possibly to losslessly330 #: forward all arguments.331 #:332 #: .. versionadded:: 4.0333 self.ignore_unknown_options = ignore_unknown_options334335 if help_option_names is None:336 if parent is not None:337 help_option_names = parent.help_option_names338 else:339 help_option_names = ['--help']340341 #: The names for the help options.342 self.help_option_names = help_option_names343344 if token_normalize_func is None and parent is not None:345 token_normalize_func = parent.token_normalize_func346347 #: An optional normalization function for tokens. This is348 #: options, choices, commands etc.349 self.token_normalize_func = token_normalize_func350351 #: Indicates if resilient parsing is enabled. In that case Click352 #: will do its best to not cause any failures and default values353 #: will be ignored. Useful for completion.354 self.resilient_parsing = resilient_parsing355356 # If there is no envvar prefix yet, but the parent has one and357 # the command on this level has a name, we can expand the envvar358 # prefix automatically.359 if auto_envvar_prefix is None:360 if parent is not None \361 and parent.auto_envvar_prefix is not None and \362 self.info_name is not None:363 auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,364 self.info_name.upper())365 else:366 auto_envvar_prefix = auto_envvar_prefix.upper()367 if auto_envvar_prefix is not None:368 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")369 self.auto_envvar_prefix = auto_envvar_prefix370371 if color is None and parent is not None:372 color = parent.color373374 #: Controls if styling output is wanted or not.375 self.color = color376377 self.show_default = show_default378379 self._close_callbacks = []380 self._depth = 0381 self._source_by_paramname = {}382 383 def __enter__(self):384 self._depth += 1385 push_context(self)386 return self387388 def __exit__(self, exc_type, exc_value, tb):389 self._depth -= 1390 if self._depth == 0:391 self.close()392 pop_context()393394 @contextmanager395 def scope(self, cleanup=True):396 """This helper method can be used with the context object to promote397 it to the current thread local (see :func:`get_current_context`).398 The default behavior of this is to invoke the cleanup functions which399 can be disabled by setting `cleanup` to `False`. The cleanup400 functions are typically used for things such as closing file handles.401402 If the cleanup is intended the context object can also be directly403 used as a context manager.404405 Example usage::406407 with ctx.scope():408 assert get_current_context() is ctx409410 This is equivalent::411412 with ctx:413 assert get_current_context() is ctx414415 .. versionadded:: 5.0416417 :param cleanup: controls if the cleanup functions should be run or418 not. The default is to run these functions. In419 some situations the context only wants to be420 temporarily pushed in which case this can be disabled.421 Nested pushes automatically defer the cleanup.422 """423 if not cleanup:424 self._depth += 1425 try:426 with self as rv:427 yield rv428 finally:429 if not cleanup:430 self._depth -= 1431432 @property433 def meta(self):434 """This is a dictionary which is shared with all the contexts435 that are nested. It exists so that click utilities can store some436 state here if they need to. It is however the responsibility of437 that code to manage this dictionary well.438439 The keys are supposed to be unique dotted strings. For instance440 module paths are a good choice for it. What is stored in there is441 irrelevant for the operation of click. However what is important is442 that code that places data here adheres to the general semantics of443 the system.444445 Example usage::446447 LANG_KEY = __name__ + '.lang'448449 def set_language(value):450 ctx = get_current_context()451 ctx.meta[LANG_KEY] = value452453 def get_language():454 return get_current_context().meta.get(LANG_KEY, 'en_US')455456 .. versionadded:: 5.0457 """458 return self._meta459460 def make_formatter(self):461 """Creates the formatter for the help and usage output."""462 return HelpFormatter(width=self.terminal_width,463 max_width=self.max_content_width)464465 def call_on_close(self, f):466 """This decorator remembers a function as callback that should be467 executed when the context tears down. This is most useful to bind468 resource handling to the script execution. For instance, file objects469 opened by the :class:`File` type will register their close callbacks470 here.471472 :param f: the function to execute on teardown.473 """474 self._close_callbacks.append(f)475 return f476477 def close(self):478 """Invokes all close callbacks."""479 for cb in self._close_callbacks:480 cb()481 self._close_callbacks = []482483 @property484 def command_path(self):485 """The computed command path. This is used for the ``usage``486 information on the help page. It's automatically created by487 combining the info names of the chain of contexts to the root.488 """489 rv = ''490 if self.info_name is not None:491 rv = self.info_name492 if self.parent is not None:493 rv = self.parent.command_path + ' ' + rv494 return rv.lstrip()495496 def find_root(self):497 """Finds the outermost context."""498 node = self499 while node.parent is not None:500 node = node.parent501 return node502503 def find_object(self, object_type):504 """Finds the closest object of a given type."""505 node = self506 while node is not None:507 if isinstance(node.obj, object_type):508 return node.obj509 node = node.parent510511 def ensure_object(self, object_type):512 """Like :meth:`find_object` but sets the innermost object to a513 new instance of `object_type` if it does not exist.514 """515 rv = self.find_object(object_type)516 if rv is None:517 self.obj = rv = object_type()518 return rv519520 def lookup_default(self, name):521 """Looks up the default for a parameter name. This by default522 looks into the :attr:`default_map` if available.523 """524 if self.default_map is not None:525 rv = self.default_map.get(name)526 if callable(rv):527 rv = rv()528 return rv529530 def fail(self, message):531 """Aborts the execution of the program with a specific error532 message.533534 :param message: the error message to fail with.535 """536 raise UsageError(message, self)537538 def abort(self):539 """Aborts the script."""540 raise Abort()541542 def exit(self, code=0):543 """Exits the application with a given exit code."""544 raise Exit(code)545546 def get_usage(self):547 """Helper method to get formatted usage string for the current548 context and command.549 """550 return self.command.get_usage(self)551552 def get_help(self):553 """Helper method to get formatted help page for the current554 context and command.555 """556 return self.command.get_help(self)557558 def invoke(*args, **kwargs):559 """Invokes a command callback in exactly the way it expects. There560 are two ways to invoke this method:561562 1. the first argument can be a callback and all other arguments and563 keyword arguments are forwarded directly to the function.564 2. the first argument is a click command object. In that case all565 arguments are forwarded as well but proper click parameters566 (options and click arguments) must be keyword arguments and Click567 will fill in defaults.568569 Note that before Click 3.2 keyword arguments were not properly filled570 in against the intention of this code and no context was created. For571 more information about this change and why it was done in a bugfix572 release see :ref:`upgrade-to-3.2`.573 """574 self, callback = args[:2]575 ctx = self576577 # It's also possible to invoke another command which might or578 # might not have a callback. In that case we also fill579 # in defaults and make a new context for this command.580 if isinstance(callback, Command):581 other_cmd = callback582 callback = other_cmd.callback583 ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)584 if callback is None:585 raise TypeError('The given command does not have a '586 'callback that can be invoked.')587588 for param in other_cmd.params:589 if param.name not in kwargs and param.expose_value:590 kwargs[param.name] = param.get_default(ctx)591592 args = args[2:]593 with augment_usage_errors(self):594 with ctx:595 return callback(*args, **kwargs)596597 def forward(*args, **kwargs):598 """Similar to :meth:`invoke` but fills in default keyword599 arguments from the current context if the other command expects600 it. This cannot invoke callbacks directly, only other commands.601 """602 self, cmd = args[:2]603604 # It's also possible to invoke another command which might or605 # might not have a callback.606 if not isinstance(cmd, Command):607 raise TypeError('Callback is not a command.')608609 for param in self.params:610 if param not in kwargs:611 kwargs[param] = self.params[param]612613 return self.invoke(cmd, **kwargs)614615 def set_parameter_source(self, name, source):616 """Set the source of a parameter.617618 This indicates the location from which the value of the619 parameter was obtained.620621 :param name: the name of the command line parameter622 :param source: the source of the command line parameter, which623 should be a valid ParameterSource value624 """625 ParameterSource.validate(source)626 self._source_by_paramname[name] = source627628 def get_parameter_source(self, name):629 """Get the source of a parameter.630631 This indicates the location from which the value of the632 parameter was obtained. This can be useful for determining633 when a user specified an option on the command line that is634 the same as the default. In that case, the source would be635 ParameterSource.COMMANDLINE, even though the value of the636 parameter was equivalent to the default.637638 :param name: the name of the command line parameter639 :returns: the source640 :rtype: ParameterSource641 """642 return self._source_by_paramname[name]643644645class BaseCommand(object):646 """The base command implements the minimal API contract of commands.647 Most code will never use this as it does not implement a lot of useful648 functionality but it can act as the direct subclass of alternative649 parsing methods that do not depend on the Click parser.650651 For instance, this can be used to bridge Click and other systems like652 argparse or docopt.653654 Because base commands do not implement a lot of the API that other655 parts of Click take for granted, they are not supported for all656 operations. For instance, they cannot be used with the decorators657 usually and they have no built-in callback system.658659 .. versionchanged:: 2.0660 Added the `context_settings` parameter.661662 :param name: the name of the command to use unless a group overrides it.663 :param context_settings: an optional dictionary with defaults that are664 passed to the context object.665 """666 #: the default for the :attr:`Context.allow_extra_args` flag.667 allow_extra_args = False668 #: the default for the :attr:`Context.allow_interspersed_args` flag.669 allow_interspersed_args = True670 #: the default for the :attr:`Context.ignore_unknown_options` flag.671 ignore_unknown_options = False672673 def __init__(self, name, context_settings=None):674 #: the name the command thinks it has. Upon registering a command675 #: on a :class:`Group` the group will default the command name676 #: with this information. You should instead use the677 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.678 self.name = name679 if context_settings is None:680 context_settings = {}681 #: an optional dictionary with defaults passed to the context.682 self.context_settings = context_settings683684 def __repr__(self):685 return "<%s %s>" % (self.__class__.__name__, self.name)686687 def get_usage(self, ctx):688 raise NotImplementedError('Base commands cannot get usage')689690 def get_help(self, ctx):691 raise NotImplementedError('Base commands cannot get help')692693 def make_context(self, info_name, args, parent=None, **extra):694 """This function when given an info name and arguments will kick695 off the parsing and create a new :class:`Context`. It does not696 invoke the actual command callback though.697698 :param info_name: the info name for this invokation. Generally this699 is the most descriptive name for the script or700 command. For the toplevel script it's usually701 the name of the script, for commands below it it's702 the name of the script.703 :param args: the arguments to parse as list of strings.704 :param parent: the parent context if available.705 :param extra: extra keyword arguments forwarded to the context706 constructor.707 """708 for key, value in iteritems(self.context_settings):709 if key not in extra:710 extra[key] = value711 ctx = Context(self, info_name=info_name, parent=parent, **extra)712 with ctx.scope(cleanup=False):713 self.parse_args(ctx, args)714 return ctx715716 def parse_args(self, ctx, args):717 """Given a context and a list of arguments this creates the parser718 and parses the arguments, then modifies the context as necessary.719 This is automatically invoked by :meth:`make_context`.720 """721 raise NotImplementedError('Base commands do not know how to parse '722 'arguments.')723724 def invoke(self, ctx):725 """Given a context, this invokes the command. The default726 implementation is raising a not implemented error.727 """728 raise NotImplementedError('Base commands are not invokable by default')729730 def main(self, args=None, prog_name=None, complete_var=None,731 standalone_mode=True, **extra):732 """This is the way to invoke a script with all the bells and733 whistles as a command line application. This will always terminate734 the application after a call. If this is not wanted, ``SystemExit``735 needs to be caught.736737 This method is also available by directly calling the instance of738 a :class:`Command`.739740 .. versionadded:: 3.0741 Added the `standalone_mode` flag to control the standalone mode.742743 :param args: the arguments that should be used for parsing. If not744 provided, ``sys.argv[1:]`` is used.745 :param prog_name: the program name that should be used. By default746 the program name is constructed by taking the file747 name from ``sys.argv[0]``.748 :param complete_var: the environment variable that controls the749 bash completion support. The default is750 ``"_<prog_name>_COMPLETE"`` with prog_name in751 uppercase.752 :param standalone_mode: the default behavior is to invoke the script753 in standalone mode. Click will then754 handle exceptions and convert them into755 error messages and the function will never756 return but shut down the interpreter. If757 this is set to `False` they will be758 propagated to the caller and the return759 value of this function is the return value760 of :meth:`invoke`.761 :param extra: extra keyword arguments are forwarded to the context762 constructor. See :class:`Context` for more information.763 """764 # If we are in Python 3, we will verify that the environment is765 # sane at this point or reject further execution to avoid a766 # broken script.767 if not PY2:768 _verify_python3_env()769 else:770 _check_for_unicode_literals()771772 if args is None:773 args = get_os_args()774 else:775 args = list(args)776777 if prog_name is None:778 prog_name = make_str(os.path.basename(779 sys.argv and sys.argv[0] or __file__))780781 # Hook for the Bash completion. This only activates if the Bash782 # completion is actually enabled, otherwise this is quite a fast783 # noop.784 _bashcomplete(self, prog_name, complete_var)785786 try:787 try:788 with self.make_context(prog_name, args, **extra) as ctx:789 rv = self.invoke(ctx)790 if not standalone_mode:791 return rv792 # it's not safe to `ctx.exit(rv)` here!793 # note that `rv` may actually contain data like "1" which794 # has obvious effects795 # more subtle case: `rv=[None, None]` can come out of796 # chained commands which all returned `None` -- so it's not797 # even always obvious that `rv` indicates success/failure798 # by its truthiness/falsiness799 ctx.exit()800 except (EOFError, KeyboardInterrupt):801 echo(file=sys.stderr)802 raise Abort()803 except ClickException as e:804 if not standalone_mode:805 raise806 e.show()807 sys.exit(e.exit_code)808 except IOError as e:809 if e.errno == errno.EPIPE:810 sys.stdout = PacifyFlushWrapper(sys.stdout)811 sys.stderr = PacifyFlushWrapper(sys.stderr)812 sys.exit(1)813 else:814 raise815 except Exit as e:816 if standalone_mode:817 sys.exit(e.exit_code)818 else:819 # in non-standalone mode, return the exit code820 # note that this is only reached if `self.invoke` above raises821 # an Exit explicitly -- thus bypassing the check there which822 # would return its result823 # the results of non-standalone execution may therefore be824 # somewhat ambiguous: if there are codepaths which lead to825 # `ctx.exit(1)` and to `return 1`, the caller won't be able to826 # tell the difference between the two827 return e.exit_code828 except Abort:829 if not standalone_mode:830 raise831 echo('Aborted!', file=sys.stderr)832 sys.exit(1)833834 def __call__(self, *args, **kwargs):835 """Alias for :meth:`main`."""836 return self.main(*args, **kwargs)837838839class Command(BaseCommand):840 """Commands are the basic building block of command line interfaces in841 Click. A basic command handles command line parsing and might dispatch842 more parsing to commands nested below it.843844 .. versionchanged:: 2.0845 Added the `context_settings` parameter.846 .. versionchanged:: 8.0847 Added repr showing the command name848 .. versionchanged:: 7.1849 Added the `no_args_is_help` parameter.850851 :param name: the name of the command to use unless a group overrides it.852 :param context_settings: an optional dictionary with defaults that are853 passed to the context object.854 :param callback: the callback to invoke. This is optional.855 :param params: the parameters to register with this command. This can856 be either :class:`Option` or :class:`Argument` objects.857 :param help: the help string to use for this command.858 :param epilog: like the help string but it's printed at the end of the859 help page after everything else.860 :param short_help: the short help to use for this command. This is861 shown on the command listing of the parent command.862 :param add_help_option: by default each command registers a ``--help``863 option. This can be disabled by this parameter.864 :param no_args_is_help: this controls what happens if no arguments are865 provided. This option is disabled by default.866 If enabled this will add ``--help`` as argument867 if no arguments are passed868 :param hidden: hide this command from help outputs.869870 :param deprecated: issues a message indicating that871 the command is deprecated.872 """873874 def __init__(self, name, context_settings=None, callback=None,875 params=None, help=None, epilog=None, short_help=None,876 options_metavar='[OPTIONS]', add_help_option=True,877 no_args_is_help=False, hidden=False, deprecated=False):878 BaseCommand.__init__(self, name, context_settings)879 #: the callback to execute when the command fires. This might be880 #: `None` in which case nothing happens.881 self.callback = callback882 #: the list of parameters for this command in the order they883 #: should show up in the help page and execute. Eager parameters884 #: will automatically be handled before non eager ones.885 self.params = params or []886 # if a form feed (page break) is found in the help text, truncate help887 # text to the content preceding the first form feed888 if help and '\f' in help:889 help = help.split('\f', 1)[0]890 self.help = help891 self.epilog = epilog892 self.options_metavar = options_metavar893 self.short_help = short_help894 self.add_help_option = add_help_option895 self.no_args_is_help = no_args_is_help896 self.hidden = hidden897 self.deprecated = deprecated898899 def __repr__(self):900 return '<%s %s>' % (self.__class__.__name__, self.name)901902 def get_usage(self, ctx):903 """Formats the usage line into a string and returns it.904905 Calls :meth:`format_usage` internally.906 """907 formatter = ctx.make_formatter()908 self.format_usage(ctx, formatter)909 return formatter.getvalue().rstrip('\n')910911 def get_params(self, ctx):912 rv = self.params913 help_option = self.get_help_option(ctx)914 if help_option is not None:915 rv = rv + [help_option]916 return rv917918 def format_usage(self, ctx, formatter):919 """Writes the usage line into the formatter.920921 This is a low-level method called by :meth:`get_usage`.922 """923 pieces = self.collect_usage_pieces(ctx)924 formatter.write_usage(ctx.command_path, ' '.join(pieces))925926 def collect_usage_pieces(self, ctx):927 """Returns all the pieces that go into the usage line and returns928 it as a list of strings.929 """930 rv = [self.options_metavar]931 for param in self.get_params(ctx):932 rv.extend(param.get_usage_pieces(ctx))933 return rv934935 def get_help_option_names(self, ctx):936 """Returns the names for the help option."""937 all_names = set(ctx.help_option_names)938 for param in self.params:939 all_names.difference_update(param.opts)940 all_names.difference_update(param.secondary_opts)941 return all_names942943 def get_help_option(self, ctx):944 """Returns the help option object."""945 help_options = self.get_help_option_names(ctx)946 if not help_options or not self.add_help_option:947 return948949 def show_help(ctx, param, value):950 if value and not ctx.resilient_parsing:951 echo(ctx.get_help(), color=ctx.color)952 ctx.exit()953 return Option(help_options, is_flag=True,954 is_eager=True, expose_value=False,955 callback=show_help,956 help='Show this message and exit.')957958 def make_parser(self, ctx):959 """Creates the underlying option parser for this command."""960 parser = OptionParser(ctx)961 for param in self.get_params(ctx):962 param.add_to_parser(parser, ctx)963 return parser964965 def get_help(self, ctx):966 """Formats the help into a string and returns it.967968 Calls :meth:`format_help` internally.969 """970 formatter = ctx.make_formatter()971 self.format_help(ctx, formatter)972 return formatter.getvalue().rstrip('\n')973974 def get_short_help_str(self, limit=45):975 """Gets short help for the command or makes it by shortening the long help string."""976 return self.short_help or self.help and make_default_short_help(self.help, limit) or ''977978 def format_help(self, ctx, formatter):979 """Writes the help into the formatter if it exists.980981 This is a low-level method called by :meth:`get_help`.982983 This calls the following methods:984985 - :meth:`format_usage`986 - :meth:`format_help_text`987 - :meth:`format_options`988 - :meth:`format_epilog`989 """990 self.format_usage(ctx, formatter)991 self.format_help_text(ctx, formatter)992 self.format_options(ctx, formatter)993 self.format_epilog(ctx, formatter)994995 def format_help_text(self, ctx, formatter):996 """Writes the help text to the formatter if it exists."""997 if self.help:998 formatter.write_paragraph()999 with formatter.indentation():1000 help_text = self.help1001 if self.deprecated:1002 help_text += DEPRECATED_HELP_NOTICE1003 formatter.write_text(help_text)1004 elif self.deprecated:1005 formatter.write_paragraph()1006 with formatter.indentation():1007 formatter.write_text(DEPRECATED_HELP_NOTICE)10081009 def format_options(self, ctx, formatter):1010 """Writes all the options into the formatter if they exist."""1011 opts = []1012 for param in self.get_params(ctx):1013 rv = param.get_help_record(ctx)1014 if rv is not None:1015 opts.append(rv)10161017 if opts:1018 with formatter.section('Options'):1019 formatter.write_dl(opts)10201021 def format_epilog(self, ctx, formatter):1022 """Writes the epilog into the formatter if it exists."""1023 if self.epilog:1024 formatter.write_paragraph()1025 with formatter.indentation():1026 formatter.write_text(self.epilog)10271028 def parse_args(self, ctx, args):1029 if not args and self.no_args_is_help and not ctx.resilient_parsing:1030 echo(ctx.get_help(), color=ctx.color)1031 ctx.exit()10321033 parser = self.make_parser(ctx)1034 opts, args, param_order = parser.parse_args(args=args)10351036 for param in iter_params_for_processing(1037 param_order, self.get_params(ctx)):1038 value, args = param.handle_parse_result(ctx, opts, args)10391040 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1041 ctx.fail('Got unexpected extra argument%s (%s)'1042 % (len(args) != 1 and 's' or '',1043 ' '.join(map(make_str, args))))10441045 ctx.args = args1046 return args10471048 def invoke(self, ctx):1049 """Given a context, this invokes the attached callback (if it exists)1050 in the right way.1051 """1052 _maybe_show_deprecated_notice(self)1053 if self.callback is not None:1054 return ctx.invoke(self.callback, **ctx.params)105510561057class MultiCommand(Command):1058 """A multi command is the basic implementation of a command that1059 dispatches to subcommands. The most common version is the1060 :class:`Group`.10611062 :param invoke_without_command: this controls how the multi command itself1063 is invoked. By default it's only invoked1064 if a subcommand is provided.1065 :param no_args_is_help: this controls what happens if no arguments are1066 provided. This option is enabled by default if1067 `invoke_without_command` is disabled or disabled1068 if it's enabled. If enabled this will add1069 ``--help`` as argument if no arguments are1070 passed.1071 :param subcommand_metavar: the string that is used in the documentation1072 to indicate the subcommand place.1073 :param chain: if this is set to `True` chaining of multiple subcommands1074 is enabled. This restricts the form of commands in that1075 they cannot have optional arguments but it allows1076 multiple commands to be chained together.1077 :param result_callback: the result callback to attach to this multi1078 command.1079 """1080 allow_extra_args = True1081 allow_interspersed_args = False10821083 def __init__(self, name=None, invoke_without_command=False,1084 no_args_is_help=None, subcommand_metavar=None,1085 chain=False, result_callback=None, **attrs):1086 Command.__init__(self, name, **attrs)1087 if no_args_is_help is None:1088 no_args_is_help = not invoke_without_command1089 self.no_args_is_help = no_args_is_help1090 self.invoke_without_command = invoke_without_command1091 if subcommand_metavar is None:1092 if chain:1093 subcommand_metavar = SUBCOMMANDS_METAVAR1094 else:1095 subcommand_metavar = SUBCOMMAND_METAVAR1096 self.subcommand_metavar = subcommand_metavar1097 self.chain = chain1098 #: The result callback that is stored. This can be set or1099 #: overridden with the :func:`resultcallback` decorator.1100 self.result_callback = result_callback11011102 if self.chain:1103 for param in self.params:1104 if isinstance(param, Argument) and not param.required:1105 raise RuntimeError('Multi commands in chain mode cannot '1106 'have optional arguments.')11071108 def collect_usage_pieces(self, ctx):1109 rv = Command.collect_usage_pieces(self, ctx)1110 rv.append(self.subcommand_metavar)1111 return rv11121113 def format_options(self, ctx, formatter):1114 Command.format_options(self, ctx, formatter)1115 self.format_commands(ctx, formatter)11161117 def resultcallback(self, replace=False):1118 """Adds a result callback to the chain command. By default if a1119 result callback is already registered this will chain them but1120 this can be disabled with the `replace` parameter. The result1121 callback is invoked with the return value of the subcommand1122 (or the list of return values from all subcommands if chaining1123 is enabled) as well as the parameters as they would be passed1124 to the main callback.11251126 Example::11271128 @click.group()1129 @click.option('-i', '--input', default=23)1130 def cli(input):1131 return 4211321133 @cli.resultcallback()1134 def process_result(result, input):1135 return result + input11361137 .. versionadded:: 3.011381139 :param replace: if set to `True` an already existing result1140 callback will be removed.1141 """1142 def decorator(f):1143 old_callback = self.result_callback1144 if old_callback is None or replace:1145 self.result_callback = f1146 return f1147 def function(__value, *args, **kwargs):1148 return f(old_callback(__value, *args, **kwargs),1149 *args, **kwargs)1150 self.result_callback = rv = update_wrapper(function, f)1151 return rv1152 return decorator11531154 def format_commands(self, ctx, formatter):1155 """Extra format methods for multi methods that adds all the commands1156 after the options.1157 """1158 commands = []1159 for subcommand in self.list_commands(ctx):1160 cmd = self.get_command(ctx, subcommand)1161 # What is this, the tool lied about a command. Ignore it1162 if cmd is None:1163 continue1164 if cmd.hidden:1165 continue11661167 commands.append((subcommand, cmd))11681169 # allow for 3 times the default spacing1170 if len(commands):1171 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)11721173 rows = []1174 for subcommand, cmd in commands:1175 help = cmd.get_short_help_str(limit)1176 rows.append((subcommand, help))11771178 if rows:1179 with formatter.section('Commands'):1180 formatter.write_dl(rows)11811182 def parse_args(self, ctx, args):1183 if not args and self.no_args_is_help and not ctx.resilient_parsing:1184 echo(ctx.get_help(), color=ctx.color)1185 ctx.exit()11861187 rest = Command.parse_args(self, ctx, args)1188 if self.chain:1189 ctx.protected_args = rest1190 ctx.args = []1191 elif rest:1192 ctx.protected_args, ctx.args = rest[:1], rest[1:]11931194 return ctx.args11951196 def invoke(self, ctx):1197 def _process_result(value):1198 if self.result_callback is not None:1199 value = ctx.invoke(self.result_callback, value,1200 **ctx.params)1201 return value12021203 if not ctx.protected_args:1204 # If we are invoked without command the chain flag controls1205 # how this happens. If we are not in chain mode, the return1206 # value here is the return value of the command.1207 # If however we are in chain mode, the return value is the1208 # return value of the result processor invoked with an empty1209 # list (which means that no subcommand actually was executed).1210 if self.invoke_without_command:1211 if not self.chain:1212 return Command.invoke(self, ctx)1213 with ctx:1214 Command.invoke(self, ctx)1215 return _process_result([])1216 ctx.fail('Missing command.')12171218 # Fetch args back out1219 args = ctx.protected_args + ctx.args1220 ctx.args = []1221 ctx.protected_args = []12221223 # If we're not in chain mode, we only allow the invocation of a1224 # single command but we also inform the current context about the1225 # name of the command to invoke.1226 if not self.chain:1227 # Make sure the context is entered so we do not clean up1228 # resources until the result processor has worked.1229 with ctx:1230 cmd_name, cmd, args = self.resolve_command(ctx, args)1231 ctx.invoked_subcommand = cmd_name1232 Command.invoke(self, ctx)1233 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1234 with sub_ctx:1235 return _process_result(sub_ctx.command.invoke(sub_ctx))12361237 # In chain mode we create the contexts step by step, but after the1238 # base command has been invoked. Because at that point we do not1239 # know the subcommands yet, the invoked subcommand attribute is1240 # set to ``*`` to inform the command that subcommands are executed1241 # but nothing else.1242 with ctx:1243 ctx.invoked_subcommand = args and '*' or None1244 Command.invoke(self, ctx)12451246 # Otherwise we make every single context and invoke them in a1247 # chain. In that case the return value to the result processor1248 # is the list of all invoked subcommand's results.1249 contexts = []1250 while args:1251 cmd_name, cmd, args = self.resolve_command(ctx, args)1252 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,1253 allow_extra_args=True,1254 allow_interspersed_args=False)1255 contexts.append(sub_ctx)1256 args, sub_ctx.args = sub_ctx.args, []12571258 rv = []1259 for sub_ctx in contexts:1260 with sub_ctx:1261 rv.append(sub_ctx.command.invoke(sub_ctx))1262 return _process_result(rv)12631264 def resolve_command(self, ctx, args):1265 cmd_name = make_str(args[0])1266 original_cmd_name = cmd_name12671268 # Get the command1269 cmd = self.get_command(ctx, cmd_name)12701271 # If we can't find the command but there is a normalization1272 # function available, we try with that one.1273 if cmd is None and ctx.token_normalize_func is not None:1274 cmd_name = ctx.token_normalize_func(cmd_name)1275 cmd = self.get_command(ctx, cmd_name)12761277 # If we don't find the command we want to show an error message1278 # to the user that it was not provided. However, there is1279 # something else we should do: if the first argument looks like1280 # an option we want to kick off parsing again for arguments to1281 # resolve things like --help which now should go to the main1282 # place.1283 if cmd is None and not ctx.resilient_parsing:1284 if split_opt(cmd_name)[0]:1285 self.parse_args(ctx, ctx.args)1286 ctx.fail('No such command "%s".' % original_cmd_name)12871288 return cmd_name, cmd, args[1:]12891290 def get_command(self, ctx, cmd_name):1291 """Given a context and a command name, this returns a1292 :class:`Command` object if it exists or returns `None`.1293 """1294 raise NotImplementedError()12951296 def list_commands(self, ctx):1297 """Returns a list of subcommand names in the order they should1298 appear.1299 """1300 return []130113021303class Group(MultiCommand):1304 """A group allows a command to have subcommands attached. This is the1305 most common way to implement nesting in Click.13061307 :param commands: a dictionary of commands.1308 """13091310 def __init__(self, name=None, commands=None, **attrs):1311 MultiCommand.__init__(self, name, **attrs)1312 #: the registered subcommands by their exported names.1313 self.commands = commands or {}13141315 def add_command(self, cmd, name=None):1316 """Registers another :class:`Command` with this group. If the name1317 is not provided, the name of the command is used.1318 """1319 name = name or cmd.name1320 if name is None:1321 raise TypeError('Command has no name.')1322 _check_multicommand(self, name, cmd, register=True)1323 self.commands[name] = cmd13241325 def command(self, *args, **kwargs):1326 """A shortcut decorator for declaring and attaching a command to1327 the group. This takes the same arguments as :func:`command` but1328 immediately registers the created command with this instance by1329 calling into :meth:`add_command`.1330 """1331 def decorator(f):1332 cmd = command(*args, **kwargs)(f)1333 self.add_command(cmd)1334 return cmd1335 return decorator13361337 def group(self, *args, **kwargs):1338 """A shortcut decorator for declaring and attaching a group to1339 the group. This takes the same arguments as :func:`group` but1340 immediately registers the created command with this instance by1341 calling into :meth:`add_command`.1342 """1343 def decorator(f):1344 cmd = group(*args, **kwargs)(f)1345 self.add_command(cmd)1346 return cmd1347 return decorator13481349 def get_command(self, ctx, cmd_name):1350 return self.commands.get(cmd_name)13511352 def list_commands(self, ctx):1353 return sorted(self.commands)135413551356class CommandCollection(MultiCommand):1357 """A command collection is a multi command that merges multiple multi1358 commands together into one. This is a straightforward implementation1359 that accepts a list of different multi commands as sources and1360 provides all the commands for each of them.1361 """13621363 def __init__(self, name=None, sources=None, **attrs):1364 MultiCommand.__init__(self, name, **attrs)1365 #: The list of registered multi commands.1366 self.sources = sources or []13671368 def add_source(self, multi_cmd):1369 """Adds a new multi command to the chain dispatcher."""1370 self.sources.append(multi_cmd)13711372 def get_command(self, ctx, cmd_name):1373 for source in self.sources:1374 rv = source.get_command(ctx, cmd_name)1375 if rv is not None:1376 if self.chain:1377 _check_multicommand(self, cmd_name, rv)1378 return rv13791380 def list_commands(self, ctx):1381 rv = set()1382 for source in self.sources:1383 rv.update(source.list_commands(ctx))1384 return sorted(rv)138513861387class Parameter(object):1388 r"""A parameter to a command comes in two versions: they are either1389 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1390 not supported by design as some of the internals for parsing are1391 intentionally not finalized.13921393 Some settings are supported by both options and arguments.13941395 :param param_decls: the parameter declarations for this option or1396 argument. This is a list of flags or argument1397 names.1398 :param type: the type that should be used. Either a :class:`ParamType`1399 or a Python type. The later is converted into the former1400 automatically if supported.1401 :param required: controls if this is optional or not.1402 :param default: the default value if omitted. This can also be a callable,1403 in which case it's invoked when the default is needed1404 without any arguments.1405 :param callback: a callback that should be executed after the parameter1406 was matched. This is called as ``fn(ctx, param,1407 value)`` and needs to return the value. Before Click1408 2.0, the signature was ``(ctx, value)``.1409 :param nargs: the number of arguments to match. If not ``1`` the return1410 value is a tuple instead of single value. The default for1411 nargs is ``1`` (except if the type is a tuple, then it's1412 the arity of the tuple). If ``nargs=-1``, all remaining1413 parameters are collected.1414 :param metavar: how the value is represented in the help page.1415 :param expose_value: if this is `True` then the value is passed onwards1416 to the command callback and stored on the context,1417 otherwise it's skipped.1418 :param is_eager: eager values are processed before non eager ones. This1419 should not be set for arguments or it will inverse the1420 order of processing.1421 :param envvar: a string or list of strings that are environment variables1422 that should be checked.14231424 .. versionchanged:: 7.11425 Empty environment variables are ignored rather than taking the1426 empty string value. This makes it possible for scripts to clear1427 variables if they can't unset them.14281429 .. versionchanged:: 2.01430 Changed signature for parameter callback to also be passed the1431 parameter. The old callback format will still work, but it will1432 raise a warning to give you a chance to migrate the code easier.1433 """1434 param_type_name = 'parameter'14351436 def __init__(self, param_decls=None, type=None, required=False,1437 default=None, callback=None, nargs=None, metavar=None,1438 expose_value=True, is_eager=False, envvar=None,1439 autocompletion=None):1440 self.name, self.opts, self.secondary_opts = \1441 self._parse_decls(param_decls or (), expose_value)14421443 self.type = convert_type(type, default)14441445 # Default nargs to what the type tells us if we have that1446 # information available.1447 if nargs is None:1448 if self.type.is_composite:1449 nargs = self.type.arity1450 else:1451 nargs = 114521453 self.required = required1454 self.callback = callback1455 self.nargs = nargs1456 self.multiple = False1457 self.expose_value = expose_value1458 self.default = default1459 self.is_eager = is_eager1460 self.metavar = metavar1461 self.envvar = envvar1462 self.autocompletion = autocompletion14631464 def __repr__(self):1465 return "<%s %s>" % (self.__class__.__name__, self.name)14661467 @property1468 def human_readable_name(self):1469 """Returns the human readable name of this parameter. This is the1470 same as the name for options, but the metavar for arguments.1471 """1472 return self.name14731474 def make_metavar(self):1475 if self.metavar is not None:1476 return self.metavar1477 metavar = self.type.get_metavar(self)1478 if metavar is None:1479 metavar = self.type.name.upper()1480 if self.nargs != 1:1481 metavar += '...'1482 return metavar14831484 def get_default(self, ctx):1485 """Given a context variable this calculates the default value."""1486 # Otherwise go with the regular default.1487 if callable(self.default):1488 rv = self.default()1489 else:1490 rv = self.default1491 return self.type_cast_value(ctx, rv)14921493 def add_to_parser(self, parser, ctx):1494 pass14951496 def consume_value(self, ctx, opts):1497 value = opts.get(self.name)1498 source = ParameterSource.COMMANDLINE1499 if value is None:1500 value = self.value_from_envvar(ctx)1501 source = ParameterSource.ENVIRONMENT1502 if value is None:1503 value = ctx.lookup_default(self.name)1504 source = ParameterSource.DEFAULT_MAP1505 if value is not None:1506 ctx.set_parameter_source(self.name, source)1507 return value15081509 def type_cast_value(self, ctx, value):1510 """Given a value this runs it properly through the type system.1511 This automatically handles things like `nargs` and `multiple` as1512 well as composite types.1513 """1514 if self.type.is_composite:1515 if self.nargs <= 1:1516 raise TypeError('Attempted to invoke composite type '1517 'but nargs has been set to %s. This is '1518 'not supported; nargs needs to be set to '1519 'a fixed value > 1.' % self.nargs)1520 if self.multiple:1521 return tuple(self.type(x or (), self, ctx) for x in value or ())1522 return self.type(value or (), self, ctx)15231524 def _convert(value, level):1525 if level == 0:1526 return self.type(value, self, ctx)1527 return tuple(_convert(x, level - 1) for x in value or ())1528 return _convert(value, (self.nargs != 1) + bool(self.multiple))15291530 def process_value(self, ctx, value):1531 """Given a value and context this runs the logic to convert the1532 value as necessary.1533 """1534 # If the value we were given is None we do nothing. This way1535 # code that calls this can easily figure out if something was1536 # not provided. Otherwise it would be converted into an empty1537 # tuple for multiple invocations which is inconvenient.1538 if value is not None:1539 return self.type_cast_value(ctx, value)15401541 def value_is_missing(self, value):1542 if value is None:1543 return True1544 if (self.nargs != 1 or self.multiple) and value == ():1545 return True1546 return False15471548 def full_process_value(self, ctx, value):1549 value = self.process_value(ctx, value)15501551 if value is None and not ctx.resilient_parsing:1552 value = self.get_default(ctx)1553 if value is not None:1554 ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)15551556 if self.required and self.value_is_missing(value):1557 raise MissingParameter(ctx=ctx, param=self)15581559 return value15601561 def resolve_envvar_value(self, ctx):1562 if self.envvar is None:1563 return1564 if isinstance(self.envvar, (tuple, list)):1565 for envvar in self.envvar:1566 rv = os.environ.get(envvar)1567 if rv is not None:1568 return rv1569 else:1570 rv = os.environ.get(self.envvar)15711572 if rv != "":1573 return rv15741575 def value_from_envvar(self, ctx):1576 rv = self.resolve_envvar_value(ctx)1577 if rv is not None and self.nargs != 1:1578 rv = self.type.split_envvar_value(rv)1579 return rv15801581 def handle_parse_result(self, ctx, opts, args):1582 with augment_usage_errors(ctx, param=self):1583 value = self.consume_value(ctx, opts)1584 try:1585 value = self.full_process_value(ctx, value)1586 except Exception:1587 if not ctx.resilient_parsing:1588 raise1589 value = None1590 if self.callback is not None:1591 try:1592 value = invoke_param_callback(1593 self.callback, ctx, self, value)1594 except Exception:1595 if not ctx.resilient_parsing:1596 raise15971598 if self.expose_value:1599 ctx.params[self.name] = value1600 return value, args16011602 def get_help_record(self, ctx):1603 pass16041605 def get_usage_pieces(self, ctx):1606 return []16071608 def get_error_hint(self, ctx):1609 """Get a stringified version of the param for use in error messages to1610 indicate which param caused the error.1611 """1612 hint_list = self.opts or [self.human_readable_name]1613 return ' / '.join('"%s"' % x for x in hint_list)161416151616class Option(Parameter):1617 """Options are usually optional values on the command line and1618 have some extra features that arguments don't have.16191620 All other parameters are passed onwards to the parameter constructor.16211622 :param show_default: controls if the default value should be shown on the1623 help page. Normally, defaults are not shown. If this1624 value is a string, it shows the string instead of the1625 value. This is particularly useful for dynamic options.1626 :param show_envvar: controls if an environment variable should be shown on1627 the help page. Normally, environment variables1628 are not shown.1629 :param prompt: if set to `True` or a non empty string then the user will be1630 prompted for input. If set to `True` the prompt will be the1631 option name capitalized.1632 :param confirmation_prompt: if set then the value will need to be confirmed1633 if it was prompted for.1634 :param hide_input: if this is `True` then the input on the prompt will be1635 hidden from the user. This is useful for password1636 input.1637 :param is_flag: forces this option to act as a flag. The default is1638 auto detection.1639 :param flag_value: which value should be used for this flag if it's1640 enabled. This is set to a boolean automatically if1641 the option string contains a slash to mark two options.1642 :param multiple: if this is set to `True` then the argument is accepted1643 multiple times and recorded. This is similar to ``nargs``1644 in how it works but supports arbitrary number of1645 arguments.1646 :param count: this flag makes an option increment an integer.1647 :param allow_from_autoenv: if this is enabled then the value of this1648 parameter will be pulled from an environment1649 variable in case a prefix is defined on the1650 context.1651 :param help: the help string.1652 :param hidden: hide this option from help outputs.1653 """1654 param_type_name = 'option'16551656 def __init__(self, param_decls=None, show_default=False,1657 prompt=False, confirmation_prompt=False,1658 hide_input=False, is_flag=None, flag_value=None,1659 multiple=False, count=False, allow_from_autoenv=True,1660 type=None, help=None, hidden=False, show_choices=True,1661 show_envvar=False, **attrs):1662 default_is_missing = attrs.get('default', _missing) is _missing1663 Parameter.__init__(self, param_decls, type=type, **attrs)16641665 if prompt is True:1666 prompt_text = self.name.replace('_', ' ').capitalize()1667 elif prompt is False:1668 prompt_text = None1669 else:1670 prompt_text = prompt1671 self.prompt = prompt_text1672 self.confirmation_prompt = confirmation_prompt1673 self.hide_input = hide_input1674 self.hidden = hidden16751676 # Flags1677 if is_flag is None:1678 if flag_value is not None:1679 is_flag = True1680 else:1681 is_flag = bool(self.secondary_opts)1682 if is_flag and default_is_missing:1683 self.default = False1684 if flag_value is None:1685 flag_value = not self.default1686 self.is_flag = is_flag1687 self.flag_value = flag_value1688 if self.is_flag and isinstance(self.flag_value, bool) \1689 and type in [None, bool]:1690 self.type = BOOL1691 self.is_bool_flag = True1692 else:1693 self.is_bool_flag = False16941695 # Counting1696 self.count = count1697 if count:1698 if type is None:1699 self.type = IntRange(min=0)1700 if default_is_missing:1701 self.default = 017021703 self.multiple = multiple1704 self.allow_from_autoenv = allow_from_autoenv1705 self.help = help1706 self.show_default = show_default1707 self.show_choices = show_choices1708 self.show_envvar = show_envvar17091710 # Sanity check for stuff we don't support1711 if __debug__:1712 if self.nargs < 0:1713 raise TypeError('Options cannot have nargs < 0')1714 if self.prompt and self.is_flag and not self.is_bool_flag:1715 raise TypeError('Cannot prompt for flags that are not bools.')1716 if not self.is_bool_flag and self.secondary_opts:1717 raise TypeError('Got secondary option for non boolean flag.')1718 if self.is_bool_flag and self.hide_input \1719 and self.prompt is not None:1720 raise TypeError('Hidden input does not work with boolean '1721 'flag prompts.')1722 if self.count:1723 if self.multiple:1724 raise TypeError('Options cannot be multiple and count '1725 'at the same time.')1726 elif self.is_flag:1727 raise TypeError('Options cannot be count and flags at '1728 'the same time.')17291730 def _parse_decls(self, decls, expose_value):1731 opts = []1732 secondary_opts = []1733 name = None1734 possible_names = []17351736 for decl in decls:1737 if isidentifier(decl):1738 if name is not None:1739 raise TypeError('Name defined twice')1740 name = decl1741 else:1742 split_char = decl[:1] == '/' and ';' or '/'1743 if split_char in decl:1744 first, second = decl.split(split_char, 1)1745 first = first.rstrip()1746 if first:1747 possible_names.append(split_opt(first))1748 opts.append(first)1749 second = second.lstrip()1750 if second:1751 secondary_opts.append(second.lstrip())1752 else:1753 possible_names.append(split_opt(decl))1754 opts.append(decl)17551756 if name is None and possible_names:1757 possible_names.sort(key=lambda x: -len(x[0])) # group long options first1758 name = possible_names[0][1].replace('-', '_').lower()1759 if not isidentifier(name):1760 name = None17611762 if name is None:1763 if not expose_value:1764 return None, opts, secondary_opts1765 raise TypeError('Could not determine name for option')17661767 if not opts and not secondary_opts:1768 raise TypeError('No options defined but a name was passed (%s). '1769 'Did you mean to declare an argument instead '1770 'of an option?' % name)17711772 return name, opts, secondary_opts17731774 def add_to_parser(self, parser, ctx):1775 kwargs = {1776 'dest': self.name,1777 'nargs': self.nargs,1778 'obj': self,1779 }17801781 if self.multiple:1782 action = 'append'1783 elif self.count:1784 action = 'count'1785 else:1786 action = 'store'17871788 if self.is_flag:1789 kwargs.pop('nargs', None)1790 if self.is_bool_flag and self.secondary_opts:1791 parser.add_option(self.opts, action=action + '_const',1792 const=True, **kwargs)1793 parser.add_option(self.secondary_opts, action=action +1794 '_const', const=False, **kwargs)1795 else:1796 parser.add_option(self.opts, action=action + '_const',1797 const=self.flag_value,1798 **kwargs)1799 else:1800 kwargs['action'] = action1801 parser.add_option(self.opts, **kwargs)18021803 def get_help_record(self, ctx):1804 if self.hidden:1805 return1806 any_prefix_is_slash = []18071808 def _write_opts(opts):1809 rv, any_slashes = join_options(opts)1810 if any_slashes:1811 any_prefix_is_slash[:] = [True]1812 if not self.is_flag and not self.count:1813 rv += ' ' + self.make_metavar()1814 return rv18151816 rv = [_write_opts(self.opts)]1817 if self.secondary_opts:1818 rv.append(_write_opts(self.secondary_opts))18191820 help = self.help or ''1821 extra = []1822 if self.show_envvar:1823 envvar = self.envvar1824 if envvar is None:1825 if self.allow_from_autoenv and \1826 ctx.auto_envvar_prefix is not None:1827 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1828 if envvar is not None:1829 extra.append('env var: %s' % (1830 ', '.join('%s' % d for d in envvar)1831 if isinstance(envvar, (list, tuple))1832 else envvar, ))1833 if self.default is not None and \1834 (self.show_default or ctx.show_default):1835 if isinstance(self.show_default, string_types):1836 default_string = '({})'.format(self.show_default)1837 elif isinstance(self.default, (list, tuple)):1838 default_string = ', '.join('%s' % d for d in self.default)1839 elif inspect.isfunction(self.default):1840 default_string = "(dynamic)"1841 else:1842 default_string = self.default1843 extra.append('default: {}'.format(default_string))18441845 if self.required:1846 extra.append('required')1847 if extra:1848 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))18491850 return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)18511852 def get_default(self, ctx):1853 # If we're a non boolean flag our default is more complex because1854 # we need to look at all flags in the same group to figure out1855 # if we're the the default one in which case we return the flag1856 # value as default.1857 if self.is_flag and not self.is_bool_flag:1858 for param in ctx.command.params:1859 if param.name == self.name and param.default:1860 return param.flag_value1861 return None1862 return Parameter.get_default(self, ctx)18631864 def prompt_for_value(self, ctx):1865 """This is an alternative flow that can be activated in the full1866 value processing if a value does not exist. It will prompt the1867 user until a valid value exists and then returns the processed1868 value as result.1869 """1870 # Calculate the default before prompting anything to be stable.1871 default = self.get_default(ctx)18721873 # If this is a prompt for a flag we need to handle this1874 # differently.1875 if self.is_bool_flag:1876 return confirm(self.prompt, default)18771878 return prompt(self.prompt, default=default, type=self.type,1879 hide_input=self.hide_input, show_choices=self.show_choices,1880 confirmation_prompt=self.confirmation_prompt,1881 value_proc=lambda x: self.process_value(ctx, x))18821883 def resolve_envvar_value(self, ctx):1884 rv = Parameter.resolve_envvar_value(self, ctx)1885 if rv is not None:1886 return rv1887 if self.allow_from_autoenv and \1888 ctx.auto_envvar_prefix is not None:1889 envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1890 return os.environ.get(envvar)18911892 def value_from_envvar(self, ctx):1893 rv = self.resolve_envvar_value(ctx)1894 if rv is None:1895 return None1896 value_depth = (self.nargs != 1) + bool(self.multiple)1897 if value_depth > 0 and rv is not None:1898 rv = self.type.split_envvar_value(rv)1899 if self.multiple and self.nargs != 1:1900 rv = batch(rv, self.nargs)1901 return rv19021903 def full_process_value(self, ctx, value):1904 if value is None and self.prompt is not None \1905 and not ctx.resilient_parsing:1906 return self.prompt_for_value(ctx)1907 return Parameter.full_process_value(self, ctx, value)190819091910class Argument(Parameter):1911 """Arguments are positional parameters to a command. They generally1912 provide fewer features than options but can have infinite ``nargs``1913 and are required by default.19141915 All parameters are passed onwards to the parameter constructor.1916 """1917 param_type_name = 'argument'19181919 def __init__(self, param_decls, required=None, **attrs):1920 if required is None:1921 if attrs.get('default') is not None:1922 required = False1923 else:1924 required = attrs.get('nargs', 1) > 01925 Parameter.__init__(self, param_decls, required=required, **attrs)1926 if self.default is not None and self.nargs < 0:1927 raise TypeError('nargs=-1 in combination with a default value '1928 'is not supported.')19291930 @property1931 def human_readable_name(self):1932 if self.metavar is not None:1933 return self.metavar1934 return self.name.upper()19351936 def make_metavar(self):1937 if self.metavar is not None:1938 return self.metavar1939 var = self.type.get_metavar(self)1940 if not var:1941 var = self.name.upper()1942 if not self.required:1943 var = '[%s]' % var1944 if self.nargs != 1:1945 var += '...'1946 return var19471948 def _parse_decls(self, decls, expose_value):1949 if not decls:1950 if not expose_value:1951 return None, [], []1952 raise TypeError('Could not determine name for argument')1953 if len(decls) == 1:1954 name = arg = decls[0]1955 name = name.replace('-', '_').lower()1956 else:1957 raise TypeError('Arguments take exactly one '1958 'parameter declaration, got %d' % len(decls))1959 return name, [arg], []19601961 def get_usage_pieces(self, ctx):1962 return [self.make_metavar()]19631964 def get_error_hint(self, ctx):1965 return '"%s"' % self.make_metavar()19661967 def add_to_parser(self, parser, ctx):1968 parser.add_argument(dest=self.name, nargs=self.nargs,1969 obj=self)197019711972# Circular dependency between decorators and core1973from .decorators import command, group
deleted:click/decorators.py-311 removed
1import sys2import inspect34from functools import update_wrapper56from ._compat import iteritems7from ._unicodefun import _check_for_unicode_literals8from .utils import echo9from .globals import get_current_context101112def 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)192021def 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)293031def 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`.3637 This generates a decorator that works roughly like this::3839 from functools import update_wrapper4041 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 decorator4849 :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 decorator676869def _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)909192def 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.9697 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.100101 All keyword arguments are forwarded to the underlying command class.102103 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`.106107 :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 decorator119120121def 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)128129130def _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)137138139def 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.145146 :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 decorator154155156def 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.162163 :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()169170 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 decorator176177178def confirmation_option(*param_decls, **attrs):179 """Shortcut for confirmation prompts that can be ignored by passing180 ``--yes`` as parameter.181182 This is equivalent to decorating a function with :func:`option` with183 the following parameters::184185 def callback(ctx, param, value):186 if not value:187 ctx.abort()188189 @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 decorator206207208def password_option(*param_decls, **attrs):209 """Shortcut for password prompts.210211 This is equivalent to decorating a function with :func:`option` with212 the following parameters::213214 @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 decorator226227228def 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.232233 :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 = ''245246 def decorator(f):247 prog_name = attrs.pop('prog_name', None)248 message = attrs.pop('message', '%(prog)s, version %(version)s')249250 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()276277 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 decorator284285286def 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.290291 Like :func:`version_option`, this is implemented as eager option that292 prints in the callback and exits.293294 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 decorator308309310# Circular dependencies between core and decorators311from .core import Command, Group, Argument, Option
deleted:click/exceptions.py-248 removed
1from ._compat import PY2, filename_to_ui, get_text_stderr2from .utils import echo345def _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_hint91011class ClickException(Exception):12 """An exception that Click can handle and show to the user."""1314 #: The exit code for this exception15 exit_code = 11617 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 = message2425 def format_message(self):26 return self.message2728 def __str__(self):29 return self.message3031 if PY2:32 __unicode__ = __str__3334 def __str__(self):35 return self.message.encode('utf-8')3637 def show(self, file=None):38 if file is None:39 file = get_text_stderr()40 echo('Error: %s' % self.format_message(), file=file)414243class UsageError(ClickException):44 """An internal exception that signals a usage error. This typically45 aborts any further handling.4647 :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 = 25253 def __init__(self, message, ctx=None):54 ClickException.__init__(self, message)55 self.ctx = ctx56 self.cmd = self.ctx and self.ctx.command or None5758 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)717273class 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).7879 .. versionadded:: 2.08081 :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 """9091 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_hint9697 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)105106 return 'Invalid value for %s: %s' % (param_hint, self.message)107108109class MissingParameter(BadParameter):110 """Raised if click required an option or argument but it was not111 provided when invoking the script.112113 .. versionadded:: 4.0114115 :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 """120121 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_type125126 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)134135 param_type = self.param_type136 if param_type is None and self.param is not None:137 param_type = self.param.param_type_name138139 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_extra147148 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 )154155 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.message161162 if PY2:163 __unicode__ = __str__164165 def __str__(self):166 return self.__unicode__().encode("utf-8")167168169class NoSuchOption(UsageError):170 """Raised if click attempted to handle an option that does not171 exist.172173 .. versionadded:: 4.0174 """175176 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 = possibilities183184 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)193194195class 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.199200 .. versionadded:: 4.0201202 :param option_name: the name of the option being used incorrectly.203 """204205 def __init__(self, option_name, message, ctx=None):206 UsageError.__init__(self, message, ctx)207 self.option_name = option_name208209210class 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.214215 .. versionadded:: 6.0216 """217218 def __init__(self, message, ctx=None):219 UsageError.__init__(self, message, ctx)220221222class FileError(ClickException):223 """Raised if a file cannot be opened."""224225 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 = filename232233 def format_message(self):234 return 'Could not open file %s: %s' % (self.ui_filename, self.message)235236237class Abort(RuntimeError):238 """An internal signalling exception that signals Click to abort."""239240241class Exit(RuntimeError):242 """An exception that indicates that the application should exit with some243 status code.244245 :param code: the status code to exit with.246 """247 def __init__(self, code=0):248 self.exit_code = code
deleted:click/formatting.py-262 removed
1from contextlib import contextmanager2from .termui import get_terminal_size3from .parser import split_opt4from ._compat import term_len567# Can force a width. This is used by the test system8FORCED_WIDTH = None91011def 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()))171819def iter_rows(rows, col_count):20 for row in rows:21 row = tuple(row)22 yield row + ('',) * (col_count - len(row))232425def 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).3132 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.3536 :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)5253 p = []54 buf = []55 indent = None5657 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[:]6566 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()7778 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))8586 return '\n\n'.join(rv)878889class 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.9394 At present, it always writes into memory.9596 :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 """100101 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 = []112113 def write(self, string):114 """Writes a unicode string into the internal buffer."""115 self.buffer.append(string)116117 def indent(self):118 """Increases the indentation."""119 self.current_indent += self.indent_increment120121 def dedent(self):122 """Decreases the indentation."""123 self.current_indent -= self.indent_increment124125 def write_usage(self, prog, args='', prefix='Usage: '):126 """Writes a usage line into the buffer.127128 :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_indent134135 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))149150 self.write('\n')151152 def write_heading(self, heading):153 """Writes a heading into the buffer."""154 self.write('%*s%s:\n' % (self.current_indent, '', heading))155156 def write_paragraph(self):157 """Writes a paragraph into the buffer."""158 if self.buffer:159 self.write('\n')160161 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')172173 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.176177 :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')186187 first_col = min(widths[0], col_max) + col_spacing188189 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))199200 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()203204 if lines:205 self.write(lines[0] + '\n')206207 for line in lines[1:]:208 self.write('%*s%s\n' % (first_col + self.current_indent, '', line))209210 if len(lines) > 1:211 # separate long help from next option212 self.write("\n")213 else:214 self.write('\n')215216 @contextmanager217 def section(self, name):218 """Helpful context manager that writes a paragraph, a heading,219 and the indents.220221 :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()230231 @contextmanager232 def indentation(self):233 """A context manager that increases the indentation."""234 self.indent()235 try:236 yield237 finally:238 self.dedent()239240 def getvalue(self):241 """Returns the buffer contents."""242 return ''.join(self.buffer)243244245def 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))258259 rv.sort(key=lambda x: x[0])260261 rv = ', '.join(x[1] for x in rv)262 return rv, any_prefix_is_slash
deleted:click/globals.py-48 removed
1from threading import local234_local = local()567def 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.1314 To push the current context, :meth:`Context.scope` can be used.1516 .. versionadded:: 5.01718 :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.')272829def push_context(ctx):30 """Pushes a new context to the current stack."""31 _local.__dict__.setdefault('stack', []).append(ctx)323334def pop_context():35 """Removes the top level from the stack."""36 _local.stack.pop()373839def 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.color
deleted:click/parser.py-435 removed
1# -*- coding: utf-8 -*-2"""3This module started out as largely a copy paste from the stdlib's4optparse module with the features removed that we do not need from5optparse because we implement them in Click on a higher level (for6instance type handling, help formatting and a lot more).78The plan is to remove more and more from here over time.910The reason this is a different module and not optparse from the stdlib11is that there are differences in 2.x and 3.x about the error messages12generated and optparse in the stdlib uses gettext for no good reason13and might cause us issues.1415Click uses parts of optparse written by Gregory P. Ward and maintained16by the Python Software Foundation. This is limited to code in parser.py.1718Copyright 2001-2006 Gregory P. Ward. All rights reserved.19Copyright 2002-2006 Python Software Foundation. All rights reserved.20"""2122# This code uses parts of optparse written by Gregory P. Ward and23# maintained by the Python Software Foundation.24# Copyright 2001-2006 Gregory P. Ward25# Copyright 2002-2006 Python Software Foundation2627import re28from collections import deque29from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \30 BadArgumentUsage313233def _unpack_args(args, nargs_spec):34 """Given an iterable of arguments and an iterable of nargs specifications,35 it returns a tuple with all the unpacked arguments at the first index36 and all remaining arguments as the second.3738 The nargs specification is the number of arguments that should be consumed39 or `-1` to indicate that this position should eat up all the remainders.4041 Missing items are filled with `None`.42 """43 args = deque(args)44 nargs_spec = deque(nargs_spec)45 rv = []46 spos = None4748 def _fetch(c):49 try:50 if spos is None:51 return c.popleft()52 else:53 return c.pop()54 except IndexError:55 return None5657 while nargs_spec:58 nargs = _fetch(nargs_spec)59 if nargs == 1:60 rv.append(_fetch(args))61 elif nargs > 1:62 x = [_fetch(args) for _ in range(nargs)]63 # If we're reversed, we're pulling in the arguments in reverse,64 # so we need to turn them around.65 if spos is not None:66 x.reverse()67 rv.append(tuple(x))68 elif nargs < 0:69 if spos is not None:70 raise TypeError('Cannot have two nargs < 0')71 spos = len(rv)72 rv.append(None)7374 # spos is the position of the wildcard (star). If it's not `None`,75 # we fill it with the remainder.76 if spos is not None:77 rv[spos] = tuple(args)78 args = []79 rv[spos + 1:] = reversed(rv[spos + 1:])8081 return tuple(rv), list(args)828384def _error_opt_args(nargs, opt):85 if nargs == 1:86 raise BadOptionUsage(opt, '%s option requires an argument' % opt)87 raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))888990def split_opt(opt):91 first = opt[:1]92 if first.isalnum():93 return '', opt94 if opt[1:2] == first:95 return opt[:2], opt[2:]96 return first, opt[1:]979899def normalize_opt(opt, ctx):100 if ctx is None or ctx.token_normalize_func is None:101 return opt102 prefix, opt = split_opt(opt)103 return prefix + ctx.token_normalize_func(opt)104105106def split_arg_string(string):107 """Given an argument string this attempts to split it into small parts."""108 rv = []109 for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"110 r'|"([^"\\]*(?:\\.[^"\\]*)*)"'111 r'|\S+)\s*', string, re.S):112 arg = match.group().strip()113 if arg[:1] == arg[-1:] and arg[:1] in '"\'':114 arg = arg[1:-1].encode('ascii', 'backslashreplace') \115 .decode('unicode-escape')116 try:117 arg = type(string)(arg)118 except UnicodeError:119 pass120 rv.append(arg)121 return rv122123124class Option(object):125126 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):127 self._short_opts = []128 self._long_opts = []129 self.prefixes = set()130131 for opt in opts:132 prefix, value = split_opt(opt)133 if not prefix:134 raise ValueError('Invalid start character for option (%s)'135 % opt)136 self.prefixes.add(prefix[0])137 if len(prefix) == 1 and len(value) == 1:138 self._short_opts.append(opt)139 else:140 self._long_opts.append(opt)141 self.prefixes.add(prefix)142143 if action is None:144 action = 'store'145146 self.dest = dest147 self.action = action148 self.nargs = nargs149 self.const = const150 self.obj = obj151152 @property153 def takes_value(self):154 return self.action in ('store', 'append')155156 def process(self, value, state):157 if self.action == 'store':158 state.opts[self.dest] = value159 elif self.action == 'store_const':160 state.opts[self.dest] = self.const161 elif self.action == 'append':162 state.opts.setdefault(self.dest, []).append(value)163 elif self.action == 'append_const':164 state.opts.setdefault(self.dest, []).append(self.const)165 elif self.action == 'count':166 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1167 else:168 raise ValueError('unknown action %r' % self.action)169 state.order.append(self.obj)170171172class Argument(object):173174 def __init__(self, dest, nargs=1, obj=None):175 self.dest = dest176 self.nargs = nargs177 self.obj = obj178179 def process(self, value, state):180 if self.nargs > 1:181 holes = sum(1 for x in value if x is None)182 if holes == len(value):183 value = None184 elif holes != 0:185 raise BadArgumentUsage('argument %s takes %d values'186 % (self.dest, self.nargs))187 state.opts[self.dest] = value188 state.order.append(self.obj)189190191class ParsingState(object):192193 def __init__(self, rargs):194 self.opts = {}195 self.largs = []196 self.rargs = rargs197 self.order = []198199200class OptionParser(object):201 """The option parser is an internal class that is ultimately used to202 parse options and arguments. It's modelled after optparse and brings203 a similar but vastly simplified API. It should generally not be used204 directly as the high level Click classes wrap it for you.205206 It's not nearly as extensible as optparse or argparse as it does not207 implement features that are implemented on a higher level (such as208 types or defaults).209210 :param ctx: optionally the :class:`~click.Context` where this parser211 should go with.212 """213214 def __init__(self, ctx=None):215 #: The :class:`~click.Context` for this parser. This might be216 #: `None` for some advanced use cases.217 self.ctx = ctx218 #: This controls how the parser deals with interspersed arguments.219 #: If this is set to `False`, the parser will stop on the first220 #: non-option. Click uses this to implement nested subcommands221 #: safely.222 self.allow_interspersed_args = True223 #: This tells the parser how to deal with unknown options. By224 #: default it will error out (which is sensible), but there is a225 #: second mode where it will ignore it and continue processing226 #: after shifting all the unknown options into the resulting args.227 self.ignore_unknown_options = False228 if ctx is not None:229 self.allow_interspersed_args = ctx.allow_interspersed_args230 self.ignore_unknown_options = ctx.ignore_unknown_options231 self._short_opt = {}232 self._long_opt = {}233 self._opt_prefixes = set(['-', '--'])234 self._args = []235236 def add_option(self, opts, dest, action=None, nargs=1, const=None,237 obj=None):238 """Adds a new option named `dest` to the parser. The destination239 is not inferred (unlike with optparse) and needs to be explicitly240 provided. Action can be any of ``store``, ``store_const``,241 ``append``, ``appnd_const`` or ``count``.242243 The `obj` can be used to identify the option in the order list244 that is returned from the parser.245 """246 if obj is None:247 obj = dest248 opts = [normalize_opt(opt, self.ctx) for opt in opts]249 option = Option(opts, dest, action=action, nargs=nargs,250 const=const, obj=obj)251 self._opt_prefixes.update(option.prefixes)252 for opt in option._short_opts:253 self._short_opt[opt] = option254 for opt in option._long_opts:255 self._long_opt[opt] = option256257 def add_argument(self, dest, nargs=1, obj=None):258 """Adds a positional argument named `dest` to the parser.259260 The `obj` can be used to identify the option in the order list261 that is returned from the parser.262 """263 if obj is None:264 obj = dest265 self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))266267 def parse_args(self, args):268 """Parses positional arguments and returns ``(values, args, order)``269 for the parsed options and arguments as well as the leftover270 arguments if there are any. The order is a list of objects as they271 appear on the command line. If arguments appear multiple times they272 will be memorized multiple times as well.273 """274 state = ParsingState(args)275 try:276 self._process_args_for_options(state)277 self._process_args_for_args(state)278 except UsageError:279 if self.ctx is None or not self.ctx.resilient_parsing:280 raise281 return state.opts, state.largs, state.order282283 def _process_args_for_args(self, state):284 pargs, args = _unpack_args(state.largs + state.rargs,285 [x.nargs for x in self._args])286287 for idx, arg in enumerate(self._args):288 arg.process(pargs[idx], state)289290 state.largs = args291 state.rargs = []292293 def _process_args_for_options(self, state):294 while state.rargs:295 arg = state.rargs.pop(0)296 arglen = len(arg)297 # Double dashes always handled explicitly regardless of what298 # prefixes are valid.299 if arg == '--':300 return301 elif arg[:1] in self._opt_prefixes and arglen > 1:302 self._process_opts(arg, state)303 elif self.allow_interspersed_args:304 state.largs.append(arg)305 else:306 state.rargs.insert(0, arg)307 return308309 # Say this is the original argument list:310 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]311 # ^312 # (we are about to process arg(i)).313 #314 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of315 # [arg0, ..., arg(i-1)] (any options and their arguments will have316 # been removed from largs).317 #318 # The while loop will usually consume 1 or more arguments per pass.319 # If it consumes 1 (eg. arg is an option that takes no arguments),320 # then after _process_arg() is done the situation is:321 #322 # largs = subset of [arg0, ..., arg(i)]323 # rargs = [arg(i+1), ..., arg(N-1)]324 #325 # If allow_interspersed_args is false, largs will always be326 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but327 # not a very interesting subset!328329 def _match_long_opt(self, opt, explicit_value, state):330 if opt not in self._long_opt:331 possibilities = [word for word in self._long_opt332 if word.startswith(opt)]333 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)334335 option = self._long_opt[opt]336 if option.takes_value:337 # At this point it's safe to modify rargs by injecting the338 # explicit value, because no exception is raised in this339 # branch. This means that the inserted value will be fully340 # consumed.341 if explicit_value is not None:342 state.rargs.insert(0, explicit_value)343344 nargs = option.nargs345 if len(state.rargs) < nargs:346 _error_opt_args(nargs, opt)347 elif nargs == 1:348 value = state.rargs.pop(0)349 else:350 value = tuple(state.rargs[:nargs])351 del state.rargs[:nargs]352353 elif explicit_value is not None:354 raise BadOptionUsage(opt, '%s option does not take a value' % opt)355356 else:357 value = None358359 option.process(value, state)360361 def _match_short_opt(self, arg, state):362 stop = False363 i = 1364 prefix = arg[0]365 unknown_options = []366367 for ch in arg[1:]:368 opt = normalize_opt(prefix + ch, self.ctx)369 option = self._short_opt.get(opt)370 i += 1371372 if not option:373 if self.ignore_unknown_options:374 unknown_options.append(ch)375 continue376 raise NoSuchOption(opt, ctx=self.ctx)377 if option.takes_value:378 # Any characters left in arg? Pretend they're the379 # next arg, and stop consuming characters of arg.380 if i < len(arg):381 state.rargs.insert(0, arg[i:])382 stop = True383384 nargs = option.nargs385 if len(state.rargs) < nargs:386 _error_opt_args(nargs, opt)387 elif nargs == 1:388 value = state.rargs.pop(0)389 else:390 value = tuple(state.rargs[:nargs])391 del state.rargs[:nargs]392393 else:394 value = None395396 option.process(value, state)397398 if stop:399 break400401 # If we got any unknown options we re-combinate the string of the402 # remaining options and re-attach the prefix, then report that403 # to the state as new larg. This way there is basic combinatorics404 # that can be achieved while still ignoring unknown arguments.405 if self.ignore_unknown_options and unknown_options:406 state.largs.append(prefix + ''.join(unknown_options))407408 def _process_opts(self, arg, state):409 explicit_value = None410 # Long option handling happens in two parts. The first part is411 # supporting explicitly attached values. In any case, we will try412 # to long match the option first.413 if '=' in arg:414 long_opt, explicit_value = arg.split('=', 1)415 else:416 long_opt = arg417 norm_long_opt = normalize_opt(long_opt, self.ctx)418419 # At this point we will match the (assumed) long option through420 # the long option matching code. Note that this allows options421 # like "-foo" to be matched as long options.422 try:423 self._match_long_opt(norm_long_opt, explicit_value, state)424 except NoSuchOption:425 # At this point the long option matching failed, and we need426 # to try with short options. However there is a special rule427 # which says, that if we have a two character options prefix428 # (applies to "--foo" for instance), we do not dispatch to the429 # short option code and will instead raise the no option430 # error.431 if arg[:2] not in self._opt_prefixes:432 return self._match_short_opt(arg, state)433 if not self.ignore_unknown_options:434 raise435 state.largs.append(arg)
deleted:click/termui.py-635 removed
1import io2import os3import sys4import struct5import inspect6import itertools78from ._compat import raw_input, text_type, string_types, \9 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN10from .utils import echo11from .exceptions import Abort, UsageError12from .types import convert_type, Choice, Path13from .globals import resolve_color_default14from .utils import LazyFile151617# The prompt functions to use. The doc tools currently override these18# functions to customize how they work.19visible_prompt_func = raw_input2021_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'414243def hidden_prompt_func(prompt):44 import getpass45 return getpass.getpass(prompt)464748def _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 + suffix555657def _format_default(default):58 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):59 return default.name6061 return default626364def 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.6970 If the user aborts the input by sending a interrupt signal, this71 function will catch it and raise a :exc:`Abort` exception.7273 .. versionadded:: 7.074 Added the show_choices parameter.7576 .. versionadded:: 6.077 Added unicode support for cmd.exe on Windows.7879 .. versionadded:: 4.080 Added the `err` parameter.8182 :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 = None102103 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()117118 if value_proc is None:119 value_proc = convert_type(type, default)120121 prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)122123 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)148149150def confirm(text, default=False, abort=False, prompt_suffix=': ',151 show_default=True, err=False):152 """Prompts for confirmation (yes/no question).153154 If the user aborts the input by sending a interrupt signal this155 function will catch it and raise a :exc:`Abort` exception.156157 .. versionadded:: 4.0158 Added the `err` parameter.159160 :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 rv192193194def 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.lines205206 # 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 size214215 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 cr224225 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])239240241def echo_via_pager(text_or_generator, color=None):242 """This function takes a text and shows it via an environment specific243 pager on stdout.244245 .. versionchanged:: 3.0246 Added the `color` flag.247248 :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)254255 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)261262 # 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)265266 from ._termui_impl import pager267 return pager(itertools.chain(text_generator, "\n"), color)268269270def 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.282283 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.288289 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.294295 No printing must happen or the progress bar will be unintentionally296 destroyed.297298 Example usage::299300 with progressbar(items) as bar:301 for item in bar:302 do_something_with(item)303304 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::308309 with progressbar(length=chunks.total_bytes) as bar:310 for chunk in chunks:311 process_chunk(chunk)312 bar.update(chunks.bytes)313314 The ``update()`` method also takes an optional value specifying the315 ``current_item`` at the new position. This is useful when used316 together with ``item_show_func`` to customize the output for each317 manual step::318319 with click.progressbar(320 length=total_size,321 label='Unzipping archive',322 item_show_func=lambda a: a.filename323 ) as bar:324 for archive in zip_file:325 archive.extract()326 bar.update(archive.size, archive)327328 .. versionadded:: 2.0329330 .. versionadded:: 4.0331 Added the `color` parameter. Added a `update` method to the332 progressbar object.333334 :param iterable: an iterable to iterate over. If not provided the length335 is required.336 :param length: the number of items to iterate over. By default the337 progressbar will attempt to ask the iterator about its338 length, which might or might not work. If an iterable is339 also provided this parameter can be used to override the340 length. If an iterable is not provided the progress bar341 will iterate over a range of that length.342 :param label: the label to show next to the progress bar.343 :param show_eta: enables or disables the estimated time display. This is344 automatically disabled if the length cannot be345 determined.346 :param show_percent: enables or disables the percentage display. The347 default is `True` if the iterable has a length or348 `False` if not.349 :param show_pos: enables or disables the absolute position display. The350 default is `False`.351 :param item_show_func: a function called with the current item which352 can return a string to show the current item353 next to the progress bar. Note that the current354 item can be `None`!355 :param fill_char: the character to use to show the filled part of the356 progress bar.357 :param empty_char: the character to use to show the non-filled part of358 the progress bar.359 :param bar_template: the format string to use as template for the bar.360 The parameters in it are ``label`` for the label,361 ``bar`` for the progress bar and ``info`` for the362 info section.363 :param info_sep: the separator between multiple info items (eta etc.)364 :param width: the width of the progress bar in characters, 0 means full365 terminal width366 :param file: the file to write to. If this is not a terminal then367 only the label is printed.368 :param color: controls if the terminal supports ANSI colors or not. The369 default is autodetection. This is only needed if ANSI370 codes are included anywhere in the progress bar output371 which is not the case by default.372 """373 from ._termui_impl import ProgressBar374 color = resolve_color_default(color)375 return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,376 show_percent=show_percent, show_pos=show_pos,377 item_show_func=item_show_func, fill_char=fill_char,378 empty_char=empty_char, bar_template=bar_template,379 info_sep=info_sep, file=file, label=label,380 width=width, color=color)381382383def clear():384 """Clears the terminal screen. This will have the effect of clearing385 the whole visible space of the terminal and moving the cursor to the386 top left. This does not do anything if not connected to a terminal.387388 .. versionadded:: 2.0389 """390 if not isatty(sys.stdout):391 return392 # If we're on Windows and we don't have colorama available, then we393 # clear the screen by shelling out. Otherwise we can use an escape394 # sequence.395 if WIN:396 os.system('cls')397 else:398 sys.stdout.write('\033[2J\033[1;1H')399400401def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,402 blink=None, reverse=None, reset=True):403 """Styles a text with ANSI styles and returns the new string. By404 default the styling is self contained which means that at the end405 of the string a reset code is issued. This can be prevented by406 passing ``reset=False``.407408 Examples::409410 click.echo(click.style('Hello World!', fg='green'))411 click.echo(click.style('ATTENTION!', blink=True))412 click.echo(click.style('Some things', reverse=True, fg='cyan'))413414 Supported color names:415416 * ``black`` (might be a gray)417 * ``red``418 * ``green``419 * ``yellow`` (might be an orange)420 * ``blue``421 * ``magenta``422 * ``cyan``423 * ``white`` (might be light gray)424 * ``bright_black``425 * ``bright_red``426 * ``bright_green``427 * ``bright_yellow``428 * ``bright_blue``429 * ``bright_magenta``430 * ``bright_cyan``431 * ``bright_white``432 * ``reset`` (reset the color code only)433434 .. versionadded:: 2.0435436 .. versionadded:: 7.0437 Added support for bright colors.438439 :param text: the string to style with ansi codes.440 :param fg: if provided this will become the foreground color.441 :param bg: if provided this will become the background color.442 :param bold: if provided this will enable or disable bold mode.443 :param dim: if provided this will enable or disable dim mode. This is444 badly supported.445 :param underline: if provided this will enable or disable underline.446 :param blink: if provided this will enable or disable blinking.447 :param reverse: if provided this will enable or disable inverse448 rendering (foreground becomes background and the449 other way round).450 :param reset: by default a reset-all code is added at the end of the451 string which means that styles do not carry over. This452 can be disabled to compose styles.453 """454 bits = []455 if fg:456 try:457 bits.append('\033[%dm' % (_ansi_colors[fg]))458 except KeyError:459 raise TypeError('Unknown color %r' % fg)460 if bg:461 try:462 bits.append('\033[%dm' % (_ansi_colors[bg] + 10))463 except KeyError:464 raise TypeError('Unknown color %r' % bg)465 if bold is not None:466 bits.append('\033[%dm' % (1 if bold else 22))467 if dim is not None:468 bits.append('\033[%dm' % (2 if dim else 22))469 if underline is not None:470 bits.append('\033[%dm' % (4 if underline else 24))471 if blink is not None:472 bits.append('\033[%dm' % (5 if blink else 25))473 if reverse is not None:474 bits.append('\033[%dm' % (7 if reverse else 27))475 bits.append(text)476 if reset:477 bits.append(_ansi_reset_all)478 return ''.join(bits)479480481def unstyle(text):482 """Removes ANSI styling information from a string. Usually it's not483 necessary to use this function as Click's echo function will484 automatically remove styling if necessary.485486 .. versionadded:: 2.0487488 :param text: the text to remove style information from.489 """490 return strip_ansi(text)491492493def secho(message=None, file=None, nl=True, err=False, color=None, **styles):494 """This function combines :func:`echo` and :func:`style` into one495 call. As such the following two calls are the same::496497 click.secho('Hello World!', fg='green')498 click.echo(click.style('Hello World!', fg='green'))499500 All keyword arguments are forwarded to the underlying functions501 depending on which one they go with.502503 .. versionadded:: 2.0504 """505 if message is not None:506 message = style(message, **styles)507 return echo(message, file=file, nl=nl, err=err, color=color)508509510def edit(text=None, editor=None, env=None, require_save=True,511 extension='.txt', filename=None):512 r"""Edits the given text in the defined editor. If an editor is given513 (should be the full path to the executable but the regular operating514 system search path is used for finding the executable) it overrides515 the detected editor. Optionally, some environment variables can be516 used. If the editor is closed without changes, `None` is returned. In517 case a file is edited directly the return value is always `None` and518 `require_save` and `extension` are ignored.519520 If the editor cannot be opened a :exc:`UsageError` is raised.521522 Note for Windows: to simplify cross-platform usage, the newlines are523 automatically converted from POSIX to Windows and vice versa. As such,524 the message here will have ``\n`` as newline markers.525526 :param text: the text to edit.527 :param editor: optionally the editor to use. Defaults to automatic528 detection.529 :param env: environment variables to forward to the editor.530 :param require_save: if this is true, then not saving in the editor531 will make the return value become `None`.532 :param extension: the extension to tell the editor about. This defaults533 to `.txt` but changing this might change syntax534 highlighting.535 :param filename: if provided it will edit this file instead of the536 provided text contents. It will not use a temporary537 file as an indirection in that case.538 """539 from ._termui_impl import Editor540 editor = Editor(editor=editor, env=env, require_save=require_save,541 extension=extension)542 if filename is None:543 return editor.edit(text)544 editor.edit_file(filename)545546547def launch(url, wait=False, locate=False):548 """This function launches the given URL (or filename) in the default549 viewer application for this file type. If this is an executable, it550 might launch the executable in a new session. The return value is551 the exit code of the launched application. Usually, ``0`` indicates552 success.553554 Examples::555556 click.launch('https://click.palletsprojects.com/')557 click.launch('/my/downloaded/file', locate=True)558559 .. versionadded:: 2.0560561 :param url: URL or filename of the thing to launch.562 :param wait: waits for the program to stop.563 :param locate: if this is set to `True` then instead of launching the564 application associated with the URL it will attempt to565 launch a file manager with the file located. This566 might have weird effects if the URL does not point to567 the filesystem.568 """569 from ._termui_impl import open_url570 return open_url(url, wait=wait, locate=locate)571572573# If this is provided, getchar() calls into this instead. This is used574# for unittesting purposes.575_getchar = None576577578def getchar(echo=False):579 """Fetches a single character from the terminal and returns it. This580 will always return a unicode character and under certain rare581 circumstances this might return more than one character. The582 situations which more than one character is returned is when for583 whatever reason multiple characters end up in the terminal buffer or584 standard input was not actually a terminal.585586 Note that this will always read from the terminal, even if something587 is piped into the standard input.588589 Note for Windows: in rare cases when typing non-ASCII characters, this590 function might wait for a second character and then return both at once.591 This is because certain Unicode characters look like special-key markers.592593 .. versionadded:: 2.0594595 :param echo: if set to `True`, the character read will also show up on596 the terminal. The default is to not show it.597 """598 f = _getchar599 if f is None:600 from ._termui_impl import getchar as f601 return f(echo)602603604def raw_terminal():605 from ._termui_impl import raw_terminal as f606 return f()607608609def pause(info='Press any key to continue ...', err=False):610 """This command stops execution and waits for the user to press any611 key to continue. This is similar to the Windows batch "pause"612 command. If the program is not run through a terminal, this command613 will instead do nothing.614615 .. versionadded:: 2.0616617 .. versionadded:: 4.0618 Added the `err` parameter.619620 :param info: the info string to print before pausing.621 :param err: if set to message goes to ``stderr`` instead of622 ``stdout``, the same as with echo.623 """624 if not isatty(sys.stdin) or not isatty(sys.stdout):625 return626 try:627 if info:628 echo(info, nl=False, err=err)629 try:630 getchar()631 except (KeyboardInterrupt, EOFError):632 pass633 finally:634 if info:635 echo(err=err)
deleted:click/testing.py-377 removed
1import os2import sys3import shutil4import tempfile5import contextlib6import shlex78from ._compat import iteritems, PY2, string_types91011# 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.15clickpkg = sys.modules[__name__.rsplit('.', 1)[0]]161718if PY2:19 from cStringIO import StringIO20else:21 import io22 from ._compat import _find_binary_reader232425class EchoingStdin(object):2627 def __init__(self, input, output):28 self._input = input29 self._output = output3031 def __getattr__(self, x):32 return getattr(self._input, x)3334 def _echo(self, rv):35 self._output.write(rv)36 return rv3738 def read(self, n=-1):39 return self._echo(self._input.read(n))4041 def readline(self, n=-1):42 return self._echo(self._input.readline(n))4344 def readlines(self):45 return [self._echo(x) for x in self._input.readlines()]4647 def __iter__(self):48 return iter(self._echo(x) for x in self._input)4950 def __repr__(self):51 return repr(self._input)525354def 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.')6364 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)717273class Result(object):74 """Holds the captured result of an invoked CLI script."""7576 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_info9091 @property92 def output(self):93 """The (standard) output as unicode string."""94 return self.stdout9596 @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')101102 @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')109110111 def __repr__(self):112 return '<%s %s>' % (113 type(self).__name__,114 self.exception and repr(self.exception) or 'okay',115 )116117118class 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.123124 :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 """138139 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_stderr147148 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'154155 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 rv161162 @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).169170 This is automatically done in the :meth:`invoke` method.171172 .. versionadded:: 4.0173 The ``color`` parameter was added.174175 :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)181182 old_stdin = sys.stdin183 old_stdout = sys.stdout184 old_stderr = sys.stderr185 old_forced_width = clickpkg.formatting.FORCED_WIDTH186 clickpkg.formatting.FORCED_WIDTH = 80187188 env = self.make_env(env)189190 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)209210 if self.mix_stderr:211 sys.stderr = sys.stdout212213 sys.stdin = input214215 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 val221222 def hidden_input(prompt=None):223 sys.stdout.write((prompt or '') + '\n')224 sys.stdout.flush()225 return input.readline().rstrip('\r\n')226227 def _getchar(echo):228 char = sys.stdin.read(1)229 if echo:230 sys.stdout.write(char)231 sys.stdout.flush()232 return char233234 default_color = color235236 def should_strip_ansi(stream=None, color=None):237 if color is None:238 return not default_color239 return not color240241 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_ansi249250 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_width279280 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.286287 This returns a :class:`Result` object.288289 .. versionadded:: 3.0290 The ``catch_exceptions`` parameter was added.291292 .. versionchanged:: 3.0293 The result object now has an `exc_info` attribute with the294 traceback if available.295296 .. versionadded:: 4.0297 The ``color`` parameter was added.298299 :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 = 0316317 if isinstance(args, string_types):318 args = shlex.split(args)319320 try:321 prog_name = extra.pop("prog_name")322 except KeyError:323 prog_name = self.get_default_prog_name(cli)324325 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 = 0332333 if exit_code != 0:334 exception = e335336 if not isinstance(exit_code, int):337 sys.stdout.write(str(exit_code))338 sys.stdout.write('\n')339 exit_code = 1340341 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()354355 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)361362 @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 pass
deleted:click/types.py-679 removed
1import os2import stat3from datetime import datetime45from ._compat import open_stream, text_type, filename_to_ui, \6 get_filesystem_encoding, get_streerror, _get_argv_encoding, PY27from .exceptions import BadParameter8from .utils import safecall, LazyFile91011class ParamType(object):12 """Helper for converting values through types. The following is13 necessary for a valid type:1415 * 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 = False2526 #: the descriptive name of this type27 name = None2829 #: 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 = None3637 def __call__(self, value, param=None, ctx=None):38 if value is not None:39 return self.convert(value, param, ctx)4041 def get_metavar(self, param):42 """Returns the metavar default for this param if it provides one."""4344 def get_missing_message(self, param):45 """Optionally might return extra information about a missing46 parameter.4748 .. versionadded:: 2.049 """5051 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 value5657 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.6061 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)6667 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)707172class CompositeParamType(ParamType):73 is_composite = True7475 @property76 def arity(self):77 raise NotImplementedError()787980class FuncParamType(ParamType):8182 def __init__(self, func):83 self.name = func.__name__84 self.func = func8586 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)959697class UnprocessedParamType(ParamType):98 name = 'text'99100 def convert(self, value, param, ctx):101 return value102103 def __repr__(self):104 return 'UNPROCESSED'105106107class StringParamType(ParamType):108 name = 'text'109110 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 value126127 def __repr__(self):128 return 'STRING'129130131class 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.134135 You should only pass a list or tuple of choices. Other iterables136 (like generators) may lead to surprising results.137138 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.141142 See :ref:`choice-opts` for an example.143144 :param case_sensitive: Set to false to make choices case145 insensitive. Defaults to true.146 """147148 name = 'choice'149150 def __init__(self, choices, case_sensitive=True):151 self.choices = choices152 self.case_sensitive = case_sensitive153154 def get_metavar(self, param):155 return '[%s]' % '|'.join(self.choices)156157 def get_missing_message(self, param):158 return 'Choose from:\n\t%s.' % ',\n\t'.join(self.choices)159160 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}167168 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 }174175 if not self.case_sensitive:176 if PY2:177 lower = str.lower178 else:179 lower = str.casefold180181 normed_value = lower(normed_value)182 normed_choices = {183 lower(normed_choice): original184 for normed_choice, original in normed_choices.items()185 }186187 if normed_value in normed_choices:188 return normed_choices[normed_value]189190 self.fail('invalid choice: %s. (choose from %s)' %191 (value, ', '.join(self.choices)), param, ctx)192193 def __repr__(self):194 return 'Choice(%r)' % list(self.choices)195196197class DateTime(ParamType):198 """The DateTime type converts date strings into `datetime` objects.199200 The format strings which are checked are configurable, but default to some201 common (non-timezone aware) ISO 8601 formats.202203 When specifying *DateTime* formats, you should only pass a list or a tuple.204 Other iterables, like generators, may lead to surprising results.205206 The format strings are processed using ``datetime.strptime``, and this207 consequently defines the format strings which are allowed.208209 Parsing is tried using each format, in order, and the first format which210 parses successfully is used.211212 :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'218219 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 ]225226 def get_metavar(self, param):227 return '[{}]'.format('|'.join(self.formats))228229 def _try_to_convert_date(self, value, format):230 try:231 return datetime.strptime(value, format)232 except ValueError:233 return None234235 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 dtime241242 self.fail(243 'invalid datetime format: {}. (choose from {})'.format(244 value, ', '.join(self.formats)))245246 def __repr__(self):247 return 'DateTime'248249250class IntParamType(ParamType):251 name = 'integer'252253 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)258259 def __repr__(self):260 return 'INT'261262263class 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.268269 See :ref:`ranges` for an example.270 """271 name = 'integer range'272273 def __init__(self, min=None, max=None, clamp=False):274 self.min = min275 self.max = max276 self.clamp = clamp277278 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 rv297298 def __repr__(self):299 return 'IntRange(%r, %r)' % (self.min, self.max)300301302class FloatParamType(ParamType):303 name = 'float'304305 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)311312 def __repr__(self):313 return 'FLOAT'314315316class 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.321322 See :ref:`ranges` for an example.323 """324 name = 'float range'325326 def __init__(self, min=None, max=None, clamp=False):327 self.min = min328 self.max = max329 self.clamp = clamp330331 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 rv350351 def __repr__(self):352 return 'FloatRange(%r, %r)' % (self.min, self.max)353354355class BoolParamType(ParamType):356 name = 'boolean'357358 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)367368 def __repr__(self):369 return 'BOOL'370371372class UUIDParameterType(ParamType):373 name = 'uuid'374375 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)383384 def __repr__(self):385 return 'UUID'386387388class 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).392393 Files can be opened for reading or writing. The special value ``-``394 indicates stdin or stdout depending on the mode.395396 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.399400 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.406407 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.411412 See :ref:`file-args` for more information.413 """414 name = 'filename'415 envvar_list_splitter = os.path.pathsep416417 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 = atomic424425 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 False433434 def convert(self, value, param, ctx):435 try:436 if hasattr(value, 'read') or hasattr(value, 'write'):437 return value438439 lazy = self.resolve_lazy_flag(value)440441 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 f447448 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)467468469class 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.474475 .. versionchanged:: 6.0476 `allow_dash` was added.477478 :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.pathsep500501 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_type512513 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'522523 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 rv530531 def convert(self, value, param, ctx):532 rv = value533534 is_dash = self.file_okay and self.allow_dash and rv in (b'-', '-')535536 if not is_dash:537 if self.resolve_path:538 rv = os.path.realpath(rv)539540 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)549550 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)570571 return self.coerce_path_result(rv)572573574class 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.580581 For more information see :ref:`tuple-type`.582583 This can be selected by using a Python tuple literal as a type.584585 :param types: a list of types that should be used for the tuple items.586 """587588 def __init__(self, types):589 self.types = [convert_type(ty) for ty in types]590591 @property592 def name(self):593 return "<" + " ".join(ty.name for ty in self.types) + ">"594595 @property596 def arity(self):597 return len(self.types)598599 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))604605606def 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 = True617618 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 STRING636637 # 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)646647648#: 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.0660UNPROCESSED = UnprocessedParamType()661662#: A unicode string parameter type which is the implicit default. This663#: can also be selected by using ``str`` as type.664STRING = StringParamType()665666#: An integer parameter. This can also be selected by using ``int`` as667#: type.668INT = IntParamType()669670#: A floating point value parameter. This can also be selected by using671#: ``float`` as type.672FLOAT = FloatParamType()673674#: A boolean parameter. This is the default for boolean flags. This can675#: also be selected by using ``bool`` as a type.676BOOL = BoolParamType()677678#: A UUID parameter.679UUID = UUIDParameterType()
deleted:click/utils.py-440 removed
1import os2import sys34from .globals import resolve_color_default56from ._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, WIN1011if not PY2:12 from ._compat import _find_binary_writer13elif WIN:14 from ._winconsole import _get_windows_argv, \15 _hash_py_argv, _initial_argv_hash161718echo_native_types = string_types + (bytes, bytearray)192021def _posixify(name):22 return '-'.join(name.split()).lower()232425def 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 wrapper333435def 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)434445def 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 = False5152 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_length6667 return ''.join(result)686970class 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 """7677 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 = atomic8485 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 = True9697 def __getattr__(self, name):98 return getattr(self.open(), name)99100 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)104105 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 rv122123 def close(self):124 """Closes the underlying file, no matter what."""125 if self._f is not None:126 self._f.close()127128 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()134135 def __enter__(self):136 return self137138 def __exit__(self, exc_type, exc_value, tb):139 self.close_intelligently()140141 def __iter__(self):142 self.open()143 return iter(self._f)144145146class KeepOpenFile(object):147148 def __init__(self, file):149 self._file = file150151 def __getattr__(self, name):152 return getattr(self._file, name)153154 def __enter__(self):155 return self156157 def __exit__(self, exc_type, exc_value, tb):158 pass159160 def __repr__(self):161 return repr(self._file)162163 def __iter__(self):164 return iter(self._file)165166167def 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.172173 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.178179 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:182183 - add transparent handling of ANSI color codes on Windows.184 - hide ANSI codes automatically if the destination file is not a185 terminal.186187 .. _colorama: https://pypi.org/project/colorama/188189 .. 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.194195 .. versionchanged:: 2.0196 Starting with version 2.0 of Click, the echo function will work197 with colorama if it's installed.198199 .. versionadded:: 3.0200 The `err` parameter was added.201202 .. versionchanged:: 4.0203 Added the `color` flag.204205 :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()219220 # 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)223224 if nl:225 message = message or u''226 if isinstance(message, text_type):227 message += u'\n'228 else:229 message += b'\n'230231 # 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 return243244 # 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)258259 if message:260 file.write(message)261 file.flush()262263264def 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.270271 :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()278279280def 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.285286 :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)295296297def 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.302303 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::307308 with open_file(filename) as f:309 ...310311 .. versionadded:: 3.0312313 :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 f328329330def 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.335336 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.341342 .. 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:]349350351def 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.357358 :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)366367368def 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.371372 To give you an idea, for an app called ``"Foo Bar"``, something like373 the following folders could be returned:374375 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``391392 .. versionadded:: 2.0393394 :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))417418419class 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 """427428 def __init__(self, wrapped):429 self.wrapped = wrapped430431 def flush(self):432 try:433 self.wrapped.flush()434 except IOError as e:435 import errno436 if e.errno != errno.EPIPE:437 raise438439 def __getattr__(self, attr):440 return getattr(self.wrapped, attr)
modified:docs/arguments.rst-1 removed
265 unmodified lines
266267.. click:run::268269 invoke(touch, ['-foo.txt', 'bar.txt'])270
modified:docs/conf.py+1 added-3 removed
45 unmodified lines
46html_show_sourcelink = False4748# LaTeX ----------------------------------------------------------------4950latex_documents = [51 (master_doc, f"Click-{version}.tex", html_title, author, "manual")52]50latex_documents = [(master_doc, f"Click-{version}.tex", html_title, author, "manual")]
modified:examples/aliases/aliases.py+29 added-22 removed
1import os23import click45try:5 import ConfigParser as configparser6except ImportError:6 import configparser7except ImportError:8 import ConfigParser as configparser91011class Config(object):12 """The config in this example only holds aliases."""
8 unmodified lines
21 def read_config(self, filename):22 parser = configparser.RawConfigParser()23 parser.read([filename])24 try:24 self.aliases.update(parser.items('aliases'))25 self.aliases.update(parser.items("aliases"))26 except configparser.NoSectionError:27 pass2829 def write_config(self, filename):30 parser = configparser.RawConfigParser()30 parser.add_section('aliases')31 parser.add_section("aliases")32 for key, value in self.aliases.items():32 parser.set('aliases', key, value)33 with open(filename, 'wb') as file:33 parser.set("aliases", key, value)34 with open(filename, "wb") as file:35 parser.write(file)363738pass_config = click.make_pass_decorator(Config, ensure=True)
22 unmodified lines
61 # Alternative option: if we did not find an explicit alias we62 # allow automatic abbreviation of the command. "status" for63 # instance will match "st". We only allow that however if64 # there is only one command.64 matches = [x for x in self.list_commands(ctx)65 if x.lower().startswith(cmd_name.lower())]65 matches = [66 x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower())67 ]68 if not matches:69 return None70 elif len(matches) == 1:71 return click.Group.get_command(self, ctx, matches[0])70 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))72 ctx.fail("Too many matches: {}".format(", ".join(sorted(matches))))737475def read_config(ctx, param, value):76 """Callback that is used whenever --config is passed. We use this to
2 unmodified lines
79 available.80 """81 cfg = ctx.ensure_object(Config)82 if value is None:81 value = os.path.join(os.path.dirname(__file__), 'aliases.ini')83 value = os.path.join(os.path.dirname(__file__), "aliases.ini")84 cfg.read_config(value)85 return value868788@click.command(cls=AliasedGroup)87@click.option('--config', type=click.Path(exists=True, dir_okay=False),88 callback=read_config, expose_value=False,89 help='The config file to use instead of the default.')89@click.option(90 "--config",91 type=click.Path(exists=True, dir_okay=False),92 callback=read_config,93 expose_value=False,94 help="The config file to use instead of the default.",95)96def cli():97 """An example application that supports aliases."""9899100@cli.command()101def push():102 """Pushes changes."""97 click.echo('Push')103 click.echo("Push")104105106@cli.command()107def pull():108 """Pulls changes."""103 click.echo('Pull')109 click.echo("Pull")110111112@cli.command()113def clone():114 """Clones a repository."""109 click.echo('Clone')115 click.echo("Clone")116117118@cli.command()119def commit():120 """Commits pending changes."""115 click.echo('Commit')121 click.echo("Commit")122123124@cli.command()125@pass_config126def status(config):127 """Shows the status."""122 click.echo('Status for %s' % config.path)128 click.echo("Status for {}".format(config.path))129130131@cli.command()132@pass_config127@click.argument("alias_", metavar='ALIAS', type=click.STRING)133@click.argument("alias_", metavar="ALIAS", type=click.STRING)134@click.argument("cmd", type=click.STRING)129@click.option('--config_file', type=click.Path(exists=True, dir_okay=False),130 default="aliases.ini")135@click.option(136 "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini"137)138def alias(config, alias_, cmd, config_file):139 """Adds an alias to the specified configuration file."""140 config.add_alias(alias_, cmd)141 config.write_config(config_file)135 click.echo('Added %s as alias for %s' % (alias_, cmd))142 click.echo("Added '{}' as alias for '{}'".format(alias_, cmd))
modified:examples/aliases/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-aliases',5 version='1.0',6 py_modules=['aliases'],4 name="click-example-aliases",5 version="1.0",6 py_modules=["aliases"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 aliases=aliases:cli14 ''',12 """,13)
modified:examples/bashcompletion/bashcompletion.py+11 added-11 removed
1import click1import os23import click456@click.group()7def cli():8 pass9
4 unmodified lines
14 if incomplete in key:15 yield key161717@cli.command(help='A command to print environment variables')18@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):20 click.echo('Environment variable: %s' % envvar)21 click.echo('Value: %s' % os.environ[envvar])21 click.echo("Environment variable: {}".format(envvar))22 click.echo("Value: {}".format(os.environ[envvar]))232424@click.group(help='A group that holds a subcommand')25@click.group(help="A group that holds a subcommand")26def group():27 pass282930def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).32 users = [('bob', 'butcher'),33 ('alice', 'baker'),34 ('jerry', 'candlestick maker')]35 # Ths will allow completion matches based on matches within the description string too!33 users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34 # Ths will allow completion matches based on matches within the35 # description string too!36 return [user for user in users if incomplete in user[0] or incomplete in user[1]]373839@group.command(help='Choose a user')39@group.command(help="Choose a user")40@click.argument("user", type=click.STRING, autocompletion=list_users)41def subcmd(user):42 click.echo('Chosen user is %s' % user)42 click.echo("Chosen user is {}".format(user))434445cli.add_command(group)
modified:examples/bashcompletion/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-bashcompletion',5 version='1.0',6 py_modules=['bashcompletion'],4 name="click-example-bashcompletion",5 version="1.0",6 py_modules=["bashcompletion"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 bashcompletion=bashcompletion:cli14 ''',12 """,13)
modified:examples/colors/colors.py+27 added-11 removed
1import click234all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5 'cyan', 'white', 'bright_black', 'bright_red', \6 'bright_green', 'bright_yellow', 'bright_blue', \7 'bright_magenta', 'bright_cyan', 'bright_white'4all_colors = (5 "black",6 "red",7 "green",8 "yellow",9 "blue",10 "magenta",11 "cyan",12 "white",13 "bright_black",14 "bright_red",15 "bright_green",16 "bright_yellow",17 "bright_blue",18 "bright_magenta",19 "bright_cyan",20 "bright_white",21)222324@click.command()25def cli():
3 unmodified lines
2930 Give it a try!31 """32 for color in all_colors:19 click.echo(click.style('I am colored %s' % color, fg=color))33 click.echo(click.style("I am colored {}".format(color), fg=color))34 for color in all_colors:21 click.echo(click.style('I am colored %s and bold' % color,22 fg=color, bold=True))35 click.echo(36 click.style("I am colored {} and bold".format(color), fg=color, bold=True)37 )38 for color in all_colors:24 click.echo(click.style('I am reverse colored %s' % color, fg=color,25 reverse=True))39 click.echo(40 click.style("I am reverse colored {}".format(color), fg=color, reverse=True)41 )4227 click.echo(click.style('I am blinking', blink=True))28 click.echo(click.style('I am underlined', underline=True))43 click.echo(click.style("I am blinking", blink=True))44 click.echo(click.style("I am underlined", underline=True))
modified:examples/colors/setup.py+7 added-7 removed
1from setuptools import setup23setup(4 name='click-example-colors',5 version='1.0',6 py_modules=['colors'],4 name="click-example-colors",5 version="1.0",6 py_modules=["colors"],7 include_package_data=True,8 install_requires=[9 'click',9 "click",10 # Colorama is only required for Windows.11 'colorama',11 "colorama",12 ],13 entry_points='''13 entry_points="""14 [console_scripts]15 colors=colors:cli16 ''',16 """,17)
modified:examples/complex/complex/commands/cmd_init.py+5 added-5 removed
1import click1from complex.cli import pass_environment23import click455@click.command('init', short_help='Initializes a repo.')6@click.argument('path', required=False, type=click.Path(resolve_path=True))6@click.command("init", short_help="Initializes a repo.")7@click.argument("path", required=False, type=click.Path(resolve_path=True))8@pass_environment9def cli(ctx, path):10 """Initializes a repository."""11 if path is None:12 path = ctx.home12 ctx.log('Initialized the repository in %s',13 click.format_filename(path))13 ctx.log("Initialized the repository in %s", click.format_filename(path))
modified:examples/complex/complex/commands/cmd_status.py+5 added-4 removed
1import click1from complex.cli import pass_environment23import click45@click.command('status', short_help='Shows file changes.')56@click.command("status", short_help="Shows file changes.")7@pass_environment8def cli(ctx):9 """Shows file changes in the current working directory."""9 ctx.log('Changed files: none')10 ctx.vlog('bla bla bla, debug info')10 ctx.log("Changed files: none")11 ctx.vlog("bla bla bla, debug info")
modified:examples/complex/complex/cli.py+14 added-15 removed
1import os2import sys34import click566CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')7CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8910class Environment(object):1011 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14
9 unmodified lines
24 self.log(msg, *args)252627pass_environment = click.make_pass_decorator(Environment, ensure=True)28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),29 'commands'))28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))293031class ComplexCLI(click.MultiCommand):3332 def list_commands(self, ctx):33 rv = []34 for filename in os.listdir(cmd_folder):37 if filename.endswith('.py') and \38 filename.startswith('cmd_'):35 if filename.endswith(".py") and filename.startswith("cmd_"):36 rv.append(filename[4:-3])37 rv.sort()38 return rv3940 def get_command(self, ctx, name):41 try:42 if sys.version_info[0] == 2:46 name = name.encode('ascii', 'replace')47 mod = __import__('complex.commands.cmd_' + name,48 None, None, ['cli'])43 name = name.encode("ascii", "replace")44 mod = __import__(45 "complex.commands.cmd_{}".format(name), None, None, ["cli"]46 )47 except ImportError:48 return49 return mod.cli505152@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)55@click.option('--home', type=click.Path(exists=True, file_okay=False,56 resolve_path=True),57 help='Changes the folder to operate on.')58@click.option('-v', '--verbose', is_flag=True,59 help='Enables verbose mode.')53@click.option(54 "--home",55 type=click.Path(exists=True, file_okay=False, resolve_path=True),56 help="Changes the folder to operate on.",57)58@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")59@pass_environment60def cli(ctx, verbose, home):61 """A complex command line interface."""62 ctx.verbose = verbose
2 unmodified lines
modified:examples/complex/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-complex',5 version='1.0',6 packages=['complex', 'complex.commands'],4 name="click-example-complex",5 version="1.0",6 packages=["complex", "complex.commands"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 complex=complex.cli:cli14 ''',12 """,13)
modified:examples/imagepipe/imagepipe.py+94 added-66 removed
1import click1from functools import update_wrapper3from PIL import Image, ImageFilter, ImageEnhance23from PIL import Image4from PIL import ImageEnhance5from PIL import ImageFilter67import click8910@click.group(chain=True)11def cli():12 """This script processes a bunch of images through pillow in a unix13 pipe. One commands feeds into the next.
28 unmodified lines
42def processor(f):43 """Helper decorator to rewrite a function so that it returns another44 function from it.45 """4647 def new_func(*args, **kwargs):48 def processor(stream):49 return f(stream, *args, **kwargs)5051 return processor5253 return update_wrapper(new_func, f)545556def generator(f):57 """Similar to the :func:`processor` but passes through old values58 unchanged and does not pass through the values as parameter.59 """6061 @processor62 def new_func(stream, *args, **kwargs):63 for item in stream:64 yield item65 for item in f(*args, **kwargs):66 yield item6768 return update_wrapper(new_func, f)697071def copy_filename(new, old):72 new.filename = old.filename73 return new747567@cli.command('open')68@click.option('-i', '--image', 'images', type=click.Path(),69 multiple=True, help='The image file to open.')76@cli.command("open")77@click.option(78 "-i",79 "--image",80 "images",81 type=click.Path(),82 multiple=True,83 help="The image file to open.",84)85@generator86def open_cmd(images):87 """Loads one or multiple images for processing. The input parameter88 can be specified multiple times to load more than one image.89 """90 for image in images:91 try:77 click.echo('Opening "%s"' % image)78 if image == '-':92 click.echo("Opening '{}'".format(image))93 if image == "-":94 img = Image.open(click.get_binary_stdin())80 img.filename = '-'95 img.filename = "-"96 else:97 img = Image.open(image)98 yield img99 except Exception as e:85 click.echo('Could not open image "%s": %s' % (image, e), err=True)100 click.echo("Could not open image '{}': {}".format(image, e), err=True)10110288@cli.command('save')89@click.option('--filename', default='processed-%04d.png', type=click.Path(),90 help='The format for the filename.',91 show_default=True)103@cli.command("save")104@click.option(105 "--filename",106 default="processed-{:04}.png",107 type=click.Path(),108 help="The format for the filename.",109 show_default=True,110)111@processor112def save_cmd(images, filename):113 """Saves all processed images to a series of files."""114 for idx, image in enumerate(images):115 try:97 fn = filename % (idx + 1)98 click.echo('Saving "%s" as "%s"' % (image.filename, fn))116 fn = filename.format(idx + 1)117 click.echo("Saving '{}' as '{}'".format(image.filename, fn))118 yield image.save(fn)119 except Exception as e:101 click.echo('Could not save image "%s": %s' %102 (image.filename, e), err=True)120 click.echo(121 "Could not save image '{}': {}".format(image.filename, e), err=True122 )123124105@cli.command('display')125@cli.command("display")126@processor127def display_cmd(images):128 """Opens all images in an image viewer."""129 for image in images:110 click.echo('Displaying "%s"' % image.filename)130 click.echo("Displaying '{}'".format(image.filename))131 image.show()132 yield image133134115@cli.command('resize')116@click.option('-w', '--width', type=int, help='The new width of the image.')117@click.option('-h', '--height', type=int, help='The new height of the image.')135@cli.command("resize")136@click.option("-w", "--width", type=int, help="The new width of the image.")137@click.option("-h", "--height", type=int, help="The new height of the image.")138@processor139def resize_cmd(images, width, height):140 """Resizes an image by fitting it into the box without changing141 the aspect ratio.142 """143 for image in images:144 w, h = (width or image.size[0], height or image.size[1])125 click.echo('Resizing "%s" to %dx%d' % (image.filename, w, h))145 click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h))146 image.thumbnail((w, h))147 yield image148149130@cli.command('crop')131@click.option('-b', '--border', type=int, help='Crop the image from all '132 'sides by this amount.')150@cli.command("crop")151@click.option(152 "-b", "--border", type=int, help="Crop the image from all sides by this amount."153)154@processor155def crop_cmd(images, border):156 """Crops an image from all edges."""157 for image in images:
1 unmodified line
159160 if border is not None:161 for idx, val in enumerate(box):162 box[idx] = max(0, val - border)142 click.echo('Cropping "%s" by %dpx' % (image.filename, border))163 click.echo("Cropping '{}' by {}px".format(image.filename, border))164 yield copy_filename(image.crop(box), image)165 else:166 yield image167
1 unmodified line
169def convert_rotation(ctx, param, value):170 if value is None:171 return172 value = value.lower()152 if value in ('90', 'r', 'right'):173 if value in ("90", "r", "right"):174 return (Image.ROTATE_90, 90)154 if value in ('180', '-180'):175 if value in ("180", "-180"):176 return (Image.ROTATE_180, 180)156 if value in ('-90', '270', 'l', 'left'):177 if value in ("-90", "270", "l", "left"):178 return (Image.ROTATE_270, 270)158 raise click.BadParameter('invalid rotation "%s"' % value)179 raise click.BadParameter("invalid rotation '{}'".format(value))180181182def convert_flip(ctx, param, value):183 if value is None:184 return185 value = value.lower()165 if value in ('lr', 'leftright'):166 return (Image.FLIP_LEFT_RIGHT, 'left to right')167 if value in ('tb', 'topbottom', 'upsidedown', 'ud'):168 return (Image.FLIP_LEFT_RIGHT, 'top to bottom')169 raise click.BadParameter('invalid flip "%s"' % value)186 if value in ("lr", "leftright"):187 return (Image.FLIP_LEFT_RIGHT, "left to right")188 if value in ("tb", "topbottom", "upsidedown", "ud"):189 return (Image.FLIP_LEFT_RIGHT, "top to bottom")190 raise click.BadParameter("invalid flip '{}'".format(value))191192172@cli.command('transpose')173@click.option('-r', '--rotate', callback=convert_rotation,174 help='Rotates the image (in degrees)')175@click.option('-f', '--flip', callback=convert_flip,176 help='Flips the image [LR / TB]')193@cli.command("transpose")194@click.option(195 "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"196)197@click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]")198@processor199def transpose_cmd(images, rotate, flip):200 """Transposes an image by either rotating or flipping it."""201 for image in images:202 if rotate is not None:203 mode, degrees = rotate183 click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees))204 click.echo("Rotate '{}' by {}deg".format(image.filename, degrees))205 image = copy_filename(image.transpose(mode), image)206 if flip is not None:207 mode, direction = flip187 click.echo('Flip "%s" %s' % (image.filename, direction))208 click.echo("Flip '{}' {}".format(image.filename, direction))209 image = copy_filename(image.transpose(mode), image)210 yield image211212192@cli.command('blur')193@click.option('-r', '--radius', default=2, show_default=True,194 help='The blur radius.')213@cli.command("blur")214@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")215@processor216def blur_cmd(images, radius):217 """Applies gaussian blur."""218 blur = ImageFilter.GaussianBlur(radius)219 for image in images:200 click.echo('Blurring "%s" by %dpx' % (image.filename, radius))220 click.echo("Blurring '{}' by {}px".format(image.filename, radius))221 yield copy_filename(image.filter(blur), image)222223204@cli.command('smoothen')205@click.option('-i', '--iterations', default=1, show_default=True,206 help='How many iterations of the smoothen filter to run.')224@cli.command("smoothen")225@click.option(226 "-i",227 "--iterations",228 default=1,229 show_default=True,230 help="How many iterations of the smoothen filter to run.",231)232@processor233def smoothen_cmd(images, iterations):234 """Applies a smoothening filter."""235 for image in images:211 click.echo('Smoothening "%s" %d time%s' %212 (image.filename, iterations, iterations != 1 and 's' or '',))213 for x in range(iterations):236 click.echo(237 "Smoothening '{}' {} time{}".format(238 image.filename, iterations, "s" if iterations != 1 else ""239 )240 )241 for _ in range(iterations):242 image = copy_filename(image.filter(ImageFilter.BLUR), image)243 yield image244245218@cli.command('emboss')246@cli.command("emboss")247@processor248def emboss_cmd(images):249 """Embosses an image."""250 for image in images:223 click.echo('Embossing "%s"' % image.filename)251 click.echo("Embossing '{}'".format(image.filename))252 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)253254227@cli.command('sharpen')228@click.option('-f', '--factor', default=2.0,229 help='Sharpens the image.', show_default=True)255@cli.command("sharpen")256@click.option(257 "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True258)259@processor260def sharpen_cmd(images, factor):261 """Sharpens an image."""262 for image in images:234 click.echo('Sharpen "%s" by %f' % (image.filename, factor))263 click.echo("Sharpen '{}' by {}".format(image.filename, factor))264 enhancer = ImageEnhance.Sharpness(image)265 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)266267239@cli.command('paste')240@click.option('-l', '--left', default=0, help='Offset from left.')241@click.option('-r', '--right', default=0, help='Offset from right.')268@cli.command("paste")269@click.option("-l", "--left", default=0, help="Offset from left.")270@click.option("-r", "--right", default=0, help="Offset from right.")271@processor272def paste_cmd(images, left, right):273 """Pastes the second image on the first image and leaves the rest274 unchanged.
6 unmodified lines
281 if image is not None:282 yield image283 return284256 click.echo('Paste "%s" on "%s"' %257 (to_paste.filename, image.filename))285 click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename))286 mask = None259 if to_paste.mode == 'RGBA' or 'transparency' in to_paste.info:287 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:288 mask = to_paste289 image.paste(to_paste, (left, right), mask)262 image.filename += '+' + to_paste.filename290 image.filename += "+{}".format(to_paste.filename)291 yield image292293 for image in imageiter:294 yield image
modified:examples/imagepipe/setup.py+6 added-9 removed
1from setuptools import setup23setup(4 name='click-example-imagepipe',5 version='1.0',6 py_modules=['imagepipe'],4 name="click-example-imagepipe",5 version="1.0",6 py_modules=["imagepipe"],7 include_package_data=True,8 install_requires=[9 'click',10 'pillow',11 ],12 entry_points='''8 install_requires=["click", "pillow"],9 entry_points="""10 [console_scripts]11 imagepipe=imagepipe:cli15 ''',12 """,13)
modified:examples/inout/inout.py+2 added-2 removed
1import click234@click.command()5@click.argument('input', type=click.File('rb'), nargs=-1)6@click.argument('output', type=click.File('wb'))5@click.argument("input", type=click.File("rb"), nargs=-1)6@click.argument("output", type=click.File("wb"))7def cli(input, output):8 """This script works similar to the Unix `cat` command but it writes9 into a specific file (which could be the standard output as denoted by10 the ``-`` sign).
20 unmodified lines
modified:examples/inout/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-inout',5 version='0.1',6 py_modules=['inout'],4 name="click-example-inout",5 version="0.1",6 py_modules=["inout"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 inout=inout:cli14 ''',12 """,13)
modified:examples/naval/naval.py+31 added-29 removed
15 unmodified lines
16def ship():17 """Manages ships."""181920@ship.command('new')21@click.argument('name')20@ship.command("new")21@click.argument("name")22def ship_new(name):23 """Creates a new ship."""24 click.echo('Created ship %s' % name)24 click.echo("Created ship {}".format(name))252627@ship.command('move')28@click.argument('ship')29@click.argument('x', type=float)30@click.argument('y', type=float)31@click.option('--speed', metavar='KN', default=10,32 help='Speed in knots.')27@ship.command("move")28@click.argument("ship")29@click.argument("x", type=float)30@click.argument("y", type=float)31@click.option("--speed", metavar="KN", default=10, help="Speed in knots.")32def ship_move(ship, x, y, speed):33 """Moves SHIP to the new location X,Y."""35 click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed))34 click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, speed))353638@ship.command('shoot')39@click.argument('ship')40@click.argument('x', type=float)41@click.argument('y', type=float)37@ship.command("shoot")38@click.argument("ship")39@click.argument("x", type=float)40@click.argument("y", type=float)41def ship_shoot(ship, x, y):42 """Makes SHIP fire to X,Y."""44 click.echo('Ship %s fires to %s,%s' % (ship, x, y))43 click.echo("Ship {} fires to {},{}".format(ship, x, y))444547@cli.group('mine')46@cli.group("mine")47def mine():48 """Manages mines."""495052@mine.command('set')53@click.argument('x', type=float)54@click.argument('y', type=float)55@click.option('ty', '--moored', flag_value='moored',56 default=True,57 help='Moored (anchored) mine. Default.')58@click.option('ty', '--drifting', flag_value='drifting',59 help='Drifting mine.')51@mine.command("set")52@click.argument("x", type=float)53@click.argument("y", type=float)54@click.option(55 "ty",56 "--moored",57 flag_value="moored",58 default=True,59 help="Moored (anchored) mine. Default.",60)61@click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.")62def mine_set(x, y, ty):63 """Sets a mine at a specific coordinate."""62 click.echo('Set %s mine at %s,%s' % (ty, x, y))64 click.echo("Set {} mine at {},{}".format(ty, x, y))656665@mine.command('remove')66@click.argument('x', type=float)67@click.argument('y', type=float)67@mine.command("remove")68@click.argument("x", type=float)69@click.argument("y", type=float)70def mine_remove(x, y):71 """Removes a mine at a specific coordinate."""70 click.echo('Removed mine at %s,%s' % (x, y))72 click.echo("Removed mine at {},{}".format(x, y))
modified:examples/naval/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-naval',5 version='2.0',6 py_modules=['naval'],4 name="click-example-naval",5 version="2.0",6 py_modules=["naval"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 naval=naval:cli14 ''',12 """,13)
modified:examples/repo/repo.py+66 added-51 removed
1import os2import sys2import posixpath3import sys45import click678class Repo(object):99 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False1314 def set_config(self, key, value):15 self.config[key] = value16 if self.verbose:18 click.echo(' config[%s] = %s' % (key, value), file=sys.stderr)17 click.echo(" config[{}] = {}".format(key, value), file=sys.stderr)1819 def __repr__(self):21 return '<Repo %r>' % self.home20 return "<Repo {}>".format(self.home)212223pass_repo = click.make_pass_decorator(Repo)242526@click.group()28@click.option('--repo-home', envvar='REPO_HOME', default='.repo',29 metavar='PATH', help='Changes the repository folder location.')30@click.option('--config', nargs=2, multiple=True,31 metavar='KEY VALUE', help='Overrides a config key/value pair.')32@click.option('--verbose', '-v', is_flag=True,33 help='Enables verbose mode.')34@click.version_option('1.0')27@click.option(28 "--repo-home",29 envvar="REPO_HOME",30 default=".repo",31 metavar="PATH",32 help="Changes the repository folder location.",33)34@click.option(35 "--config",36 nargs=2,37 multiple=True,38 metavar="KEY VALUE",39 help="Overrides a config key/value pair.",40)41@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.")42@click.version_option("1.0")43@click.pass_context44def cli(ctx, repo_home, config, verbose):45 """Repo is a command line tool that showcases how to build complex46 command line interfaces with Click.
10 unmodified lines
57 ctx.obj.set_config(key, value)585960@cli.command()53@click.argument('src')54@click.argument('dest', required=False)55@click.option('--shallow/--deep', default=False,56 help='Makes a checkout shallow or deep. Deep by default.')57@click.option('--rev', '-r', default='HEAD',58 help='Clone a specific revision instead of HEAD.')61@click.argument("src")62@click.argument("dest", required=False)63@click.option(64 "--shallow/--deep",65 default=False,66 help="Makes a checkout shallow or deep. Deep by default.",67)68@click.option(69 "--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD."70)71@pass_repo72def clone(repo, src, dest, shallow, rev):73 """Clones a repository.74
1 unmodified line
76 is not provided this will automatically use the last path component77 of SRC and create that folder.78 """79 if dest is None:68 dest = posixpath.split(src)[-1] or '.'69 click.echo('Cloning repo %s to %s' % (src, os.path.abspath(dest)))80 dest = posixpath.split(src)[-1] or "."81 click.echo("Cloning repo {} to {}".format(src, os.path.abspath(dest)))82 repo.home = dest83 if shallow:72 click.echo('Making shallow checkout')73 click.echo('Checking out revision %s' % rev)84 click.echo("Making shallow checkout")85 click.echo("Checking out revision {}".format(rev))868788@cli.command()89@click.confirmation_option()
2 unmodified lines
92 """Deletes a repository.9394 This will throw away the current repository.95 """84 click.echo('Destroying repo %s' % repo.home)85 click.echo('Deleted!')96 click.echo("Destroying repo {}".format(repo.home))97 click.echo("Deleted!")9899100@cli.command()89@click.option('--username', prompt=True,90 help='The developer\'s shown username.')91@click.option('--email', prompt='E-Mail',92 help='The developer\'s email address')93@click.password_option(help='The login password.')101@click.option("--username", prompt=True, help="The developer's shown username.")102@click.option("--email", prompt="E-Mail", help="The developer's email address")103@click.password_option(help="The login password.")104@pass_repo105def setuser(repo, username, email, password):106 """Sets the user credentials.107108 This will override the current user config.109 """100 repo.set_config('username', username)101 repo.set_config('email', email)102 repo.set_config('password', '*' * len(password))103 click.echo('Changed credentials.')110 repo.set_config("username", username)111 repo.set_config("email", email)112 repo.set_config("password", "*" * len(password))113 click.echo("Changed credentials.")114115116@cli.command()107@click.option('--message', '-m', multiple=True,108 help='The commit message. If provided multiple times each '109 'argument gets converted into a new line.')110@click.argument('files', nargs=-1, type=click.Path())117@click.option(118 "--message",119 "-m",120 multiple=True,121 help="The commit message. If provided multiple times each"122 " argument gets converted into a new line.",123)124@click.argument("files", nargs=-1, type=click.Path())125@pass_repo126def commit(repo, files, message):127 """Commits outstanding changes.128
3 unmodified lines
132 If a list of files is omitted, all changes reported by "repo status"133 will be committed.134 """135 if not message:122 marker = '# Files to be committed:'123 hint = ['', '', marker, '#']136 marker = "# Files to be committed:"137 hint = ["", "", marker, "#"]138 for file in files:125 hint.append('# U %s' % file)126 message = click.edit('\n'.join(hint))139 hint.append("# U {}".format(file))140 message = click.edit("\n".join(hint))141 if message is None:128 click.echo('Aborted!')142 click.echo("Aborted!")143 return144 msg = message.split(marker)[0].rstrip()145 if not msg:132 click.echo('Aborted! Empty commit message')146 click.echo("Aborted! Empty commit message")147 return148 else:135 msg = '\n'.join(message)136 click.echo('Files to be committed: %s' % (files,))137 click.echo('Commit message:\n' + msg)149 msg = "\n".join(message)150 click.echo("Files to be committed: {}".format(files))151 click.echo("Commit message:\n{}".format(msg))152153140@cli.command(short_help='Copies files.')141@click.option('--force', is_flag=True,142 help='forcibly copy over an existing managed file')143@click.argument('src', nargs=-1, type=click.Path())144@click.argument('dst', type=click.Path())154@cli.command(short_help="Copies files.")155@click.option(156 "--force", is_flag=True, help="forcibly copy over an existing managed file"157)158@click.argument("src", nargs=-1, type=click.Path())159@click.argument("dst", type=click.Path())160@pass_repo161def copy(repo, src, dst, force):162 """Copies one or multiple files to a new location. This copies all163 files from SRC to DST.164 """165 for fn in src:151 click.echo('Copy from %s -> %s' % (fn, dst))166 click.echo("Copy from {} -> {}".format(fn, dst))
modified:examples/repo/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-repo',5 version='0.1',6 py_modules=['repo'],4 name="click-example-repo",5 version="0.1",6 py_modules=["repo"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 repo=repo:cli14 ''',12 """,13)
modified:examples/termui/setup.py+7 added-7 removed
1from setuptools import setup23setup(4 name='click-example-termui',5 version='1.0',6 py_modules=['termui'],4 name="click-example-termui",5 version="1.0",6 py_modules=["termui"],7 include_package_data=True,8 install_requires=[9 'click',9 "click",10 # Colorama is only required for Windows.11 'colorama',11 "colorama",12 ],13 entry_points='''13 entry_points="""14 [console_scripts]15 termui=termui:cli16 ''',16 """,17)
modified:examples/termui/termui.py+71 added-57 removed
1# coding: utf-82import click2import math4import time3import random4import time57try:8 range_type = xrange9except NameError:10 range_type = range6import click789@click.group()10def cli():
3 unmodified lines
1415@cli.command()16def colordemo():17 """Demonstrates ANSI color support."""22 for color in 'red', 'green', 'blue':23 click.echo(click.style('I am colored %s' % color, fg=color))24 click.echo(click.style('I am background colored %s' % color, bg=color))18 for color in "red", "green", "blue":19 click.echo(click.style("I am colored {}".format(color), fg=color))20 click.echo(click.style("I am background colored {}".format(color), bg=color))212223@cli.command()24def pager():25 """Demonstrates using the pager."""26 lines = []31 for x in range_type(200):32 lines.append('%s. Hello World!' % click.style(str(x), fg='green'))33 click.echo_via_pager('\n'.join(lines))27 for x in range(200):28 lines.append("{}. Hello World!".format(click.style(str(x), fg="green")))29 click.echo_via_pager("\n".join(lines))303132@cli.command()37@click.option('--count', default=8000, type=click.IntRange(1, 100000),38 help='The number of items to process.')33@click.option(34 "--count",35 default=8000,36 type=click.IntRange(1, 100000),37 help="The number of items to process.",38)39def progress(count):40 """Demonstrates the progress bar."""41 items = range_type(count)41 items = range(count)4243 def process_slowly(item):44 time.sleep(0.002 * random.random())45
1 unmodified line
47 for item in items:48 if random.random() > 0.3:49 yield item5051 with click.progressbar(items, label='Processing accounts',52 fill_char=click.style('#', fg='green')) as bar:51 with click.progressbar(52 items, label="Processing accounts", fill_char=click.style("#", fg="green")53 ) as bar:54 for item in bar:55 process_slowly(item)5657 def show_item(item):58 if item is not None:58 return 'Item #%d' % item59 return "Item #{}".format(item)6060 with click.progressbar(filter(items), label='Committing transaction',61 fill_char=click.style('#', fg='yellow'),62 item_show_func=show_item) as bar:61 with click.progressbar(62 filter(items),63 label="Committing transaction",64 fill_char=click.style("#", fg="yellow"),65 item_show_func=show_item,66 ) as bar:67 for item in bar:68 process_slowly(item)6966 with click.progressbar(length=count, label='Counting',67 bar_template='%(label)s %(bar)s | %(info)s',68 fill_char=click.style(u'█', fg='cyan'),69 empty_char=' ') as bar:70 with click.progressbar(71 length=count,72 label="Counting",73 bar_template="%(label)s %(bar)s | %(info)s",74 fill_char=click.style(u"█", fg="cyan"),75 empty_char=" ",76 ) as bar:77 for item in bar:78 process_slowly(item)7973 with click.progressbar(length=count, width=0, show_percent=False,74 show_eta=False,75 fill_char=click.style('#', fg='magenta')) as bar:80 with click.progressbar(81 length=count,82 width=0,83 show_percent=False,84 show_eta=False,85 fill_char=click.style("#", fg="magenta"),86 ) as bar:87 for item in bar:88 process_slowly(item)8990 # 'Non-linear progress bar'80 steps = [math.exp( x * 1. / 20) - 1 for x in range(20)]91 steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)]92 count = int(sum(steps))82 with click.progressbar(length=count, show_percent=False,83 label='Slowing progress bar',84 fill_char=click.style(u'█', fg='green')) as bar:93 with click.progressbar(94 length=count,95 show_percent=False,96 label="Slowing progress bar",97 fill_char=click.style(u"█", fg="green"),98 ) as bar:99 for item in steps:100 time.sleep(item)101 bar.update(item)102103104@cli.command()91@click.argument('url')105@click.argument("url")106def open(url):107 """Opens a file or URL In the default application."""108 click.launch(url)109110111@cli.command()98@click.argument('url')112@click.argument("url")113def locate(url):114 """Opens a file or URL In the default application."""115 click.launch(url, locate=True)116117118@cli.command()119def edit():120 """Opens an editor with some text in it."""107 MARKER = '# Everything below is ignored\n'108 message = click.edit('\n\n' + MARKER)121 MARKER = "# Everything below is ignored\n"122 message = click.edit("\n\n{}".format(MARKER))123 if message is not None:110 msg = message.split(MARKER, 1)[0].rstrip('\n')124 msg = message.split(MARKER, 1)[0].rstrip("\n")125 if not msg:112 click.echo('Empty message!')126 click.echo("Empty message!")127 else:114 click.echo('Message:\n' + msg)128 click.echo("Message:\n{}".format(msg))129 else:116 click.echo('You did not enter anything!')130 click.echo("You did not enter anything!")131132133@cli.command()134def clear():
9 unmodified lines
144145@cli.command()146def menu():147 """Shows a simple menu."""134 menu = 'main'148 menu = "main"149 while 1:136 if menu == 'main':137 click.echo('Main menu:')138 click.echo(' d: debug menu')139 click.echo(' q: quit')150 if menu == "main":151 click.echo("Main menu:")152 click.echo(" d: debug menu")153 click.echo(" q: quit")154 char = click.getchar()141 if char == 'd':142 menu = 'debug'143 elif char == 'q':144 menu = 'quit'155 if char == "d":156 menu = "debug"157 elif char == "q":158 menu = "quit"159 else:146 click.echo('Invalid input')147 elif menu == 'debug':148 click.echo('Debug menu')149 click.echo(' b: back')160 click.echo("Invalid input")161 elif menu == "debug":162 click.echo("Debug menu")163 click.echo(" b: back")164 char = click.getchar()151 if char == 'b':152 menu = 'main'165 if char == "b":166 menu = "main"167 else:154 click.echo('Invalid input')155 elif menu == 'quit':168 click.echo("Invalid input")169 elif menu == "quit":170 return
modified:examples/validation/setup.py+6 added-8 removed
1from setuptools import setup23setup(4 name='click-example-validation',5 version='1.0',6 py_modules=['validation'],4 name="click-example-validation",5 version="1.0",6 py_modules=["validation"],7 include_package_data=True,8 install_requires=[9 'click',10 ],11 entry_points='''8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 validation=validation:cli14 ''',12 """,13)
modified:examples/validation/validation.py+23 added-15 removed
1import click23try:4 from urllib import parse as urlparse5except ImportError:6 import urlparse789def validate_count(ctx, param, value):10 if value < 0 or value % 2 != 0:10 raise click.BadParameter('Should be a positive, even integer.')11 raise click.BadParameter("Should be a positive, even integer.")12 return value131415class URL(click.ParamType):15 name = 'url'16 name = "url"1718 def convert(self, value, param, ctx):19 if not isinstance(value, tuple):20 value = urlparse.urlparse(value)20 if value.scheme not in ('http', 'https'):21 self.fail('invalid URL scheme (%s). Only HTTP URLs are '22 'allowed' % value.scheme, param, ctx)21 if value.scheme not in ("http", "https"):22 self.fail(23 "invalid URL scheme ({}). Only HTTP URLs are"24 " allowed".format(value.scheme),25 param,26 ctx,27 )28 return value293031@click.command()27@click.option('--count', default=2, callback=validate_count,28 help='A positive even number.')29@click.option('--foo', help='A mysterious parameter.')30@click.option('--url', help='A URL', type=URL())32@click.option(33 "--count", default=2, callback=validate_count, help="A positive even number."34)35@click.option("--foo", help="A mysterious parameter.")36@click.option("--url", help="A URL", type=URL())37@click.version_option()38def cli(count, foo, url):39 """Validation.4041 This example validates parameters in different ways. It does it42 through callbacks, through a custom type as well as by validating43 manually in the function.44 """39 if foo is not None and foo != 'wat':40 raise click.BadParameter('If a value is provided it needs to be the '41 'value "wat".', param_hint=['--foo'])42 click.echo('count: %s' % count)43 click.echo('foo: %s' % foo)44 click.echo('url: %s' % repr(url))45 if foo is not None and foo != "wat":46 raise click.BadParameter(47 'If a value is provided it needs to be the value "wat".',48 param_hint=["--foo"],49 )50 click.echo("count: {}".format(count))51 click.echo("foo: {}".format(foo))52 click.echo("url: {!r}".format(url))
added:src/click/__init__.py+79 added
1"""2Click is a simple Python module inspired by the stdlib optparse to make3writing command line scripts fun. Unlike other modules, it's based4around a simple API that does not come with too much magic and is5composable.6"""7from .core import Argument8from .core import BaseCommand9from .core import Command10from .core import CommandCollection11from .core import Context12from .core import Group13from .core import MultiCommand14from .core import Option15from .core import Parameter16from .decorators import argument17from .decorators import command18from .decorators import confirmation_option19from .decorators import group20from .decorators import help_option21from .decorators import make_pass_decorator22from .decorators import option23from .decorators import pass_context24from .decorators import pass_obj25from .decorators import password_option26from .decorators import version_option27from .exceptions import Abort28from .exceptions import BadArgumentUsage29from .exceptions import BadOptionUsage30from .exceptions import BadParameter31from .exceptions import ClickException32from .exceptions import FileError33from .exceptions import MissingParameter34from .exceptions import NoSuchOption35from .exceptions import UsageError36from .formatting import HelpFormatter37from .formatting import wrap_text38from .globals import get_current_context39from .parser import OptionParser40from .termui import clear41from .termui import confirm42from .termui import echo_via_pager43from .termui import edit44from .termui import get_terminal_size45from .termui import getchar46from .termui import launch47from .termui import pause48from .termui import progressbar49from .termui import prompt50from .termui import secho51from .termui import style52from .termui import unstyle53from .types import BOOL54from .types import Choice55from .types import DateTime56from .types import File57from .types import FLOAT58from .types import FloatRange59from .types import INT60from .types import IntRange61from .types import ParamType62from .types import Path63from .types import STRING64from .types import Tuple65from .types import UNPROCESSED66from .types import UUID67from .utils import echo68from .utils import format_filename69from .utils import get_app_dir70from .utils import get_binary_stream71from .utils import get_os_args72from .utils import get_text_stream73from .utils import open_file7475# Controls if click should emit the warning about the use of unicode76# literals.77disable_unicode_literals_warning = False7879__version__ = "7.1.dev"
added:src/click/_bashcomplete.py+375 added
1import copy2import os3import re45from .core import Argument6from .core import MultiCommand7from .core import Option8from .parser import split_arg_string9from .types import Choice10from .utils import echo1112try:13 from collections import abc14except ImportError:15 import collections as abc1617WORDBREAK = "="1819# Note, only BASH version 4.4 and later have the nosort option.20COMPLETION_SCRIPT_BASH = """21%(complete_func)s() {22 local IFS=$'\n'23 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\24 COMP_CWORD=$COMP_CWORD \\25 %(autocomplete_var)s=complete $1 ) )26 return 027}2829%(complete_func)setup() {30 local COMPLETION_OPTIONS=""31 local BASH_VERSION_ARR=(${BASH_VERSION//./ })32 # Only BASH version 4.4 and later have the nosort option.33 if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] \34&& [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then35 COMPLETION_OPTIONS="-o nosort"36 fi3738 complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s39}4041%(complete_func)setup42"""4344COMPLETION_SCRIPT_ZSH = """45#compdef %(script_names)s4647%(complete_func)s() {48 local -a completions49 local -a completions_with_descriptions50 local -a response51 (( ! $+commands[%(script_names)s] )) && return 15253 response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\54 COMP_CWORD=$((CURRENT-1)) \\55 %(autocomplete_var)s=\"complete_zsh\" \\56 %(script_names)s )}")5758 for key descr in ${(kv)response}; do59 if [[ "$descr" == "_" ]]; then60 completions+=("$key")61 else62 completions_with_descriptions+=("$key":"$descr")63 fi64 done6566 if [ -n "$completions_with_descriptions" ]; then67 _describe -V unsorted completions_with_descriptions -U68 fi6970 if [ -n "$completions" ]; then71 compadd -U -V unsorted -a completions72 fi73 compstate[insert]="automenu"74}7576compdef %(complete_func)s %(script_names)s77"""7879COMPLETION_SCRIPT_FISH = (80 "complete --no-files --command %(script_names)s --arguments"81 ' "(env %(autocomplete_var)s=complete_fish'82 " COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t)"83 ' %(script_names)s)"'84)8586_completion_scripts = {87 "bash": COMPLETION_SCRIPT_BASH,88 "zsh": COMPLETION_SCRIPT_ZSH,89 "fish": COMPLETION_SCRIPT_FISH,90}9192_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")939495def get_completion_script(prog_name, complete_var, shell):96 cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))97 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)98 return (99 script100 % {101 "complete_func": "_{}_completion".format(cf_name),102 "script_names": prog_name,103 "autocomplete_var": complete_var,104 }105 ).strip() + ";"106107108def resolve_ctx(cli, prog_name, args):109 """Parse into a hierarchy of contexts. Contexts are connected110 through the parent variable.111112 :param cli: command definition113 :param prog_name: the program that is running114 :param args: full list of args115 :return: the final context/command parsed116 """117 ctx = cli.make_context(prog_name, args, resilient_parsing=True)118 args = ctx.protected_args + ctx.args119 while args:120 if isinstance(ctx.command, MultiCommand):121 if not ctx.command.chain:122 cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)123 if cmd is None:124 return ctx125 ctx = cmd.make_context(126 cmd_name, args, parent=ctx, resilient_parsing=True127 )128 args = ctx.protected_args + ctx.args129 else:130 # Walk chained subcommand contexts saving the last one.131 while args:132 cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)133 if cmd is None:134 return ctx135 sub_ctx = cmd.make_context(136 cmd_name,137 args,138 parent=ctx,139 allow_extra_args=True,140 allow_interspersed_args=False,141 resilient_parsing=True,142 )143 args = sub_ctx.args144 ctx = sub_ctx145 args = sub_ctx.protected_args + sub_ctx.args146 else:147 break148 return ctx149150151def start_of_option(param_str):152 """153 :param param_str: param_str to check154 :return: whether or not this is the start of an option declaration155 (i.e. starts "-" or "--")156 """157 return param_str and param_str[:1] == "-"158159160def is_incomplete_option(all_args, cmd_param):161 """162 :param all_args: the full original list of args supplied163 :param cmd_param: the current command parameter164 :return: whether or not the last option declaration (i.e. starts165 "-" or "--") is incomplete and corresponds to this cmd_param. In166 other words whether this cmd_param option can still accept167 values168 """169 if not isinstance(cmd_param, Option):170 return False171 if cmd_param.is_flag:172 return False173 last_option = None174 for index, arg_str in enumerate(175 reversed([arg for arg in all_args if arg != WORDBREAK])176 ):177 if index + 1 > cmd_param.nargs:178 break179 if start_of_option(arg_str):180 last_option = arg_str181182 return True if last_option and last_option in cmd_param.opts else False183184185def is_incomplete_argument(current_params, cmd_param):186 """187 :param current_params: the current params and values for this188 argument as already entered189 :param cmd_param: the current command parameter190 :return: whether or not the last argument is incomplete and191 corresponds to this cmd_param. In other words whether or not the192 this cmd_param argument can still accept values193 """194 if not isinstance(cmd_param, Argument):195 return False196 current_param_values = current_params[cmd_param.name]197 if current_param_values is None:198 return True199 if cmd_param.nargs == -1:200 return True201 if (202 isinstance(current_param_values, abc.Iterable)203 and cmd_param.nargs > 1204 and len(current_param_values) < cmd_param.nargs205 ):206 return True207 return False208209210def get_user_autocompletions(ctx, args, incomplete, cmd_param):211 """212 :param ctx: context associated with the parsed command213 :param args: full list of args214 :param incomplete: the incomplete text to autocomplete215 :param cmd_param: command definition216 :return: all the possible user-specified completions for the param217 """218 results = []219 if isinstance(cmd_param.type, Choice):220 # Choices don't support descriptions.221 results = [222 (c, None) for c in cmd_param.type.choices if str(c).startswith(incomplete)223 ]224 elif cmd_param.autocompletion is not None:225 dynamic_completions = cmd_param.autocompletion(226 ctx=ctx, args=args, incomplete=incomplete227 )228 results = [229 c if isinstance(c, tuple) else (c, None) for c in dynamic_completions230 ]231 return results232233234def get_visible_commands_starting_with(ctx, starts_with):235 """236 :param ctx: context associated with the parsed command237 :starts_with: string that visible commands must start with.238 :return: all visible (not hidden) commands that start with starts_with.239 """240 for c in ctx.command.list_commands(ctx):241 if c.startswith(starts_with):242 command = ctx.command.get_command(ctx, c)243 if not command.hidden:244 yield command245246247def add_subcommand_completions(ctx, incomplete, completions_out):248 # Add subcommand completions.249 if isinstance(ctx.command, MultiCommand):250 completions_out.extend(251 [252 (c.name, c.get_short_help_str())253 for c in get_visible_commands_starting_with(ctx, incomplete)254 ]255 )256257 # Walk up the context list and add any other completion258 # possibilities from chained commands259 while ctx.parent is not None:260 ctx = ctx.parent261 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:262 remaining_commands = [263 c264 for c in get_visible_commands_starting_with(ctx, incomplete)265 if c.name not in ctx.protected_args266 ]267 completions_out.extend(268 [(c.name, c.get_short_help_str()) for c in remaining_commands]269 )270271272def get_choices(cli, prog_name, args, incomplete):273 """274 :param cli: command definition275 :param prog_name: the program that is running276 :param args: full list of args277 :param incomplete: the incomplete text to autocomplete278 :return: all the possible completions for the incomplete279 """280 all_args = copy.deepcopy(args)281282 ctx = resolve_ctx(cli, prog_name, args)283 if ctx is None:284 return []285286 has_double_dash = "--" in all_args287288 # In newer versions of bash long opts with '='s are partitioned, but289 # it's easier to parse without the '='290 if start_of_option(incomplete) and WORDBREAK in incomplete:291 partition_incomplete = incomplete.partition(WORDBREAK)292 all_args.append(partition_incomplete[0])293 incomplete = partition_incomplete[2]294 elif incomplete == WORDBREAK:295 incomplete = ""296297 completions = []298 if not has_double_dash and start_of_option(incomplete):299 # completions for partial options300 for param in ctx.command.params:301 if isinstance(param, Option) and not param.hidden:302 param_opts = [303 param_opt304 for param_opt in param.opts + param.secondary_opts305 if param_opt not in all_args or param.multiple306 ]307 completions.extend(308 [(o, param.help) for o in param_opts if o.startswith(incomplete)]309 )310 return completions311 # completion for option values from user supplied values312 for param in ctx.command.params:313 if is_incomplete_option(all_args, param):314 return get_user_autocompletions(ctx, all_args, incomplete, param)315 # completion for argument values from user supplied values316 for param in ctx.command.params:317 if is_incomplete_argument(ctx.params, param):318 return get_user_autocompletions(ctx, all_args, incomplete, param)319320 add_subcommand_completions(ctx, incomplete, completions)321 # Sort before returning so that proper ordering can be enforced in custom types.322 return sorted(completions)323324325def do_complete(cli, prog_name, include_descriptions):326 cwords = split_arg_string(os.environ["COMP_WORDS"])327 cword = int(os.environ["COMP_CWORD"])328 args = cwords[1:cword]329 try:330 incomplete = cwords[cword]331 except IndexError:332 incomplete = ""333334 for item in get_choices(cli, prog_name, args, incomplete):335 echo(item[0])336 if include_descriptions:337 # ZSH has trouble dealing with empty array parameters when338 # returned from commands, use '_' to indicate no description339 # is present.340 echo(item[1] if item[1] else "_")341342 return True343344345def do_complete_fish(cli, prog_name):346 cwords = split_arg_string(os.environ["COMP_WORDS"])347 incomplete = os.environ["COMP_CWORD"]348 args = cwords[1:]349350 for item in get_choices(cli, prog_name, args, incomplete):351 if item[1]:352 echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))353 else:354 echo(item[0])355356 return True357358359def bashcomplete(cli, prog_name, complete_var, complete_instr):360 if "_" in complete_instr:361 command, shell = complete_instr.split("_", 1)362 else:363 command = complete_instr364 shell = "bash"365366 if command == "source":367 echo(get_completion_script(prog_name, complete_var, shell))368 return True369 elif command == "complete":370 if shell == "fish":371 return do_complete_fish(cli, prog_name)372 elif shell in {"bash", "zsh"}:373 return do_complete(cli, prog_name, shell == "zsh")374375 return False
added:src/click/_compat.py+790 added
1# flake8: noqa2import codecs3import io4import os5import re6import sys7from weakref import WeakKeyDictionary89PY2 = sys.version_info[0] == 210CYGWIN = sys.platform.startswith("cygwin")11MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)12# Determine local App Engine environment, per Google's own suggestion13APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(14 "SERVER_SOFTWARE", ""15)16WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS217DEFAULT_COLUMNS = 80181920_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")212223def get_filesystem_encoding():24 return sys.getfilesystemencoding() or sys.getdefaultencoding()252627def _make_text_stream(28 stream, encoding, errors, force_readable=False, force_writable=False29):30 if encoding is None:31 encoding = get_best_encoding(stream)32 if errors is None:33 errors = "replace"34 return _NonClosingTextIOWrapper(35 stream,36 encoding,37 errors,38 line_buffering=True,39 force_readable=force_readable,40 force_writable=force_writable,41 )424344def is_ascii_encoding(encoding):45 """Checks if a given encoding is ascii."""46 try:47 return codecs.lookup(encoding).name == "ascii"48 except LookupError:49 return False505152def get_best_encoding(stream):53 """Returns the default stream encoding if not found."""54 rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()55 if is_ascii_encoding(rv):56 return "utf-8"57 return rv585960class _NonClosingTextIOWrapper(io.TextIOWrapper):61 def __init__(62 self,63 stream,64 encoding,65 errors,66 force_readable=False,67 force_writable=False,68 **extra69 ):70 self._stream = stream = _FixupStream(stream, force_readable, force_writable)71 io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)7273 # The io module is a place where the Python 3 text behavior74 # was forced upon Python 2, so we need to unbreak75 # it to look like Python 2.76 if PY2:7778 def write(self, x):79 if isinstance(x, str) or is_bytes(x):80 try:81 self.flush()82 except Exception:83 pass84 return self.buffer.write(str(x))85 return io.TextIOWrapper.write(self, x)8687 def writelines(self, lines):88 for line in lines:89 self.write(line)9091 def __del__(self):92 try:93 self.detach()94 except Exception:95 pass9697 def isatty(self):98 # https://bitbucket.org/pypy/pypy/issue/180399 return self._stream.isatty()100101102class _FixupStream(object):103 """The new io interface needs more from streams than streams104 traditionally implement. As such, this fix-up code is necessary in105 some circumstances.106107 The forcing of readable and writable flags are there because some tools108 put badly patched objects on sys (one such offender are certain version109 of jupyter notebook).110 """111112 def __init__(self, stream, force_readable=False, force_writable=False):113 self._stream = stream114 self._force_readable = force_readable115 self._force_writable = force_writable116117 def __getattr__(self, name):118 return getattr(self._stream, name)119120 def read1(self, size):121 f = getattr(self._stream, "read1", None)122 if f is not None:123 return f(size)124 # We only dispatch to readline instead of read in Python 2 as we125 # do not want cause problems with the different implementation126 # of line buffering.127 if PY2:128 return self._stream.readline(size)129 return self._stream.read(size)130131 def readable(self):132 if self._force_readable:133 return True134 x = getattr(self._stream, "readable", None)135 if x is not None:136 return x()137 try:138 self._stream.read(0)139 except Exception:140 return False141 return True142143 def writable(self):144 if self._force_writable:145 return True146 x = getattr(self._stream, "writable", None)147 if x is not None:148 return x()149 try:150 self._stream.write("")151 except Exception:152 try:153 self._stream.write(b"")154 except Exception:155 return False156 return True157158 def seekable(self):159 x = getattr(self._stream, "seekable", None)160 if x is not None:161 return x()162 try:163 self._stream.seek(self._stream.tell())164 except Exception:165 return False166 return True167168169if PY2:170 text_type = unicode171 raw_input = raw_input172 string_types = (str, unicode)173 int_types = (int, long)174 iteritems = lambda x: x.iteritems()175 range_type = xrange176177 from pipes import quote as shlex_quote178179 def is_bytes(x):180 return isinstance(x, (buffer, bytearray))181182 _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")183184 # For Windows, we need to force stdout/stdin/stderr to binary if it's185 # fetched for that. This obviously is not the most correct way to do186 # it as it changes global state. Unfortunately, there does not seem to187 # be a clear better way to do it as just reopening the file in binary188 # mode does not change anything.189 #190 # An option would be to do what Python 3 does and to open the file as191 # binary only, patch it back to the system, and then use a wrapper192 # stream that converts newlines. It's not quite clear what's the193 # correct option here.194 #195 # This code also lives in _winconsole for the fallback to the console196 # emulation stream.197 #198 # There are also Windows environments where the `msvcrt` module is not199 # available (which is why we use try-catch instead of the WIN variable200 # here), such as the Google App Engine development server on Windows. In201 # those cases there is just nothing we can do.202 def set_binary_mode(f):203 return f204205 try:206 import msvcrt207 except ImportError:208 pass209 else:210211 def set_binary_mode(f):212 try:213 fileno = f.fileno()214 except Exception:215 pass216 else:217 msvcrt.setmode(fileno, os.O_BINARY)218 return f219220 try:221 import fcntl222 except ImportError:223 pass224 else:225226 def set_binary_mode(f):227 try:228 fileno = f.fileno()229 except Exception:230 pass231 else:232 flags = fcntl.fcntl(fileno, fcntl.F_GETFL)233 fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)234 return f235236 def isidentifier(x):237 return _identifier_re.search(x) is not None238239 def get_binary_stdin():240 return set_binary_mode(sys.stdin)241242 def get_binary_stdout():243 _wrap_std_stream("stdout")244 return set_binary_mode(sys.stdout)245246 def get_binary_stderr():247 _wrap_std_stream("stderr")248 return set_binary_mode(sys.stderr)249250 def get_text_stdin(encoding=None, errors=None):251 rv = _get_windows_console_stream(sys.stdin, encoding, errors)252 if rv is not None:253 return rv254 return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)255256 def get_text_stdout(encoding=None, errors=None):257 _wrap_std_stream("stdout")258 rv = _get_windows_console_stream(sys.stdout, encoding, errors)259 if rv is not None:260 return rv261 return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)262263 def get_text_stderr(encoding=None, errors=None):264 _wrap_std_stream("stderr")265 rv = _get_windows_console_stream(sys.stderr, encoding, errors)266 if rv is not None:267 return rv268 return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)269270 def filename_to_ui(value):271 if isinstance(value, bytes):272 value = value.decode(get_filesystem_encoding(), "replace")273 return value274275276else:277 import io278279 text_type = str280 raw_input = input281 string_types = (str,)282 int_types = (int,)283 range_type = range284 isidentifier = lambda x: x.isidentifier()285 iteritems = lambda x: iter(x.items())286287 from shlex import quote as shlex_quote288289 def is_bytes(x):290 return isinstance(x, (bytes, memoryview, bytearray))291292 def _is_binary_reader(stream, default=False):293 try:294 return isinstance(stream.read(0), bytes)295 except Exception:296 return default297 # This happens in some cases where the stream was already298 # closed. In this case, we assume the default.299300 def _is_binary_writer(stream, default=False):301 try:302 stream.write(b"")303 except Exception:304 try:305 stream.write("")306 return False307 except Exception:308 pass309 return default310 return True311312 def _find_binary_reader(stream):313 # We need to figure out if the given stream is already binary.314 # This can happen because the official docs recommend detaching315 # the streams to get binary streams. Some code might do this, so316 # we need to deal with this case explicitly.317 if _is_binary_reader(stream, False):318 return stream319320 buf = getattr(stream, "buffer", None)321322 # Same situation here; this time we assume that the buffer is323 # actually binary in case it's closed.324 if buf is not None and _is_binary_reader(buf, True):325 return buf326327 def _find_binary_writer(stream):328 # We need to figure out if the given stream is already binary.329 # This can happen because the official docs recommend detaching330 # the streams to get binary streams. Some code might do this, so331 # we need to deal with this case explicitly.332 if _is_binary_writer(stream, False):333 return stream334335 buf = getattr(stream, "buffer", None)336337 # Same situation here; this time we assume that the buffer is338 # actually binary in case it's closed.339 if buf is not None and _is_binary_writer(buf, True):340 return buf341342 def _stream_is_misconfigured(stream):343 """A stream is misconfigured if its encoding is ASCII."""344 # If the stream does not have an encoding set, we assume it's set345 # to ASCII. This appears to happen in certain unittest346 # environments. It's not quite clear what the correct behavior is347 # but this at least will force Click to recover somehow.348 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")349350 def _is_compat_stream_attr(stream, attr, value):351 """A stream attribute is compatible if it is equal to the352 desired value or the desired value is unset and the attribute353 has a value.354 """355 stream_value = getattr(stream, attr, None)356 return stream_value == value or (value is None and stream_value is not None)357358 def _is_compatible_text_stream(stream, encoding, errors):359 """Check if a stream's encoding and errors attributes are360 compatible with the desired values.361 """362 return _is_compat_stream_attr(363 stream, "encoding", encoding364 ) and _is_compat_stream_attr(stream, "errors", errors)365366 def _force_correct_text_stream(367 text_stream,368 encoding,369 errors,370 is_binary,371 find_binary,372 force_readable=False,373 force_writable=False,374 ):375 if is_binary(text_stream, False):376 binary_reader = text_stream377 else:378 # If the stream looks compatible, and won't default to a379 # misconfigured ascii encoding, return it as-is.380 if _is_compatible_text_stream(text_stream, encoding, errors) and not (381 encoding is None and _stream_is_misconfigured(text_stream)382 ):383 return text_stream384385 # Otherwise, get the underlying binary reader.386 binary_reader = find_binary(text_stream)387388 # If that's not possible, silently use the original reader389 # and get mojibake instead of exceptions.390 if binary_reader is None:391 return text_stream392393 # Default errors to replace instead of strict in order to get394 # something that works.395 if errors is None:396 errors = "replace"397398 # Wrap the binary stream in a text stream with the correct399 # encoding parameters.400 return _make_text_stream(401 binary_reader,402 encoding,403 errors,404 force_readable=force_readable,405 force_writable=force_writable,406 )407408 def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):409 return _force_correct_text_stream(410 text_reader,411 encoding,412 errors,413 _is_binary_reader,414 _find_binary_reader,415 force_readable=force_readable,416 )417418 def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):419 return _force_correct_text_stream(420 text_writer,421 encoding,422 errors,423 _is_binary_writer,424 _find_binary_writer,425 force_writable=force_writable,426 )427428 def get_binary_stdin():429 reader = _find_binary_reader(sys.stdin)430 if reader is None:431 raise RuntimeError("Was not able to determine binary stream for sys.stdin.")432 return reader433434 def get_binary_stdout():435 writer = _find_binary_writer(sys.stdout)436 if writer is None:437 raise RuntimeError(438 "Was not able to determine binary stream for sys.stdout."439 )440 return writer441442 def get_binary_stderr():443 writer = _find_binary_writer(sys.stderr)444 if writer is None:445 raise RuntimeError(446 "Was not able to determine binary stream for sys.stderr."447 )448 return writer449450 def get_text_stdin(encoding=None, errors=None):451 rv = _get_windows_console_stream(sys.stdin, encoding, errors)452 if rv is not None:453 return rv454 return _force_correct_text_reader(455 sys.stdin, encoding, errors, force_readable=True456 )457458 def get_text_stdout(encoding=None, errors=None):459 rv = _get_windows_console_stream(sys.stdout, encoding, errors)460 if rv is not None:461 return rv462 return _force_correct_text_writer(463 sys.stdout, encoding, errors, force_writable=True464 )465466 def get_text_stderr(encoding=None, errors=None):467 rv = _get_windows_console_stream(sys.stderr, encoding, errors)468 if rv is not None:469 return rv470 return _force_correct_text_writer(471 sys.stderr, encoding, errors, force_writable=True472 )473474 def filename_to_ui(value):475 if isinstance(value, bytes):476 value = value.decode(get_filesystem_encoding(), "replace")477 else:478 value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")479 return value480481482def get_streerror(e, default=None):483 if hasattr(e, "strerror"):484 msg = e.strerror485 else:486 if default is not None:487 msg = default488 else:489 msg = str(e)490 if isinstance(msg, bytes):491 msg = msg.decode("utf-8", "replace")492 return msg493494495def _wrap_io_open(file, mode, encoding, errors):496 """On Python 2, :func:`io.open` returns a text file wrapper that497 requires passing ``unicode`` to ``write``. Need to open the file in498 binary mode then wrap it in a subclass that can write ``str`` and499 ``unicode``.500501 Also handles not passing ``encoding`` and ``errors`` in binary mode.502 """503 binary = "b" in mode504505 if binary:506 kwargs = {}507 else:508 kwargs = {"encoding": encoding, "errors": errors}509510 if not PY2 or binary:511 return io.open(file, mode, **kwargs)512513 f = io.open(file, "{}b".format(mode.replace("t", "")))514 return _make_text_stream(f, **kwargs)515516517def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):518 binary = "b" in mode519520 # Standard streams first. These are simple because they don't need521 # special handling for the atomic flag. It's entirely ignored.522 if filename == "-":523 if any(m in mode for m in ["w", "a", "x"]):524 if binary:525 return get_binary_stdout(), False526 return get_text_stdout(encoding=encoding, errors=errors), False527 if binary:528 return get_binary_stdin(), False529 return get_text_stdin(encoding=encoding, errors=errors), False530531 # Non-atomic writes directly go out through the regular open functions.532 if not atomic:533 return _wrap_io_open(filename, mode, encoding, errors), True534535 # Some usability stuff for atomic writes536 if "a" in mode:537 raise ValueError(538 "Appending to an existing file is not supported, because that"539 " would involve an expensive `copy`-operation to a temporary"540 " file. Open the file in normal `w`-mode and copy explicitly"541 " if that's what you're after."542 )543 if "x" in mode:544 raise ValueError("Use the `overwrite`-parameter instead.")545 if "w" not in mode:546 raise ValueError("Atomic writes only make sense with `w`-mode.")547548 # Atomic writes are more complicated. They work by opening a file549 # as a proxy in the same folder and then using the fdopen550 # functionality to wrap it in a Python file. Then we wrap it in an551 # atomic file that moves the file over on close.552 import errno553 import random554555 try:556 perm = os.stat(filename).st_mode557 except OSError:558 perm = None559560 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL561562 if binary:563 flags |= getattr(os, "O_BINARY", 0)564565 while True:566 tmp_filename = os.path.join(567 os.path.dirname(filename),568 ".__atomic-write{:08x}".format(random.randrange(1 << 32)),569 )570 try:571 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)572 break573 except OSError as e:574 if e.errno == errno.EEXIST or (575 os.name == "nt"576 and e.errno == errno.EACCES577 and os.path.isdir(e.filename)578 and os.access(e.filename, os.W_OK)579 ):580 continue581 raise582583 if perm is not None:584 os.chmod(tmp_filename, perm) # in case perm includes bits in umask585586 f = _wrap_io_open(fd, mode, encoding, errors)587 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True588589590# Used in a destructor call, needs extra protection from interpreter cleanup.591if hasattr(os, "replace"):592 _replace = os.replace593 _can_replace = True594else:595 _replace = os.rename596 _can_replace = not WIN597598599class _AtomicFile(object):600 def __init__(self, f, tmp_filename, real_filename):601 self._f = f602 self._tmp_filename = tmp_filename603 self._real_filename = real_filename604 self.closed = False605606 @property607 def name(self):608 return self._real_filename609610 def close(self, delete=False):611 if self.closed:612 return613 self._f.close()614 if not _can_replace:615 try:616 os.remove(self._real_filename)617 except OSError:618 pass619 _replace(self._tmp_filename, self._real_filename)620 self.closed = True621622 def __getattr__(self, name):623 return getattr(self._f, name)624625 def __enter__(self):626 return self627628 def __exit__(self, exc_type, exc_value, tb):629 self.close(delete=exc_type is not None)630631 def __repr__(self):632 return repr(self._f)633634635auto_wrap_for_ansi = None636colorama = None637get_winterm_size = None638639640def strip_ansi(value):641 return _ansi_re.sub("", value)642643644def _is_jupyter_kernel_output(stream):645 if WIN:646 # TODO: Couldn't test on Windows, should't try to support until647 # someone tests the details wrt colorama.648 return649650 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):651 stream = stream._stream652653 return stream.__class__.__module__.startswith("ipykernel.")654655656def should_strip_ansi(stream=None, color=None):657 if color is None:658 if stream is None:659 stream = sys.stdin660 return not isatty(stream) and not _is_jupyter_kernel_output(stream)661 return not color662663664# If we're on Windows, we provide transparent integration through665# colorama. This will make ANSI colors through the echo function666# work automatically.667if WIN:668 # Windows has a smaller terminal669 DEFAULT_COLUMNS = 79670671 from ._winconsole import _get_windows_console_stream, _wrap_std_stream672673 def _get_argv_encoding():674 import locale675676 return locale.getpreferredencoding()677678 if PY2:679680 def raw_input(prompt=""):681 sys.stderr.flush()682 if prompt:683 stdout = _default_text_stdout()684 stdout.write(prompt)685 stdin = _default_text_stdin()686 return stdin.readline().rstrip("\r\n")687688 try:689 import colorama690 except ImportError:691 pass692 else:693 _ansi_stream_wrappers = WeakKeyDictionary()694695 def auto_wrap_for_ansi(stream, color=None):696 """This function wraps a stream so that calls through colorama697 are issued to the win32 console API to recolor on demand. It698 also ensures to reset the colors if a write call is interrupted699 to not destroy the console afterwards.700 """701 try:702 cached = _ansi_stream_wrappers.get(stream)703 except Exception:704 cached = None705 if cached is not None:706 return cached707 strip = should_strip_ansi(stream, color)708 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)709 rv = ansi_wrapper.stream710 _write = rv.write711712 def _safe_write(s):713 try:714 return _write(s)715 except:716 ansi_wrapper.reset_all()717 raise718719 rv.write = _safe_write720 try:721 _ansi_stream_wrappers[stream] = rv722 except Exception:723 pass724 return rv725726 def get_winterm_size():727 win = colorama.win32.GetConsoleScreenBufferInfo(728 colorama.win32.STDOUT729 ).srWindow730 return win.Right - win.Left, win.Bottom - win.Top731732733else:734735 def _get_argv_encoding():736 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()737738 _get_windows_console_stream = lambda *x: None739 _wrap_std_stream = lambda *x: None740741742def term_len(x):743 return len(strip_ansi(x))744745746def isatty(stream):747 try:748 return stream.isatty()749 except Exception:750 return False751752753def _make_cached_stream_func(src_func, wrapper_func):754 cache = WeakKeyDictionary()755756 def func():757 stream = src_func()758 try:759 rv = cache.get(stream)760 except Exception:761 rv = None762 if rv is not None:763 return rv764 rv = wrapper_func()765 try:766 stream = src_func() # In case wrapper_func() modified the stream767 cache[stream] = rv768 except Exception:769 pass770 return rv771772 return func773774775_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)776_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)777_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)778779780binary_streams = {781 "stdin": get_binary_stdin,782 "stdout": get_binary_stdout,783 "stderr": get_binary_stderr,784}785786text_streams = {787 "stdin": get_text_stdin,788 "stdout": get_text_stdout,789 "stderr": get_text_stderr,790}
added:src/click/_termui_impl.py+680 added
1# -*- coding: utf-8 -*-2"""3This module contains implementations for the termui module. To keep the4import time of Click down, some infrequently used functionality is5placed in this module and only imported as needed.6"""7import contextlib8import math9import os10import sys11import time1213from ._compat import _default_text_stdout14from ._compat import CYGWIN15from ._compat import get_best_encoding16from ._compat import int_types17from ._compat import isatty18from ._compat import open_stream19from ._compat import range_type20from ._compat import shlex_quote21from ._compat import strip_ansi22from ._compat import term_len23from ._compat import WIN24from .exceptions import ClickException25from .utils import echo2627if os.name == "nt":28 BEFORE_BAR = "\r"29 AFTER_BAR = "\n"30else:31 BEFORE_BAR = "\r\033[?25l"32 AFTER_BAR = "\033[?25h\n"333435def _length_hint(obj):36 """Returns the length hint of an object."""37 try:38 return len(obj)39 except (AttributeError, TypeError):40 try:41 get_hint = type(obj).__length_hint__42 except AttributeError:43 return None44 try:45 hint = get_hint(obj)46 except TypeError:47 return None48 if hint is NotImplemented or not isinstance(hint, int_types) or hint < 0:49 return None50 return hint515253class ProgressBar(object):54 def __init__(55 self,56 iterable,57 length=None,58 fill_char="#",59 empty_char=" ",60 bar_template="%(bar)s",61 info_sep=" ",62 show_eta=True,63 show_percent=None,64 show_pos=False,65 item_show_func=None,66 label=None,67 file=None,68 color=None,69 width=30,70 ):71 self.fill_char = fill_char72 self.empty_char = empty_char73 self.bar_template = bar_template74 self.info_sep = info_sep75 self.show_eta = show_eta76 self.show_percent = show_percent77 self.show_pos = show_pos78 self.item_show_func = item_show_func79 self.label = label or ""80 if file is None:81 file = _default_text_stdout()82 self.file = file83 self.color = color84 self.width = width85 self.autowidth = width == 08687 if length is None:88 length = _length_hint(iterable)89 if iterable is None:90 if length is None:91 raise TypeError("iterable or length is required")92 iterable = range_type(length)93 self.iter = iter(iterable)94 self.length = length95 self.length_known = length is not None96 self.pos = 097 self.avg = []98 self.start = self.last_eta = time.time()99 self.eta_known = False100 self.finished = False101 self.max_width = None102 self.entered = False103 self.current_item = None104 self.is_hidden = not isatty(self.file)105 self._last_line = None106 self.short_limit = 0.5107108 def __enter__(self):109 self.entered = True110 self.render_progress()111 return self112113 def __exit__(self, exc_type, exc_value, tb):114 self.render_finish()115116 def __iter__(self):117 if not self.entered:118 raise RuntimeError("You need to use progress bars in a with block.")119 self.render_progress()120 return self.generator()121122 def __next__(self):123 # Iteration is defined in terms of a generator function,124 # returned by iter(self); use that to define next(). This works125 # because `self.iter` is an iterable consumed by that generator,126 # so it is re-entry safe. Calling `next(self.generator())`127 # twice works and does "what you want".128 return next(iter(self))129130 # Python 2 compat131 next = __next__132133 def is_fast(self):134 return time.time() - self.start <= self.short_limit135136 def render_finish(self):137 if self.is_hidden or self.is_fast():138 return139 self.file.write(AFTER_BAR)140 self.file.flush()141142 @property143 def pct(self):144 if self.finished:145 return 1.0146 return min(self.pos / (float(self.length) or 1), 1.0)147148 @property149 def time_per_iteration(self):150 if not self.avg:151 return 0.0152 return sum(self.avg) / float(len(self.avg))153154 @property155 def eta(self):156 if self.length_known and not self.finished:157 return self.time_per_iteration * (self.length - self.pos)158 return 0.0159160 def format_eta(self):161 if self.eta_known:162 t = int(self.eta)163 seconds = t % 60164 t //= 60165 minutes = t % 60166 t //= 60167 hours = t % 24168 t //= 24169 if t > 0:170 return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds)171 else:172 return "{:02}:{:02}:{:02}".format(hours, minutes, seconds)173 return ""174175 def format_pos(self):176 pos = str(self.pos)177 if self.length_known:178 pos += "/{}".format(self.length)179 return pos180181 def format_pct(self):182 return "{: 4}%".format(int(self.pct * 100))[1:]183184 def format_bar(self):185 if self.length_known:186 bar_length = int(self.pct * self.width)187 bar = self.fill_char * bar_length188 bar += self.empty_char * (self.width - bar_length)189 elif self.finished:190 bar = self.fill_char * self.width191 else:192 bar = list(self.empty_char * (self.width or 1))193 if self.time_per_iteration != 0:194 bar[195 int(196 (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)197 * self.width198 )199 ] = self.fill_char200 bar = "".join(bar)201 return bar202203 def format_progress_line(self):204 show_percent = self.show_percent205206 info_bits = []207 if self.length_known and show_percent is None:208 show_percent = not self.show_pos209210 if self.show_pos:211 info_bits.append(self.format_pos())212 if show_percent:213 info_bits.append(self.format_pct())214 if self.show_eta and self.eta_known and not self.finished:215 info_bits.append(self.format_eta())216 if self.item_show_func is not None:217 item_info = self.item_show_func(self.current_item)218 if item_info is not None:219 info_bits.append(item_info)220221 return (222 self.bar_template223 % {224 "label": self.label,225 "bar": self.format_bar(),226 "info": self.info_sep.join(info_bits),227 }228 ).rstrip()229230 def render_progress(self):231 from .termui import get_terminal_size232233 if self.is_hidden:234 return235236 buf = []237 # Update width in case the terminal has been resized238 if self.autowidth:239 old_width = self.width240 self.width = 0241 clutter_length = term_len(self.format_progress_line())242 new_width = max(0, get_terminal_size()[0] - clutter_length)243 if new_width < old_width:244 buf.append(BEFORE_BAR)245 buf.append(" " * self.max_width)246 self.max_width = new_width247 self.width = new_width248249 clear_width = self.width250 if self.max_width is not None:251 clear_width = self.max_width252253 buf.append(BEFORE_BAR)254 line = self.format_progress_line()255 line_len = term_len(line)256 if self.max_width is None or self.max_width < line_len:257 self.max_width = line_len258259 buf.append(line)260 buf.append(" " * (clear_width - line_len))261 line = "".join(buf)262 # Render the line only if it changed.263264 if line != self._last_line and not self.is_fast():265 self._last_line = line266 echo(line, file=self.file, color=self.color, nl=False)267 self.file.flush()268269 def make_step(self, n_steps):270 self.pos += n_steps271 if self.length_known and self.pos >= self.length:272 self.finished = True273274 if (time.time() - self.last_eta) < 1.0:275 return276277 self.last_eta = time.time()278279 # self.avg is a rolling list of length <= 7 of steps where steps are280 # defined as time elapsed divided by the total progress through281 # self.length.282 if self.pos:283 step = (time.time() - self.start) / self.pos284 else:285 step = time.time() - self.start286287 self.avg = self.avg[-6:] + [step]288289 self.eta_known = self.length_known290291 def update(self, n_steps, current_item=None):292 """Update the progress bar by advancing a specified number of293 steps, and optionally set the ``current_item`` for this new294 position.295296 :param n_steps: Number of steps to advance.297 :param current_item: Optional item to set as ``current_item``298 for the updated position.299300 .. versionadded:: 8.0301 Added the ``current_item`` optional parameter.302 """303 self.make_step(n_steps)304 if current_item is not None:305 self.current_item = current_item306 self.render_progress()307308 def finish(self):309 self.eta_known = 0310 self.current_item = None311 self.finished = True312313 def generator(self):314 """Return a generator which yields the items added to the bar315 during construction, and updates the progress bar *after* the316 yielded block returns.317 """318 # WARNING: the iterator interface for `ProgressBar` relies on319 # this and only works because this is a simple generator which320 # doesn't create or manage additional state. If this function321 # changes, the impact should be evaluated both against322 # `iter(bar)` and `next(bar)`. `next()` in particular may call323 # `self.generator()` repeatedly, and this must remain safe in324 # order for that interface to work.325 if not self.entered:326 raise RuntimeError("You need to use progress bars in a with block.")327328 if self.is_hidden:329 for rv in self.iter:330 yield rv331 else:332 for rv in self.iter:333 self.current_item = rv334 yield rv335 self.update(1)336 self.finish()337 self.render_progress()338339340def pager(generator, color=None):341 """Decide what method to use for paging through text."""342 stdout = _default_text_stdout()343 if not isatty(sys.stdin) or not isatty(stdout):344 return _nullpager(stdout, generator, color)345 pager_cmd = (os.environ.get("PAGER", None) or "").strip()346 if pager_cmd:347 if WIN:348 return _tempfilepager(generator, pager_cmd, color)349 return _pipepager(generator, pager_cmd, color)350 if os.environ.get("TERM") in ("dumb", "emacs"):351 return _nullpager(stdout, generator, color)352 if WIN or sys.platform.startswith("os2"):353 return _tempfilepager(generator, "more <", color)354 if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:355 return _pipepager(generator, "less", color)356357 import tempfile358359 fd, filename = tempfile.mkstemp()360 os.close(fd)361 try:362 if (363 hasattr(os, "system")364 and os.system("more {}".format(shlex_quote(filename))) == 0365 ):366 return _pipepager(generator, "more", color)367 return _nullpager(stdout, generator, color)368 finally:369 os.unlink(filename)370371372def _pipepager(generator, cmd, color):373 """Page through text by feeding it to another program. Invoking a374 pager through this might support colors.375 """376 import subprocess377378 env = dict(os.environ)379380 # If we're piping to less we might support colors under the381 # condition that382 cmd_detail = cmd.rsplit("/", 1)[-1].split()383 if color is None and cmd_detail[0] == "less":384 less_flags = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:]))385 if not less_flags:386 env["LESS"] = "-R"387 color = True388 elif "r" in less_flags or "R" in less_flags:389 color = True390391 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)392 encoding = get_best_encoding(c.stdin)393 try:394 for text in generator:395 if not color:396 text = strip_ansi(text)397398 c.stdin.write(text.encode(encoding, "replace"))399 except (IOError, KeyboardInterrupt):400 pass401 else:402 c.stdin.close()403404 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting405 # search or other commands inside less).406 #407 # That means when the user hits ^C, the parent process (click) terminates,408 # but less is still alive, paging the output and messing up the terminal.409 #410 # If the user wants to make the pager exit on ^C, they should set411 # `LESS='-K'`. It's not our decision to make.412 while True:413 try:414 c.wait()415 except KeyboardInterrupt:416 pass417 else:418 break419420421def _tempfilepager(generator, cmd, color):422 """Page through text by invoking a program on a temporary file."""423 import tempfile424425 filename = tempfile.mktemp()426 # TODO: This never terminates if the passed generator never terminates.427 text = "".join(generator)428 if not color:429 text = strip_ansi(text)430 encoding = get_best_encoding(sys.stdout)431 with open_stream(filename, "wb")[0] as f:432 f.write(text.encode(encoding))433 try:434 os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename)))435 finally:436 os.unlink(filename)437438439def _nullpager(stream, generator, color):440 """Simply print unformatted text. This is the ultimate fallback."""441 for text in generator:442 if not color:443 text = strip_ansi(text)444 stream.write(text)445446447class Editor(object):448 def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):449 self.editor = editor450 self.env = env451 self.require_save = require_save452 self.extension = extension453454 def get_editor(self):455 if self.editor is not None:456 return self.editor457 for key in "VISUAL", "EDITOR":458 rv = os.environ.get(key)459 if rv:460 return rv461 if WIN:462 return "notepad"463 for editor in "sensible-editor", "vim", "nano":464 if os.system("which {} >/dev/null 2>&1".format(editor)) == 0:465 return editor466 return "vi"467468 def edit_file(self, filename):469 import subprocess470471 editor = self.get_editor()472 if self.env:473 environ = os.environ.copy()474 environ.update(self.env)475 else:476 environ = None477 try:478 c = subprocess.Popen(479 "{} {}".format(shlex_quote(editor), shlex_quote(filename)),480 env=environ,481 shell=True,482 )483 exit_code = c.wait()484 if exit_code != 0:485 raise ClickException("{}: Editing failed!".format(editor))486 except OSError as e:487 raise ClickException("{}: Editing failed: {}".format(editor, e))488489 def edit(self, text):490 import tempfile491492 text = text or ""493 binary_data = type(text) in [bytes, bytearray]494495 if not binary_data and text and not text.endswith("\n"):496 text += "\n"497498 fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)499 try:500 if not binary_data:501 if WIN:502 encoding = "utf-8-sig"503 text = text.replace("\n", "\r\n")504 else:505 encoding = "utf-8"506 text = text.encode(encoding)507508 f = os.fdopen(fd, "wb")509 f.write(text)510 f.close()511 timestamp = os.path.getmtime(name)512513 self.edit_file(name)514515 if self.require_save and os.path.getmtime(name) == timestamp:516 return None517518 f = open(name, "rb")519 try:520 rv = f.read()521 finally:522 f.close()523 if binary_data:524 return rv525 else:526 return rv.decode("utf-8-sig").replace("\r\n", "\n")527 finally:528 os.unlink(name)529530531def open_url(url, wait=False, locate=False):532 import subprocess533534 def _unquote_file(url):535 try:536 import urllib537 except ImportError:538 import urllib539 if url.startswith("file://"):540 url = urllib.unquote(url[7:])541 return url542543 if sys.platform == "darwin":544 args = ["open"]545 if wait:546 args.append("-W")547 if locate:548 args.append("-R")549 args.append(_unquote_file(url))550 null = open("/dev/null", "w")551 try:552 return subprocess.Popen(args, stderr=null).wait()553 finally:554 null.close()555 elif WIN:556 if locate:557 url = _unquote_file(url)558 args = "explorer /select,{}".format(shlex_quote(url))559 else:560 args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url))561 return os.system(args)562 elif CYGWIN:563 if locate:564 url = _unquote_file(url)565 args = "cygstart {}".format(shlex_quote(os.path.dirname(url)))566 else:567 args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url))568 return os.system(args)569570 try:571 if locate:572 url = os.path.dirname(_unquote_file(url)) or "."573 else:574 url = _unquote_file(url)575 c = subprocess.Popen(["xdg-open", url])576 if wait:577 return c.wait()578 return 0579 except OSError:580 if url.startswith(("http://", "https://")) and not locate and not wait:581 import webbrowser582583 webbrowser.open(url)584 return 0585 return 1586587588def _translate_ch_to_exc(ch):589 if ch == u"\x03":590 raise KeyboardInterrupt()591 if ch == u"\x04" and not WIN: # Unix-like, Ctrl+D592 raise EOFError()593 if ch == u"\x1a" and WIN: # Windows, Ctrl+Z594 raise EOFError()595596597if WIN:598 import msvcrt599600 @contextlib.contextmanager601 def raw_terminal():602 yield603604 def getchar(echo):605 # The function `getch` will return a bytes object corresponding to606 # the pressed character. Since Windows 10 build 1803, it will also607 # return \x00 when called a second time after pressing a regular key.608 #609 # `getwch` does not share this probably-bugged behavior. Moreover, it610 # returns a Unicode object by default, which is what we want.611 #612 # Either of these functions will return \x00 or \xe0 to indicate613 # a special key, and you need to call the same function again to get614 # the "rest" of the code. The fun part is that \u00e0 is615 # "latin small letter a with grave", so if you type that on a French616 # keyboard, you _also_ get a \xe0.617 # E.g., consider the Up arrow. This returns \xe0 and then \x48. The618 # resulting Unicode string reads as "a with grave" + "capital H".619 # This is indistinguishable from when the user actually types620 # "a with grave" and then "capital H".621 #622 # When \xe0 is returned, we assume it's part of a special-key sequence623 # and call `getwch` again, but that means that when the user types624 # the \u00e0 character, `getchar` doesn't return until a second625 # character is typed.626 # The alternative is returning immediately, but that would mess up627 # cross-platform handling of arrow keys and others that start with628 # \xe0. Another option is using `getch`, but then we can't reliably629 # read non-ASCII characters, because return values of `getch` are630 # limited to the current 8-bit codepage.631 #632 # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`633 # is doing the right thing in more situations than with `getch`.634 if echo:635 func = msvcrt.getwche636 else:637 func = msvcrt.getwch638639 rv = func()640 if rv in (u"\x00", u"\xe0"):641 # \x00 and \xe0 are control characters that indicate special key,642 # see above.643 rv += func()644 _translate_ch_to_exc(rv)645 return rv646647648else:649 import tty650 import termios651652 @contextlib.contextmanager653 def raw_terminal():654 if not isatty(sys.stdin):655 f = open("/dev/tty")656 fd = f.fileno()657 else:658 fd = sys.stdin.fileno()659 f = None660 try:661 old_settings = termios.tcgetattr(fd)662 try:663 tty.setraw(fd)664 yield fd665 finally:666 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)667 sys.stdout.flush()668 if f is not None:669 f.close()670 except termios.error:671 pass672673 def getchar(echo):674 with raw_terminal() as fd:675 ch = os.read(fd, 32)676 ch = ch.decode(get_best_encoding(sys.stdin), "replace")677 if echo and isatty(sys.stdout):678 sys.stdout.write(ch)679 _translate_ch_to_exc(ch)680 return ch
added:src/click/_textwrap.py+37 added
1import textwrap2from contextlib import contextmanager345class TextWrapper(textwrap.TextWrapper):6 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):7 space_left = max(width - cur_len, 1)89 if self.break_long_words:10 last = reversed_chunks[-1]11 cut = last[:space_left]12 res = last[space_left:]13 cur_line.append(cut)14 reversed_chunks[-1] = res15 elif not cur_line:16 cur_line.append(reversed_chunks.pop())1718 @contextmanager19 def extra_indent(self, indent):20 old_initial_indent = self.initial_indent21 old_subsequent_indent = self.subsequent_indent22 self.initial_indent += indent23 self.subsequent_indent += indent24 try:25 yield26 finally:27 self.initial_indent = old_initial_indent28 self.subsequent_indent = old_subsequent_indent2930 def indent_only(self, text):31 rv = []32 for idx, line in enumerate(text.splitlines()):33 indent = self.initial_indent34 if idx > 0:35 indent = self.subsequent_indent36 rv.append(indent + line)37 return "\n".join(rv)
added:src/click/_unicodefun.py+131 added
1import codecs2import os3import sys45from ._compat import PY2678def _find_unicode_literals_frame():9 import __future__1011 if not hasattr(sys, "_getframe"): # not all Python implementations have it12 return 013 frm = sys._getframe(1)14 idx = 115 while frm is not None:16 if frm.f_globals.get("__name__", "").startswith("click."):17 frm = frm.f_back18 idx += 119 elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:20 return idx21 else:22 break23 return 0242526def _check_for_unicode_literals():27 if not __debug__:28 return2930 from . import disable_unicode_literals_warning3132 if not PY2 or disable_unicode_literals_warning:33 return34 bad_frame = _find_unicode_literals_frame()35 if bad_frame <= 0:36 return37 from warnings import warn3839 warn(40 Warning(41 "Click detected the use of the unicode_literals __future__"42 " import. This is heavily discouraged because it can"43 " introduce subtle bugs in your code. You should instead"44 ' use explicit u"" literals for your unicode strings. For'45 " more information see"46 " https://click.palletsprojects.com/python3/"47 ),48 stacklevel=bad_frame,49 )505152def _verify_python3_env():53 """Ensures that the environment is good for unicode on Python 3."""54 if PY2:55 return56 try:57 import locale5859 fs_enc = codecs.lookup(locale.getpreferredencoding()).name60 except Exception:61 fs_enc = "ascii"62 if fs_enc != "ascii":63 return6465 extra = ""66 if os.name == "posix":67 import subprocess6869 try:70 rv = subprocess.Popen(71 ["locale", "-a"], stdout=subprocess.PIPE, stderr=subprocess.PIPE72 ).communicate()[0]73 except OSError:74 rv = b""75 good_locales = set()76 has_c_utf8 = False7778 # Make sure we're operating on text here.79 if isinstance(rv, bytes):80 rv = rv.decode("ascii", "replace")8182 for line in rv.splitlines():83 locale = line.strip()84 if locale.lower().endswith((".utf-8", ".utf8")):85 good_locales.add(locale)86 if locale.lower() in ("c.utf8", "c.utf-8"):87 has_c_utf8 = True8889 extra += "\n\n"90 if not good_locales:91 extra += (92 "Additional information: on this system no suitable"93 " UTF-8 locales were discovered. This most likely"94 " requires resolving by reconfiguring the locale"95 " system."96 )97 elif has_c_utf8:98 extra += (99 "This system supports the C.UTF-8 locale which is"100 " recommended. You might be able to resolve your issue"101 " by exporting the following environment variables:\n\n"102 " export LC_ALL=C.UTF-8\n"103 " export LANG=C.UTF-8"104 )105 else:106 extra += (107 "This system lists a couple of UTF-8 supporting locales"108 " that you can pick from. The following suitable"109 " locales were discovered: {}".format(", ".join(sorted(good_locales)))110 )111112 bad_locale = None113 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):114 if locale and locale.lower().endswith((".utf-8", ".utf8")):115 bad_locale = locale116 if locale is not None:117 break118 if bad_locale is not None:119 extra += (120 "\n\nClick discovered that you exported a UTF-8 locale"121 " but the locale system could not pick up from it"122 " because it does not exist. The exported locale is"123 " '{}' but it is not supported".format(bad_locale)124 )125126 raise RuntimeError(127 "Click will abort further execution because Python 3 was"128 " configured to use ASCII as encoding for the environment."129 " Consult https://click.palletsprojects.com/python3/ for"130 " mitigation steps.{}".format(extra)131 )
added:src/click/_winconsole.py+370 added
1# -*- coding: utf-8 -*-2# This module is based on the excellent work by Adam Bartoš who3# provided a lot of what went into the implementation here in4# the discussion to issue1602 in the Python bug tracker.5#6# There are some general differences in regards to how this works7# compared to the original patches as we do not need to patch8# the entire interpreter but just work in our little world of9# echo and prompt.10import ctypes11import io12import os13import sys14import time15import zlib16from ctypes import byref17from ctypes import c_char18from ctypes import c_char_p19from ctypes import c_int20from ctypes import c_ssize_t21from ctypes import c_ulong22from ctypes import c_void_p23from ctypes import POINTER24from ctypes import py_object25from ctypes import windll26from ctypes import WinError27from ctypes import WINFUNCTYPE28from ctypes.wintypes import DWORD29from ctypes.wintypes import HANDLE30from ctypes.wintypes import LPCWSTR31from ctypes.wintypes import LPWSTR3233import msvcrt3435from ._compat import _NonClosingTextIOWrapper36from ._compat import PY237from ._compat import text_type3839try:40 from ctypes import pythonapi4142 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer43 PyBuffer_Release = pythonapi.PyBuffer_Release44except ImportError:45 pythonapi = None464748c_ssize_p = POINTER(c_ssize_t)4950kernel32 = windll.kernel3251GetStdHandle = kernel32.GetStdHandle52ReadConsoleW = kernel32.ReadConsoleW53WriteConsoleW = kernel32.WriteConsoleW54GetConsoleMode = kernel32.GetConsoleMode55GetLastError = kernel32.GetLastError56GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))57CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(58 ("CommandLineToArgvW", windll.shell32)59)60LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(61 ("LocalFree", windll.kernel32)62)636465STDIN_HANDLE = GetStdHandle(-10)66STDOUT_HANDLE = GetStdHandle(-11)67STDERR_HANDLE = GetStdHandle(-12)686970PyBUF_SIMPLE = 071PyBUF_WRITABLE = 17273ERROR_SUCCESS = 074ERROR_NOT_ENOUGH_MEMORY = 875ERROR_OPERATION_ABORTED = 9957677STDIN_FILENO = 078STDOUT_FILENO = 179STDERR_FILENO = 28081EOF = b"\x1a"82MAX_BYTES_WRITTEN = 32767838485class Py_buffer(ctypes.Structure):86 _fields_ = [87 ("buf", c_void_p),88 ("obj", py_object),89 ("len", c_ssize_t),90 ("itemsize", c_ssize_t),91 ("readonly", c_int),92 ("ndim", c_int),93 ("format", c_char_p),94 ("shape", c_ssize_p),95 ("strides", c_ssize_p),96 ("suboffsets", c_ssize_p),97 ("internal", c_void_p),98 ]99100 if PY2:101 _fields_.insert(-1, ("smalltable", c_ssize_t * 2))102103104# On PyPy we cannot get buffers so our ability to operate here is105# severely limited.106if pythonapi is None:107 get_buffer = None108else:109110 def get_buffer(obj, writable=False):111 buf = Py_buffer()112 flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE113 PyObject_GetBuffer(py_object(obj), byref(buf), flags)114 try:115 buffer_type = c_char * buf.len116 return buffer_type.from_address(buf.buf)117 finally:118 PyBuffer_Release(byref(buf))119120121class _WindowsConsoleRawIOBase(io.RawIOBase):122 def __init__(self, handle):123 self.handle = handle124125 def isatty(self):126 io.RawIOBase.isatty(self)127 return True128129130class _WindowsConsoleReader(_WindowsConsoleRawIOBase):131 def readable(self):132 return True133134 def readinto(self, b):135 bytes_to_be_read = len(b)136 if not bytes_to_be_read:137 return 0138 elif bytes_to_be_read % 2:139 raise ValueError(140 "cannot read odd number of bytes from UTF-16-LE encoded console"141 )142143 buffer = get_buffer(b, writable=True)144 code_units_to_be_read = bytes_to_be_read // 2145 code_units_read = c_ulong()146147 rv = ReadConsoleW(148 HANDLE(self.handle),149 buffer,150 code_units_to_be_read,151 byref(code_units_read),152 None,153 )154 if GetLastError() == ERROR_OPERATION_ABORTED:155 # wait for KeyboardInterrupt156 time.sleep(0.1)157 if not rv:158 raise OSError("Windows error: {}".format(GetLastError()))159160 if buffer[0] == EOF:161 return 0162 return 2 * code_units_read.value163164165class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):166 def writable(self):167 return True168169 @staticmethod170 def _get_error_message(errno):171 if errno == ERROR_SUCCESS:172 return "ERROR_SUCCESS"173 elif errno == ERROR_NOT_ENOUGH_MEMORY:174 return "ERROR_NOT_ENOUGH_MEMORY"175 return "Windows error {}".format(errno)176177 def write(self, b):178 bytes_to_be_written = len(b)179 buf = get_buffer(b)180 code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2181 code_units_written = c_ulong()182183 WriteConsoleW(184 HANDLE(self.handle),185 buf,186 code_units_to_be_written,187 byref(code_units_written),188 None,189 )190 bytes_written = 2 * code_units_written.value191192 if bytes_written == 0 and bytes_to_be_written > 0:193 raise OSError(self._get_error_message(GetLastError()))194 return bytes_written195196197class ConsoleStream(object):198 def __init__(self, text_stream, byte_stream):199 self._text_stream = text_stream200 self.buffer = byte_stream201202 @property203 def name(self):204 return self.buffer.name205206 def write(self, x):207 if isinstance(x, text_type):208 return self._text_stream.write(x)209 try:210 self.flush()211 except Exception:212 pass213 return self.buffer.write(x)214215 def writelines(self, lines):216 for line in lines:217 self.write(line)218219 def __getattr__(self, name):220 return getattr(self._text_stream, name)221222 def isatty(self):223 return self.buffer.isatty()224225 def __repr__(self):226 return "<ConsoleStream name={!r} encoding={!r}>".format(227 self.name, self.encoding228 )229230231class WindowsChunkedWriter(object):232 """233 Wraps a stream (such as stdout), acting as a transparent proxy for all234 attribute access apart from method 'write()' which we wrap to write in235 limited chunks due to a Windows limitation on binary console streams.236 """237238 def __init__(self, wrapped):239 # double-underscore everything to prevent clashes with names of240 # attributes on the wrapped stream object.241 self.__wrapped = wrapped242243 def __getattr__(self, name):244 return getattr(self.__wrapped, name)245246 def write(self, text):247 total_to_write = len(text)248 written = 0249250 while written < total_to_write:251 to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)252 self.__wrapped.write(text[written : written + to_write])253 written += to_write254255256_wrapped_std_streams = set()257258259def _wrap_std_stream(name):260 # Python 2 & Windows 7 and below261 if (262 PY2263 and sys.getwindowsversion()[:2] <= (6, 1)264 and name not in _wrapped_std_streams265 ):266 setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))267 _wrapped_std_streams.add(name)268269270def _get_text_stdin(buffer_stream):271 text_stream = _NonClosingTextIOWrapper(272 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),273 "utf-16-le",274 "strict",275 line_buffering=True,276 )277 return ConsoleStream(text_stream, buffer_stream)278279280def _get_text_stdout(buffer_stream):281 text_stream = _NonClosingTextIOWrapper(282 io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),283 "utf-16-le",284 "strict",285 line_buffering=True,286 )287 return ConsoleStream(text_stream, buffer_stream)288289290def _get_text_stderr(buffer_stream):291 text_stream = _NonClosingTextIOWrapper(292 io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),293 "utf-16-le",294 "strict",295 line_buffering=True,296 )297 return ConsoleStream(text_stream, buffer_stream)298299300if PY2:301302 def _hash_py_argv():303 return zlib.crc32("\x00".join(sys.argv[1:]))304305 _initial_argv_hash = _hash_py_argv()306307 def _get_windows_argv():308 argc = c_int(0)309 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))310 if not argv_unicode:311 raise WinError()312 try:313 argv = [argv_unicode[i] for i in range(0, argc.value)]314 finally:315 LocalFree(argv_unicode)316 del argv_unicode317318 if not hasattr(sys, "frozen"):319 argv = argv[1:]320 while len(argv) > 0:321 arg = argv[0]322 if not arg.startswith("-") or arg == "-":323 break324 argv = argv[1:]325 if arg.startswith(("-c", "-m")):326 break327328 return argv[1:]329330331_stream_factories = {332 0: _get_text_stdin,333 1: _get_text_stdout,334 2: _get_text_stderr,335}336337338def _is_console(f):339 if not hasattr(f, "fileno"):340 return False341342 try:343 fileno = f.fileno()344 except OSError:345 return False346347 handle = msvcrt.get_osfhandle(fileno)348 return bool(GetConsoleMode(handle, byref(DWORD())))349350351def _get_windows_console_stream(f, encoding, errors):352 if (353 get_buffer is not None354 and encoding in ("utf-16-le", None)355 and errors in ("strict", None)356 and _is_console(f)357 ):358 func = _stream_factories.get(f.fileno())359 if func is not None:360 if not PY2:361 f = getattr(f, "buffer", None)362 if f is None:363 return None364 else:365 # If we are on Python 2 we need to set the stream that we366 # deal with to binary mode as otherwise the exercise if a367 # bit moot. The same problems apply as for368 # get_binary_stdin and friends from _compat.369 msvcrt.setmode(f.fileno(), os.O_BINARY)370 return func(f)
added:src/click/core.py+2108 added
1import errno2import inspect3import os4import sys5from contextlib import contextmanager6from functools import update_wrapper7from itertools import repeat89from ._compat import isidentifier10from ._compat import iteritems11from ._compat import PY212from ._compat import string_types13from ._unicodefun import _check_for_unicode_literals14from ._unicodefun import _verify_python3_env15from .exceptions import Abort16from .exceptions import BadParameter17from .exceptions import ClickException18from .exceptions import Exit19from .exceptions import MissingParameter20from .exceptions import UsageError21from .formatting import HelpFormatter22from .formatting import join_options23from .globals import pop_context24from .globals import push_context25from .parser import OptionParser26from .parser import split_opt27from .termui import confirm28from .termui import prompt29from .termui import style30from .types import BOOL31from .types import convert_type32from .types import IntRange33from .utils import echo34from .utils import get_os_args35from .utils import make_default_short_help36from .utils import make_str37from .utils import PacifyFlushWrapper3839_missing = object()4041SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."42SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."4344DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."464748def _maybe_show_deprecated_notice(cmd):49 if cmd.deprecated:50 echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)515253def fast_exit(code):54 """Exit without garbage collection, this speeds up exit by about 10ms for55 things like bash completion.56 """57 sys.stdout.flush()58 sys.stderr.flush()59 os._exit(code)606162def _bashcomplete(cmd, prog_name, complete_var=None):63 """Internal handler for the bash completion support."""64 if complete_var is None:65 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())66 complete_instr = os.environ.get(complete_var)67 if not complete_instr:68 return6970 from ._bashcomplete import bashcomplete7172 if bashcomplete(cmd, prog_name, complete_var, complete_instr):73 fast_exit(1)747576def _check_multicommand(base_command, cmd_name, cmd, register=False):77 if not base_command.chain or not isinstance(cmd, MultiCommand):78 return79 if register:80 hint = (81 "It is not possible to add multi commands as children to"82 " another multi command that is in chain mode."83 )84 else:85 hint = (86 "Found a multi command as subcommand to a multi command"87 " that is in chain mode. This is not supported."88 )89 raise RuntimeError(90 "{}. Command '{}' is set to chain and '{}' was added as"91 " subcommand but it in itself is a multi command. ('{}' is a {}"92 " within a chained {} named '{}').".format(93 hint,94 base_command.name,95 cmd_name,96 cmd_name,97 cmd.__class__.__name__,98 base_command.__class__.__name__,99 base_command.name,100 )101 )102103104def batch(iterable, batch_size):105 return list(zip(*repeat(iter(iterable), batch_size)))106107108def invoke_param_callback(callback, ctx, param, value):109 code = getattr(callback, "__code__", None)110 args = getattr(code, "co_argcount", 3)111112 if args < 3:113 # This will become a warning in Click 3.0:114 from warnings import warn115116 warn(117 Warning(118 "Invoked legacy parameter callback '{}'. The new"119 " signature for such callbacks starting with Click 2.0"120 " is (ctx, param, value).".format(callback)121 ),122 stacklevel=3,123 )124 return callback(ctx, value)125 return callback(ctx, param, value)126127128@contextmanager129def augment_usage_errors(ctx, param=None):130 """Context manager that attaches extra information to exceptions."""131 try:132 yield133 except BadParameter as e:134 if e.ctx is None:135 e.ctx = ctx136 if param is not None and e.param is None:137 e.param = param138 raise139 except UsageError as e:140 if e.ctx is None:141 e.ctx = ctx142 raise143144145def iter_params_for_processing(invocation_order, declaration_order):146 """Given a sequence of parameters in the order as should be considered147 for processing and an iterable of parameters that exist, this returns148 a list in the correct order as they should be processed.149 """150151 def sort_key(item):152 try:153 idx = invocation_order.index(item)154 except ValueError:155 idx = float("inf")156 return (not item.is_eager, idx)157158 return sorted(declaration_order, key=sort_key)159160161class ParameterSource(object):162 """This is an enum that indicates the source of a command line parameter.163164 The enum has one of the following values: COMMANDLINE,165 ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the166 default value in the decorator was used. This class should be167 converted to an enum when Python 2 support is dropped.168 """169170 COMMANDLINE = "COMMANDLINE"171 ENVIRONMENT = "ENVIRONMENT"172 DEFAULT = "DEFAULT"173 DEFAULT_MAP = "DEFAULT_MAP"174175 VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP}176177 @classmethod178 def validate(cls, value):179 """Validate that the specified value is a valid enum.180181 This method will raise a ValueError if the value is182 not a valid enum.183184 :param value: the string value to verify185 """186 if value not in cls.VALUES:187 raise ValueError(188 "Invalid ParameterSource value: '{}'. Valid "189 "values are: {}".format(value, ",".join(cls.VALUES))190 )191192193class Context(object):194 """The context is a special internal object that holds state relevant195 for the script execution at every single level. It's normally invisible196 to commands unless they opt-in to getting access to it.197198 The context is useful as it can pass internal objects around and can199 control special execution features such as reading data from200 environment variables.201202 A context can be used as context manager in which case it will call203 :meth:`close` on teardown.204205 .. versionadded:: 2.0206 Added the `resilient_parsing`, `help_option_names`,207 `token_normalize_func` parameters.208209 .. versionadded:: 3.0210 Added the `allow_extra_args` and `allow_interspersed_args`211 parameters.212213 .. versionadded:: 4.0214 Added the `color`, `ignore_unknown_options`, and215 `max_content_width` parameters.216217 .. versionadded:: 7.1218 Added the `show_default` parameter.219220 :param command: the command class for this context.221 :param parent: the parent context.222 :param info_name: the info name for this invocation. Generally this223 is the most descriptive name for the script or224 command. For the toplevel script it is usually225 the name of the script, for commands below it it's226 the name of the script.227 :param obj: an arbitrary object of user data.228 :param auto_envvar_prefix: the prefix to use for automatic environment229 variables. If this is `None` then reading230 from environment variables is disabled. This231 does not affect manually set environment232 variables which are always read.233 :param default_map: a dictionary (like object) with default values234 for parameters.235 :param terminal_width: the width of the terminal. The default is236 inherit from parent context. If no context237 defines the terminal width then auto238 detection will be applied.239 :param max_content_width: the maximum width for content rendered by240 Click (this currently only affects help241 pages). This defaults to 80 characters if242 not overridden. In other words: even if the243 terminal is larger than that, Click will not244 format things wider than 80 characters by245 default. In addition to that, formatters might246 add some safety mapping on the right.247 :param resilient_parsing: if this flag is enabled then Click will248 parse without any interactivity or callback249 invocation. Default values will also be250 ignored. This is useful for implementing251 things such as completion support.252 :param allow_extra_args: if this is set to `True` then extra arguments253 at the end will not raise an error and will be254 kept on the context. The default is to inherit255 from the command.256 :param allow_interspersed_args: if this is set to `False` then options257 and arguments cannot be mixed. The258 default is to inherit from the command.259 :param ignore_unknown_options: instructs click to ignore options it does260 not know and keeps them for later261 processing.262 :param help_option_names: optionally a list of strings that define how263 the default help parameter is named. The264 default is ``['--help']``.265 :param token_normalize_func: an optional function that is used to266 normalize tokens (options, choices,267 etc.). This for instance can be used to268 implement case insensitive behavior.269 :param color: controls if the terminal supports ANSI colors or not. The270 default is autodetection. This is only needed if ANSI271 codes are used in texts that Click prints which is by272 default not the case. This for instance would affect273 help output.274 :param show_default: if True, shows defaults for all options.275 Even if an option is later created with show_default=False,276 this command-level setting overrides it.277 """278279 def __init__(280 self,281 command,282 parent=None,283 info_name=None,284 obj=None,285 auto_envvar_prefix=None,286 default_map=None,287 terminal_width=None,288 max_content_width=None,289 resilient_parsing=False,290 allow_extra_args=None,291 allow_interspersed_args=None,292 ignore_unknown_options=None,293 help_option_names=None,294 token_normalize_func=None,295 color=None,296 show_default=None,297 ):298 #: the parent context or `None` if none exists.299 self.parent = parent300 #: the :class:`Command` for this context.301 self.command = command302 #: the descriptive information name303 self.info_name = info_name304 #: the parsed parameters except if the value is hidden in which305 #: case it's not remembered.306 self.params = {}307 #: the leftover arguments.308 self.args = []309 #: protected arguments. These are arguments that are prepended310 #: to `args` when certain parsing scenarios are encountered but311 #: must be never propagated to another arguments. This is used312 #: to implement nested parsing.313 self.protected_args = []314 if obj is None and parent is not None:315 obj = parent.obj316 #: the user object stored.317 self.obj = obj318 self._meta = getattr(parent, "meta", {})319320 #: A dictionary (-like object) with defaults for parameters.321 if (322 default_map is None323 and parent is not None324 and parent.default_map is not None325 ):326 default_map = parent.default_map.get(info_name)327 self.default_map = default_map328329 #: This flag indicates if a subcommand is going to be executed. A330 #: group callback can use this information to figure out if it's331 #: being executed directly or because the execution flow passes332 #: onwards to a subcommand. By default it's None, but it can be333 #: the name of the subcommand to execute.334 #:335 #: If chaining is enabled this will be set to ``'*'`` in case336 #: any commands are executed. It is however not possible to337 #: figure out which ones. If you require this knowledge you338 #: should use a :func:`resultcallback`.339 self.invoked_subcommand = None340341 if terminal_width is None and parent is not None:342 terminal_width = parent.terminal_width343 #: The width of the terminal (None is autodetection).344 self.terminal_width = terminal_width345346 if max_content_width is None and parent is not None:347 max_content_width = parent.max_content_width348 #: The maximum width of formatted content (None implies a sensible349 #: default which is 80 for most things).350 self.max_content_width = max_content_width351352 if allow_extra_args is None:353 allow_extra_args = command.allow_extra_args354 #: Indicates if the context allows extra args or if it should355 #: fail on parsing.356 #:357 #: .. versionadded:: 3.0358 self.allow_extra_args = allow_extra_args359360 if allow_interspersed_args is None:361 allow_interspersed_args = command.allow_interspersed_args362 #: Indicates if the context allows mixing of arguments and363 #: options or not.364 #:365 #: .. versionadded:: 3.0366 self.allow_interspersed_args = allow_interspersed_args367368 if ignore_unknown_options is None:369 ignore_unknown_options = command.ignore_unknown_options370 #: Instructs click to ignore options that a command does not371 #: understand and will store it on the context for later372 #: processing. This is primarily useful for situations where you373 #: want to call into external programs. Generally this pattern is374 #: strongly discouraged because it's not possibly to losslessly375 #: forward all arguments.376 #:377 #: .. versionadded:: 4.0378 self.ignore_unknown_options = ignore_unknown_options379380 if help_option_names is None:381 if parent is not None:382 help_option_names = parent.help_option_names383 else:384 help_option_names = ["--help"]385386 #: The names for the help options.387 self.help_option_names = help_option_names388389 if token_normalize_func is None and parent is not None:390 token_normalize_func = parent.token_normalize_func391392 #: An optional normalization function for tokens. This is393 #: options, choices, commands etc.394 self.token_normalize_func = token_normalize_func395396 #: Indicates if resilient parsing is enabled. In that case Click397 #: will do its best to not cause any failures and default values398 #: will be ignored. Useful for completion.399 self.resilient_parsing = resilient_parsing400401 # If there is no envvar prefix yet, but the parent has one and402 # the command on this level has a name, we can expand the envvar403 # prefix automatically.404 if auto_envvar_prefix is None:405 if (406 parent is not None407 and parent.auto_envvar_prefix is not None408 and self.info_name is not None409 ):410 auto_envvar_prefix = "{}_{}".format(411 parent.auto_envvar_prefix, self.info_name.upper()412 )413 else:414 auto_envvar_prefix = auto_envvar_prefix.upper()415 if auto_envvar_prefix is not None:416 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")417 self.auto_envvar_prefix = auto_envvar_prefix418419 if color is None and parent is not None:420 color = parent.color421422 #: Controls if styling output is wanted or not.423 self.color = color424425 self.show_default = show_default426427 self._close_callbacks = []428 self._depth = 0429 self._source_by_paramname = {}430431 def __enter__(self):432 self._depth += 1433 push_context(self)434 return self435436 def __exit__(self, exc_type, exc_value, tb):437 self._depth -= 1438 if self._depth == 0:439 self.close()440 pop_context()441442 @contextmanager443 def scope(self, cleanup=True):444 """This helper method can be used with the context object to promote445 it to the current thread local (see :func:`get_current_context`).446 The default behavior of this is to invoke the cleanup functions which447 can be disabled by setting `cleanup` to `False`. The cleanup448 functions are typically used for things such as closing file handles.449450 If the cleanup is intended the context object can also be directly451 used as a context manager.452453 Example usage::454455 with ctx.scope():456 assert get_current_context() is ctx457458 This is equivalent::459460 with ctx:461 assert get_current_context() is ctx462463 .. versionadded:: 5.0464465 :param cleanup: controls if the cleanup functions should be run or466 not. The default is to run these functions. In467 some situations the context only wants to be468 temporarily pushed in which case this can be disabled.469 Nested pushes automatically defer the cleanup.470 """471 if not cleanup:472 self._depth += 1473 try:474 with self as rv:475 yield rv476 finally:477 if not cleanup:478 self._depth -= 1479480 @property481 def meta(self):482 """This is a dictionary which is shared with all the contexts483 that are nested. It exists so that click utilities can store some484 state here if they need to. It is however the responsibility of485 that code to manage this dictionary well.486487 The keys are supposed to be unique dotted strings. For instance488 module paths are a good choice for it. What is stored in there is489 irrelevant for the operation of click. However what is important is490 that code that places data here adheres to the general semantics of491 the system.492493 Example usage::494495 LANG_KEY = f'{__name__}.lang'496497 def set_language(value):498 ctx = get_current_context()499 ctx.meta[LANG_KEY] = value500501 def get_language():502 return get_current_context().meta.get(LANG_KEY, 'en_US')503504 .. versionadded:: 5.0505 """506 return self._meta507508 def make_formatter(self):509 """Creates the formatter for the help and usage output."""510 return HelpFormatter(511 width=self.terminal_width, max_width=self.max_content_width512 )513514 def call_on_close(self, f):515 """This decorator remembers a function as callback that should be516 executed when the context tears down. This is most useful to bind517 resource handling to the script execution. For instance, file objects518 opened by the :class:`File` type will register their close callbacks519 here.520521 :param f: the function to execute on teardown.522 """523 self._close_callbacks.append(f)524 return f525526 def close(self):527 """Invokes all close callbacks."""528 for cb in self._close_callbacks:529 cb()530 self._close_callbacks = []531532 @property533 def command_path(self):534 """The computed command path. This is used for the ``usage``535 information on the help page. It's automatically created by536 combining the info names of the chain of contexts to the root.537 """538 rv = ""539 if self.info_name is not None:540 rv = self.info_name541 if self.parent is not None:542 rv = "{} {}".format(self.parent.command_path, rv)543 return rv.lstrip()544545 def find_root(self):546 """Finds the outermost context."""547 node = self548 while node.parent is not None:549 node = node.parent550 return node551552 def find_object(self, object_type):553 """Finds the closest object of a given type."""554 node = self555 while node is not None:556 if isinstance(node.obj, object_type):557 return node.obj558 node = node.parent559560 def ensure_object(self, object_type):561 """Like :meth:`find_object` but sets the innermost object to a562 new instance of `object_type` if it does not exist.563 """564 rv = self.find_object(object_type)565 if rv is None:566 self.obj = rv = object_type()567 return rv568569 def lookup_default(self, name):570 """Looks up the default for a parameter name. This by default571 looks into the :attr:`default_map` if available.572 """573 if self.default_map is not None:574 rv = self.default_map.get(name)575 if callable(rv):576 rv = rv()577 return rv578579 def fail(self, message):580 """Aborts the execution of the program with a specific error581 message.582583 :param message: the error message to fail with.584 """585 raise UsageError(message, self)586587 def abort(self):588 """Aborts the script."""589 raise Abort()590591 def exit(self, code=0):592 """Exits the application with a given exit code."""593 raise Exit(code)594595 def get_usage(self):596 """Helper method to get formatted usage string for the current597 context and command.598 """599 return self.command.get_usage(self)600601 def get_help(self):602 """Helper method to get formatted help page for the current603 context and command.604 """605 return self.command.get_help(self)606607 def invoke(*args, **kwargs): # noqa: B902608 """Invokes a command callback in exactly the way it expects. There609 are two ways to invoke this method:610611 1. the first argument can be a callback and all other arguments and612 keyword arguments are forwarded directly to the function.613 2. the first argument is a click command object. In that case all614 arguments are forwarded as well but proper click parameters615 (options and click arguments) must be keyword arguments and Click616 will fill in defaults.617618 Note that before Click 3.2 keyword arguments were not properly filled619 in against the intention of this code and no context was created. For620 more information about this change and why it was done in a bugfix621 release see :ref:`upgrade-to-3.2`.622 """623 self, callback = args[:2]624 ctx = self625626 # It's also possible to invoke another command which might or627 # might not have a callback. In that case we also fill628 # in defaults and make a new context for this command.629 if isinstance(callback, Command):630 other_cmd = callback631 callback = other_cmd.callback632 ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)633 if callback is None:634 raise TypeError(635 "The given command does not have a callback that can be invoked."636 )637638 for param in other_cmd.params:639 if param.name not in kwargs and param.expose_value:640 kwargs[param.name] = param.get_default(ctx)641642 args = args[2:]643 with augment_usage_errors(self):644 with ctx:645 return callback(*args, **kwargs)646647 def forward(*args, **kwargs): # noqa: B902648 """Similar to :meth:`invoke` but fills in default keyword649 arguments from the current context if the other command expects650 it. This cannot invoke callbacks directly, only other commands.651 """652 self, cmd = args[:2]653654 # It's also possible to invoke another command which might or655 # might not have a callback.656 if not isinstance(cmd, Command):657 raise TypeError("Callback is not a command.")658659 for param in self.params:660 if param not in kwargs:661 kwargs[param] = self.params[param]662663 return self.invoke(cmd, **kwargs)664665 def set_parameter_source(self, name, source):666 """Set the source of a parameter.667668 This indicates the location from which the value of the669 parameter was obtained.670671 :param name: the name of the command line parameter672 :param source: the source of the command line parameter, which673 should be a valid ParameterSource value674 """675 ParameterSource.validate(source)676 self._source_by_paramname[name] = source677678 def get_parameter_source(self, name):679 """Get the source of a parameter.680681 This indicates the location from which the value of the682 parameter was obtained. This can be useful for determining683 when a user specified an option on the command line that is684 the same as the default. In that case, the source would be685 ParameterSource.COMMANDLINE, even though the value of the686 parameter was equivalent to the default.687688 :param name: the name of the command line parameter689 :returns: the source690 :rtype: ParameterSource691 """692 return self._source_by_paramname[name]693694695class BaseCommand(object):696 """The base command implements the minimal API contract of commands.697 Most code will never use this as it does not implement a lot of useful698 functionality but it can act as the direct subclass of alternative699 parsing methods that do not depend on the Click parser.700701 For instance, this can be used to bridge Click and other systems like702 argparse or docopt.703704 Because base commands do not implement a lot of the API that other705 parts of Click take for granted, they are not supported for all706 operations. For instance, they cannot be used with the decorators707 usually and they have no built-in callback system.708709 .. versionchanged:: 2.0710 Added the `context_settings` parameter.711712 :param name: the name of the command to use unless a group overrides it.713 :param context_settings: an optional dictionary with defaults that are714 passed to the context object.715 """716717 #: the default for the :attr:`Context.allow_extra_args` flag.718 allow_extra_args = False719 #: the default for the :attr:`Context.allow_interspersed_args` flag.720 allow_interspersed_args = True721 #: the default for the :attr:`Context.ignore_unknown_options` flag.722 ignore_unknown_options = False723724 def __init__(self, name, context_settings=None):725 #: the name the command thinks it has. Upon registering a command726 #: on a :class:`Group` the group will default the command name727 #: with this information. You should instead use the728 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.729 self.name = name730 if context_settings is None:731 context_settings = {}732 #: an optional dictionary with defaults passed to the context.733 self.context_settings = context_settings734735 def __repr__(self):736 return "<{} {}>".format(self.__class__.__name__, self.name)737738 def get_usage(self, ctx):739 raise NotImplementedError("Base commands cannot get usage")740741 def get_help(self, ctx):742 raise NotImplementedError("Base commands cannot get help")743744 def make_context(self, info_name, args, parent=None, **extra):745 """This function when given an info name and arguments will kick746 off the parsing and create a new :class:`Context`. It does not747 invoke the actual command callback though.748749 :param info_name: the info name for this invokation. Generally this750 is the most descriptive name for the script or751 command. For the toplevel script it's usually752 the name of the script, for commands below it it's753 the name of the script.754 :param args: the arguments to parse as list of strings.755 :param parent: the parent context if available.756 :param extra: extra keyword arguments forwarded to the context757 constructor.758 """759 for key, value in iteritems(self.context_settings):760 if key not in extra:761 extra[key] = value762 ctx = Context(self, info_name=info_name, parent=parent, **extra)763 with ctx.scope(cleanup=False):764 self.parse_args(ctx, args)765 return ctx766767 def parse_args(self, ctx, args):768 """Given a context and a list of arguments this creates the parser769 and parses the arguments, then modifies the context as necessary.770 This is automatically invoked by :meth:`make_context`.771 """772 raise NotImplementedError("Base commands do not know how to parse arguments.")773774 def invoke(self, ctx):775 """Given a context, this invokes the command. The default776 implementation is raising a not implemented error.777 """778 raise NotImplementedError("Base commands are not invokable by default")779780 def main(781 self,782 args=None,783 prog_name=None,784 complete_var=None,785 standalone_mode=True,786 **extra787 ):788 """This is the way to invoke a script with all the bells and789 whistles as a command line application. This will always terminate790 the application after a call. If this is not wanted, ``SystemExit``791 needs to be caught.792793 This method is also available by directly calling the instance of794 a :class:`Command`.795796 .. versionadded:: 3.0797 Added the `standalone_mode` flag to control the standalone mode.798799 :param args: the arguments that should be used for parsing. If not800 provided, ``sys.argv[1:]`` is used.801 :param prog_name: the program name that should be used. By default802 the program name is constructed by taking the file803 name from ``sys.argv[0]``.804 :param complete_var: the environment variable that controls the805 bash completion support. The default is806 ``"_<prog_name>_COMPLETE"`` with prog_name in807 uppercase.808 :param standalone_mode: the default behavior is to invoke the script809 in standalone mode. Click will then810 handle exceptions and convert them into811 error messages and the function will never812 return but shut down the interpreter. If813 this is set to `False` they will be814 propagated to the caller and the return815 value of this function is the return value816 of :meth:`invoke`.817 :param extra: extra keyword arguments are forwarded to the context818 constructor. See :class:`Context` for more information.819 """820 # If we are in Python 3, we will verify that the environment is821 # sane at this point or reject further execution to avoid a822 # broken script.823 if not PY2:824 _verify_python3_env()825 else:826 _check_for_unicode_literals()827828 if args is None:829 args = get_os_args()830 else:831 args = list(args)832833 if prog_name is None:834 prog_name = make_str(835 os.path.basename(sys.argv[0] if sys.argv else __file__)836 )837838 # Hook for the Bash completion. This only activates if the Bash839 # completion is actually enabled, otherwise this is quite a fast840 # noop.841 _bashcomplete(self, prog_name, complete_var)842843 try:844 try:845 with self.make_context(prog_name, args, **extra) as ctx:846 rv = self.invoke(ctx)847 if not standalone_mode:848 return rv849 # it's not safe to `ctx.exit(rv)` here!850 # note that `rv` may actually contain data like "1" which851 # has obvious effects852 # more subtle case: `rv=[None, None]` can come out of853 # chained commands which all returned `None` -- so it's not854 # even always obvious that `rv` indicates success/failure855 # by its truthiness/falsiness856 ctx.exit()857 except (EOFError, KeyboardInterrupt):858 echo(file=sys.stderr)859 raise Abort()860 except ClickException as e:861 if not standalone_mode:862 raise863 e.show()864 sys.exit(e.exit_code)865 except IOError as e:866 if e.errno == errno.EPIPE:867 sys.stdout = PacifyFlushWrapper(sys.stdout)868 sys.stderr = PacifyFlushWrapper(sys.stderr)869 sys.exit(1)870 else:871 raise872 except Exit as e:873 if standalone_mode:874 sys.exit(e.exit_code)875 else:876 # in non-standalone mode, return the exit code877 # note that this is only reached if `self.invoke` above raises878 # an Exit explicitly -- thus bypassing the check there which879 # would return its result880 # the results of non-standalone execution may therefore be881 # somewhat ambiguous: if there are codepaths which lead to882 # `ctx.exit(1)` and to `return 1`, the caller won't be able to883 # tell the difference between the two884 return e.exit_code885 except Abort:886 if not standalone_mode:887 raise888 echo("Aborted!", file=sys.stderr)889 sys.exit(1)890891 def __call__(self, *args, **kwargs):892 """Alias for :meth:`main`."""893 return self.main(*args, **kwargs)894895896class Command(BaseCommand):897 """Commands are the basic building block of command line interfaces in898 Click. A basic command handles command line parsing and might dispatch899 more parsing to commands nested below it.900901 .. versionchanged:: 2.0902 Added the `context_settings` parameter.903 .. versionchanged:: 8.0904 Added repr showing the command name905 .. versionchanged:: 7.1906 Added the `no_args_is_help` parameter.907908 :param name: the name of the command to use unless a group overrides it.909 :param context_settings: an optional dictionary with defaults that are910 passed to the context object.911 :param callback: the callback to invoke. This is optional.912 :param params: the parameters to register with this command. This can913 be either :class:`Option` or :class:`Argument` objects.914 :param help: the help string to use for this command.915 :param epilog: like the help string but it's printed at the end of the916 help page after everything else.917 :param short_help: the short help to use for this command. This is918 shown on the command listing of the parent command.919 :param add_help_option: by default each command registers a ``--help``920 option. This can be disabled by this parameter.921 :param no_args_is_help: this controls what happens if no arguments are922 provided. This option is disabled by default.923 If enabled this will add ``--help`` as argument924 if no arguments are passed925 :param hidden: hide this command from help outputs.926927 :param deprecated: issues a message indicating that928 the command is deprecated.929 """930931 def __init__(932 self,933 name,934 context_settings=None,935 callback=None,936 params=None,937 help=None,938 epilog=None,939 short_help=None,940 options_metavar="[OPTIONS]",941 add_help_option=True,942 no_args_is_help=False,943 hidden=False,944 deprecated=False,945 ):946 BaseCommand.__init__(self, name, context_settings)947 #: the callback to execute when the command fires. This might be948 #: `None` in which case nothing happens.949 self.callback = callback950 #: the list of parameters for this command in the order they951 #: should show up in the help page and execute. Eager parameters952 #: will automatically be handled before non eager ones.953 self.params = params or []954 # if a form feed (page break) is found in the help text, truncate help955 # text to the content preceding the first form feed956 if help and "\f" in help:957 help = help.split("\f", 1)[0]958 self.help = help959 self.epilog = epilog960 self.options_metavar = options_metavar961 self.short_help = short_help962 self.add_help_option = add_help_option963 self.no_args_is_help = no_args_is_help964 self.hidden = hidden965 self.deprecated = deprecated966967 def __repr__(self):968 return "<{} {}>".format(self.__class__.__name__, self.name)969970 def get_usage(self, ctx):971 """Formats the usage line into a string and returns it.972973 Calls :meth:`format_usage` internally.974 """975 formatter = ctx.make_formatter()976 self.format_usage(ctx, formatter)977 return formatter.getvalue().rstrip("\n")978979 def get_params(self, ctx):980 rv = self.params981 help_option = self.get_help_option(ctx)982 if help_option is not None:983 rv = rv + [help_option]984 return rv985986 def format_usage(self, ctx, formatter):987 """Writes the usage line into the formatter.988989 This is a low-level method called by :meth:`get_usage`.990 """991 pieces = self.collect_usage_pieces(ctx)992 formatter.write_usage(ctx.command_path, " ".join(pieces))993994 def collect_usage_pieces(self, ctx):995 """Returns all the pieces that go into the usage line and returns996 it as a list of strings.997 """998 rv = [self.options_metavar]999 for param in self.get_params(ctx):1000 rv.extend(param.get_usage_pieces(ctx))1001 return rv10021003 def get_help_option_names(self, ctx):1004 """Returns the names for the help option."""1005 all_names = set(ctx.help_option_names)1006 for param in self.params:1007 all_names.difference_update(param.opts)1008 all_names.difference_update(param.secondary_opts)1009 return all_names10101011 def get_help_option(self, ctx):1012 """Returns the help option object."""1013 help_options = self.get_help_option_names(ctx)1014 if not help_options or not self.add_help_option:1015 return10161017 def show_help(ctx, param, value):1018 if value and not ctx.resilient_parsing:1019 echo(ctx.get_help(), color=ctx.color)1020 ctx.exit()10211022 return Option(1023 help_options,1024 is_flag=True,1025 is_eager=True,1026 expose_value=False,1027 callback=show_help,1028 help="Show this message and exit.",1029 )10301031 def make_parser(self, ctx):1032 """Creates the underlying option parser for this command."""1033 parser = OptionParser(ctx)1034 for param in self.get_params(ctx):1035 param.add_to_parser(parser, ctx)1036 return parser10371038 def get_help(self, ctx):1039 """Formats the help into a string and returns it.10401041 Calls :meth:`format_help` internally.1042 """1043 formatter = ctx.make_formatter()1044 self.format_help(ctx, formatter)1045 return formatter.getvalue().rstrip("\n")10461047 def get_short_help_str(self, limit=45):1048 """Gets short help for the command or makes it by shortening the1049 long help string.1050 """1051 return (1052 self.short_help1053 or self.help1054 and make_default_short_help(self.help, limit)1055 or ""1056 )10571058 def format_help(self, ctx, formatter):1059 """Writes the help into the formatter if it exists.10601061 This is a low-level method called by :meth:`get_help`.10621063 This calls the following methods:10641065 - :meth:`format_usage`1066 - :meth:`format_help_text`1067 - :meth:`format_options`1068 - :meth:`format_epilog`1069 """1070 self.format_usage(ctx, formatter)1071 self.format_help_text(ctx, formatter)1072 self.format_options(ctx, formatter)1073 self.format_epilog(ctx, formatter)10741075 def format_help_text(self, ctx, formatter):1076 """Writes the help text to the formatter if it exists."""1077 if self.help:1078 formatter.write_paragraph()1079 with formatter.indentation():1080 help_text = self.help1081 if self.deprecated:1082 help_text += DEPRECATED_HELP_NOTICE1083 formatter.write_text(help_text)1084 elif self.deprecated:1085 formatter.write_paragraph()1086 with formatter.indentation():1087 formatter.write_text(DEPRECATED_HELP_NOTICE)10881089 def format_options(self, ctx, formatter):1090 """Writes all the options into the formatter if they exist."""1091 opts = []1092 for param in self.get_params(ctx):1093 rv = param.get_help_record(ctx)1094 if rv is not None:1095 opts.append(rv)10961097 if opts:1098 with formatter.section("Options"):1099 formatter.write_dl(opts)11001101 def format_epilog(self, ctx, formatter):1102 """Writes the epilog into the formatter if it exists."""1103 if self.epilog:1104 formatter.write_paragraph()1105 with formatter.indentation():1106 formatter.write_text(self.epilog)11071108 def parse_args(self, ctx, args):1109 if not args and self.no_args_is_help and not ctx.resilient_parsing:1110 echo(ctx.get_help(), color=ctx.color)1111 ctx.exit()11121113 parser = self.make_parser(ctx)1114 opts, args, param_order = parser.parse_args(args=args)11151116 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1117 value, args = param.handle_parse_result(ctx, opts, args)11181119 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1120 ctx.fail(1121 "Got unexpected extra argument{} ({})".format(1122 "s" if len(args) != 1 else "", " ".join(map(make_str, args))1123 )1124 )11251126 ctx.args = args1127 return args11281129 def invoke(self, ctx):1130 """Given a context, this invokes the attached callback (if it exists)1131 in the right way.1132 """1133 _maybe_show_deprecated_notice(self)1134 if self.callback is not None:1135 return ctx.invoke(self.callback, **ctx.params)113611371138class MultiCommand(Command):1139 """A multi command is the basic implementation of a command that1140 dispatches to subcommands. The most common version is the1141 :class:`Group`.11421143 :param invoke_without_command: this controls how the multi command itself1144 is invoked. By default it's only invoked1145 if a subcommand is provided.1146 :param no_args_is_help: this controls what happens if no arguments are1147 provided. This option is enabled by default if1148 `invoke_without_command` is disabled or disabled1149 if it's enabled. If enabled this will add1150 ``--help`` as argument if no arguments are1151 passed.1152 :param subcommand_metavar: the string that is used in the documentation1153 to indicate the subcommand place.1154 :param chain: if this is set to `True` chaining of multiple subcommands1155 is enabled. This restricts the form of commands in that1156 they cannot have optional arguments but it allows1157 multiple commands to be chained together.1158 :param result_callback: the result callback to attach to this multi1159 command.1160 """11611162 allow_extra_args = True1163 allow_interspersed_args = False11641165 def __init__(1166 self,1167 name=None,1168 invoke_without_command=False,1169 no_args_is_help=None,1170 subcommand_metavar=None,1171 chain=False,1172 result_callback=None,1173 **attrs1174 ):1175 Command.__init__(self, name, **attrs)1176 if no_args_is_help is None:1177 no_args_is_help = not invoke_without_command1178 self.no_args_is_help = no_args_is_help1179 self.invoke_without_command = invoke_without_command1180 if subcommand_metavar is None:1181 if chain:1182 subcommand_metavar = SUBCOMMANDS_METAVAR1183 else:1184 subcommand_metavar = SUBCOMMAND_METAVAR1185 self.subcommand_metavar = subcommand_metavar1186 self.chain = chain1187 #: The result callback that is stored. This can be set or1188 #: overridden with the :func:`resultcallback` decorator.1189 self.result_callback = result_callback11901191 if self.chain:1192 for param in self.params:1193 if isinstance(param, Argument) and not param.required:1194 raise RuntimeError(1195 "Multi commands in chain mode cannot have"1196 " optional arguments."1197 )11981199 def collect_usage_pieces(self, ctx):1200 rv = Command.collect_usage_pieces(self, ctx)1201 rv.append(self.subcommand_metavar)1202 return rv12031204 def format_options(self, ctx, formatter):1205 Command.format_options(self, ctx, formatter)1206 self.format_commands(ctx, formatter)12071208 def resultcallback(self, replace=False):1209 """Adds a result callback to the chain command. By default if a1210 result callback is already registered this will chain them but1211 this can be disabled with the `replace` parameter. The result1212 callback is invoked with the return value of the subcommand1213 (or the list of return values from all subcommands if chaining1214 is enabled) as well as the parameters as they would be passed1215 to the main callback.12161217 Example::12181219 @click.group()1220 @click.option('-i', '--input', default=23)1221 def cli(input):1222 return 4212231224 @cli.resultcallback()1225 def process_result(result, input):1226 return result + input12271228 .. versionadded:: 3.012291230 :param replace: if set to `True` an already existing result1231 callback will be removed.1232 """12331234 def decorator(f):1235 old_callback = self.result_callback1236 if old_callback is None or replace:1237 self.result_callback = f1238 return f12391240 def function(__value, *args, **kwargs):1241 return f(old_callback(__value, *args, **kwargs), *args, **kwargs)12421243 self.result_callback = rv = update_wrapper(function, f)1244 return rv12451246 return decorator12471248 def format_commands(self, ctx, formatter):1249 """Extra format methods for multi methods that adds all the commands1250 after the options.1251 """1252 commands = []1253 for subcommand in self.list_commands(ctx):1254 cmd = self.get_command(ctx, subcommand)1255 # What is this, the tool lied about a command. Ignore it1256 if cmd is None:1257 continue1258 if cmd.hidden:1259 continue12601261 commands.append((subcommand, cmd))12621263 # allow for 3 times the default spacing1264 if len(commands):1265 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)12661267 rows = []1268 for subcommand, cmd in commands:1269 help = cmd.get_short_help_str(limit)1270 rows.append((subcommand, help))12711272 if rows:1273 with formatter.section("Commands"):1274 formatter.write_dl(rows)12751276 def parse_args(self, ctx, args):1277 if not args and self.no_args_is_help and not ctx.resilient_parsing:1278 echo(ctx.get_help(), color=ctx.color)1279 ctx.exit()12801281 rest = Command.parse_args(self, ctx, args)1282 if self.chain:1283 ctx.protected_args = rest1284 ctx.args = []1285 elif rest:1286 ctx.protected_args, ctx.args = rest[:1], rest[1:]12871288 return ctx.args12891290 def invoke(self, ctx):1291 def _process_result(value):1292 if self.result_callback is not None:1293 value = ctx.invoke(self.result_callback, value, **ctx.params)1294 return value12951296 if not ctx.protected_args:1297 # If we are invoked without command the chain flag controls1298 # how this happens. If we are not in chain mode, the return1299 # value here is the return value of the command.1300 # If however we are in chain mode, the return value is the1301 # return value of the result processor invoked with an empty1302 # list (which means that no subcommand actually was executed).1303 if self.invoke_without_command:1304 if not self.chain:1305 return Command.invoke(self, ctx)1306 with ctx:1307 Command.invoke(self, ctx)1308 return _process_result([])1309 ctx.fail("Missing command.")13101311 # Fetch args back out1312 args = ctx.protected_args + ctx.args1313 ctx.args = []1314 ctx.protected_args = []13151316 # If we're not in chain mode, we only allow the invocation of a1317 # single command but we also inform the current context about the1318 # name of the command to invoke.1319 if not self.chain:1320 # Make sure the context is entered so we do not clean up1321 # resources until the result processor has worked.1322 with ctx:1323 cmd_name, cmd, args = self.resolve_command(ctx, args)1324 ctx.invoked_subcommand = cmd_name1325 Command.invoke(self, ctx)1326 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1327 with sub_ctx:1328 return _process_result(sub_ctx.command.invoke(sub_ctx))13291330 # In chain mode we create the contexts step by step, but after the1331 # base command has been invoked. Because at that point we do not1332 # know the subcommands yet, the invoked subcommand attribute is1333 # set to ``*`` to inform the command that subcommands are executed1334 # but nothing else.1335 with ctx:1336 ctx.invoked_subcommand = "*" if args else None1337 Command.invoke(self, ctx)13381339 # Otherwise we make every single context and invoke them in a1340 # chain. In that case the return value to the result processor1341 # is the list of all invoked subcommand's results.1342 contexts = []1343 while args:1344 cmd_name, cmd, args = self.resolve_command(ctx, args)1345 sub_ctx = cmd.make_context(1346 cmd_name,1347 args,1348 parent=ctx,1349 allow_extra_args=True,1350 allow_interspersed_args=False,1351 )1352 contexts.append(sub_ctx)1353 args, sub_ctx.args = sub_ctx.args, []13541355 rv = []1356 for sub_ctx in contexts:1357 with sub_ctx:1358 rv.append(sub_ctx.command.invoke(sub_ctx))1359 return _process_result(rv)13601361 def resolve_command(self, ctx, args):1362 cmd_name = make_str(args[0])1363 original_cmd_name = cmd_name13641365 # Get the command1366 cmd = self.get_command(ctx, cmd_name)13671368 # If we can't find the command but there is a normalization1369 # function available, we try with that one.1370 if cmd is None and ctx.token_normalize_func is not None:1371 cmd_name = ctx.token_normalize_func(cmd_name)1372 cmd = self.get_command(ctx, cmd_name)13731374 # If we don't find the command we want to show an error message1375 # to the user that it was not provided. However, there is1376 # something else we should do: if the first argument looks like1377 # an option we want to kick off parsing again for arguments to1378 # resolve things like --help which now should go to the main1379 # place.1380 if cmd is None and not ctx.resilient_parsing:1381 if split_opt(cmd_name)[0]:1382 self.parse_args(ctx, ctx.args)1383 ctx.fail("No such command '{}'.".format(original_cmd_name))13841385 return cmd_name, cmd, args[1:]13861387 def get_command(self, ctx, cmd_name):1388 """Given a context and a command name, this returns a1389 :class:`Command` object if it exists or returns `None`.1390 """1391 raise NotImplementedError()13921393 def list_commands(self, ctx):1394 """Returns a list of subcommand names in the order they should1395 appear.1396 """1397 return []139813991400class Group(MultiCommand):1401 """A group allows a command to have subcommands attached. This is the1402 most common way to implement nesting in Click.14031404 :param commands: a dictionary of commands.1405 """14061407 def __init__(self, name=None, commands=None, **attrs):1408 MultiCommand.__init__(self, name, **attrs)1409 #: the registered subcommands by their exported names.1410 self.commands = commands or {}14111412 def add_command(self, cmd, name=None):1413 """Registers another :class:`Command` with this group. If the name1414 is not provided, the name of the command is used.1415 """1416 name = name or cmd.name1417 if name is None:1418 raise TypeError("Command has no name.")1419 _check_multicommand(self, name, cmd, register=True)1420 self.commands[name] = cmd14211422 def command(self, *args, **kwargs):1423 """A shortcut decorator for declaring and attaching a command to1424 the group. This takes the same arguments as :func:`command` but1425 immediately registers the created command with this instance by1426 calling into :meth:`add_command`.1427 """1428 from .decorators import command14291430 def decorator(f):1431 cmd = command(*args, **kwargs)(f)1432 self.add_command(cmd)1433 return cmd14341435 return decorator14361437 def group(self, *args, **kwargs):1438 """A shortcut decorator for declaring and attaching a group to1439 the group. This takes the same arguments as :func:`group` but1440 immediately registers the created command with this instance by1441 calling into :meth:`add_command`.1442 """1443 from .decorators import group14441445 def decorator(f):1446 cmd = group(*args, **kwargs)(f)1447 self.add_command(cmd)1448 return cmd14491450 return decorator14511452 def get_command(self, ctx, cmd_name):1453 return self.commands.get(cmd_name)14541455 def list_commands(self, ctx):1456 return sorted(self.commands)145714581459class CommandCollection(MultiCommand):1460 """A command collection is a multi command that merges multiple multi1461 commands together into one. This is a straightforward implementation1462 that accepts a list of different multi commands as sources and1463 provides all the commands for each of them.1464 """14651466 def __init__(self, name=None, sources=None, **attrs):1467 MultiCommand.__init__(self, name, **attrs)1468 #: The list of registered multi commands.1469 self.sources = sources or []14701471 def add_source(self, multi_cmd):1472 """Adds a new multi command to the chain dispatcher."""1473 self.sources.append(multi_cmd)14741475 def get_command(self, ctx, cmd_name):1476 for source in self.sources:1477 rv = source.get_command(ctx, cmd_name)1478 if rv is not None:1479 if self.chain:1480 _check_multicommand(self, cmd_name, rv)1481 return rv14821483 def list_commands(self, ctx):1484 rv = set()1485 for source in self.sources:1486 rv.update(source.list_commands(ctx))1487 return sorted(rv)148814891490class Parameter(object):1491 r"""A parameter to a command comes in two versions: they are either1492 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1493 not supported by design as some of the internals for parsing are1494 intentionally not finalized.14951496 Some settings are supported by both options and arguments.14971498 :param param_decls: the parameter declarations for this option or1499 argument. This is a list of flags or argument1500 names.1501 :param type: the type that should be used. Either a :class:`ParamType`1502 or a Python type. The later is converted into the former1503 automatically if supported.1504 :param required: controls if this is optional or not.1505 :param default: the default value if omitted. This can also be a callable,1506 in which case it's invoked when the default is needed1507 without any arguments.1508 :param callback: a callback that should be executed after the parameter1509 was matched. This is called as ``fn(ctx, param,1510 value)`` and needs to return the value. Before Click1511 2.0, the signature was ``(ctx, value)``.1512 :param nargs: the number of arguments to match. If not ``1`` the return1513 value is a tuple instead of single value. The default for1514 nargs is ``1`` (except if the type is a tuple, then it's1515 the arity of the tuple). If ``nargs=-1``, all remaining1516 parameters are collected.1517 :param metavar: how the value is represented in the help page.1518 :param expose_value: if this is `True` then the value is passed onwards1519 to the command callback and stored on the context,1520 otherwise it's skipped.1521 :param is_eager: eager values are processed before non eager ones. This1522 should not be set for arguments or it will inverse the1523 order of processing.1524 :param envvar: a string or list of strings that are environment variables1525 that should be checked.15261527 .. versionchanged:: 7.11528 Empty environment variables are ignored rather than taking the1529 empty string value. This makes it possible for scripts to clear1530 variables if they can't unset them.15311532 .. versionchanged:: 2.01533 Changed signature for parameter callback to also be passed the1534 parameter. The old callback format will still work, but it will1535 raise a warning to give you a chance to migrate the code easier.1536 """1537 param_type_name = "parameter"15381539 def __init__(1540 self,1541 param_decls=None,1542 type=None,1543 required=False,1544 default=None,1545 callback=None,1546 nargs=None,1547 metavar=None,1548 expose_value=True,1549 is_eager=False,1550 envvar=None,1551 autocompletion=None,1552 ):1553 self.name, self.opts, self.secondary_opts = self._parse_decls(1554 param_decls or (), expose_value1555 )15561557 self.type = convert_type(type, default)15581559 # Default nargs to what the type tells us if we have that1560 # information available.1561 if nargs is None:1562 if self.type.is_composite:1563 nargs = self.type.arity1564 else:1565 nargs = 115661567 self.required = required1568 self.callback = callback1569 self.nargs = nargs1570 self.multiple = False1571 self.expose_value = expose_value1572 self.default = default1573 self.is_eager = is_eager1574 self.metavar = metavar1575 self.envvar = envvar1576 self.autocompletion = autocompletion15771578 def __repr__(self):1579 return "<{} {}>".format(self.__class__.__name__, self.name)15801581 @property1582 def human_readable_name(self):1583 """Returns the human readable name of this parameter. This is the1584 same as the name for options, but the metavar for arguments.1585 """1586 return self.name15871588 def make_metavar(self):1589 if self.metavar is not None:1590 return self.metavar1591 metavar = self.type.get_metavar(self)1592 if metavar is None:1593 metavar = self.type.name.upper()1594 if self.nargs != 1:1595 metavar += "..."1596 return metavar15971598 def get_default(self, ctx):1599 """Given a context variable this calculates the default value."""1600 # Otherwise go with the regular default.1601 if callable(self.default):1602 rv = self.default()1603 else:1604 rv = self.default1605 return self.type_cast_value(ctx, rv)16061607 def add_to_parser(self, parser, ctx):1608 pass16091610 def consume_value(self, ctx, opts):1611 value = opts.get(self.name)1612 source = ParameterSource.COMMANDLINE1613 if value is None:1614 value = self.value_from_envvar(ctx)1615 source = ParameterSource.ENVIRONMENT1616 if value is None:1617 value = ctx.lookup_default(self.name)1618 source = ParameterSource.DEFAULT_MAP1619 if value is not None:1620 ctx.set_parameter_source(self.name, source)1621 return value16221623 def type_cast_value(self, ctx, value):1624 """Given a value this runs it properly through the type system.1625 This automatically handles things like `nargs` and `multiple` as1626 well as composite types.1627 """1628 if self.type.is_composite:1629 if self.nargs <= 1:1630 raise TypeError(1631 "Attempted to invoke composite type but nargs has"1632 " been set to {}. This is not supported; nargs"1633 " needs to be set to a fixed value > 1.".format(self.nargs)1634 )1635 if self.multiple:1636 return tuple(self.type(x or (), self, ctx) for x in value or ())1637 return self.type(value or (), self, ctx)16381639 def _convert(value, level):1640 if level == 0:1641 return self.type(value, self, ctx)1642 return tuple(_convert(x, level - 1) for x in value or ())16431644 return _convert(value, (self.nargs != 1) + bool(self.multiple))16451646 def process_value(self, ctx, value):1647 """Given a value and context this runs the logic to convert the1648 value as necessary.1649 """1650 # If the value we were given is None we do nothing. This way1651 # code that calls this can easily figure out if something was1652 # not provided. Otherwise it would be converted into an empty1653 # tuple for multiple invocations which is inconvenient.1654 if value is not None:1655 return self.type_cast_value(ctx, value)16561657 def value_is_missing(self, value):1658 if value is None:1659 return True1660 if (self.nargs != 1 or self.multiple) and value == ():1661 return True1662 return False16631664 def full_process_value(self, ctx, value):1665 value = self.process_value(ctx, value)16661667 if value is None and not ctx.resilient_parsing:1668 value = self.get_default(ctx)1669 if value is not None:1670 ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)16711672 if self.required and self.value_is_missing(value):1673 raise MissingParameter(ctx=ctx, param=self)16741675 return value16761677 def resolve_envvar_value(self, ctx):1678 if self.envvar is None:1679 return1680 if isinstance(self.envvar, (tuple, list)):1681 for envvar in self.envvar:1682 rv = os.environ.get(envvar)1683 if rv is not None:1684 return rv1685 else:1686 rv = os.environ.get(self.envvar)16871688 if rv != "":1689 return rv16901691 def value_from_envvar(self, ctx):1692 rv = self.resolve_envvar_value(ctx)1693 if rv is not None and self.nargs != 1:1694 rv = self.type.split_envvar_value(rv)1695 return rv16961697 def handle_parse_result(self, ctx, opts, args):1698 with augment_usage_errors(ctx, param=self):1699 value = self.consume_value(ctx, opts)1700 try:1701 value = self.full_process_value(ctx, value)1702 except Exception:1703 if not ctx.resilient_parsing:1704 raise1705 value = None1706 if self.callback is not None:1707 try:1708 value = invoke_param_callback(self.callback, ctx, self, value)1709 except Exception:1710 if not ctx.resilient_parsing:1711 raise17121713 if self.expose_value:1714 ctx.params[self.name] = value1715 return value, args17161717 def get_help_record(self, ctx):1718 pass17191720 def get_usage_pieces(self, ctx):1721 return []17221723 def get_error_hint(self, ctx):1724 """Get a stringified version of the param for use in error messages to1725 indicate which param caused the error.1726 """1727 hint_list = self.opts or [self.human_readable_name]1728 return " / ".join(repr(x) for x in hint_list)172917301731class Option(Parameter):1732 """Options are usually optional values on the command line and1733 have some extra features that arguments don't have.17341735 All other parameters are passed onwards to the parameter constructor.17361737 :param show_default: controls if the default value should be shown on the1738 help page. Normally, defaults are not shown. If this1739 value is a string, it shows the string instead of the1740 value. This is particularly useful for dynamic options.1741 :param show_envvar: controls if an environment variable should be shown on1742 the help page. Normally, environment variables1743 are not shown.1744 :param prompt: if set to `True` or a non empty string then the user will be1745 prompted for input. If set to `True` the prompt will be the1746 option name capitalized.1747 :param confirmation_prompt: if set then the value will need to be confirmed1748 if it was prompted for.1749 :param hide_input: if this is `True` then the input on the prompt will be1750 hidden from the user. This is useful for password1751 input.1752 :param is_flag: forces this option to act as a flag. The default is1753 auto detection.1754 :param flag_value: which value should be used for this flag if it's1755 enabled. This is set to a boolean automatically if1756 the option string contains a slash to mark two options.1757 :param multiple: if this is set to `True` then the argument is accepted1758 multiple times and recorded. This is similar to ``nargs``1759 in how it works but supports arbitrary number of1760 arguments.1761 :param count: this flag makes an option increment an integer.1762 :param allow_from_autoenv: if this is enabled then the value of this1763 parameter will be pulled from an environment1764 variable in case a prefix is defined on the1765 context.1766 :param help: the help string.1767 :param hidden: hide this option from help outputs.1768 """17691770 param_type_name = "option"17711772 def __init__(1773 self,1774 param_decls=None,1775 show_default=False,1776 prompt=False,1777 confirmation_prompt=False,1778 hide_input=False,1779 is_flag=None,1780 flag_value=None,1781 multiple=False,1782 count=False,1783 allow_from_autoenv=True,1784 type=None,1785 help=None,1786 hidden=False,1787 show_choices=True,1788 show_envvar=False,1789 **attrs1790 ):1791 default_is_missing = attrs.get("default", _missing) is _missing1792 Parameter.__init__(self, param_decls, type=type, **attrs)17931794 if prompt is True:1795 prompt_text = self.name.replace("_", " ").capitalize()1796 elif prompt is False:1797 prompt_text = None1798 else:1799 prompt_text = prompt1800 self.prompt = prompt_text1801 self.confirmation_prompt = confirmation_prompt1802 self.hide_input = hide_input1803 self.hidden = hidden18041805 # Flags1806 if is_flag is None:1807 if flag_value is not None:1808 is_flag = True1809 else:1810 is_flag = bool(self.secondary_opts)1811 if is_flag and default_is_missing:1812 self.default = False1813 if flag_value is None:1814 flag_value = not self.default1815 self.is_flag = is_flag1816 self.flag_value = flag_value1817 if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:1818 self.type = BOOL1819 self.is_bool_flag = True1820 else:1821 self.is_bool_flag = False18221823 # Counting1824 self.count = count1825 if count:1826 if type is None:1827 self.type = IntRange(min=0)1828 if default_is_missing:1829 self.default = 018301831 self.multiple = multiple1832 self.allow_from_autoenv = allow_from_autoenv1833 self.help = help1834 self.show_default = show_default1835 self.show_choices = show_choices1836 self.show_envvar = show_envvar18371838 # Sanity check for stuff we don't support1839 if __debug__:1840 if self.nargs < 0:1841 raise TypeError("Options cannot have nargs < 0")1842 if self.prompt and self.is_flag and not self.is_bool_flag:1843 raise TypeError("Cannot prompt for flags that are not bools.")1844 if not self.is_bool_flag and self.secondary_opts:1845 raise TypeError("Got secondary option for non boolean flag.")1846 if self.is_bool_flag and self.hide_input and self.prompt is not None:1847 raise TypeError("Hidden input does not work with boolean flag prompts.")1848 if self.count:1849 if self.multiple:1850 raise TypeError(1851 "Options cannot be multiple and count at the same time."1852 )1853 elif self.is_flag:1854 raise TypeError(1855 "Options cannot be count and flags at the same time."1856 )18571858 def _parse_decls(self, decls, expose_value):1859 opts = []1860 secondary_opts = []1861 name = None1862 possible_names = []18631864 for decl in decls:1865 if isidentifier(decl):1866 if name is not None:1867 raise TypeError("Name defined twice")1868 name = decl1869 else:1870 split_char = ";" if decl[:1] == "/" else "/"1871 if split_char in decl:1872 first, second = decl.split(split_char, 1)1873 first = first.rstrip()1874 if first:1875 possible_names.append(split_opt(first))1876 opts.append(first)1877 second = second.lstrip()1878 if second:1879 secondary_opts.append(second.lstrip())1880 else:1881 possible_names.append(split_opt(decl))1882 opts.append(decl)18831884 if name is None and possible_names:1885 possible_names.sort(key=lambda x: -len(x[0])) # group long options first1886 name = possible_names[0][1].replace("-", "_").lower()1887 if not isidentifier(name):1888 name = None18891890 if name is None:1891 if not expose_value:1892 return None, opts, secondary_opts1893 raise TypeError("Could not determine name for option")18941895 if not opts and not secondary_opts:1896 raise TypeError(1897 "No options defined but a name was passed ({}). Did you"1898 " mean to declare an argument instead of an option?".format(name)1899 )19001901 return name, opts, secondary_opts19021903 def add_to_parser(self, parser, ctx):1904 kwargs = {1905 "dest": self.name,1906 "nargs": self.nargs,1907 "obj": self,1908 }19091910 if self.multiple:1911 action = "append"1912 elif self.count:1913 action = "count"1914 else:1915 action = "store"19161917 if self.is_flag:1918 kwargs.pop("nargs", None)1919 action_const = "{}_const".format(action)1920 if self.is_bool_flag and self.secondary_opts:1921 parser.add_option(self.opts, action=action_const, const=True, **kwargs)1922 parser.add_option(1923 self.secondary_opts, action=action_const, const=False, **kwargs1924 )1925 else:1926 parser.add_option(1927 self.opts, action=action_const, const=self.flag_value, **kwargs1928 )1929 else:1930 kwargs["action"] = action1931 parser.add_option(self.opts, **kwargs)19321933 def get_help_record(self, ctx):1934 if self.hidden:1935 return1936 any_prefix_is_slash = []19371938 def _write_opts(opts):1939 rv, any_slashes = join_options(opts)1940 if any_slashes:1941 any_prefix_is_slash[:] = [True]1942 if not self.is_flag and not self.count:1943 rv += " {}".format(self.make_metavar())1944 return rv19451946 rv = [_write_opts(self.opts)]1947 if self.secondary_opts:1948 rv.append(_write_opts(self.secondary_opts))19491950 help = self.help or ""1951 extra = []1952 if self.show_envvar:1953 envvar = self.envvar1954 if envvar is None:1955 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1956 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1957 if envvar is not None:1958 extra.append(1959 "env var: {}".format(1960 ", ".join(str(d) for d in envvar)1961 if isinstance(envvar, (list, tuple))1962 else envvar1963 )1964 )1965 if self.default is not None and (self.show_default or ctx.show_default):1966 if isinstance(self.show_default, string_types):1967 default_string = "({})".format(self.show_default)1968 elif isinstance(self.default, (list, tuple)):1969 default_string = ", ".join(str(d) for d in self.default)1970 elif inspect.isfunction(self.default):1971 default_string = "(dynamic)"1972 else:1973 default_string = self.default1974 extra.append("default: {}".format(default_string))19751976 if self.required:1977 extra.append("required")1978 if extra:1979 help = "{}[{}]".format(1980 "{} ".format(help) if help else "", "; ".join(extra)1981 )19821983 return ("; " if any_prefix_is_slash else " / ").join(rv), help19841985 def get_default(self, ctx):1986 # If we're a non boolean flag our default is more complex because1987 # we need to look at all flags in the same group to figure out1988 # if we're the the default one in which case we return the flag1989 # value as default.1990 if self.is_flag and not self.is_bool_flag:1991 for param in ctx.command.params:1992 if param.name == self.name and param.default:1993 return param.flag_value1994 return None1995 return Parameter.get_default(self, ctx)19961997 def prompt_for_value(self, ctx):1998 """This is an alternative flow that can be activated in the full1999 value processing if a value does not exist. It will prompt the2000 user until a valid value exists and then returns the processed2001 value as result.2002 """2003 # Calculate the default before prompting anything to be stable.2004 default = self.get_default(ctx)20052006 # If this is a prompt for a flag we need to handle this2007 # differently.2008 if self.is_bool_flag:2009 return confirm(self.prompt, default)20102011 return prompt(2012 self.prompt,2013 default=default,2014 type=self.type,2015 hide_input=self.hide_input,2016 show_choices=self.show_choices,2017 confirmation_prompt=self.confirmation_prompt,2018 value_proc=lambda x: self.process_value(ctx, x),2019 )20202021 def resolve_envvar_value(self, ctx):2022 rv = Parameter.resolve_envvar_value(self, ctx)2023 if rv is not None:2024 return rv2025 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:2026 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())2027 return os.environ.get(envvar)20282029 def value_from_envvar(self, ctx):2030 rv = self.resolve_envvar_value(ctx)2031 if rv is None:2032 return None2033 value_depth = (self.nargs != 1) + bool(self.multiple)2034 if value_depth > 0 and rv is not None:2035 rv = self.type.split_envvar_value(rv)2036 if self.multiple and self.nargs != 1:2037 rv = batch(rv, self.nargs)2038 return rv20392040 def full_process_value(self, ctx, value):2041 if value is None and self.prompt is not None and not ctx.resilient_parsing:2042 return self.prompt_for_value(ctx)2043 return Parameter.full_process_value(self, ctx, value)204420452046class Argument(Parameter):2047 """Arguments are positional parameters to a command. They generally2048 provide fewer features than options but can have infinite ``nargs``2049 and are required by default.20502051 All parameters are passed onwards to the parameter constructor.2052 """20532054 param_type_name = "argument"20552056 def __init__(self, param_decls, required=None, **attrs):2057 if required is None:2058 if attrs.get("default") is not None:2059 required = False2060 else:2061 required = attrs.get("nargs", 1) > 02062 Parameter.__init__(self, param_decls, required=required, **attrs)2063 if self.default is not None and self.nargs < 0:2064 raise TypeError(2065 "nargs=-1 in combination with a default value is not supported."2066 )20672068 @property2069 def human_readable_name(self):2070 if self.metavar is not None:2071 return self.metavar2072 return self.name.upper()20732074 def make_metavar(self):2075 if self.metavar is not None:2076 return self.metavar2077 var = self.type.get_metavar(self)2078 if not var:2079 var = self.name.upper()2080 if not self.required:2081 var = "[{}]".format(var)2082 if self.nargs != 1:2083 var += "..."2084 return var20852086 def _parse_decls(self, decls, expose_value):2087 if not decls:2088 if not expose_value:2089 return None, [], []2090 raise TypeError("Could not determine name for argument")2091 if len(decls) == 1:2092 name = arg = decls[0]2093 name = name.replace("-", "_").lower()2094 else:2095 raise TypeError(2096 "Arguments take exactly one parameter declaration, got"2097 " {}".format(len(decls))2098 )2099 return name, [arg], []21002101 def get_usage_pieces(self, ctx):2102 return [self.make_metavar()]21032104 def get_error_hint(self, ctx):2105 return repr(self.make_metavar())21062107 def add_to_parser(self, parser, ctx):2108 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
added:src/click/decorators.py+333 added
1import inspect2import sys3from functools import update_wrapper45from ._compat import iteritems6from ._unicodefun import _check_for_unicode_literals7from .core import Argument8from .core import Command9from .core import Group10from .core import Option11from .globals import get_current_context12from .utils import echo131415def pass_context(f):16 """Marks a callback as wanting to receive the current context17 object as first argument.18 """1920 def new_func(*args, **kwargs):21 return f(get_current_context(), *args, **kwargs)2223 return update_wrapper(new_func, f)242526def pass_obj(f):27 """Similar to :func:`pass_context`, but only pass the object on the28 context onwards (:attr:`Context.obj`). This is useful if that object29 represents the state of a nested system.30 """3132 def new_func(*args, **kwargs):33 return f(get_current_context().obj, *args, **kwargs)3435 return update_wrapper(new_func, f)363738def make_pass_decorator(object_type, ensure=False):39 """Given an object type this creates a decorator that will work40 similar to :func:`pass_obj` but instead of passing the object of the41 current context, it will find the innermost context of type42 :func:`object_type`.4344 This generates a decorator that works roughly like this::4546 from functools import update_wrapper4748 def decorator(f):49 @pass_context50 def new_func(ctx, *args, **kwargs):51 obj = ctx.find_object(object_type)52 return ctx.invoke(f, obj, *args, **kwargs)53 return update_wrapper(new_func, f)54 return decorator5556 :param object_type: the type of the object to pass.57 :param ensure: if set to `True`, a new object will be created and58 remembered on the context if it's not there yet.59 """6061 def decorator(f):62 def new_func(*args, **kwargs):63 ctx = get_current_context()64 if ensure:65 obj = ctx.ensure_object(object_type)66 else:67 obj = ctx.find_object(object_type)68 if obj is None:69 raise RuntimeError(70 "Managed to invoke callback without a context"71 " object of type '{}' existing".format(object_type.__name__)72 )73 return ctx.invoke(f, obj, *args, **kwargs)7475 return update_wrapper(new_func, f)7677 return decorator787980def _make_command(f, name, attrs, cls):81 if isinstance(f, Command):82 raise TypeError("Attempted to convert a callback into a command twice.")83 try:84 params = f.__click_params__85 params.reverse()86 del f.__click_params__87 except AttributeError:88 params = []89 help = attrs.get("help")90 if help is None:91 help = inspect.getdoc(f)92 if isinstance(help, bytes):93 help = help.decode("utf-8")94 else:95 help = inspect.cleandoc(help)96 attrs["help"] = help97 _check_for_unicode_literals()98 return cls(99 name=name or f.__name__.lower().replace("_", "-"),100 callback=f,101 params=params,102 **attrs103 )104105106def command(name=None, cls=None, **attrs):107 r"""Creates a new :class:`Command` and uses the decorated function as108 callback. This will also automatically attach all decorated109 :func:`option`\s and :func:`argument`\s as parameters to the command.110111 The name of the command defaults to the name of the function with112 underscores replaced by dashes. If you want to change that, you can113 pass the intended name as the first argument.114115 All keyword arguments are forwarded to the underlying command class.116117 Once decorated the function turns into a :class:`Command` instance118 that can be invoked as a command line utility or be attached to a119 command :class:`Group`.120121 :param name: the name of the command. This defaults to the function122 name with underscores replaced by dashes.123 :param cls: the command class to instantiate. This defaults to124 :class:`Command`.125 """126 if cls is None:127 cls = Command128129 def decorator(f):130 cmd = _make_command(f, name, attrs, cls)131 cmd.__doc__ = f.__doc__132 return cmd133134 return decorator135136137def group(name=None, **attrs):138 """Creates a new :class:`Group` with a function as callback. This139 works otherwise the same as :func:`command` just that the `cls`140 parameter is set to :class:`Group`.141 """142 attrs.setdefault("cls", Group)143 return command(name, **attrs)144145146def _param_memo(f, param):147 if isinstance(f, Command):148 f.params.append(param)149 else:150 if not hasattr(f, "__click_params__"):151 f.__click_params__ = []152 f.__click_params__.append(param)153154155def argument(*param_decls, **attrs):156 """Attaches an argument to the command. All positional arguments are157 passed as parameter declarations to :class:`Argument`; all keyword158 arguments are forwarded unchanged (except ``cls``).159 This is equivalent to creating an :class:`Argument` instance manually160 and attaching it to the :attr:`Command.params` list.161162 :param cls: the argument class to instantiate. This defaults to163 :class:`Argument`.164 """165166 def decorator(f):167 ArgumentClass = attrs.pop("cls", Argument)168 _param_memo(f, ArgumentClass(param_decls, **attrs))169 return f170171 return decorator172173174def option(*param_decls, **attrs):175 """Attaches an option to the command. All positional arguments are176 passed as parameter declarations to :class:`Option`; all keyword177 arguments are forwarded unchanged (except ``cls``).178 This is equivalent to creating an :class:`Option` instance manually179 and attaching it to the :attr:`Command.params` list.180181 :param cls: the option class to instantiate. This defaults to182 :class:`Option`.183 """184185 def decorator(f):186 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=187 option_attrs = attrs.copy()188189 if "help" in option_attrs:190 option_attrs["help"] = inspect.cleandoc(option_attrs["help"])191 OptionClass = option_attrs.pop("cls", Option)192 _param_memo(f, OptionClass(param_decls, **option_attrs))193 return f194195 return decorator196197198def confirmation_option(*param_decls, **attrs):199 """Shortcut for confirmation prompts that can be ignored by passing200 ``--yes`` as parameter.201202 This is equivalent to decorating a function with :func:`option` with203 the following parameters::204205 def callback(ctx, param, value):206 if not value:207 ctx.abort()208209 @click.command()210 @click.option('--yes', is_flag=True, callback=callback,211 expose_value=False, prompt='Do you want to continue?')212 def dropdb():213 pass214 """215216 def decorator(f):217 def callback(ctx, param, value):218 if not value:219 ctx.abort()220221 attrs.setdefault("is_flag", True)222 attrs.setdefault("callback", callback)223 attrs.setdefault("expose_value", False)224 attrs.setdefault("prompt", "Do you want to continue?")225 attrs.setdefault("help", "Confirm the action without prompting.")226 return option(*(param_decls or ("--yes",)), **attrs)(f)227228 return decorator229230231def password_option(*param_decls, **attrs):232 """Shortcut for password prompts.233234 This is equivalent to decorating a function with :func:`option` with235 the following parameters::236237 @click.command()238 @click.option('--password', prompt=True, confirmation_prompt=True,239 hide_input=True)240 def changeadmin(password):241 pass242 """243244 def decorator(f):245 attrs.setdefault("prompt", True)246 attrs.setdefault("confirmation_prompt", True)247 attrs.setdefault("hide_input", True)248 return option(*(param_decls or ("--password",)), **attrs)(f)249250 return decorator251252253def version_option(version=None, *param_decls, **attrs):254 """Adds a ``--version`` option which immediately ends the program255 printing out the version number. This is implemented as an eager256 option that prints the version and exits the program in the callback.257258 :param version: the version number to show. If not provided Click259 attempts an auto discovery via setuptools.260 :param prog_name: the name of the program (defaults to autodetection)261 :param message: custom message to show instead of the default262 (``'%(prog)s, version %(version)s'``)263 :param others: everything else is forwarded to :func:`option`.264 """265 if version is None:266 if hasattr(sys, "_getframe"):267 module = sys._getframe(1).f_globals.get("__name__")268 else:269 module = ""270271 def decorator(f):272 prog_name = attrs.pop("prog_name", None)273 message = attrs.pop("message", "%(prog)s, version %(version)s")274275 def callback(ctx, param, value):276 if not value or ctx.resilient_parsing:277 return278 prog = prog_name279 if prog is None:280 prog = ctx.find_root().info_name281 ver = version282 if ver is None:283 try:284 import pkg_resources285 except ImportError:286 pass287 else:288 for dist in pkg_resources.working_set:289 scripts = dist.get_entry_map().get("console_scripts") or {}290 for _, entry_point in iteritems(scripts):291 if entry_point.module_name == module:292 ver = dist.version293 break294 if ver is None:295 raise RuntimeError("Could not determine version")296 echo(message % {"prog": prog, "version": ver}, color=ctx.color)297 ctx.exit()298299 attrs.setdefault("is_flag", True)300 attrs.setdefault("expose_value", False)301 attrs.setdefault("is_eager", True)302 attrs.setdefault("help", "Show the version and exit.")303 attrs["callback"] = callback304 return option(*(param_decls or ("--version",)), **attrs)(f)305306 return decorator307308309def help_option(*param_decls, **attrs):310 """Adds a ``--help`` option which immediately ends the program311 printing out the help page. This is usually unnecessary to add as312 this is added by default to all commands unless suppressed.313314 Like :func:`version_option`, this is implemented as eager option that315 prints in the callback and exits.316317 All arguments are forwarded to :func:`option`.318 """319320 def decorator(f):321 def callback(ctx, param, value):322 if value and not ctx.resilient_parsing:323 echo(ctx.get_help(), color=ctx.color)324 ctx.exit()325326 attrs.setdefault("is_flag", True)327 attrs.setdefault("expose_value", False)328 attrs.setdefault("help", "Show this message and exit.")329 attrs.setdefault("is_eager", True)330 attrs["callback"] = callback331 return option(*(param_decls or ("--help",)), **attrs)(f)332333 return decorator
added:src/click/exceptions.py+253 added
1from ._compat import filename_to_ui2from ._compat import get_text_stderr3from ._compat import PY24from .utils import echo567def _join_param_hints(param_hint):8 if isinstance(param_hint, (tuple, list)):9 return " / ".join(repr(x) for x in param_hint)10 return param_hint111213class ClickException(Exception):14 """An exception that Click can handle and show to the user."""1516 #: The exit code for this exception17 exit_code = 11819 def __init__(self, message):20 ctor_msg = message21 if PY2:22 if ctor_msg is not None:23 ctor_msg = ctor_msg.encode("utf-8")24 Exception.__init__(self, ctor_msg)25 self.message = message2627 def format_message(self):28 return self.message2930 def __str__(self):31 return self.message3233 if PY2:34 __unicode__ = __str__3536 def __str__(self):37 return self.message.encode("utf-8")3839 def show(self, file=None):40 if file is None:41 file = get_text_stderr()42 echo("Error: {}".format(self.format_message(), file=file))434445class UsageError(ClickException):46 """An internal exception that signals a usage error. This typically47 aborts any further handling.4849 :param message: the error message to display.50 :param ctx: optionally the context that caused this error. Click will51 fill in the context automatically in some situations.52 """5354 exit_code = 25556 def __init__(self, message, ctx=None):57 ClickException.__init__(self, message)58 self.ctx = ctx59 self.cmd = self.ctx.command if self.ctx else None6061 def show(self, file=None):62 if file is None:63 file = get_text_stderr()64 color = None65 hint = ""66 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67 hint = "Try '{} {}' for help.\n".format(68 self.ctx.command_path, self.ctx.help_option_names[0]69 )70 if self.ctx is not None:71 color = self.ctx.color72 echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)73 echo("Error: {}".format(self.format_message()), file=file, color=color)747576class BadParameter(UsageError):77 """An exception that formats out a standardized error message for a78 bad parameter. This is useful when thrown from a callback or type as79 Click will attach contextual information to it (for instance, which80 parameter it is).8182 .. versionadded:: 2.08384 :param param: the parameter object that caused this error. This can85 be left out, and Click will attach this info itself86 if possible.87 :param param_hint: a string that shows up as parameter name. This88 can be used as alternative to `param` in cases89 where custom validation should happen. If it is90 a string it's used as such, if it's a list then91 each item is quoted and separated.92 """9394 def __init__(self, message, ctx=None, param=None, param_hint=None):95 UsageError.__init__(self, message, ctx)96 self.param = param97 self.param_hint = param_hint9899 def format_message(self):100 if self.param_hint is not None:101 param_hint = self.param_hint102 elif self.param is not None:103 param_hint = self.param.get_error_hint(self.ctx)104 else:105 return "Invalid value: {}".format(self.message)106 param_hint = _join_param_hints(param_hint)107108 return "Invalid value for {}: {}".format(param_hint, self.message)109110111class MissingParameter(BadParameter):112 """Raised if click required an option or argument but it was not113 provided when invoking the script.114115 .. versionadded:: 4.0116117 :param param_type: a string that indicates the type of the parameter.118 The default is to inherit the parameter type from119 the given `param`. Valid values are ``'parameter'``,120 ``'option'`` or ``'argument'``.121 """122123 def __init__(124 self, message=None, ctx=None, param=None, param_hint=None, param_type=None125 ):126 BadParameter.__init__(self, message, ctx, param, param_hint)127 self.param_type = param_type128129 def format_message(self):130 if self.param_hint is not None:131 param_hint = self.param_hint132 elif self.param is not None:133 param_hint = self.param.get_error_hint(self.ctx)134 else:135 param_hint = None136 param_hint = _join_param_hints(param_hint)137138 param_type = self.param_type139 if param_type is None and self.param is not None:140 param_type = self.param.param_type_name141142 msg = self.message143 if self.param is not None:144 msg_extra = self.param.type.get_missing_message(self.param)145 if msg_extra:146 if msg:147 msg += ". {}".format(msg_extra)148 else:149 msg = msg_extra150151 return "Missing {}{}{}{}".format(152 param_type,153 " {}".format(param_hint) if param_hint else "",154 ". " if msg else ".",155 msg or "",156 )157158 def __str__(self):159 if self.message is None:160 param_name = self.param.name if self.param else None161 return "missing parameter: {}".format(param_name)162 else:163 return self.message164165 if PY2:166 __unicode__ = __str__167168 def __str__(self):169 return self.__unicode__().encode("utf-8")170171172class NoSuchOption(UsageError):173 """Raised if click attempted to handle an option that does not174 exist.175176 .. versionadded:: 4.0177 """178179 def __init__(self, option_name, message=None, possibilities=None, ctx=None):180 if message is None:181 message = "no such option: {}".format(option_name)182 UsageError.__init__(self, message, ctx)183 self.option_name = option_name184 self.possibilities = possibilities185186 def format_message(self):187 bits = [self.message]188 if self.possibilities:189 if len(self.possibilities) == 1:190 bits.append("Did you mean {}?".format(self.possibilities[0]))191 else:192 possibilities = sorted(self.possibilities)193 bits.append("(Possible options: {})".format(", ".join(possibilities)))194 return " ".join(bits)195196197class BadOptionUsage(UsageError):198 """Raised if an option is generally supplied but the use of the option199 was incorrect. This is for instance raised if the number of arguments200 for an option is not correct.201202 .. versionadded:: 4.0203204 :param option_name: the name of the option being used incorrectly.205 """206207 def __init__(self, option_name, message, ctx=None):208 UsageError.__init__(self, message, ctx)209 self.option_name = option_name210211212class BadArgumentUsage(UsageError):213 """Raised if an argument is generally supplied but the use of the argument214 was incorrect. This is for instance raised if the number of values215 for an argument is not correct.216217 .. versionadded:: 6.0218 """219220 def __init__(self, message, ctx=None):221 UsageError.__init__(self, message, ctx)222223224class FileError(ClickException):225 """Raised if a file cannot be opened."""226227 def __init__(self, filename, hint=None):228 ui_filename = filename_to_ui(filename)229 if hint is None:230 hint = "unknown error"231 ClickException.__init__(self, hint)232 self.ui_filename = ui_filename233 self.filename = filename234235 def format_message(self):236 return "Could not open file {}: {}".format(self.ui_filename, self.message)237238239class Abort(RuntimeError):240 """An internal signalling exception that signals Click to abort."""241242243class Exit(RuntimeError):244 """An exception that indicates that the application should exit with some245 status code.246247 :param code: the status code to exit with.248 """249250 __slots__ = ("exit_code",)251252 def __init__(self, code=0):253 self.exit_code = code
added:src/click/formatting.py+283 added
1from contextlib import contextmanager23from ._compat import term_len4from .parser import split_opt5from .termui import get_terminal_size67# Can force a width. This is used by the test system8FORCED_WIDTH = None91011def 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()))171819def iter_rows(rows, col_count):20 for row in rows:21 row = tuple(row)22 yield row + ("",) * (col_count - len(row))232425def wrap_text(26 text, width=78, initial_indent="", subsequent_indent="", preserve_paragraphs=False27):28 """A helper function that intelligently wraps text. By default, it29 assumes that it operates on a single paragraph of text but if the30 `preserve_paragraphs` parameter is provided it will intelligently31 handle paragraphs (defined by two empty lines).3233 If paragraphs are handled, a paragraph can be prefixed with an empty34 line containing the ``\\b`` character (``\\x08``) to indicate that35 no rewrapping should happen in that block.3637 :param text: the text that should be rewrapped.38 :param width: the maximum width for the text.39 :param initial_indent: the initial indent that should be placed on the40 first line as a string.41 :param subsequent_indent: the indent string that should be placed on42 each consecutive line.43 :param preserve_paragraphs: if this flag is set then the wrapping will44 intelligently handle paragraphs.45 """46 from ._textwrap import TextWrapper4748 text = text.expandtabs()49 wrapper = TextWrapper(50 width,51 initial_indent=initial_indent,52 subsequent_indent=subsequent_indent,53 replace_whitespace=False,54 )55 if not preserve_paragraphs:56 return wrapper.fill(text)5758 p = []59 buf = []60 indent = None6162 def _flush_par():63 if not buf:64 return65 if buf[0].strip() == "\b":66 p.append((indent or 0, True, "\n".join(buf[1:])))67 else:68 p.append((indent or 0, False, " ".join(buf)))69 del buf[:]7071 for line in text.splitlines():72 if not line:73 _flush_par()74 indent = None75 else:76 if indent is None:77 orig_len = term_len(line)78 line = line.lstrip()79 indent = orig_len - term_len(line)80 buf.append(line)81 _flush_par()8283 rv = []84 for indent, raw, text in p:85 with wrapper.extra_indent(" " * indent):86 if raw:87 rv.append(wrapper.indent_only(text))88 else:89 rv.append(wrapper.fill(text))9091 return "\n\n".join(rv)929394class HelpFormatter(object):95 """This class helps with formatting text-based help pages. It's96 usually just needed for very special internal cases, but it's also97 exposed so that developers can write their own fancy outputs.9899 At present, it always writes into memory.100101 :param indent_increment: the additional increment for each level.102 :param width: the width for the text. This defaults to the terminal103 width clamped to a maximum of 78.104 """105106 def __init__(self, indent_increment=2, width=None, max_width=None):107 self.indent_increment = indent_increment108 if max_width is None:109 max_width = 80110 if width is None:111 width = FORCED_WIDTH112 if width is None:113 width = max(min(get_terminal_size()[0], max_width) - 2, 50)114 self.width = width115 self.current_indent = 0116 self.buffer = []117118 def write(self, string):119 """Writes a unicode string into the internal buffer."""120 self.buffer.append(string)121122 def indent(self):123 """Increases the indentation."""124 self.current_indent += self.indent_increment125126 def dedent(self):127 """Decreases the indentation."""128 self.current_indent -= self.indent_increment129130 def write_usage(self, prog, args="", prefix="Usage: "):131 """Writes a usage line into the buffer.132133 :param prog: the program name.134 :param args: whitespace separated list of arguments.135 :param prefix: the prefix for the first line.136 """137 usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)138 text_width = self.width - self.current_indent139140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.142 indent = " " * term_len(usage_prefix)143 self.write(144 wrap_text(145 args,146 text_width,147 initial_indent=usage_prefix,148 subsequent_indent=indent,149 )150 )151 else:152 # The prefix is too long, put the arguments on the next line.153 self.write(usage_prefix)154 self.write("\n")155 indent = " " * (max(self.current_indent, term_len(prefix)) + 4)156 self.write(157 wrap_text(158 args, text_width, initial_indent=indent, subsequent_indent=indent159 )160 )161162 self.write("\n")163164 def write_heading(self, heading):165 """Writes a heading into the buffer."""166 self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))167168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:171 self.write("\n")172173 def write_text(self, text):174 """Writes re-indented text into the buffer. This rewraps and175 preserves paragraphs.176 """177 text_width = max(self.width - self.current_indent, 11)178 indent = " " * self.current_indent179 self.write(180 wrap_text(181 text,182 text_width,183 initial_indent=indent,184 subsequent_indent=indent,185 preserve_paragraphs=True,186 )187 )188 self.write("\n")189190 def write_dl(self, rows, col_max=30, col_spacing=2):191 """Writes a definition list into the buffer. This is how options192 and commands are usually formatted.193194 :param rows: a list of two item tuples for the terms and values.195 :param col_max: the maximum width of the first column.196 :param col_spacing: the number of spaces between the first and197 second column.198 """199 rows = list(rows)200 widths = measure_table(rows)201 if len(widths) != 2:202 raise TypeError("Expected two columns for definition list")203204 first_col = min(widths[0], col_max) + col_spacing205206 for first, second in iter_rows(rows, len(widths)):207 self.write("{:>{w}}{}".format("", first, w=self.current_indent))208 if not second:209 self.write("\n")210 continue211 if term_len(first) <= first_col - col_spacing:212 self.write(" " * (first_col - term_len(first)))213 else:214 self.write("\n")215 self.write(" " * (first_col + self.current_indent))216217 text_width = max(self.width - first_col - 2, 10)218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220221 if lines:222 self.write("{}\n".format(lines[0]))223224 for line in lines[1:]:225 self.write(226 "{:>{w}}{}\n".format(227 "", line, w=first_col + self.current_indent228 )229 )230231 if len(lines) > 1:232 # separate long help from next option233 self.write("\n")234 else:235 self.write("\n")236237 @contextmanager238 def section(self, name):239 """Helpful context manager that writes a paragraph, a heading,240 and the indents.241242 :param name: the section name that is written as heading.243 """244 self.write_paragraph()245 self.write_heading(name)246 self.indent()247 try:248 yield249 finally:250 self.dedent()251252 @contextmanager253 def indentation(self):254 """A context manager that increases the indentation."""255 self.indent()256 try:257 yield258 finally:259 self.dedent()260261 def getvalue(self):262 """Returns the buffer contents."""263 return "".join(self.buffer)264265266def join_options(options):267 """Given a list of option strings this joins them in the most appropriate268 way and returns them in the form ``(formatted_string,269 any_prefix_is_slash)`` where the second item in the tuple is a flag that270 indicates if any of the option prefixes was a slash.271 """272 rv = []273 any_prefix_is_slash = False274 for opt in options:275 prefix = split_opt(opt)[0]276 if prefix == "/":277 any_prefix_is_slash = True278 rv.append((len(prefix), opt))279280 rv.sort(key=lambda x: x[0])281282 rv = ", ".join(x[1] for x in rv)283 return rv, any_prefix_is_slash
added:src/click/globals.py+47 added
1from threading import local23_local = local()456def get_current_context(silent=False):7 """Returns the current click context. This can be used as a way to8 access the current context object from anywhere. This is a more implicit9 alternative to the :func:`pass_context` decorator. This function is10 primarily useful for helpers such as :func:`echo` which might be11 interested in changing its behavior based on the current context.1213 To push the current context, :meth:`Context.scope` can be used.1415 .. versionadded:: 5.01617 :param silent: if set to `True` the return value is `None` if no context18 is available. The default behavior is to raise a19 :exc:`RuntimeError`.20 """21 try:22 return _local.stack[-1]23 except (AttributeError, IndexError):24 if not silent:25 raise RuntimeError("There is no active click context.")262728def push_context(ctx):29 """Pushes a new context to the current stack."""30 _local.__dict__.setdefault("stack", []).append(ctx)313233def pop_context():34 """Removes the top level from the stack."""35 _local.stack.pop()363738def resolve_color_default(color=None):39 """"Internal helper to get the default value of the color flag. If a40 value is passed it's returned unchanged, otherwise it's looked up from41 the current context.42 """43 if color is not None:44 return color45 ctx = get_current_context(silent=True)46 if ctx is not None:47 return ctx.color
added:src/click/parser.py+432 added
1# -*- coding: utf-8 -*-2"""3This module started out as largely a copy paste from the stdlib's4optparse module with the features removed that we do not need from5optparse because we implement them in Click on a higher level (for6instance type handling, help formatting and a lot more).78The plan is to remove more and more from here over time.910The reason this is a different module and not optparse from the stdlib11is that there are differences in 2.x and 3.x about the error messages12generated and optparse in the stdlib uses gettext for no good reason13and might cause us issues.1415Click uses parts of optparse written by Gregory P. Ward and maintained16by the Python Software Foundation. This is limited to code in parser.py.1718Copyright 2001-2006 Gregory P. Ward. All rights reserved.19Copyright 2002-2006 Python Software Foundation. All rights reserved.20"""21# This code uses parts of optparse written by Gregory P. Ward and22# maintained by the Python Software Foundation.23# Copyright 2001-2006 Gregory P. Ward24# Copyright 2002-2006 Python Software Foundation25import re26from collections import deque2728from .exceptions import BadArgumentUsage29from .exceptions import BadOptionUsage30from .exceptions import NoSuchOption31from .exceptions import UsageError323334def _unpack_args(args, nargs_spec):35 """Given an iterable of arguments and an iterable of nargs specifications,36 it returns a tuple with all the unpacked arguments at the first index37 and all remaining arguments as the second.3839 The nargs specification is the number of arguments that should be consumed40 or `-1` to indicate that this position should eat up all the remainders.4142 Missing items are filled with `None`.43 """44 args = deque(args)45 nargs_spec = deque(nargs_spec)46 rv = []47 spos = None4849 def _fetch(c):50 try:51 if spos is None:52 return c.popleft()53 else:54 return c.pop()55 except IndexError:56 return None5758 while nargs_spec:59 nargs = _fetch(nargs_spec)60 if nargs == 1:61 rv.append(_fetch(args))62 elif nargs > 1:63 x = [_fetch(args) for _ in range(nargs)]64 # If we're reversed, we're pulling in the arguments in reverse,65 # so we need to turn them around.66 if spos is not None:67 x.reverse()68 rv.append(tuple(x))69 elif nargs < 0:70 if spos is not None:71 raise TypeError("Cannot have two nargs < 0")72 spos = len(rv)73 rv.append(None)7475 # spos is the position of the wildcard (star). If it's not `None`,76 # we fill it with the remainder.77 if spos is not None:78 rv[spos] = tuple(args)79 args = []80 rv[spos + 1 :] = reversed(rv[spos + 1 :])8182 return tuple(rv), list(args)838485def _error_opt_args(nargs, opt):86 if nargs == 1:87 raise BadOptionUsage(opt, "{} option requires an argument".format(opt))88 raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs))899091def split_opt(opt):92 first = opt[:1]93 if first.isalnum():94 return "", opt95 if opt[1:2] == first:96 return opt[:2], opt[2:]97 return first, opt[1:]9899100def normalize_opt(opt, ctx):101 if ctx is None or ctx.token_normalize_func is None:102 return opt103 prefix, opt = split_opt(opt)104 return prefix + ctx.token_normalize_func(opt)105106107def split_arg_string(string):108 """Given an argument string this attempts to split it into small parts."""109 rv = []110 for match in re.finditer(111 r"('([^'\\]*(?:\\.[^'\\]*)*)'|\"([^\"\\]*(?:\\.[^\"\\]*)*)\"|\S+)\s*",112 string,113 re.S,114 ):115 arg = match.group().strip()116 if arg[:1] == arg[-1:] and arg[:1] in "\"'":117 arg = arg[1:-1].encode("ascii", "backslashreplace").decode("unicode-escape")118 try:119 arg = type(string)(arg)120 except UnicodeError:121 pass122 rv.append(arg)123 return rv124125126class Option(object):127 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):128 self._short_opts = []129 self._long_opts = []130 self.prefixes = set()131132 for opt in opts:133 prefix, value = split_opt(opt)134 if not prefix:135 raise ValueError("Invalid start character for option ({})".format(opt))136 self.prefixes.add(prefix[0])137 if len(prefix) == 1 and len(value) == 1:138 self._short_opts.append(opt)139 else:140 self._long_opts.append(opt)141 self.prefixes.add(prefix)142143 if action is None:144 action = "store"145146 self.dest = dest147 self.action = action148 self.nargs = nargs149 self.const = const150 self.obj = obj151152 @property153 def takes_value(self):154 return self.action in ("store", "append")155156 def process(self, value, state):157 if self.action == "store":158 state.opts[self.dest] = value159 elif self.action == "store_const":160 state.opts[self.dest] = self.const161 elif self.action == "append":162 state.opts.setdefault(self.dest, []).append(value)163 elif self.action == "append_const":164 state.opts.setdefault(self.dest, []).append(self.const)165 elif self.action == "count":166 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1167 else:168 raise ValueError("unknown action '{}'".format(self.action))169 state.order.append(self.obj)170171172class Argument(object):173 def __init__(self, dest, nargs=1, obj=None):174 self.dest = dest175 self.nargs = nargs176 self.obj = obj177178 def process(self, value, state):179 if self.nargs > 1:180 holes = sum(1 for x in value if x is None)181 if holes == len(value):182 value = None183 elif holes != 0:184 raise BadArgumentUsage(185 "argument {} takes {} values".format(self.dest, self.nargs)186 )187 state.opts[self.dest] = value188 state.order.append(self.obj)189190191class ParsingState(object):192 def __init__(self, rargs):193 self.opts = {}194 self.largs = []195 self.rargs = rargs196 self.order = []197198199class OptionParser(object):200 """The option parser is an internal class that is ultimately used to201 parse options and arguments. It's modelled after optparse and brings202 a similar but vastly simplified API. It should generally not be used203 directly as the high level Click classes wrap it for you.204205 It's not nearly as extensible as optparse or argparse as it does not206 implement features that are implemented on a higher level (such as207 types or defaults).208209 :param ctx: optionally the :class:`~click.Context` where this parser210 should go with.211 """212213 def __init__(self, ctx=None):214 #: The :class:`~click.Context` for this parser. This might be215 #: `None` for some advanced use cases.216 self.ctx = ctx217 #: This controls how the parser deals with interspersed arguments.218 #: If this is set to `False`, the parser will stop on the first219 #: non-option. Click uses this to implement nested subcommands220 #: safely.221 self.allow_interspersed_args = True222 #: This tells the parser how to deal with unknown options. By223 #: default it will error out (which is sensible), but there is a224 #: second mode where it will ignore it and continue processing225 #: after shifting all the unknown options into the resulting args.226 self.ignore_unknown_options = False227 if ctx is not None:228 self.allow_interspersed_args = ctx.allow_interspersed_args229 self.ignore_unknown_options = ctx.ignore_unknown_options230 self._short_opt = {}231 self._long_opt = {}232 self._opt_prefixes = {"-", "--"}233 self._args = []234235 def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None):236 """Adds a new option named `dest` to the parser. The destination237 is not inferred (unlike with optparse) and needs to be explicitly238 provided. Action can be any of ``store``, ``store_const``,239 ``append``, ``appnd_const`` or ``count``.240241 The `obj` can be used to identify the option in the order list242 that is returned from the parser.243 """244 if obj is None:245 obj = dest246 opts = [normalize_opt(opt, self.ctx) for opt in opts]247 option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj)248 self._opt_prefixes.update(option.prefixes)249 for opt in option._short_opts:250 self._short_opt[opt] = option251 for opt in option._long_opts:252 self._long_opt[opt] = option253254 def add_argument(self, dest, nargs=1, obj=None):255 """Adds a positional argument named `dest` to the parser.256257 The `obj` can be used to identify the option in the order list258 that is returned from the parser.259 """260 if obj is None:261 obj = dest262 self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))263264 def parse_args(self, args):265 """Parses positional arguments and returns ``(values, args, order)``266 for the parsed options and arguments as well as the leftover267 arguments if there are any. The order is a list of objects as they268 appear on the command line. If arguments appear multiple times they269 will be memorized multiple times as well.270 """271 state = ParsingState(args)272 try:273 self._process_args_for_options(state)274 self._process_args_for_args(state)275 except UsageError:276 if self.ctx is None or not self.ctx.resilient_parsing:277 raise278 return state.opts, state.largs, state.order279280 def _process_args_for_args(self, state):281 pargs, args = _unpack_args(282 state.largs + state.rargs, [x.nargs for x in self._args]283 )284285 for idx, arg in enumerate(self._args):286 arg.process(pargs[idx], state)287288 state.largs = args289 state.rargs = []290291 def _process_args_for_options(self, state):292 while state.rargs:293 arg = state.rargs.pop(0)294 arglen = len(arg)295 # Double dashes always handled explicitly regardless of what296 # prefixes are valid.297 if arg == "--":298 return299 elif arg[:1] in self._opt_prefixes and arglen > 1:300 self._process_opts(arg, state)301 elif self.allow_interspersed_args:302 state.largs.append(arg)303 else:304 state.rargs.insert(0, arg)305 return306307 # Say this is the original argument list:308 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]309 # ^310 # (we are about to process arg(i)).311 #312 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of313 # [arg0, ..., arg(i-1)] (any options and their arguments will have314 # been removed from largs).315 #316 # The while loop will usually consume 1 or more arguments per pass.317 # If it consumes 1 (eg. arg is an option that takes no arguments),318 # then after _process_arg() is done the situation is:319 #320 # largs = subset of [arg0, ..., arg(i)]321 # rargs = [arg(i+1), ..., arg(N-1)]322 #323 # If allow_interspersed_args is false, largs will always be324 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but325 # not a very interesting subset!326327 def _match_long_opt(self, opt, explicit_value, state):328 if opt not in self._long_opt:329 possibilities = [word for word in self._long_opt if word.startswith(opt)]330 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)331332 option = self._long_opt[opt]333 if option.takes_value:334 # At this point it's safe to modify rargs by injecting the335 # explicit value, because no exception is raised in this336 # branch. This means that the inserted value will be fully337 # consumed.338 if explicit_value is not None:339 state.rargs.insert(0, explicit_value)340341 nargs = option.nargs342 if len(state.rargs) < nargs:343 _error_opt_args(nargs, opt)344 elif nargs == 1:345 value = state.rargs.pop(0)346 else:347 value = tuple(state.rargs[:nargs])348 del state.rargs[:nargs]349350 elif explicit_value is not None:351 raise BadOptionUsage(opt, "{} option does not take a value".format(opt))352353 else:354 value = None355356 option.process(value, state)357358 def _match_short_opt(self, arg, state):359 stop = False360 i = 1361 prefix = arg[0]362 unknown_options = []363364 for ch in arg[1:]:365 opt = normalize_opt(prefix + ch, self.ctx)366 option = self._short_opt.get(opt)367 i += 1368369 if not option:370 if self.ignore_unknown_options:371 unknown_options.append(ch)372 continue373 raise NoSuchOption(opt, ctx=self.ctx)374 if option.takes_value:375 # Any characters left in arg? Pretend they're the376 # next arg, and stop consuming characters of arg.377 if i < len(arg):378 state.rargs.insert(0, arg[i:])379 stop = True380381 nargs = option.nargs382 if len(state.rargs) < nargs:383 _error_opt_args(nargs, opt)384 elif nargs == 1:385 value = state.rargs.pop(0)386 else:387 value = tuple(state.rargs[:nargs])388 del state.rargs[:nargs]389390 else:391 value = None392393 option.process(value, state)394395 if stop:396 break397398 # If we got any unknown options we re-combinate the string of the399 # remaining options and re-attach the prefix, then report that400 # to the state as new larg. This way there is basic combinatorics401 # that can be achieved while still ignoring unknown arguments.402 if self.ignore_unknown_options and unknown_options:403 state.largs.append("{}{}".format(prefix, "".join(unknown_options)))404405 def _process_opts(self, arg, state):406 explicit_value = None407 # Long option handling happens in two parts. The first part is408 # supporting explicitly attached values. In any case, we will try409 # to long match the option first.410 if "=" in arg:411 long_opt, explicit_value = arg.split("=", 1)412 else:413 long_opt = arg414 norm_long_opt = normalize_opt(long_opt, self.ctx)415416 # At this point we will match the (assumed) long option through417 # the long option matching code. Note that this allows options418 # like "-foo" to be matched as long options.419 try:420 self._match_long_opt(norm_long_opt, explicit_value, state)421 except NoSuchOption:422 # At this point the long option matching failed, and we need423 # to try with short options. However there is a special rule424 # which says, that if we have a two character options prefix425 # (applies to "--foo" for instance), we do not dispatch to the426 # short option code and will instead raise the no option427 # error.428 if arg[:2] not in self._opt_prefixes:429 return self._match_short_opt(arg, state)430 if not self.ignore_unknown_options:431 raise432 state.largs.append(arg)
added:src/click/termui.py+695 added
1import inspect2import io3import itertools4import os5import struct6import sys78from ._compat import DEFAULT_COLUMNS9from ._compat import get_winterm_size10from ._compat import isatty11from ._compat import raw_input12from ._compat import string_types13from ._compat import strip_ansi14from ._compat import text_type15from ._compat import WIN16from .exceptions import Abort17from .exceptions import UsageError18from .globals import resolve_color_default19from .types import Choice20from .types import convert_type21from .types import Path22from .utils import echo23from .utils import LazyFile2425# The prompt functions to use. The doc tools currently override these26# functions to customize how they work.27visible_prompt_func = raw_input2829_ansi_colors = {30 "black": 30,31 "red": 31,32 "green": 32,33 "yellow": 33,34 "blue": 34,35 "magenta": 35,36 "cyan": 36,37 "white": 37,38 "reset": 39,39 "bright_black": 90,40 "bright_red": 91,41 "bright_green": 92,42 "bright_yellow": 93,43 "bright_blue": 94,44 "bright_magenta": 95,45 "bright_cyan": 96,46 "bright_white": 97,47}48_ansi_reset_all = "\033[0m"495051def hidden_prompt_func(prompt):52 import getpass5354 return getpass.getpass(prompt)555657def _build_prompt(58 text, suffix, show_default=False, default=None, show_choices=True, type=None59):60 prompt = text61 if type is not None and show_choices and isinstance(type, Choice):62 prompt += " ({})".format(", ".join(map(str, type.choices)))63 if default is not None and show_default:64 prompt = "{} [{}]".format(prompt, _format_default(default))65 return prompt + suffix666768def _format_default(default):69 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):70 return default.name7172 return default737475def prompt(76 text,77 default=None,78 hide_input=False,79 confirmation_prompt=False,80 type=None,81 value_proc=None,82 prompt_suffix=": ",83 show_default=True,84 err=False,85 show_choices=True,86):87 """Prompts a user for input. This is a convenience function that can88 be used to prompt a user for input later.8990 If the user aborts the input by sending a interrupt signal, this91 function will catch it and raise a :exc:`Abort` exception.9293 .. versionadded:: 7.094 Added the show_choices parameter.9596 .. versionadded:: 6.097 Added unicode support for cmd.exe on Windows.9899 .. versionadded:: 4.0100 Added the `err` parameter.101102 :param text: the text to show for the prompt.103 :param default: the default value to use if no input happens. If this104 is not given it will prompt until it's aborted.105 :param hide_input: if this is set to true then the input value will106 be hidden.107 :param confirmation_prompt: asks for confirmation for the value.108 :param type: the type to use to check the value against.109 :param value_proc: if this parameter is provided it's a function that110 is invoked instead of the type conversion to111 convert a value.112 :param prompt_suffix: a suffix that should be added to the prompt.113 :param show_default: shows or hides the default value in the prompt.114 :param err: if set to true the file defaults to ``stderr`` instead of115 ``stdout``, the same as with echo.116 :param show_choices: Show or hide choices if the passed type is a Choice.117 For example if type is a Choice of either day or week,118 show_choices is true and text is "Group by" then the119 prompt will be "Group by (day, week): ".120 """121 result = None122123 def prompt_func(text):124 f = hidden_prompt_func if hide_input else visible_prompt_func125 try:126 # Write the prompt separately so that we get nice127 # coloring through colorama on Windows128 echo(text, nl=False, err=err)129 return f("")130 except (KeyboardInterrupt, EOFError):131 # getpass doesn't print a newline if the user aborts input with ^C.132 # Allegedly this behavior is inherited from getpass(3).133 # A doc bug has been filed at https://bugs.python.org/issue24711134 if hide_input:135 echo(None, err=err)136 raise Abort()137138 if value_proc is None:139 value_proc = convert_type(type, default)140141 prompt = _build_prompt(142 text, prompt_suffix, show_default, default, show_choices, type143 )144145 while 1:146 while 1:147 value = prompt_func(prompt)148 if value:149 break150 elif default is not None:151 if isinstance(value_proc, Path):152 # validate Path default value(exists, dir_okay etc.)153 value = default154 break155 return default156 try:157 result = value_proc(value)158 except UsageError as e:159 echo("Error: {}".format(e.message), err=err) # noqa: B306160 continue161 if not confirmation_prompt:162 return result163 while 1:164 value2 = prompt_func("Repeat for confirmation: ")165 if value2:166 break167 if value == value2:168 return result169 echo("Error: the two entered values do not match", err=err)170171172def confirm(173 text, default=False, abort=False, prompt_suffix=": ", show_default=True, err=False174):175 """Prompts for confirmation (yes/no question).176177 If the user aborts the input by sending a interrupt signal this178 function will catch it and raise a :exc:`Abort` exception.179180 .. versionadded:: 4.0181 Added the `err` parameter.182183 :param text: the question to ask.184 :param default: the default for the prompt.185 :param abort: if this is set to `True` a negative answer aborts the186 exception by raising :exc:`Abort`.187 :param prompt_suffix: a suffix that should be added to the prompt.188 :param show_default: shows or hides the default value in the prompt.189 :param err: if set to true the file defaults to ``stderr`` instead of190 ``stdout``, the same as with echo.191 """192 prompt = _build_prompt(193 text, prompt_suffix, show_default, "Y/n" if default else "y/N"194 )195 while 1:196 try:197 # Write the prompt separately so that we get nice198 # coloring through colorama on Windows199 echo(prompt, nl=False, err=err)200 value = visible_prompt_func("").lower().strip()201 except (KeyboardInterrupt, EOFError):202 raise Abort()203 if value in ("y", "yes"):204 rv = True205 elif value in ("n", "no"):206 rv = False207 elif value == "":208 rv = default209 else:210 echo("Error: invalid input", err=err)211 continue212 break213 if abort and not rv:214 raise Abort()215 return rv216217218def get_terminal_size():219 """Returns the current size of the terminal as tuple in the form220 ``(width, height)`` in columns and rows.221 """222 # If shutil has get_terminal_size() (Python 3.3 and later) use that223 if sys.version_info >= (3, 3):224 import shutil225226 shutil_get_terminal_size = getattr(shutil, "get_terminal_size", None)227 if shutil_get_terminal_size:228 sz = shutil_get_terminal_size()229 return sz.columns, sz.lines230231 # We provide a sensible default for get_winterm_size() when being invoked232 # inside a subprocess. Without this, it would not provide a useful input.233 if get_winterm_size is not None:234 size = get_winterm_size()235 if size == (0, 0):236 return (79, 24)237 else:238 return size239240 def ioctl_gwinsz(fd):241 try:242 import fcntl243 import termios244245 cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))246 except Exception:247 return248 return cr249250 cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)251 if not cr:252 try:253 fd = os.open(os.ctermid(), os.O_RDONLY)254 try:255 cr = ioctl_gwinsz(fd)256 finally:257 os.close(fd)258 except Exception:259 pass260 if not cr or not cr[0] or not cr[1]:261 cr = (os.environ.get("LINES", 25), os.environ.get("COLUMNS", DEFAULT_COLUMNS))262 return int(cr[1]), int(cr[0])263264265def echo_via_pager(text_or_generator, color=None):266 """This function takes a text and shows it via an environment specific267 pager on stdout.268269 .. versionchanged:: 3.0270 Added the `color` flag.271272 :param text_or_generator: the text to page, or alternatively, a273 generator emitting the text to page.274 :param color: controls if the pager supports ANSI colors or not. The275 default is autodetection.276 """277 color = resolve_color_default(color)278279 if inspect.isgeneratorfunction(text_or_generator):280 i = text_or_generator()281 elif isinstance(text_or_generator, string_types):282 i = [text_or_generator]283 else:284 i = iter(text_or_generator)285286 # convert every element of i to a text type if necessary287 text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i)288289 from ._termui_impl import pager290291 return pager(itertools.chain(text_generator, "\n"), color)292293294def progressbar(295 iterable=None,296 length=None,297 label=None,298 show_eta=True,299 show_percent=None,300 show_pos=False,301 item_show_func=None,302 fill_char="#",303 empty_char="-",304 bar_template="%(label)s [%(bar)s] %(info)s",305 info_sep=" ",306 width=36,307 file=None,308 color=None,309):310 """This function creates an iterable context manager that can be used311 to iterate over something while showing a progress bar. It will312 either iterate over the `iterable` or `length` items (that are counted313 up). While iteration happens, this function will print a rendered314 progress bar to the given `file` (defaults to stdout) and will attempt315 to calculate remaining time and more. By default, this progress bar316 will not be rendered if the file is not a terminal.317318 The context manager creates the progress bar. When the context319 manager is entered the progress bar is already created. With every320 iteration over the progress bar, the iterable passed to the bar is321 advanced and the bar is updated. When the context manager exits,322 a newline is printed and the progress bar is finalized on screen.323324 Note: The progress bar is currently designed for use cases where the325 total progress can be expected to take at least several seconds.326 Because of this, the ProgressBar class object won't display327 progress that is considered too fast, and progress where the time328 between steps is less than a second.329330 No printing must happen or the progress bar will be unintentionally331 destroyed.332333 Example usage::334335 with progressbar(items) as bar:336 for item in bar:337 do_something_with(item)338339 Alternatively, if no iterable is specified, one can manually update the340 progress bar through the `update()` method instead of directly341 iterating over the progress bar. The update method accepts the number342 of steps to increment the bar with::343344 with progressbar(length=chunks.total_bytes) as bar:345 for chunk in chunks:346 process_chunk(chunk)347 bar.update(chunks.bytes)348349 The ``update()`` method also takes an optional value specifying the350 ``current_item`` at the new position. This is useful when used351 together with ``item_show_func`` to customize the output for each352 manual step::353354 with click.progressbar(355 length=total_size,356 label='Unzipping archive',357 item_show_func=lambda a: a.filename358 ) as bar:359 for archive in zip_file:360 archive.extract()361 bar.update(archive.size, archive)362363 .. versionadded:: 2.0364365 .. versionadded:: 4.0366 Added the `color` parameter. Added a `update` method to the367 progressbar object.368369 :param iterable: an iterable to iterate over. If not provided the length370 is required.371 :param length: the number of items to iterate over. By default the372 progressbar will attempt to ask the iterator about its373 length, which might or might not work. If an iterable is374 also provided this parameter can be used to override the375 length. If an iterable is not provided the progress bar376 will iterate over a range of that length.377 :param label: the label to show next to the progress bar.378 :param show_eta: enables or disables the estimated time display. This is379 automatically disabled if the length cannot be380 determined.381 :param show_percent: enables or disables the percentage display. The382 default is `True` if the iterable has a length or383 `False` if not.384 :param show_pos: enables or disables the absolute position display. The385 default is `False`.386 :param item_show_func: a function called with the current item which387 can return a string to show the current item388 next to the progress bar. Note that the current389 item can be `None`!390 :param fill_char: the character to use to show the filled part of the391 progress bar.392 :param empty_char: the character to use to show the non-filled part of393 the progress bar.394 :param bar_template: the format string to use as template for the bar.395 The parameters in it are ``label`` for the label,396 ``bar`` for the progress bar and ``info`` for the397 info section.398 :param info_sep: the separator between multiple info items (eta etc.)399 :param width: the width of the progress bar in characters, 0 means full400 terminal width401 :param file: the file to write to. If this is not a terminal then402 only the label is printed.403 :param color: controls if the terminal supports ANSI colors or not. The404 default is autodetection. This is only needed if ANSI405 codes are included anywhere in the progress bar output406 which is not the case by default.407 """408 from ._termui_impl import ProgressBar409410 color = resolve_color_default(color)411 return ProgressBar(412 iterable=iterable,413 length=length,414 show_eta=show_eta,415 show_percent=show_percent,416 show_pos=show_pos,417 item_show_func=item_show_func,418 fill_char=fill_char,419 empty_char=empty_char,420 bar_template=bar_template,421 info_sep=info_sep,422 file=file,423 label=label,424 width=width,425 color=color,426 )427428429def clear():430 """Clears the terminal screen. This will have the effect of clearing431 the whole visible space of the terminal and moving the cursor to the432 top left. This does not do anything if not connected to a terminal.433434 .. versionadded:: 2.0435 """436 if not isatty(sys.stdout):437 return438 # If we're on Windows and we don't have colorama available, then we439 # clear the screen by shelling out. Otherwise we can use an escape440 # sequence.441 if WIN:442 os.system("cls")443 else:444 sys.stdout.write("\033[2J\033[1;1H")445446447def style(448 text,449 fg=None,450 bg=None,451 bold=None,452 dim=None,453 underline=None,454 blink=None,455 reverse=None,456 reset=True,457):458 """Styles a text with ANSI styles and returns the new string. By459 default the styling is self contained which means that at the end460 of the string a reset code is issued. This can be prevented by461 passing ``reset=False``.462463 Examples::464465 click.echo(click.style('Hello World!', fg='green'))466 click.echo(click.style('ATTENTION!', blink=True))467 click.echo(click.style('Some things', reverse=True, fg='cyan'))468469 Supported color names:470471 * ``black`` (might be a gray)472 * ``red``473 * ``green``474 * ``yellow`` (might be an orange)475 * ``blue``476 * ``magenta``477 * ``cyan``478 * ``white`` (might be light gray)479 * ``bright_black``480 * ``bright_red``481 * ``bright_green``482 * ``bright_yellow``483 * ``bright_blue``484 * ``bright_magenta``485 * ``bright_cyan``486 * ``bright_white``487 * ``reset`` (reset the color code only)488489 .. versionadded:: 2.0490491 .. versionadded:: 7.0492 Added support for bright colors.493494 :param text: the string to style with ansi codes.495 :param fg: if provided this will become the foreground color.496 :param bg: if provided this will become the background color.497 :param bold: if provided this will enable or disable bold mode.498 :param dim: if provided this will enable or disable dim mode. This is499 badly supported.500 :param underline: if provided this will enable or disable underline.501 :param blink: if provided this will enable or disable blinking.502 :param reverse: if provided this will enable or disable inverse503 rendering (foreground becomes background and the504 other way round).505 :param reset: by default a reset-all code is added at the end of the506 string which means that styles do not carry over. This507 can be disabled to compose styles.508 """509 bits = []510 if fg:511 try:512 bits.append("\033[{}m".format(_ansi_colors[fg]))513 except KeyError:514 raise TypeError("Unknown color '{}'".format(fg))515 if bg:516 try:517 bits.append("\033[{}m".format(_ansi_colors[bg] + 10))518 except KeyError:519 raise TypeError("Unknown color '{}'".format(bg))520 if bold is not None:521 bits.append("\033[{}m".format(1 if bold else 22))522 if dim is not None:523 bits.append("\033[{}m".format(2 if dim else 22))524 if underline is not None:525 bits.append("\033[{}m".format(4 if underline else 24))526 if blink is not None:527 bits.append("\033[{}m".format(5 if blink else 25))528 if reverse is not None:529 bits.append("\033[{}m".format(7 if reverse else 27))530 bits.append(text)531 if reset:532 bits.append(_ansi_reset_all)533 return "".join(bits)534535536def unstyle(text):537 """Removes ANSI styling information from a string. Usually it's not538 necessary to use this function as Click's echo function will539 automatically remove styling if necessary.540541 .. versionadded:: 2.0542543 :param text: the text to remove style information from.544 """545 return strip_ansi(text)546547548def secho(message=None, file=None, nl=True, err=False, color=None, **styles):549 """This function combines :func:`echo` and :func:`style` into one550 call. As such the following two calls are the same::551552 click.secho('Hello World!', fg='green')553 click.echo(click.style('Hello World!', fg='green'))554555 All keyword arguments are forwarded to the underlying functions556 depending on which one they go with.557558 .. versionadded:: 2.0559 """560 if message is not None:561 message = style(message, **styles)562 return echo(message, file=file, nl=nl, err=err, color=color)563564565def edit(566 text=None, editor=None, env=None, require_save=True, extension=".txt", filename=None567):568 r"""Edits the given text in the defined editor. If an editor is given569 (should be the full path to the executable but the regular operating570 system search path is used for finding the executable) it overrides571 the detected editor. Optionally, some environment variables can be572 used. If the editor is closed without changes, `None` is returned. In573 case a file is edited directly the return value is always `None` and574 `require_save` and `extension` are ignored.575576 If the editor cannot be opened a :exc:`UsageError` is raised.577578 Note for Windows: to simplify cross-platform usage, the newlines are579 automatically converted from POSIX to Windows and vice versa. As such,580 the message here will have ``\n`` as newline markers.581582 :param text: the text to edit.583 :param editor: optionally the editor to use. Defaults to automatic584 detection.585 :param env: environment variables to forward to the editor.586 :param require_save: if this is true, then not saving in the editor587 will make the return value become `None`.588 :param extension: the extension to tell the editor about. This defaults589 to `.txt` but changing this might change syntax590 highlighting.591 :param filename: if provided it will edit this file instead of the592 provided text contents. It will not use a temporary593 file as an indirection in that case.594 """595 from ._termui_impl import Editor596597 editor = Editor(598 editor=editor, env=env, require_save=require_save, extension=extension599 )600 if filename is None:601 return editor.edit(text)602 editor.edit_file(filename)603604605def launch(url, wait=False, locate=False):606 """This function launches the given URL (or filename) in the default607 viewer application for this file type. If this is an executable, it608 might launch the executable in a new session. The return value is609 the exit code of the launched application. Usually, ``0`` indicates610 success.611612 Examples::613614 click.launch('https://click.palletsprojects.com/')615 click.launch('/my/downloaded/file', locate=True)616617 .. versionadded:: 2.0618619 :param url: URL or filename of the thing to launch.620 :param wait: waits for the program to stop.621 :param locate: if this is set to `True` then instead of launching the622 application associated with the URL it will attempt to623 launch a file manager with the file located. This624 might have weird effects if the URL does not point to625 the filesystem.626 """627 from ._termui_impl import open_url628629 return open_url(url, wait=wait, locate=locate)630631632# If this is provided, getchar() calls into this instead. This is used633# for unittesting purposes.634_getchar = None635636637def getchar(echo=False):638 """Fetches a single character from the terminal and returns it. This639 will always return a unicode character and under certain rare640 circumstances this might return more than one character. The641 situations which more than one character is returned is when for642 whatever reason multiple characters end up in the terminal buffer or643 standard input was not actually a terminal.644645 Note that this will always read from the terminal, even if something646 is piped into the standard input.647648 Note for Windows: in rare cases when typing non-ASCII characters, this649 function might wait for a second character and then return both at once.650 This is because certain Unicode characters look like special-key markers.651652 .. versionadded:: 2.0653654 :param echo: if set to `True`, the character read will also show up on655 the terminal. The default is to not show it.656 """657 f = _getchar658 if f is None:659 from ._termui_impl import getchar as f660 return f(echo)661662663def raw_terminal():664 from ._termui_impl import raw_terminal as f665666 return f()667668669def pause(info="Press any key to continue ...", err=False):670 """This command stops execution and waits for the user to press any671 key to continue. This is similar to the Windows batch "pause"672 command. If the program is not run through a terminal, this command673 will instead do nothing.674675 .. versionadded:: 2.0676677 .. versionadded:: 4.0678 Added the `err` parameter.679680 :param info: the info string to print before pausing.681 :param err: if set to message goes to ``stderr`` instead of682 ``stdout``, the same as with echo.683 """684 if not isatty(sys.stdin) or not isatty(sys.stdout):685 return686 try:687 if info:688 echo(info, nl=False, err=err)689 try:690 getchar()691 except (KeyboardInterrupt, EOFError):692 pass693 finally:694 if info:695 echo(err=err)
added:src/click/testing.py+382 added
1import contextlib2import os3import shlex4import shutil5import sys6import tempfile78from . import formatting9from . import termui10from . import utils11from ._compat import iteritems12from ._compat import PY213from ._compat import string_types141516if PY2:17 from cStringIO import StringIO18else:19 import io20 from ._compat import _find_binary_reader212223class EchoingStdin(object):24 def __init__(self, input, output):25 self._input = input26 self._output = output2728 def __getattr__(self, x):29 return getattr(self._input, x)3031 def _echo(self, rv):32 self._output.write(rv)33 return rv3435 def read(self, n=-1):36 return self._echo(self._input.read(n))3738 def readline(self, n=-1):39 return self._echo(self._input.readline(n))4041 def readlines(self):42 return [self._echo(x) for x in self._input.readlines()]4344 def __iter__(self):45 return iter(self._echo(x) for x in self._input)4647 def __repr__(self):48 return repr(self._input)495051def make_input_stream(input, charset):52 # Is already an input stream.53 if hasattr(input, "read"):54 if PY2:55 return input56 rv = _find_binary_reader(input)57 if rv is not None:58 return rv59 raise TypeError("Could not find binary reader for input stream.")6061 if input is None:62 input = b""63 elif not isinstance(input, bytes):64 input = input.encode(charset)65 if PY2:66 return StringIO(input)67 return io.BytesIO(input)686970class Result(object):71 """Holds the captured result of an invoked CLI script."""7273 def __init__(74 self, runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None75 ):76 #: The runner that created the result77 self.runner = runner78 #: The standard output as bytes.79 self.stdout_bytes = stdout_bytes80 #: The standard error as bytes, or None if not available81 self.stderr_bytes = stderr_bytes82 #: The exit code as integer.83 self.exit_code = exit_code84 #: The exception that happened if one did.85 self.exception = exception86 #: The traceback87 self.exc_info = exc_info8889 @property90 def output(self):91 """The (standard) output as unicode string."""92 return self.stdout9394 @property95 def stdout(self):96 """The standard output as unicode string."""97 return self.stdout_bytes.decode(self.runner.charset, "replace").replace(98 "\r\n", "\n"99 )100101 @property102 def stderr(self):103 """The standard error as unicode string."""104 if self.stderr_bytes is None:105 raise ValueError("stderr not separately captured")106 return self.stderr_bytes.decode(self.runner.charset, "replace").replace(107 "\r\n", "\n"108 )109110 def __repr__(self):111 return "<{} {}>".format(112 type(self).__name__, repr(self.exception) if self.exception else "okay"113 )114115116class CliRunner(object):117 """The CLI runner provides functionality to invoke a Click command line118 script for unittesting purposes in a isolated environment. This only119 works in single-threaded systems without any concurrency as it changes the120 global interpreter state.121122 :param charset: the character set for the input and output data. This is123 UTF-8 by default and should not be changed currently as124 the reporting to Click only works in Python 2 properly.125 :param env: a dictionary with environment variables for overriding.126 :param echo_stdin: if this is set to `True`, then reading from stdin writes127 to stdout. This is useful for showing examples in128 some circumstances. Note that regular prompts129 will automatically echo the input.130 :param mix_stderr: if this is set to `False`, then stdout and stderr are131 preserved as independent streams. This is useful for132 Unix-philosophy apps that have predictable stdout and133 noisy stderr, such that each may be measured134 independently135 """136137 def __init__(self, charset=None, env=None, echo_stdin=False, mix_stderr=True):138 if charset is None:139 charset = "utf-8"140 self.charset = charset141 self.env = env or {}142 self.echo_stdin = echo_stdin143 self.mix_stderr = mix_stderr144145 def get_default_prog_name(self, cli):146 """Given a command object it will return the default program name147 for it. The default is the `name` attribute or ``"root"`` if not148 set.149 """150 return cli.name or "root"151152 def make_env(self, overrides=None):153 """Returns the environment overrides for invoking a script."""154 rv = dict(self.env)155 if overrides:156 rv.update(overrides)157 return rv158159 @contextlib.contextmanager160 def isolation(self, input=None, env=None, color=False):161 """A context manager that sets up the isolation for invoking of a162 command line tool. This sets up stdin with the given input data163 and `os.environ` with the overrides from the given dictionary.164 This also rebinds some internals in Click to be mocked (like the165 prompt functionality).166167 This is automatically done in the :meth:`invoke` method.168169 .. versionadded:: 4.0170 The ``color`` parameter was added.171172 :param input: the input stream to put into sys.stdin.173 :param env: the environment overrides as dictionary.174 :param color: whether the output should contain color codes. The175 application can still override this explicitly.176 """177 input = make_input_stream(input, self.charset)178179 old_stdin = sys.stdin180 old_stdout = sys.stdout181 old_stderr = sys.stderr182 old_forced_width = formatting.FORCED_WIDTH183 formatting.FORCED_WIDTH = 80184185 env = self.make_env(env)186187 if PY2:188 bytes_output = StringIO()189 if self.echo_stdin:190 input = EchoingStdin(input, bytes_output)191 sys.stdout = bytes_output192 if not self.mix_stderr:193 bytes_error = StringIO()194 sys.stderr = bytes_error195 else:196 bytes_output = io.BytesIO()197 if self.echo_stdin:198 input = EchoingStdin(input, bytes_output)199 input = io.TextIOWrapper(input, encoding=self.charset)200 sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)201 if not self.mix_stderr:202 bytes_error = io.BytesIO()203 sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)204205 if self.mix_stderr:206 sys.stderr = sys.stdout207208 sys.stdin = input209210 def visible_input(prompt=None):211 sys.stdout.write(prompt or "")212 val = input.readline().rstrip("\r\n")213 sys.stdout.write("{}\n".format(val))214 sys.stdout.flush()215 return val216217 def hidden_input(prompt=None):218 sys.stdout.write("{}\n".format(prompt or ""))219 sys.stdout.flush()220 return input.readline().rstrip("\r\n")221222 def _getchar(echo):223 char = sys.stdin.read(1)224 if echo:225 sys.stdout.write(char)226 sys.stdout.flush()227 return char228229 default_color = color230231 def should_strip_ansi(stream=None, color=None):232 if color is None:233 return not default_color234 return not color235236 old_visible_prompt_func = termui.visible_prompt_func237 old_hidden_prompt_func = termui.hidden_prompt_func238 old__getchar_func = termui._getchar239 old_should_strip_ansi = utils.should_strip_ansi240 termui.visible_prompt_func = visible_input241 termui.hidden_prompt_func = hidden_input242 termui._getchar = _getchar243 utils.should_strip_ansi = should_strip_ansi244245 old_env = {}246 try:247 for key, value in iteritems(env):248 old_env[key] = os.environ.get(key)249 if value is None:250 try:251 del os.environ[key]252 except Exception:253 pass254 else:255 os.environ[key] = value256 yield (bytes_output, not self.mix_stderr and bytes_error)257 finally:258 for key, value in iteritems(old_env):259 if value is None:260 try:261 del os.environ[key]262 except Exception:263 pass264 else:265 os.environ[key] = value266 sys.stdout = old_stdout267 sys.stderr = old_stderr268 sys.stdin = old_stdin269 termui.visible_prompt_func = old_visible_prompt_func270 termui.hidden_prompt_func = old_hidden_prompt_func271 termui._getchar = old__getchar_func272 utils.should_strip_ansi = old_should_strip_ansi273 formatting.FORCED_WIDTH = old_forced_width274275 def invoke(276 self,277 cli,278 args=None,279 input=None,280 env=None,281 catch_exceptions=True,282 color=False,283 **extra284 ):285 """Invokes a command in an isolated environment. The arguments are286 forwarded directly to the command line script, the `extra` keyword287 arguments are passed to the :meth:`~clickpkg.Command.main` function of288 the command.289290 This returns a :class:`Result` object.291292 .. versionadded:: 3.0293 The ``catch_exceptions`` parameter was added.294295 .. versionchanged:: 3.0296 The result object now has an `exc_info` attribute with the297 traceback if available.298299 .. versionadded:: 4.0300 The ``color`` parameter was added.301302 :param cli: the command to invoke303 :param args: the arguments to invoke. It may be given as an iterable304 or a string. When given as string it will be interpreted305 as a Unix shell command. More details at306 :func:`shlex.split`.307 :param input: the input data for `sys.stdin`.308 :param env: the environment overrides.309 :param catch_exceptions: Whether to catch any other exceptions than310 ``SystemExit``.311 :param extra: the keyword arguments to pass to :meth:`main`.312 :param color: whether the output should contain color codes. The313 application can still override this explicitly.314 """315 exc_info = None316 with self.isolation(input=input, env=env, color=color) as outstreams:317 exception = None318 exit_code = 0319320 if isinstance(args, string_types):321 args = shlex.split(args)322323 try:324 prog_name = extra.pop("prog_name")325 except KeyError:326 prog_name = self.get_default_prog_name(cli)327328 try:329 cli.main(args=args or (), prog_name=prog_name, **extra)330 except SystemExit as e:331 exc_info = sys.exc_info()332 exit_code = e.code333 if exit_code is None:334 exit_code = 0335336 if exit_code != 0:337 exception = e338339 if not isinstance(exit_code, int):340 sys.stdout.write(str(exit_code))341 sys.stdout.write("\n")342 exit_code = 1343344 except Exception as e:345 if not catch_exceptions:346 raise347 exception = e348 exit_code = 1349 exc_info = sys.exc_info()350 finally:351 sys.stdout.flush()352 stdout = outstreams[0].getvalue()353 if self.mix_stderr:354 stderr = None355 else:356 stderr = outstreams[1].getvalue()357358 return Result(359 runner=self,360 stdout_bytes=stdout,361 stderr_bytes=stderr,362 exit_code=exit_code,363 exception=exception,364 exc_info=exc_info,365 )366367 @contextlib.contextmanager368 def isolated_filesystem(self):369 """A context manager that creates a temporary folder and changes370 the current working directory to it for isolated filesystem tests.371 """372 cwd = os.getcwd()373 t = tempfile.mkdtemp()374 os.chdir(t)375 try:376 yield t377 finally:378 os.chdir(cwd)379 try:380 shutil.rmtree(t)381 except (OSError, IOError): # noqa: B014382 pass
added:src/click/types.py+762 added
1import os2import stat3from datetime import datetime45from ._compat import _get_argv_encoding6from ._compat import filename_to_ui7from ._compat import get_filesystem_encoding8from ._compat import get_streerror9from ._compat import open_stream10from ._compat import PY211from ._compat import text_type12from .exceptions import BadParameter13from .utils import LazyFile14from .utils import safecall151617class ParamType(object):18 """Helper for converting values through types. The following is19 necessary for a valid type:2021 * it needs a name22 * it needs to pass through None unchanged23 * it needs to convert from a string24 * it needs to convert its result type through unchanged25 (eg: needs to be idempotent)26 * it needs to be able to deal with param and context being `None`.27 This can be the case when the object is used with prompt28 inputs.29 """3031 is_composite = False3233 #: the descriptive name of this type34 name = None3536 #: if a list of this type is expected and the value is pulled from a37 #: string environment variable, this is what splits it up. `None`38 #: means any whitespace. For all parameters the general rule is that39 #: whitespace splits them up. The exception are paths and files which40 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on41 #: Windows).42 envvar_list_splitter = None4344 def __call__(self, value, param=None, ctx=None):45 if value is not None:46 return self.convert(value, param, ctx)4748 def get_metavar(self, param):49 """Returns the metavar default for this param if it provides one."""5051 def get_missing_message(self, param):52 """Optionally might return extra information about a missing53 parameter.5455 .. versionadded:: 2.056 """5758 def convert(self, value, param, ctx):59 """Converts the value. This is not invoked for values that are60 `None` (the missing value).61 """62 return value6364 def split_envvar_value(self, rv):65 """Given a value from an environment variable this splits it up66 into small chunks depending on the defined envvar list splitter.6768 If the splitter is set to `None`, which means that whitespace splits,69 then leading and trailing whitespace is ignored. Otherwise, leading70 and trailing splitters usually lead to empty items being included.71 """72 return (rv or "").split(self.envvar_list_splitter)7374 def fail(self, message, param=None, ctx=None):75 """Helper method to fail with an invalid value message."""76 raise BadParameter(message, ctx=ctx, param=param)777879class CompositeParamType(ParamType):80 is_composite = True8182 @property83 def arity(self):84 raise NotImplementedError()858687class FuncParamType(ParamType):88 def __init__(self, func):89 self.name = func.__name__90 self.func = func9192 def convert(self, value, param, ctx):93 try:94 return self.func(value)95 except ValueError:96 try:97 value = text_type(value)98 except UnicodeError:99 value = str(value).decode("utf-8", "replace")100 self.fail(value, param, ctx)101102103class UnprocessedParamType(ParamType):104 name = "text"105106 def convert(self, value, param, ctx):107 return value108109 def __repr__(self):110 return "UNPROCESSED"111112113class StringParamType(ParamType):114 name = "text"115116 def convert(self, value, param, ctx):117 if isinstance(value, bytes):118 enc = _get_argv_encoding()119 try:120 value = value.decode(enc)121 except UnicodeError:122 fs_enc = get_filesystem_encoding()123 if fs_enc != enc:124 try:125 value = value.decode(fs_enc)126 except UnicodeError:127 value = value.decode("utf-8", "replace")128 else:129 value = value.decode("utf-8", "replace")130 return value131 return value132133 def __repr__(self):134 return "STRING"135136137class Choice(ParamType):138 """The choice type allows a value to be checked against a fixed set139 of supported values. All of these values have to be strings.140141 You should only pass a list or tuple of choices. Other iterables142 (like generators) may lead to surprising results.143144 The resulting value will always be one of the originally passed choices145 regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``146 being specified.147148 See :ref:`choice-opts` for an example.149150 :param case_sensitive: Set to false to make choices case151 insensitive. Defaults to true.152 """153154 name = "choice"155156 def __init__(self, choices, case_sensitive=True):157 self.choices = choices158 self.case_sensitive = case_sensitive159160 def get_metavar(self, param):161 return "[{}]".format("|".join(self.choices))162163 def get_missing_message(self, param):164 return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))165166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase169 # preserve original `value` to produce an accurate message in170 # `self.fail`171 normed_value = value172 normed_choices = {choice: choice for choice in self.choices}173174 if ctx is not None and ctx.token_normalize_func is not None:175 normed_value = ctx.token_normalize_func(value)176 normed_choices = {177 ctx.token_normalize_func(normed_choice): original178 for normed_choice, original in normed_choices.items()179 }180181 if not self.case_sensitive:182 if PY2:183 lower = str.lower184 else:185 lower = str.casefold186187 normed_value = lower(normed_value)188 normed_choices = {189 lower(normed_choice): original190 for normed_choice, original in normed_choices.items()191 }192193 if normed_value in normed_choices:194 return normed_choices[normed_value]195196 self.fail(197 "invalid choice: {}. (choose from {})".format(198 value, ", ".join(self.choices)199 ),200 param,201 ctx,202 )203204 def __repr__(self):205 return "Choice('{}')".format(list(self.choices))206207208class DateTime(ParamType):209 """The DateTime type converts date strings into `datetime` objects.210211 The format strings which are checked are configurable, but default to some212 common (non-timezone aware) ISO 8601 formats.213214 When specifying *DateTime* formats, you should only pass a list or a tuple.215 Other iterables, like generators, may lead to surprising results.216217 The format strings are processed using ``datetime.strptime``, and this218 consequently defines the format strings which are allowed.219220 Parsing is tried using each format, in order, and the first format which221 parses successfully is used.222223 :param formats: A list or tuple of date format strings, in the order in224 which they should be tried. Defaults to225 ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,226 ``'%Y-%m-%d %H:%M:%S'``.227 """228229 name = "datetime"230231 def __init__(self, formats=None):232 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]233234 def get_metavar(self, param):235 return "[{}]".format("|".join(self.formats))236237 def _try_to_convert_date(self, value, format):238 try:239 return datetime.strptime(value, format)240 except ValueError:241 return None242243 def convert(self, value, param, ctx):244 # Exact match245 for format in self.formats:246 dtime = self._try_to_convert_date(value, format)247 if dtime:248 return dtime249250 self.fail(251 "invalid datetime format: {}. (choose from {})".format(252 value, ", ".join(self.formats)253 )254 )255256 def __repr__(self):257 return "DateTime"258259260class IntParamType(ParamType):261 name = "integer"262263 def convert(self, value, param, ctx):264 try:265 return int(value)266 except ValueError:267 self.fail("{} is not a valid integer".format(value), param, ctx)268269 def __repr__(self):270 return "INT"271272273class IntRange(IntParamType):274 """A parameter that works similar to :data:`click.INT` but restricts275 the value to fit into a range. The default behavior is to fail if the276 value falls outside the range, but it can also be silently clamped277 between the two edges.278279 See :ref:`ranges` for an example.280 """281282 name = "integer range"283284 def __init__(self, min=None, max=None, clamp=False):285 self.min = min286 self.max = max287 self.clamp = clamp288289 def convert(self, value, param, ctx):290 rv = IntParamType.convert(self, value, param, ctx)291 if self.clamp:292 if self.min is not None and rv < self.min:293 return self.min294 if self.max is not None and rv > self.max:295 return self.max296 if (297 self.min is not None298 and rv < self.min299 or self.max is not None300 and rv > self.max301 ):302 if self.min is None:303 self.fail(304 "{} is bigger than the maximum valid value {}.".format(305 rv, self.max306 ),307 param,308 ctx,309 )310 elif self.max is None:311 self.fail(312 "{} is smaller than the minimum valid value {}.".format(313 rv, self.min314 ),315 param,316 ctx,317 )318 else:319 self.fail(320 "{} is not in the valid range of {} to {}.".format(321 rv, self.min, self.max322 ),323 param,324 ctx,325 )326 return rv327328 def __repr__(self):329 return "IntRange({}, {})".format(self.min, self.max)330331332class FloatParamType(ParamType):333 name = "float"334335 def convert(self, value, param, ctx):336 try:337 return float(value)338 except ValueError:339 self.fail(340 "{} is not a valid floating point value".format(value), param, ctx341 )342343 def __repr__(self):344 return "FLOAT"345346347class FloatRange(FloatParamType):348 """A parameter that works similar to :data:`click.FLOAT` but restricts349 the value to fit into a range. The default behavior is to fail if the350 value falls outside the range, but it can also be silently clamped351 between the two edges.352353 See :ref:`ranges` for an example.354 """355356 name = "float range"357358 def __init__(self, min=None, max=None, clamp=False):359 self.min = min360 self.max = max361 self.clamp = clamp362363 def convert(self, value, param, ctx):364 rv = FloatParamType.convert(self, value, param, ctx)365 if self.clamp:366 if self.min is not None and rv < self.min:367 return self.min368 if self.max is not None and rv > self.max:369 return self.max370 if (371 self.min is not None372 and rv < self.min373 or self.max is not None374 and rv > self.max375 ):376 if self.min is None:377 self.fail(378 "{} is bigger than the maximum valid value {}.".format(379 rv, self.max380 ),381 param,382 ctx,383 )384 elif self.max is None:385 self.fail(386 "{} is smaller than the minimum valid value {}.".format(387 rv, self.min388 ),389 param,390 ctx,391 )392 else:393 self.fail(394 "{} is not in the valid range of {} to {}.".format(395 rv, self.min, self.max396 ),397 param,398 ctx,399 )400 return rv401402 def __repr__(self):403 return "FloatRange({}, {})".format(self.min, self.max)404405406class BoolParamType(ParamType):407 name = "boolean"408409 def convert(self, value, param, ctx):410 if isinstance(value, bool):411 return bool(value)412 value = value.lower()413 if value in ("true", "t", "1", "yes", "y"):414 return True415 elif value in ("false", "f", "0", "no", "n"):416 return False417 self.fail("{} is not a valid boolean".format(value), param, ctx)418419 def __repr__(self):420 return "BOOL"421422423class UUIDParameterType(ParamType):424 name = "uuid"425426 def convert(self, value, param, ctx):427 import uuid428429 try:430 if PY2 and isinstance(value, text_type):431 value = value.encode("ascii")432 return uuid.UUID(value)433 except ValueError:434 self.fail("{} is not a valid UUID value".format(value), param, ctx)435436 def __repr__(self):437 return "UUID"438439440class File(ParamType):441 """Declares a parameter to be a file for reading or writing. The file442 is automatically closed once the context tears down (after the command443 finished working).444445 Files can be opened for reading or writing. The special value ``-``446 indicates stdin or stdout depending on the mode.447448 By default, the file is opened for reading text data, but it can also be449 opened in binary mode or for writing. The encoding parameter can be used450 to force a specific encoding.451452 The `lazy` flag controls if the file should be opened immediately or upon453 first IO. The default is to be non-lazy for standard input and output454 streams as well as files opened for reading, `lazy` otherwise. When opening a455 file lazily for reading, it is still opened temporarily for validation, but456 will not be held open until first IO. lazy is mainly useful when opening457 for writing to avoid creating the file until it is needed.458459 Starting with Click 2.0, files can also be opened atomically in which460 case all writes go into a separate file in the same folder and upon461 completion the file will be moved over to the original location. This462 is useful if a file regularly read by other users is modified.463464 See :ref:`file-args` for more information.465 """466467 name = "filename"468 envvar_list_splitter = os.path.pathsep469470 def __init__(471 self, mode="r", encoding=None, errors="strict", lazy=None, atomic=False472 ):473 self.mode = mode474 self.encoding = encoding475 self.errors = errors476 self.lazy = lazy477 self.atomic = atomic478479 def resolve_lazy_flag(self, value):480 if self.lazy is not None:481 return self.lazy482 if value == "-":483 return False484 elif "w" in self.mode:485 return True486 return False487488 def convert(self, value, param, ctx):489 try:490 if hasattr(value, "read") or hasattr(value, "write"):491 return value492493 lazy = self.resolve_lazy_flag(value)494495 if lazy:496 f = LazyFile(497 value, self.mode, self.encoding, self.errors, atomic=self.atomic498 )499 if ctx is not None:500 ctx.call_on_close(f.close_intelligently)501 return f502503 f, should_close = open_stream(504 value, self.mode, self.encoding, self.errors, atomic=self.atomic505 )506 # If a context is provided, we automatically close the file507 # at the end of the context execution (or flush out). If a508 # context does not exist, it's the caller's responsibility to509 # properly close the file. This for instance happens when the510 # type is used with prompts.511 if ctx is not None:512 if should_close:513 ctx.call_on_close(safecall(f.close))514 else:515 ctx.call_on_close(safecall(f.flush))516 return f517 except (IOError, OSError) as e: # noqa: B014518 self.fail(519 "Could not open file: {}: {}".format(520 filename_to_ui(value), get_streerror(e)521 ),522 param,523 ctx,524 )525526527class Path(ParamType):528 """The path type is similar to the :class:`File` type but it performs529 different checks. First of all, instead of returning an open file530 handle it returns just the filename. Secondly, it can perform various531 basic checks about what the file or directory should be.532533 .. versionchanged:: 6.0534 `allow_dash` was added.535536 :param exists: if set to true, the file or directory needs to exist for537 this value to be valid. If this is not required and a538 file does indeed not exist, then all further checks are539 silently skipped.540 :param file_okay: controls if a file is a possible value.541 :param dir_okay: controls if a directory is a possible value.542 :param writable: if true, a writable check is performed.543 :param readable: if true, a readable check is performed.544 :param resolve_path: if this is true, then the path is fully resolved545 before the value is passed onwards. This means546 that it's absolute and symlinks are resolved. It547 will not expand a tilde-prefix, as this is548 supposed to be done by the shell only.549 :param allow_dash: If this is set to `True`, a single dash to indicate550 standard streams is permitted.551 :param path_type: optionally a string type that should be used to552 represent the path. The default is `None` which553 means the return value will be either bytes or554 unicode depending on what makes most sense given the555 input data Click deals with.556 """557558 envvar_list_splitter = os.path.pathsep559560 def __init__(561 self,562 exists=False,563 file_okay=True,564 dir_okay=True,565 writable=False,566 readable=True,567 resolve_path=False,568 allow_dash=False,569 path_type=None,570 ):571 self.exists = exists572 self.file_okay = file_okay573 self.dir_okay = dir_okay574 self.writable = writable575 self.readable = readable576 self.resolve_path = resolve_path577 self.allow_dash = allow_dash578 self.type = path_type579580 if self.file_okay and not self.dir_okay:581 self.name = "file"582 self.path_type = "File"583 elif self.dir_okay and not self.file_okay:584 self.name = "directory"585 self.path_type = "Directory"586 else:587 self.name = "path"588 self.path_type = "Path"589590 def coerce_path_result(self, rv):591 if self.type is not None and not isinstance(rv, self.type):592 if self.type is text_type:593 rv = rv.decode(get_filesystem_encoding())594 else:595 rv = rv.encode(get_filesystem_encoding())596 return rv597598 def convert(self, value, param, ctx):599 rv = value600601 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")602603 if not is_dash:604 if self.resolve_path:605 rv = os.path.realpath(rv)606607 try:608 st = os.stat(rv)609 except OSError:610 if not self.exists:611 return self.coerce_path_result(rv)612 self.fail(613 "{} '{}' does not exist.".format(614 self.path_type, filename_to_ui(value)615 ),616 param,617 ctx,618 )619620 if not self.file_okay and stat.S_ISREG(st.st_mode):621 self.fail(622 "{} '{}' is a file.".format(self.path_type, filename_to_ui(value)),623 param,624 ctx,625 )626 if not self.dir_okay and stat.S_ISDIR(st.st_mode):627 self.fail(628 "{} '{}' is a directory.".format(629 self.path_type, filename_to_ui(value)630 ),631 param,632 ctx,633 )634 if self.writable and not os.access(value, os.W_OK):635 self.fail(636 "{} '{}' is not writable.".format(637 self.path_type, filename_to_ui(value)638 ),639 param,640 ctx,641 )642 if self.readable and not os.access(value, os.R_OK):643 self.fail(644 "{} '{}' is not readable.".format(645 self.path_type, filename_to_ui(value)646 ),647 param,648 ctx,649 )650651 return self.coerce_path_result(rv)652653654class Tuple(CompositeParamType):655 """The default behavior of Click is to apply a type on a value directly.656 This works well in most cases, except for when `nargs` is set to a fixed657 count and different types should be used for different items. In this658 case the :class:`Tuple` type can be used. This type can only be used659 if `nargs` is set to a fixed number.660661 For more information see :ref:`tuple-type`.662663 This can be selected by using a Python tuple literal as a type.664665 :param types: a list of types that should be used for the tuple items.666 """667668 def __init__(self, types):669 self.types = [convert_type(ty) for ty in types]670671 @property672 def name(self):673 return "<{}>".format(" ".join(ty.name for ty in self.types))674675 @property676 def arity(self):677 return len(self.types)678679 def convert(self, value, param, ctx):680 if len(value) != len(self.types):681 raise TypeError(682 "It would appear that nargs is set to conflict with the"683 " composite type arity."684 )685 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))686687688def convert_type(ty, default=None):689 """Converts a callable or python type into the most appropriate690 param type.691 """692 guessed_type = False693 if ty is None and default is not None:694 if isinstance(default, tuple):695 ty = tuple(map(type, default))696 else:697 ty = type(default)698 guessed_type = True699700 if isinstance(ty, tuple):701 return Tuple(ty)702 if isinstance(ty, ParamType):703 return ty704 if ty is text_type or ty is str or ty is None:705 return STRING706 if ty is int:707 return INT708 # Booleans are only okay if not guessed. This is done because for709 # flags the default value is actually a bit of a lie in that it710 # indicates which of the flags is the one we want. See get_default()711 # for more information.712 if ty is bool and not guessed_type:713 return BOOL714 if ty is float:715 return FLOAT716 if guessed_type:717 return STRING718719 # Catch a common mistake720 if __debug__:721 try:722 if issubclass(ty, ParamType):723 raise AssertionError(724 "Attempted to use an uninstantiated parameter type ({}).".format(ty)725 )726 except TypeError:727 pass728 return FuncParamType(ty)729730731#: A dummy parameter type that just does nothing. From a user's732#: perspective this appears to just be the same as `STRING` but internally733#: no string conversion takes place. This is necessary to achieve the734#: same bytes/unicode behavior on Python 2/3 in situations where you want735#: to not convert argument types. This is usually useful when working736#: with file paths as they can appear in bytes and unicode.737#:738#: For path related uses the :class:`Path` type is a better choice but739#: there are situations where an unprocessed type is useful which is why740#: it is is provided.741#:742#: .. versionadded:: 4.0743UNPROCESSED = UnprocessedParamType()744745#: A unicode string parameter type which is the implicit default. This746#: can also be selected by using ``str`` as type.747STRING = StringParamType()748749#: An integer parameter. This can also be selected by using ``int`` as750#: type.751INT = IntParamType()752753#: A floating point value parameter. This can also be selected by using754#: ``float`` as type.755FLOAT = FloatParamType()756757#: A boolean parameter. This is the default for boolean flags. This can758#: also be selected by using ``bool`` as a type.759BOOL = BoolParamType()760761#: A UUID parameter.762UUID = UUIDParameterType()
added:src/click/utils.py+455 added
1import os2import sys34from ._compat import _default_text_stderr5from ._compat import _default_text_stdout6from ._compat import auto_wrap_for_ansi7from ._compat import binary_streams8from ._compat import filename_to_ui9from ._compat import get_filesystem_encoding10from ._compat import get_streerror11from ._compat import is_bytes12from ._compat import open_stream13from ._compat import PY214from ._compat import should_strip_ansi15from ._compat import string_types16from ._compat import strip_ansi17from ._compat import text_streams18from ._compat import text_type19from ._compat import WIN20from .globals import resolve_color_default2122if not PY2:23 from ._compat import _find_binary_writer24elif WIN:25 from ._winconsole import _get_windows_argv26 from ._winconsole import _hash_py_argv27 from ._winconsole import _initial_argv_hash2829echo_native_types = string_types + (bytes, bytearray)303132def _posixify(name):33 return "-".join(name.split()).lower()343536def safecall(func):37 """Wraps a function so that it swallows exceptions."""3839 def wrapper(*args, **kwargs):40 try:41 return func(*args, **kwargs)42 except Exception:43 pass4445 return wrapper464748def make_str(value):49 """Converts a value into a valid string."""50 if isinstance(value, bytes):51 try:52 return value.decode(get_filesystem_encoding())53 except UnicodeError:54 return value.decode("utf-8", "replace")55 return text_type(value)565758def make_default_short_help(help, max_length=45):59 """Return a condensed version of help string."""60 words = help.split()61 total_length = 062 result = []63 done = False6465 for word in words:66 if word[-1:] == ".":67 done = True68 new_length = 1 + len(word) if result else len(word)69 if total_length + new_length > max_length:70 result.append("...")71 done = True72 else:73 if result:74 result.append(" ")75 result.append(word)76 if done:77 break78 total_length += new_length7980 return "".join(result)818283class LazyFile(object):84 """A lazy file works like a regular file but it does not fully open85 the file but it does perform some basic checks early to see if the86 filename parameter does make sense. This is useful for safely opening87 files for writing.88 """8990 def __init__(91 self, filename, mode="r", encoding=None, errors="strict", atomic=False92 ):93 self.name = filename94 self.mode = mode95 self.encoding = encoding96 self.errors = errors97 self.atomic = atomic9899 if filename == "-":100 self._f, self.should_close = open_stream(filename, mode, encoding, errors)101 else:102 if "r" in mode:103 # Open and close the file in case we're opening it for104 # reading so that we can catch at least some errors in105 # some cases early.106 open(filename, mode).close()107 self._f = None108 self.should_close = True109110 def __getattr__(self, name):111 return getattr(self.open(), name)112113 def __repr__(self):114 if self._f is not None:115 return repr(self._f)116 return "<unopened file '{}' {}>".format(self.name, self.mode)117118 def open(self):119 """Opens the file if it's not yet open. This call might fail with120 a :exc:`FileError`. Not handling this error will produce an error121 that Click shows.122 """123 if self._f is not None:124 return self._f125 try:126 rv, self.should_close = open_stream(127 self.name, self.mode, self.encoding, self.errors, atomic=self.atomic128 )129 except (IOError, OSError) as e: # noqa: E402130 from .exceptions import FileError131132 raise FileError(self.name, hint=get_streerror(e))133 self._f = rv134 return rv135136 def close(self):137 """Closes the underlying file, no matter what."""138 if self._f is not None:139 self._f.close()140141 def close_intelligently(self):142 """This function only closes the file if it was opened by the lazy143 file wrapper. For instance this will never close stdin.144 """145 if self.should_close:146 self.close()147148 def __enter__(self):149 return self150151 def __exit__(self, exc_type, exc_value, tb):152 self.close_intelligently()153154 def __iter__(self):155 self.open()156 return iter(self._f)157158159class KeepOpenFile(object):160 def __init__(self, file):161 self._file = file162163 def __getattr__(self, name):164 return getattr(self._file, name)165166 def __enter__(self):167 return self168169 def __exit__(self, exc_type, exc_value, tb):170 pass171172 def __repr__(self):173 return repr(self._file)174175 def __iter__(self):176 return iter(self._file)177178179def echo(message=None, file=None, nl=True, err=False, color=None):180 """Prints a message plus a newline to the given file or stdout. On181 first sight, this looks like the print function, but it has improved182 support for handling Unicode and binary data that does not fail no183 matter how badly configured the system is.184185 Primarily it means that you can print binary data as well as Unicode186 data on both 2.x and 3.x to the given file in the most appropriate way187 possible. This is a very carefree function in that it will try its188 best to not fail. As of Click 6.0 this includes support for unicode189 output on the Windows console.190191 In addition to that, if `colorama`_ is installed, the echo function will192 also support clever handling of ANSI codes. Essentially it will then193 do the following:194195 - add transparent handling of ANSI color codes on Windows.196 - hide ANSI codes automatically if the destination file is not a197 terminal.198199 .. _colorama: https://pypi.org/project/colorama/200201 .. versionchanged:: 6.0202 As of Click 6.0 the echo function will properly support unicode203 output on the windows console. Not that click does not modify204 the interpreter in any way which means that `sys.stdout` or the205 print statement or function will still not provide unicode support.206207 .. versionchanged:: 2.0208 Starting with version 2.0 of Click, the echo function will work209 with colorama if it's installed.210211 .. versionadded:: 3.0212 The `err` parameter was added.213214 .. versionchanged:: 4.0215 Added the `color` flag.216217 :param message: the message to print218 :param file: the file to write to (defaults to ``stdout``)219 :param err: if set to true the file defaults to ``stderr`` instead of220 ``stdout``. This is faster and easier than calling221 :func:`get_text_stderr` yourself.222 :param nl: if set to `True` (the default) a newline is printed afterwards.223 :param color: controls if the terminal supports ANSI colors or not. The224 default is autodetection.225 """226 if file is None:227 if err:228 file = _default_text_stderr()229 else:230 file = _default_text_stdout()231232 # Convert non bytes/text into the native string type.233 if message is not None and not isinstance(message, echo_native_types):234 message = text_type(message)235236 if nl:237 message = message or u""238 if isinstance(message, text_type):239 message += u"\n"240 else:241 message += b"\n"242243 # If there is a message, and we're in Python 3, and the value looks244 # like bytes, we manually need to find the binary stream and write the245 # message in there. This is done separately so that most stream246 # types will work as you would expect. Eg: you can write to StringIO247 # for other cases.248 if message and not PY2 and is_bytes(message):249 binary_file = _find_binary_writer(file)250 if binary_file is not None:251 file.flush()252 binary_file.write(message)253 binary_file.flush()254 return255256 # ANSI-style support. If there is no message or we are dealing with257 # bytes nothing is happening. If we are connected to a file we want258 # to strip colors. If we are on windows we either wrap the stream259 # to strip the color or we use the colorama support to translate the260 # ansi codes to API calls.261 if message and not is_bytes(message):262 color = resolve_color_default(color)263 if should_strip_ansi(file, color):264 message = strip_ansi(message)265 elif WIN:266 if auto_wrap_for_ansi is not None:267 file = auto_wrap_for_ansi(file)268 elif not color:269 message = strip_ansi(message)270271 if message:272 file.write(message)273 file.flush()274275276def get_binary_stream(name):277 """Returns a system stream for byte processing. This essentially278 returns the stream from the sys module with the given name but it279 solves some compatibility issues between different Python versions.280 Primarily this function is necessary for getting binary streams on281 Python 3.282283 :param name: the name of the stream to open. Valid names are ``'stdin'``,284 ``'stdout'`` and ``'stderr'``285 """286 opener = binary_streams.get(name)287 if opener is None:288 raise TypeError("Unknown standard stream '{}'".format(name))289 return opener()290291292def get_text_stream(name, encoding=None, errors="strict"):293 """Returns a system stream for text processing. This usually returns294 a wrapped stream around a binary stream returned from295 :func:`get_binary_stream` but it also can take shortcuts on Python 3296 for already correctly configured streams.297298 :param name: the name of the stream to open. Valid names are ``'stdin'``,299 ``'stdout'`` and ``'stderr'``300 :param encoding: overrides the detected default encoding.301 :param errors: overrides the default error mode.302 """303 opener = text_streams.get(name)304 if opener is None:305 raise TypeError("Unknown standard stream '{}'".format(name))306 return opener(encoding, errors)307308309def open_file(310 filename, mode="r", encoding=None, errors="strict", lazy=False, atomic=False311):312 """This is similar to how the :class:`File` works but for manual313 usage. Files are opened non lazy by default. This can open regular314 files as well as stdin/stdout if ``'-'`` is passed.315316 If stdin/stdout is returned the stream is wrapped so that the context317 manager will not close the stream accidentally. This makes it possible318 to always use the function like this without having to worry to319 accidentally close a standard stream::320321 with open_file(filename) as f:322 ...323324 .. versionadded:: 3.0325326 :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).327 :param mode: the mode in which to open the file.328 :param encoding: the encoding to use.329 :param errors: the error handling for this file.330 :param lazy: can be flipped to true to open the file lazily.331 :param atomic: in atomic mode writes go into a temporary file and it's332 moved on close.333 """334 if lazy:335 return LazyFile(filename, mode, encoding, errors, atomic=atomic)336 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)337 if not should_close:338 f = KeepOpenFile(f)339 return f340341342def get_os_args():343 """This returns the argument part of sys.argv in the most appropriate344 form for processing. What this means is that this return value is in345 a format that works for Click to process but does not necessarily346 correspond well to what's actually standard for the interpreter.347348 On most environments the return value is ``sys.argv[:1]`` unchanged.349 However if you are on Windows and running Python 2 the return value350 will actually be a list of unicode strings instead because the351 default behavior on that platform otherwise will not be able to352 carry all possible values that sys.argv can have.353354 .. versionadded:: 6.0355 """356 # We can only extract the unicode argv if sys.argv has not been357 # changed since the startup of the application.358 if PY2 and WIN and _initial_argv_hash == _hash_py_argv():359 return _get_windows_argv()360 return sys.argv[1:]361362363def format_filename(filename, shorten=False):364 """Formats a filename for user display. The main purpose of this365 function is to ensure that the filename can be displayed at all. This366 will decode the filename to unicode if necessary in a way that it will367 not fail. Optionally, it can shorten the filename to not include the368 full path to the filename.369370 :param filename: formats a filename for UI display. This will also convert371 the filename into unicode without failing.372 :param shorten: this optionally shortens the filename to strip of the373 path that leads up to it.374 """375 if shorten:376 filename = os.path.basename(filename)377 return filename_to_ui(filename)378379380def get_app_dir(app_name, roaming=True, force_posix=False):381 r"""Returns the config folder for the application. The default behavior382 is to return whatever is most appropriate for the operating system.383384 To give you an idea, for an app called ``"Foo Bar"``, something like385 the following folders could be returned:386387 Mac OS X:388 ``~/Library/Application Support/Foo Bar``389 Mac OS X (POSIX):390 ``~/.foo-bar``391 Unix:392 ``~/.config/foo-bar``393 Unix (POSIX):394 ``~/.foo-bar``395 Win XP (roaming):396 ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``397 Win XP (not roaming):398 ``C:\Documents and Settings\<user>\Application Data\Foo Bar``399 Win 7 (roaming):400 ``C:\Users\<user>\AppData\Roaming\Foo Bar``401 Win 7 (not roaming):402 ``C:\Users\<user>\AppData\Local\Foo Bar``403404 .. versionadded:: 2.0405406 :param app_name: the application name. This should be properly capitalized407 and can contain whitespace.408 :param roaming: controls if the folder should be roaming or not on Windows.409 Has no affect otherwise.410 :param force_posix: if this is set to `True` then on any POSIX system the411 folder will be stored in the home folder with a leading412 dot instead of the XDG config home or darwin's413 application support folder.414 """415 if WIN:416 key = "APPDATA" if roaming else "LOCALAPPDATA"417 folder = os.environ.get(key)418 if folder is None:419 folder = os.path.expanduser("~")420 return os.path.join(folder, app_name)421 if force_posix:422 return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))423 if sys.platform == "darwin":424 return os.path.join(425 os.path.expanduser("~/Library/Application Support"), app_name426 )427 return os.path.join(428 os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),429 _posixify(app_name),430 )431432433class PacifyFlushWrapper(object):434 """This wrapper is used to catch and suppress BrokenPipeErrors resulting435 from ``.flush()`` being called on broken pipe during the shutdown/final-GC436 of the Python interpreter. Notably ``.flush()`` is always called on437 ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any438 other cleanup code, and the case where the underlying file is not a broken439 pipe, all calls and attributes are proxied.440 """441442 def __init__(self, wrapped):443 self.wrapped = wrapped444445 def flush(self):446 try:447 self.wrapped.flush()448 except IOError as e:449 import errno450451 if e.errno != errno.EPIPE:452 raise453454 def __getattr__(self, attr):455 return getattr(self.wrapped, attr)
modified:tests/conftest.py+3 added-3 removed
1from click.testing import CliRunner21import pytest23from click.testing import CliRunner456@pytest.fixture(scope='function')6@pytest.fixture(scope="function")7def runner(request):8 return CliRunner()
modified:tests/test_arguments.py+116 added-129 removed
1# -*- coding: utf-8 -*-2import sys34import pytest56import click4import sys5from click._compat import PY2, text_type7from click._compat import PY28from click._compat import text_type91011def test_nargs_star(runner):12 @click.command()10 @click.argument('src', nargs=-1)11 @click.argument('dst')13 @click.argument("src", nargs=-1)14 @click.argument("dst")15 def copy(src, dst):13 click.echo('src=%s' % '|'.join(src))14 click.echo('dst=%s' % dst)16 click.echo("src={}".format("|".join(src)))17 click.echo("dst={}".format(dst))1816 result = runner.invoke(copy, ['foo.txt', 'bar.txt', 'dir'])19 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])20 assert not result.exception18 assert result.output.splitlines() == [19 'src=foo.txt|bar.txt',20 'dst=dir',21 ]21 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]222324def test_nargs_default(runner):25 try:25 with pytest.raises(TypeError, match="nargs=-1"):2627 @click.command()27 @click.argument('src', nargs=-1, default=42)28 @click.argument("src", nargs=-1, default=42)29 def copy(src):30 pass30 except TypeError as e:31 assert 'nargs=-1' in str(e)32 else:33 assert False313233def test_nargs_tup(runner):34 @click.command()38 @click.argument('name', nargs=1)39 @click.argument('point', nargs=2, type=click.INT)35 @click.argument("name", nargs=1)36 @click.argument("point", nargs=2, type=click.INT)37 def copy(name, point):41 click.echo('name=%s' % name)42 click.echo('point=%d/%d' % point)38 click.echo("name={}".format(name))39 click.echo("point={0[0]}/{0[1]}".format(point))4044 result = runner.invoke(copy, ['peter', '1', '2'])41 result = runner.invoke(copy, ["peter", "1", "2"])42 assert not result.exception46 assert result.output.splitlines() == [47 'name=peter',48 'point=1/2',49 ]43 assert result.output.splitlines() == ["name=peter", "point=1/2"]444546def test_nargs_tup_composite(runner):47 variations = [
3 unmodified lines
51 dict(nargs=2, type=(str, int)),52 ]5354 for opts in variations:5556 @click.command()62 @click.argument('item', **opts)57 @click.argument("item", **opts)58 def copy(item):64 click.echo('name=%s id=%d' % item)59 click.echo("name={0[0]} id={0[1]:d}".format(item))6066 result = runner.invoke(copy, ['peter', '1'])61 result = runner.invoke(copy, ["peter", "1"])62 assert not result.exception68 assert result.output.splitlines() == [69 'name=peter id=1',70 ]63 assert result.output.splitlines() == ["name=peter id=1"]646566def test_nargs_err(runner):67 @click.command()75 @click.argument('x')68 @click.argument("x")69 def copy(x):70 click.echo(x)7179 result = runner.invoke(copy, ['foo'])72 result = runner.invoke(copy, ["foo"])73 assert not result.exception81 assert result.output == 'foo\n'74 assert result.output == "foo\n"7583 result = runner.invoke(copy, ['foo', 'bar'])76 result = runner.invoke(copy, ["foo", "bar"])77 assert result.exit_code == 285 assert 'Got unexpected extra argument (bar)' in result.output78 assert "Got unexpected extra argument (bar)" in result.output798081def test_bytes_args(runner, monkeypatch):82 @click.command()90 @click.argument('arg')83 @click.argument("arg")84 def from_bytes(arg):92 assert isinstance(arg, text_type), "UTF-8 encoded argument should be implicitly converted to Unicode"85 assert isinstance(86 arg, text_type87 ), "UTF-8 encoded argument should be implicitly converted to Unicode"8889 # Simulate empty locale environment variables90 if PY2:96 monkeypatch.setattr(sys.stdin, 'encoding', 'ANSI_X3.4-1968')97 monkeypatch.setattr(sys, 'getfilesystemencoding', lambda: 'ANSI_X3.4-1968')98 monkeypatch.setattr(sys, 'getdefaultencoding', lambda: 'ascii')91 monkeypatch.setattr(sys.stdin, "encoding", "ANSI_X3.4-1968")92 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "ANSI_X3.4-1968")93 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "ascii")94 else:100 monkeypatch.setattr(sys.stdin, 'encoding', 'utf-8')101 monkeypatch.setattr(sys, 'getfilesystemencoding', lambda: 'utf-8')102 monkeypatch.setattr(sys, 'getdefaultencoding', lambda: 'utf-8')95 monkeypatch.setattr(sys.stdin, "encoding", "utf-8")96 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")97 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")98104 runner.invoke(from_bytes, [u'Something outside of ASCII range: 林'.encode('UTF-8')],105 catch_exceptions=False)99 runner.invoke(100 from_bytes,101 [u"Something outside of ASCII range: 林".encode("UTF-8")],102 catch_exceptions=False,103 )104105106def test_file_args(runner):107 @click.command()110 @click.argument('input', type=click.File('rb'))111 @click.argument('output', type=click.File('wb'))108 @click.argument("input", type=click.File("rb"))109 @click.argument("output", type=click.File("wb"))110 def inout(input, output):111 while True:112 chunk = input.read(1024)113 if not chunk:114 break115 output.write(chunk)116117 with runner.isolated_filesystem():120 result = runner.invoke(inout, ['-', 'hello.txt'], input='Hey!')121 assert result.output == ''118 result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")119 assert result.output == ""120 assert result.exit_code == 0123 with open('hello.txt', 'rb') as f:124 assert f.read() == b'Hey!'121 with open("hello.txt", "rb") as f:122 assert f.read() == b"Hey!"123126 result = runner.invoke(inout, ['hello.txt', '-'])127 assert result.output == 'Hey!'124 result = runner.invoke(inout, ["hello.txt", "-"])125 assert result.output == "Hey!"126 assert result.exit_code == 0127128129def test_path_args(runner):130 @click.command()133 @click.argument('input', type=click.Path(dir_okay=False, allow_dash=True))131 @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True))132 def foo(input):133 click.echo(input)134137 result = runner.invoke(foo, ['-'])138 assert result.output == '-\n'135 result = runner.invoke(foo, ["-"])136 assert result.output == "-\n"137 assert result.exit_code == 0138139140def test_file_atomics(runner):141 @click.command()144 @click.argument('output', type=click.File('wb', atomic=True))142 @click.argument("output", type=click.File("wb", atomic=True))143 def inout(output):146 output.write(b'Foo bar baz\n')144 output.write(b"Foo bar baz\n")145 output.flush()148 with open(output.name, 'rb') as f:146 with open(output.name, "rb") as f:147 old_content = f.read()150 assert old_content == b'OLD\n'148 assert old_content == b"OLD\n"149150 with runner.isolated_filesystem():153 with open('foo.txt', 'wb') as f:154 f.write(b'OLD\n')155 result = runner.invoke(inout, ['foo.txt'], input='Hey!',156 catch_exceptions=False)157 assert result.output == ''151 with open("foo.txt", "wb") as f:152 f.write(b"OLD\n")153 result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)154 assert result.output == ""155 assert result.exit_code == 0159 with open('foo.txt', 'rb') as f:160 assert f.read() == b'Foo bar baz\n'156 with open("foo.txt", "rb") as f:157 assert f.read() == b"Foo bar baz\n"158159160def test_stdout_default(runner):161 @click.command()165 @click.argument('output', type=click.File('w'), default='-')162 @click.argument("output", type=click.File("w"), default="-")163 def inout(output):167 output.write('Foo bar baz\n')164 output.write("Foo bar baz\n")165 output.flush()166167 result = runner.invoke(inout, [])168 assert not result.exception172 assert result.output == 'Foo bar baz\n'169 assert result.output == "Foo bar baz\n"170171172def test_nargs_envvar(runner):173 @click.command()177 @click.option('--arg', nargs=2)174 @click.option("--arg", nargs=2)175 def cmd(arg):179 click.echo('|'.join(arg))176 click.echo("|".join(arg))177181 result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',182 env={'TEST_ARG': 'foo bar'})178 result = runner.invoke(179 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}180 )181 assert not result.exception184 assert result.output == 'foo|bar\n'182 assert result.output == "foo|bar\n"183184 @click.command()187 @click.option('--arg', envvar='X', nargs=2)185 @click.option("--arg", envvar="X", nargs=2)186 def cmd(arg):189 click.echo('|'.join(arg))187 click.echo("|".join(arg))188191 result = runner.invoke(cmd, [], env={'X': 'foo bar'})189 result = runner.invoke(cmd, [], env={"X": "foo bar"})190 assert not result.exception193 assert result.output == 'foo|bar\n'191 assert result.output == "foo|bar\n"192193194def test_empty_nargs(runner):195 @click.command()198 @click.argument('arg', nargs=-1)196 @click.argument("arg", nargs=-1)197 def cmd(arg):200 click.echo('arg:' + '|'.join(arg))198 click.echo("arg:{}".format("|".join(arg)))199200 result = runner.invoke(cmd, [])201 assert result.exit_code == 0204 assert result.output == 'arg:\n'202 assert result.output == "arg:\n"203204 @click.command()207 @click.argument('arg', nargs=-1, required=True)205 @click.argument("arg", nargs=-1, required=True)206 def cmd2(arg):209 click.echo('arg:' + '|'.join(arg))207 click.echo("arg:{}".format("|".join(arg)))208209 result = runner.invoke(cmd2, [])210 assert result.exit_code == 2213 assert 'Missing argument "ARG..."' in result.output211 assert "Missing argument 'ARG...'" in result.output212213214def test_missing_arg(runner):215 @click.command()218 @click.argument('arg')216 @click.argument("arg")217 def cmd(arg):220 click.echo('arg:' + arg)218 click.echo("arg:{}".format(arg))219220 result = runner.invoke(cmd, [])221 assert result.exit_code == 2224 assert 'Missing argument "ARG".' in result.output222 assert "Missing argument 'ARG'." in result.output223224225def test_missing_argument_string_cast():226 ctx = click.Context(click.Command(""))
5 unmodified lines
232233234def test_implicit_non_required(runner):235 @click.command()238 @click.argument('f', default='test')236 @click.argument("f", default="test")237 def cli(f):238 click.echo(f)239240 result = runner.invoke(cli, [])241 assert result.exit_code == 0244 assert result.output == 'test\n'242 assert result.output == "test\n"243244245def test_eat_options(runner):246 @click.command()249 @click.option('-f')250 @click.argument('files', nargs=-1)247 @click.option("-f")248 @click.argument("files", nargs=-1)249 def cmd(f, files):250 for filename in files:251 click.echo(filename)252 click.echo(f)253256 result = runner.invoke(cmd, ['--', '-foo', 'bar'])257 assert result.output.splitlines() == [258 '-foo',259 'bar',260 '',261 ]254 result = runner.invoke(cmd, ["--", "-foo", "bar"])255 assert result.output.splitlines() == ["-foo", "bar", ""]256263 result = runner.invoke(cmd, ['-f', '-x', '--', '-foo', 'bar'])264 assert result.output.splitlines() == [265 '-foo',266 'bar',267 '-x',268 ]257 result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])258 assert result.output.splitlines() == ["-foo", "bar", "-x"]259260261def test_nargs_star_ordering(runner):262 @click.command()273 @click.argument('a', nargs=-1)274 @click.argument('b')275 @click.argument('c')263 @click.argument("a", nargs=-1)264 @click.argument("b")265 @click.argument("c")266 def cmd(a, b, c):267 for arg in (a, b, c):268 click.echo(arg)269280 result = runner.invoke(cmd, ['a', 'b', 'c'])281 assert result.output.splitlines() == [282 PY2 and "(u'a',)" or "('a',)",283 'b',284 'c',285 ]270 result = runner.invoke(cmd, ["a", "b", "c"])271 assert result.output.splitlines() == ["(u'a',)" if PY2 else "('a',)", "b", "c"]272273274def test_nargs_specified_plus_star_ordering(runner):275 @click.command()290 @click.argument('a', nargs=-1)291 @click.argument('b')292 @click.argument('c', nargs=2)276 @click.argument("a", nargs=-1)277 @click.argument("b")278 @click.argument("c", nargs=2)279 def cmd(a, b, c):280 for arg in (a, b, c):281 click.echo(arg)282297 result = runner.invoke(cmd, ['a', 'b', 'c', 'd', 'e', 'f'])283 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])284 assert result.output.splitlines() == [299 PY2 and "(u'a', u'b', u'c')" or "('a', 'b', 'c')",300 'd',301 PY2 and "(u'e', u'f')" or "('e', 'f')",285 "(u'a', u'b', u'c')" if PY2 else "('a', 'b', 'c')",286 "d",287 "(u'e', u'f')" if PY2 else "('e', 'f')",288 ]289290291def test_defaults_for_nargs(runner):292 @click.command()307 @click.argument('a', nargs=2, type=int, default=(1, 2))293 @click.argument("a", nargs=2, type=int, default=(1, 2))294 def cmd(a):295 x, y = a296 click.echo(x + y)297298 result = runner.invoke(cmd, [])313 assert result.output.strip() == '3'299 assert result.output.strip() == "3"300315 result = runner.invoke(cmd, ['3', '4'])316 assert result.output.strip() == '7'301 result = runner.invoke(cmd, ["3", "4"])302 assert result.output.strip() == "7"303318 result = runner.invoke(cmd, ['3'])304 result = runner.invoke(cmd, ["3"])305 assert result.exception is not None320 assert 'argument a takes 2 values' in result.output306 assert "argument a takes 2 values" in result.output307308309def test_multiple_param_decls_not_allowed(runner):310 with pytest.raises(TypeError):311312 @click.command()326 @click.argument('x', click.Choice(['a', 'b']))313 @click.argument("x", click.Choice(["a", "b"]))314 def copy(x):315 click.echo(x)
modified:tests/test_bashcomplete.py+240 added-176 removed
1# -*- coding: utf-8 -*-22import pytest34import click5from click._bashcomplete import get_choices678def choices_without_help(cli, args, incomplete):10 completions = get_choices(cli, 'dummy', args, incomplete)9 completions = get_choices(cli, "dummy", args, incomplete)10 return [c[0] for c in completions]111213def choices_with_help(cli, args, incomplete):15 return list(get_choices(cli, 'dummy', args, incomplete))14 return list(get_choices(cli, "dummy", args, incomplete))151617def test_single_command():18 @click.command()20 @click.option('--local-opt')19 @click.option("--local-opt")20 def cli(local_opt):21 pass2224 assert choices_without_help(cli, [], '-') == ['--local-opt']25 assert choices_without_help(cli, [], '') == []23 assert choices_without_help(cli, [], "-") == ["--local-opt"]24 assert choices_without_help(cli, [], "") == []252627def test_boolean_flag():28 @click.command()30 @click.option('--shout/--no-shout', default=False)29 @click.option("--shout/--no-shout", default=False)30 def cli(local_opt):31 pass3234 assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']33 assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]343536def test_multi_value_option():37 @click.group()39 @click.option('--pos', nargs=2, type=float)38 @click.option("--pos", nargs=2, type=float)39 def cli(local_opt):40 pass4142 @cli.command()44 @click.option('--local-opt')43 @click.option("--local-opt")44 def sub(local_opt):45 pass4648 assert choices_without_help(cli, [], '-') == ['--pos']49 assert choices_without_help(cli, ['--pos'], '') == []50 assert choices_without_help(cli, ['--pos', '1.0'], '') == []51 assert choices_without_help(cli, ['--pos', '1.0', '1.0'], '') == ['sub']47 assert choices_without_help(cli, [], "-") == ["--pos"]48 assert choices_without_help(cli, ["--pos"], "") == []49 assert choices_without_help(cli, ["--pos", "1.0"], "") == []50 assert choices_without_help(cli, ["--pos", "1.0", "1.0"], "") == ["sub"]515253def test_multi_option():54 @click.command()56 @click.option('--message', '-m', multiple=True)55 @click.option("--message", "-m", multiple=True)56 def cli(local_opt):57 pass5860 assert choices_without_help(cli, [], '-') == ['--message', '-m']61 assert choices_without_help(cli, ['-m'], '') == []59 assert choices_without_help(cli, [], "-") == ["--message", "-m"]60 assert choices_without_help(cli, ["-m"], "") == []616263def test_small_chain():64 @click.group()66 @click.option('--global-opt')65 @click.option("--global-opt")66 def cli(global_opt):67 pass6869 @cli.command()71 @click.option('--local-opt')70 @click.option("--local-opt")71 def sub(local_opt):72 pass7375 assert choices_without_help(cli, [], '') == ['sub']76 assert choices_without_help(cli, [], '-') == ['--global-opt']77 assert choices_without_help(cli, ['sub'], '') == []78 assert choices_without_help(cli, ['sub'], '-') == ['--local-opt']74 assert choices_without_help(cli, [], "") == ["sub"]75 assert choices_without_help(cli, [], "-") == ["--global-opt"]76 assert choices_without_help(cli, ["sub"], "") == []77 assert choices_without_help(cli, ["sub"], "-") == ["--local-opt"]787980def test_long_chain():82 @click.group('cli')83 @click.option('--cli-opt')81 @click.group("cli")82 @click.option("--cli-opt")83 def cli(cli_opt):84 pass8587 @cli.group('asub')88 @click.option('--asub-opt')86 @cli.group("asub")87 @click.option("--asub-opt")88 def asub(asub_opt):89 pass9092 @asub.group('bsub')93 @click.option('--bsub-opt')91 @asub.group("bsub")92 @click.option("--bsub-opt")93 def bsub(bsub_opt):94 pass9597 COLORS = ['red', 'green', 'blue']96 COLORS = ["red", "green", "blue"]9798 def get_colors(ctx, args, incomplete):99 for c in COLORS:100 if c.startswith(incomplete):101 yield c
2 unmodified lines
104 for c in COLORS:105 if incomplete in c:106 yield c107108 CSUB_OPT_CHOICES = ['foo', 'bar']109 CSUB_CHOICES = ['bar', 'baz']110 @bsub.command('csub')111 @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))112 @click.option('--csub', type=click.Choice(CSUB_CHOICES))113 @click.option('--search-color', autocompletion=search_colors)114 @click.argument('color', autocompletion=get_colors)108 CSUB_OPT_CHOICES = ["foo", "bar"]109 CSUB_CHOICES = ["bar", "baz"]110111 @bsub.command("csub")112 @click.option("--csub-opt", type=click.Choice(CSUB_OPT_CHOICES))113 @click.option("--csub", type=click.Choice(CSUB_CHOICES))114 @click.option("--search-color", autocompletion=search_colors)115 @click.argument("color", autocompletion=get_colors)116 def csub(csub_opt, color):117 pass118118 assert choices_without_help(cli, [], '-') == ['--cli-opt']119 assert choices_without_help(cli, [], '') == ['asub']120 assert choices_without_help(cli, ['asub'], '-') == ['--asub-opt']121 assert choices_without_help(cli, ['asub'], '') == ['bsub']122 assert choices_without_help(cli, ['asub', 'bsub'], '-') == ['--bsub-opt']123 assert choices_without_help(cli, ['asub', 'bsub'], '') == ['csub']124 assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '-') == ['--csub-opt', '--csub', '--search-color']125 assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub-opt'], '') == CSUB_OPT_CHOICES126 assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '--csub') == ['--csub-opt', '--csub']127 assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub'], '') == CSUB_CHOICES128 assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub-opt'], 'f') == ['foo']129 assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '') == COLORS130 assert choices_without_help(cli, ['asub', 'bsub', 'csub'], 'b') == ['blue']131 assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--search-color'], 'een') == ['green']119 assert choices_without_help(cli, [], "-") == ["--cli-opt"]120 assert choices_without_help(cli, [], "") == ["asub"]121 assert choices_without_help(cli, ["asub"], "-") == ["--asub-opt"]122 assert choices_without_help(cli, ["asub"], "") == ["bsub"]123 assert choices_without_help(cli, ["asub", "bsub"], "-") == ["--bsub-opt"]124 assert choices_without_help(cli, ["asub", "bsub"], "") == ["csub"]125 assert choices_without_help(cli, ["asub", "bsub", "csub"], "-") == [126 "--csub-opt",127 "--csub",128 "--search-color",129 ]130 assert (131 choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "")132 == CSUB_OPT_CHOICES133 )134 assert choices_without_help(cli, ["asub", "bsub", "csub"], "--csub") == [135 "--csub-opt",136 "--csub",137 ]138 assert (139 choices_without_help(cli, ["asub", "bsub", "csub", "--csub"], "")140 == CSUB_CHOICES141 )142 assert choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "f") == [143 "foo"144 ]145 assert choices_without_help(cli, ["asub", "bsub", "csub"], "") == COLORS146 assert choices_without_help(cli, ["asub", "bsub", "csub"], "b") == ["blue"]147 assert choices_without_help(148 cli, ["asub", "bsub", "csub", "--search-color"], "een"149 ) == ["green"]150151152def test_chaining():135 @click.group('cli', chain=True)136 @click.option('--cli-opt')137 @click.argument('arg', type=click.Choice(['cliarg1', 'cliarg2']))153 @click.group("cli", chain=True)154 @click.option("--cli-opt")155 @click.argument("arg", type=click.Choice(["cliarg1", "cliarg2"]))156 def cli(cli_opt, arg):157 pass158159 @cli.command()142 @click.option('--asub-opt')160 @click.option("--asub-opt")161 def asub(asub_opt):162 pass163146 @cli.command(help='bsub help')147 @click.option('--bsub-opt')148 @click.argument('arg', type=click.Choice(['arg1', 'arg2']))164 @cli.command(help="bsub help")165 @click.option("--bsub-opt")166 @click.argument("arg", type=click.Choice(["arg1", "arg2"]))167 def bsub(bsub_opt, arg):168 pass169170 @cli.command()153 @click.option('--csub-opt')154 @click.argument('arg', type=click.Choice(['carg1', 'carg2']), default='carg1')171 @click.option("--csub-opt")172 @click.argument("arg", type=click.Choice(["carg1", "carg2"]), default="carg1")173 def csub(csub_opt, arg):174 pass175158 assert choices_without_help(cli, [], '-') == ['--cli-opt']159 assert choices_without_help(cli, [], '') == ['cliarg1', 'cliarg2']160 assert choices_without_help(cli, ['cliarg1', 'asub'], '-') == ['--asub-opt']161 assert choices_without_help(cli, ['cliarg1', 'asub'], '') == ['bsub', 'csub']162 assert choices_without_help(cli, ['cliarg1', 'bsub'], '') == ['arg1', 'arg2']163 assert choices_without_help(cli, ['cliarg1', 'asub', '--asub-opt'], '') == []164 assert choices_without_help(cli, ['cliarg1', 'asub', '--asub-opt', '5', 'bsub'], '-') == ['--bsub-opt']165 assert choices_without_help(cli, ['cliarg1', 'asub', 'bsub'], '-') == ['--bsub-opt']166 assert choices_without_help(cli, ['cliarg1', 'asub', 'csub'], '') == ['carg1', 'carg2']167 assert choices_without_help(cli, ['cliarg1', 'bsub', 'arg1', 'csub'], '') == ['carg1', 'carg2']168 assert choices_without_help(cli, ['cliarg1', 'asub', 'csub'], '-') == ['--csub-opt']169 assert choices_with_help(cli, ['cliarg1', 'asub'], 'b') == [('bsub', 'bsub help')]176 assert choices_without_help(cli, [], "-") == ["--cli-opt"]177 assert choices_without_help(cli, [], "") == ["cliarg1", "cliarg2"]178 assert choices_without_help(cli, ["cliarg1", "asub"], "-") == ["--asub-opt"]179 assert choices_without_help(cli, ["cliarg1", "asub"], "") == ["bsub", "csub"]180 assert choices_without_help(cli, ["cliarg1", "bsub"], "") == ["arg1", "arg2"]181 assert choices_without_help(cli, ["cliarg1", "asub", "--asub-opt"], "") == []182 assert choices_without_help(183 cli, ["cliarg1", "asub", "--asub-opt", "5", "bsub"], "-"184 ) == ["--bsub-opt"]185 assert choices_without_help(cli, ["cliarg1", "asub", "bsub"], "-") == ["--bsub-opt"]186 assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "") == [187 "carg1",188 "carg2",189 ]190 assert choices_without_help(cli, ["cliarg1", "bsub", "arg1", "csub"], "") == [191 "carg1",192 "carg2",193 ]194 assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "-") == ["--csub-opt"]195 assert choices_with_help(cli, ["cliarg1", "asub"], "b") == [("bsub", "bsub help")]196197198def test_argument_choice():199 @click.command()174 @click.argument('arg1', required=True, type=click.Choice(['arg11', 'arg12']))175 @click.argument('arg2', type=click.Choice(['arg21', 'arg22']), default='arg21')176 @click.argument('arg3', type=click.Choice(['arg', 'argument']), default='arg')200 @click.argument("arg1", required=True, type=click.Choice(["arg11", "arg12"]))201 @click.argument("arg2", type=click.Choice(["arg21", "arg22"]), default="arg21")202 @click.argument("arg3", type=click.Choice(["arg", "argument"]), default="arg")203 def cli():204 pass205180 assert choices_without_help(cli, [], '') == ['arg11', 'arg12']181 assert choices_without_help(cli, [], 'arg') == ['arg11', 'arg12']182 assert choices_without_help(cli, ['arg11'], '') == ['arg21', 'arg22']183 assert choices_without_help(cli, ['arg12', 'arg21'], '') == ['arg', 'argument']184 assert choices_without_help(cli, ['arg12', 'arg21'], 'argu') == ['argument']206 assert choices_without_help(cli, [], "") == ["arg11", "arg12"]207 assert choices_without_help(cli, [], "arg") == ["arg11", "arg12"]208 assert choices_without_help(cli, ["arg11"], "") == ["arg21", "arg22"]209 assert choices_without_help(cli, ["arg12", "arg21"], "") == ["arg", "argument"]210 assert choices_without_help(cli, ["arg12", "arg21"], "argu") == ["argument"]211212213def test_option_choice():214 @click.command()189 @click.option('--opt1', type=click.Choice(['opt11', 'opt12']), help='opt1 help')190 @click.option('--opt2', type=click.Choice(['opt21', 'opt22']), default='opt21')191 @click.option('--opt3', type=click.Choice(['opt', 'option']))215 @click.option("--opt1", type=click.Choice(["opt11", "opt12"]), help="opt1 help")216 @click.option("--opt2", type=click.Choice(["opt21", "opt22"]), default="opt21")217 @click.option("--opt3", type=click.Choice(["opt", "option"]))218 def cli():219 pass220195 assert choices_with_help(cli, [], '-') == [('--opt1', 'opt1 help'),196 ('--opt2', None),197 ('--opt3', None)]198 assert choices_without_help(cli, [], '--opt') == ['--opt1', '--opt2', '--opt3']199 assert choices_without_help(cli, [], '--opt1=') == ['opt11', 'opt12']200 assert choices_without_help(cli, [], '--opt2=') == ['opt21', 'opt22']201 assert choices_without_help(cli, ['--opt2'], '=') == ['opt21', 'opt22']202 assert choices_without_help(cli, ['--opt2', '='], 'opt') == ['opt21', 'opt22']203 assert choices_without_help(cli, ['--opt1'], '') == ['opt11', 'opt12']204 assert choices_without_help(cli, ['--opt2'], '') == ['opt21', 'opt22']205 assert choices_without_help(cli, ['--opt1', 'opt11', '--opt2'], '') == ['opt21', 'opt22']206 assert choices_without_help(cli, ['--opt2', 'opt21'], '-') == ['--opt1', '--opt3']207 assert choices_without_help(cli, ['--opt1', 'opt11'], '-') == ['--opt2', '--opt3']208 assert choices_without_help(cli, ['--opt1'], 'opt') == ['opt11', 'opt12']209 assert choices_without_help(cli, ['--opt3'], 'opti') == ['option']221 assert choices_with_help(cli, [], "-") == [222 ("--opt1", "opt1 help"),223 ("--opt2", None),224 ("--opt3", None),225 ]226 assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2", "--opt3"]227 assert choices_without_help(cli, [], "--opt1=") == ["opt11", "opt12"]228 assert choices_without_help(cli, [], "--opt2=") == ["opt21", "opt22"]229 assert choices_without_help(cli, ["--opt2"], "=") == ["opt21", "opt22"]230 assert choices_without_help(cli, ["--opt2", "="], "opt") == ["opt21", "opt22"]231 assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]232 assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]233 assert choices_without_help(cli, ["--opt1", "opt11", "--opt2"], "") == [234 "opt21",235 "opt22",236 ]237 assert choices_without_help(cli, ["--opt2", "opt21"], "-") == ["--opt1", "--opt3"]238 assert choices_without_help(cli, ["--opt1", "opt11"], "-") == ["--opt2", "--opt3"]239 assert choices_without_help(cli, ["--opt1"], "opt") == ["opt11", "opt12"]240 assert choices_without_help(cli, ["--opt3"], "opti") == ["option"]241211 assert choices_without_help(cli, ['--opt1', 'invalid_opt'], '-') == ['--opt2', '--opt3']242 assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [243 "--opt2",244 "--opt3",245 ]246247248def test_option_and_arg_choice():249 @click.command()216 @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))217 @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))218 @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))250 @click.option("--opt1", type=click.Choice(["opt11", "opt12"]))251 @click.argument("arg1", required=False, type=click.Choice(["arg11", "arg12"]))252 @click.option("--opt2", type=click.Choice(["opt21", "opt22"]))253 def cli():254 pass255222 assert choices_without_help(cli, ['--opt1'], '') == ['opt11', 'opt12']223 assert choices_without_help(cli, [''], '--opt1=') == ['opt11', 'opt12']224 assert choices_without_help(cli, [], '') == ['arg11', 'arg12']225 assert choices_without_help(cli, ['--opt2'], '') == ['opt21', 'opt22']226 assert choices_without_help(cli, ['arg11'], '--opt') == ['--opt1', '--opt2']227 assert choices_without_help(cli, [], '--opt') == ['--opt1', '--opt2']256 assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]257 assert choices_without_help(cli, [""], "--opt1=") == ["opt11", "opt12"]258 assert choices_without_help(cli, [], "") == ["arg11", "arg12"]259 assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]260 assert choices_without_help(cli, ["arg11"], "--opt") == ["--opt1", "--opt2"]261 assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2"]262263264def test_boolean_flag_choice():265 @click.command()232 @click.option('--shout/--no-shout', default=False)233 @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))266 @click.option("--shout/--no-shout", default=False)267 @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))268 def cli(local_opt):269 pass270237 assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']238 assert choices_without_help(cli, ['--shout'], '') == ['arg1', 'arg2']271 assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]272 assert choices_without_help(cli, ["--shout"], "") == ["arg1", "arg2"]273274275def test_multi_value_option_choice():276 @click.command()243 @click.option('--pos', nargs=2, type=click.Choice(['pos1', 'pos2']))244 @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))277 @click.option("--pos", nargs=2, type=click.Choice(["pos1", "pos2"]))278 @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))279 def cli(local_opt):280 pass281248 assert choices_without_help(cli, ['--pos'], '') == ['pos1', 'pos2']249 assert choices_without_help(cli, ['--pos', 'pos1'], '') == ['pos1', 'pos2']250 assert choices_without_help(cli, ['--pos', 'pos1', 'pos2'], '') == ['arg1', 'arg2']251 assert choices_without_help(cli, ['--pos', 'pos1', 'pos2', 'arg1'], '') == []282 assert choices_without_help(cli, ["--pos"], "") == ["pos1", "pos2"]283 assert choices_without_help(cli, ["--pos", "pos1"], "") == ["pos1", "pos2"]284 assert choices_without_help(cli, ["--pos", "pos1", "pos2"], "") == ["arg1", "arg2"]285 assert choices_without_help(cli, ["--pos", "pos1", "pos2", "arg1"], "") == []286287288def test_multi_option_choice():289 @click.command()256 @click.option('--message', '-m', multiple=True, type=click.Choice(['m1', 'm2']))257 @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))290 @click.option("--message", "-m", multiple=True, type=click.Choice(["m1", "m2"]))291 @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))292 def cli(local_opt):293 pass294261 assert choices_without_help(cli, ['-m'], '') == ['m1', 'm2']262 assert choices_without_help(cli, ['-m', 'm1', '-m'], '') == ['m1', 'm2']263 assert choices_without_help(cli, ['-m', 'm1'], '') == ['arg1', 'arg2']295 assert choices_without_help(cli, ["-m"], "") == ["m1", "m2"]296 assert choices_without_help(cli, ["-m", "m1", "-m"], "") == ["m1", "m2"]297 assert choices_without_help(cli, ["-m", "m1"], "") == ["arg1", "arg2"]298299300def test_variadic_argument_choice():301 @click.command()268 @click.option('--opt', type=click.Choice(['opt1', 'opt2']))269 @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))302 @click.option("--opt", type=click.Choice(["opt1", "opt2"]))303 @click.argument("src", nargs=-1, type=click.Choice(["src1", "src2"]))304 def cli(local_opt):305 pass306273 assert choices_without_help(cli, ['src1', 'src2'], '') == ['src1', 'src2']274 assert choices_without_help(cli, ['src1', 'src2'], '--o') == ['--opt']275 assert choices_without_help(cli, ['src1', 'src2', '--opt'], '') == ['opt1', 'opt2']276 assert choices_without_help(cli, ['src1', 'src2'], '') == ['src1', 'src2']307 assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]308 assert choices_without_help(cli, ["src1", "src2"], "--o") == ["--opt"]309 assert choices_without_help(cli, ["src1", "src2", "--opt"], "") == ["opt1", "opt2"]310 assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]311312313def test_variadic_argument_complete():280314 def _complete(ctx, args, incomplete):282 return ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz']315 return ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]316317 @click.group()318 def entrypoint():319 pass320321 @click.command()289 @click.option('--opt', autocompletion=_complete)290 @click.argument('arg', nargs=-1)322 @click.option("--opt", autocompletion=_complete)323 @click.argument("arg", nargs=-1)324 def subcommand(opt, arg):325 pass326327 entrypoint.add_command(subcommand)328296 assert choices_without_help(entrypoint, ['subcommand', '--opt'], '') == _complete(0,0,0)297 assert choices_without_help(entrypoint, ['subcommand', 'whatever', '--opt'], '') == _complete(0,0,0)298 assert choices_without_help(entrypoint, ['subcommand', 'whatever', '--opt', 'abc'], '') == []329 assert choices_without_help(entrypoint, ["subcommand", "--opt"], "") == _complete(330 0, 0, 0331 )332 assert choices_without_help(333 entrypoint, ["subcommand", "whatever", "--opt"], ""334 ) == _complete(0, 0, 0)335 assert (336 choices_without_help(entrypoint, ["subcommand", "whatever", "--opt", "abc"], "")337 == []338 )339340341def test_long_chain_choice():342 @click.group()343 def cli():344 pass345346 @cli.group()307 @click.option('--sub-opt', type=click.Choice(['subopt1', 'subopt2']))308 @click.argument('sub-arg', required=False, type=click.Choice(['subarg1', 'subarg2']))347 @click.option("--sub-opt", type=click.Choice(["subopt1", "subopt2"]))348 @click.argument(349 "sub-arg", required=False, type=click.Choice(["subarg1", "subarg2"])350 )351 def sub(sub_opt, sub_arg):352 pass353312 @sub.command(short_help='bsub help')313 @click.option('--bsub-opt', type=click.Choice(['bsubopt1', 'bsubopt2']))314 @click.argument('bsub-arg1', required=False, type=click.Choice(['bsubarg1', 'bsubarg2']))315 @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))354 @sub.command(short_help="bsub help")355 @click.option("--bsub-opt", type=click.Choice(["bsubopt1", "bsubopt2"]))356 @click.argument(357 "bsub-arg1", required=False, type=click.Choice(["bsubarg1", "bsubarg2"])358 )359 @click.argument(360 "bbsub-arg2", required=False, type=click.Choice(["bbsubarg1", "bbsubarg2"])361 )362 def bsub(bsub_opt):363 pass364319 @sub.group('csub')365 @sub.group("csub")366 def csub():367 pass368369 @csub.command()370 def dsub():371 pass372327 assert choices_with_help(cli, ['sub', 'subarg1'], '') == [('bsub', 'bsub help'), ('csub', '')]328 assert choices_without_help(cli, ['sub'], '') == ['subarg1', 'subarg2']329 assert choices_without_help(cli, ['sub', '--sub-opt'], '') == ['subopt1', 'subopt2']330 assert choices_without_help(cli, ['sub', '--sub-opt', 'subopt1'], '') == \331 ['subarg1', 'subarg2']332 assert choices_without_help(cli,333 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-') == ['--bsub-opt']334 assert choices_without_help(cli,335 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '') == ['bsubarg1', 'bsubarg2']336 assert choices_without_help(cli,337 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '') == \338 ['bsubopt1', 'bsubopt2']339 assert choices_without_help(cli,340 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt', 'bsubopt1', 'bsubarg1'],341 '') == ['bbsubarg1', 'bbsubarg2']342 assert choices_without_help(cli,343 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'csub'],344 '') == ['dsub']373 assert choices_with_help(cli, ["sub", "subarg1"], "") == [374 ("bsub", "bsub help"),375 ("csub", ""),376 ]377 assert choices_without_help(cli, ["sub"], "") == ["subarg1", "subarg2"]378 assert choices_without_help(cli, ["sub", "--sub-opt"], "") == ["subopt1", "subopt2"]379 assert choices_without_help(cli, ["sub", "--sub-opt", "subopt1"], "") == [380 "subarg1",381 "subarg2",382 ]383 assert choices_without_help(384 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], "-"385 ) == ["--bsub-opt"]386 assert choices_without_help(387 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], ""388 ) == ["bsubarg1", "bsubarg2"]389 assert choices_without_help(390 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub", "--bsub-opt"], ""391 ) == ["bsubopt1", "bsubopt2"]392 assert choices_without_help(393 cli,394 [395 "sub",396 "--sub-opt",397 "subopt1",398 "subarg1",399 "bsub",400 "--bsub-opt",401 "bsubopt1",402 "bsubarg1",403 ],404 "",405 ) == ["bbsubarg1", "bbsubarg2"]406 assert choices_without_help(407 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "csub"], ""408 ) == ["dsub"]409410411def test_chained_multi():412 @click.group()
19 unmodified lines
432 @csub.command()433 def esub():434 pass435372 assert choices_without_help(cli, ['sub'], '') == ['bsub', 'csub']373 assert choices_without_help(cli, ['sub'], 'c') == ['csub']374 assert choices_without_help(cli, ['sub', 'csub'], '') == ['dsub', 'esub']375 assert choices_without_help(cli, ['sub', 'csub', 'dsub'], '') == ['esub']436 assert choices_without_help(cli, ["sub"], "") == ["bsub", "csub"]437 assert choices_without_help(cli, ["sub"], "c") == ["csub"]438 assert choices_without_help(cli, ["sub", "csub"], "") == ["dsub", "esub"]439 assert choices_without_help(cli, ["sub", "csub", "dsub"], "") == ["esub"]440441442def test_hidden():443 @click.group()380 @click.option('--name', hidden=True)381 @click.option('--choices', type=click.Choice([1, 2]), hidden=True)444 @click.option("--name", hidden=True)445 @click.option("--choices", type=click.Choice([1, 2]), hidden=True)446 def cli(name):447 pass448449 @cli.group(hidden=True)
8 unmodified lines
458 def asub():459 pass460461 @cli.command(hidden=True)398 @click.option('--hname')462 @click.option("--hname")463 def hsub():464 pass465402 assert choices_without_help(cli, [], '--n') == []403 assert choices_without_help(cli, [], '--c') == []466 assert choices_without_help(cli, [], "--n") == []467 assert choices_without_help(cli, [], "--c") == []468 # If the user exactly types out the hidden param, complete its options.405 assert choices_without_help(cli, ['--choices'], '') == [1, 2]406 assert choices_without_help(cli, [], '') == ['asub']407 assert choices_without_help(cli, [], '') == ['asub']408 assert choices_without_help(cli, [], 'h') == []469 assert choices_without_help(cli, ["--choices"], "") == [1, 2]470 assert choices_without_help(cli, [], "") == ["asub"]471 assert choices_without_help(cli, [], "") == ["asub"]472 assert choices_without_help(cli, [], "h") == []473 # If the user exactly types out the hidden command, complete its subcommands.410 assert choices_without_help(cli, ['hgroup'], '') == ['hgroupsub']411 assert choices_without_help(cli, ['hsub'], '--h') == ['--hname']474 assert choices_without_help(cli, ["hgroup"], "") == ["hgroupsub"]475 assert choices_without_help(cli, ["hsub"], "--h") == ["--hname"]476477478@pytest.mark.parametrize(479 ("args", "part", "expect"),
21 unmodified lines
modified:tests/test_basic.py+215 added-209 removed
1# -*- coding: utf-8 -*-2import os3import uuid45import click678def test_basic_functionality(runner):9 @click.command()10 def cli():11 """Hello World!"""11 click.echo('I EXECUTED')12 click.echo("I EXECUTED")1313 result = runner.invoke(cli, ['--help'])14 result = runner.invoke(cli, ["--help"])15 assert not result.exception15 assert 'Hello World!' in result.output16 assert 'Show this message and exit.' in result.output16 assert "Hello World!" in result.output17 assert "Show this message and exit." in result.output18 assert result.exit_code == 018 assert 'I EXECUTED' not in result.output19 assert "I EXECUTED" not in result.output2021 result = runner.invoke(cli, [])22 assert not result.exception22 assert 'I EXECUTED' in result.output23 assert "I EXECUTED" in result.output24 assert result.exit_code == 0252627def test_repr():
8 unmodified lines
36 @group.command()37 def subcommand():38 pass3939 assert repr(command) == '<Command command>'40 assert repr(group) == '<Group group>'41 assert repr(subcommand) == '<Command subcommand>'40 assert repr(command) == "<Command command>"41 assert repr(group) == "<Group group>"42 assert repr(subcommand) == "<Command subcommand>"434445def test_return_values():46 @click.command()47 def cli():48 return 424949 with cli.make_context('foo', []) as ctx:50 with cli.make_context("foo", []) as ctx:51 rv = cli.invoke(ctx)52 assert rv == 42535455def test_basic_group(runner):56 @click.group()57 def cli():58 """This is the root."""58 click.echo('ROOT EXECUTED')59 click.echo("ROOT EXECUTED")6061 @cli.command()62 def subcommand():63 """This is a subcommand."""63 click.echo('SUBCOMMAND EXECUTED')64 click.echo("SUBCOMMAND EXECUTED")6565 result = runner.invoke(cli, ['--help'])66 result = runner.invoke(cli, ["--help"])67 assert not result.exception67 assert 'COMMAND [ARGS]...' in result.output68 assert 'This is the root' in result.output69 assert 'This is a subcommand.' in result.output68 assert "COMMAND [ARGS]..." in result.output69 assert "This is the root" in result.output70 assert "This is a subcommand." in result.output71 assert result.exit_code == 071 assert 'ROOT EXECUTED' not in result.output72 assert "ROOT EXECUTED" not in result.output7373 result = runner.invoke(cli, ['subcommand'])74 result = runner.invoke(cli, ["subcommand"])75 assert not result.exception76 assert result.exit_code == 076 assert 'ROOT EXECUTED' in result.output77 assert 'SUBCOMMAND EXECUTED' in result.output77 assert "ROOT EXECUTED" in result.output78 assert "SUBCOMMAND EXECUTED" in result.output798081def test_basic_option(runner):82 @click.command()82 @click.option('--foo', default='no value')83 @click.option("--foo", default="no value")84 def cli(foo):84 click.echo('FOO:[%s]' % foo)85 click.echo(u"FOO:[{}]".format(foo))8687 result = runner.invoke(cli, [])88 assert not result.exception88 assert 'FOO:[no value]' in result.output89 assert "FOO:[no value]" in result.output9090 result = runner.invoke(cli, ['--foo=42'])91 result = runner.invoke(cli, ["--foo=42"])92 assert not result.exception92 assert 'FOO:[42]' in result.output93 assert "FOO:[42]" in result.output9494 result = runner.invoke(cli, ['--foo'])95 result = runner.invoke(cli, ["--foo"])96 assert result.exception96 assert '--foo option requires an argument' in result.output97 assert "--foo option requires an argument" in result.output9898 result = runner.invoke(cli, ['--foo='])99 result = runner.invoke(cli, ["--foo="])100 assert not result.exception100 assert 'FOO:[]' in result.output101 assert "FOO:[]" in result.output102102 result = runner.invoke(cli, [u'--foo=\N{SNOWMAN}'])103 result = runner.invoke(cli, [u"--foo=\N{SNOWMAN}"])104 assert not result.exception104 assert u'FOO:[\N{SNOWMAN}]' in result.output105 assert u"FOO:[\N{SNOWMAN}]" in result.output106107108def test_int_option(runner):109 @click.command()109 @click.option('--foo', default=42)110 @click.option("--foo", default=42)111 def cli(foo):111 click.echo('FOO:[%s]' % (foo * 2))112 click.echo("FOO:[{}]".format(foo * 2))113114 result = runner.invoke(cli, [])115 assert not result.exception115 assert 'FOO:[84]' in result.output116 assert "FOO:[84]" in result.output117117 result = runner.invoke(cli, ['--foo=23'])118 result = runner.invoke(cli, ["--foo=23"])119 assert not result.exception119 assert 'FOO:[46]' in result.output120 assert "FOO:[46]" in result.output121121 result = runner.invoke(cli, ['--foo=bar'])122 result = runner.invoke(cli, ["--foo=bar"])123 assert result.exception123 assert 'Invalid value for "--foo": bar is not a valid integer' \124 in result.output124 assert "Invalid value for '--foo': bar is not a valid integer" in result.output125126127def test_uuid_option(runner):128 @click.command()129 @click.option('--u', default='ba122011-349f-423b-873b-9d6a79c688ab',130 type=click.UUID)129 @click.option(130 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID131 )132 def cli(u):133 assert type(u) is uuid.UUID133 click.echo('U:[%s]' % u)134 click.echo("U:[{}]".format(u))135136 result = runner.invoke(cli, [])137 assert not result.exception137 assert 'U:[ba122011-349f-423b-873b-9d6a79c688ab]' in result.output138 assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output139139 result = runner.invoke(cli, ['--u=821592c1-c50e-4971-9cd6-e89dc6832f86'])140 result = runner.invoke(cli, ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"])141 assert not result.exception141 assert 'U:[821592c1-c50e-4971-9cd6-e89dc6832f86]' in result.output142 assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output143143 result = runner.invoke(cli, ['--u=bar'])144 result = runner.invoke(cli, ["--u=bar"])145 assert result.exception145 assert 'Invalid value for "--u": bar is not a valid UUID value' \146 in result.output146 assert "Invalid value for '--u': bar is not a valid UUID value" in result.output147148149def test_float_option(runner):150 @click.command()151 @click.option('--foo', default=42, type=click.FLOAT)151 @click.option("--foo", default=42, type=click.FLOAT)152 def cli(foo):153 assert type(foo) is float154 click.echo('FOO:[%s]' % foo)154 click.echo("FOO:[{}]".format(foo))155156 result = runner.invoke(cli, [])157 assert not result.exception158 assert 'FOO:[42.0]' in result.output158 assert "FOO:[42.0]" in result.output159160 result = runner.invoke(cli, ['--foo=23.5'])160 result = runner.invoke(cli, ["--foo=23.5"])161 assert not result.exception162 assert 'FOO:[23.5]' in result.output162 assert "FOO:[23.5]" in result.output163164 result = runner.invoke(cli, ['--foo=bar'])164 result = runner.invoke(cli, ["--foo=bar"])165 assert result.exception166 assert 'Invalid value for "--foo": bar is not a valid float' \167 in result.output166 assert "Invalid value for '--foo': bar is not a valid float" in result.output167168169def test_boolean_option(runner):170 for default in True, False:171172 @click.command()173 @click.option('--with-foo/--without-foo', default=default)173 @click.option("--with-foo/--without-foo", default=default)174 def cli(with_foo):175 click.echo(with_foo)176177 result = runner.invoke(cli, ['--with-foo'])177 result = runner.invoke(cli, ["--with-foo"])178 assert not result.exception179 assert result.output == 'True\n'180 result = runner.invoke(cli, ['--without-foo'])179 assert result.output == "True\n"180 result = runner.invoke(cli, ["--without-foo"])181 assert not result.exception182 assert result.output == 'False\n'182 assert result.output == "False\n"183 result = runner.invoke(cli, [])184 assert not result.exception185 assert result.output == '%s\n' % default185 assert result.output == "{}\n".format(default)186187 for default in True, False:188189 @click.command()189 @click.option('--flag', is_flag=True, default=default)190 @click.option("--flag", is_flag=True, default=default)191 def cli(flag):192 click.echo(flag)193193 result = runner.invoke(cli, ['--flag'])194 result = runner.invoke(cli, ["--flag"])195 assert not result.exception195 assert result.output == '%s\n' % (not default)196 assert result.output == "{}\n".format(not default)197 result = runner.invoke(cli, [])198 assert not result.exception198 assert result.output == '%s\n' % (default)199 assert result.output == "{}\n".format(default)200201202def test_boolean_conversion(runner):203 for default in True, False:204205 @click.command()204 @click.option('--flag', default=default, type=bool)206 @click.option("--flag", default=default, type=bool)207 def cli(flag):208 click.echo(flag)209208 for value in 'true', 't', '1', 'yes', 'y':209 result = runner.invoke(cli, ['--flag', value])210 for value in "true", "t", "1", "yes", "y":211 result = runner.invoke(cli, ["--flag", value])212 assert not result.exception211 assert result.output == 'True\n'213 assert result.output == "True\n"214213 for value in 'false', 'f', '0', 'no', 'n':214 result = runner.invoke(cli, ['--flag', value])215 for value in "false", "f", "0", "no", "n":216 result = runner.invoke(cli, ["--flag", value])217 assert not result.exception216 assert result.output == 'False\n'218 assert result.output == "False\n"219220 result = runner.invoke(cli, [])221 assert not result.exception220 assert result.output == '%s\n' % default222 assert result.output == "{}\n".format(default)223224225def test_file_option(runner):226 @click.command()225 @click.option('--file', type=click.File('w'))227 @click.option("--file", type=click.File("w"))228 def input(file):227 file.write('Hello World!\n')229 file.write("Hello World!\n")230231 @click.command()230 @click.option('--file', type=click.File('r'))232 @click.option("--file", type=click.File("r"))233 def output(file):234 click.echo(file.read())235236 with runner.isolated_filesystem():235 result_in = runner.invoke(input, ['--file=example.txt'])236 result_out = runner.invoke(output, ['--file=example.txt'])237 result_in = runner.invoke(input, ["--file=example.txt"])238 result_out = runner.invoke(output, ["--file=example.txt"])239240 assert not result_in.exception239 assert result_in.output == ''241 assert result_in.output == ""242 assert not result_out.exception241 assert result_out.output == 'Hello World!\n\n'243 assert result_out.output == "Hello World!\n\n"244245246def test_file_lazy_mode(runner):247 do_io = False248249 @click.command()248 @click.option('--file', type=click.File('w'))250 @click.option("--file", type=click.File("w"))251 def input(file):252 if do_io:251 file.write('Hello World!\n')253 file.write("Hello World!\n")254255 @click.command()254 @click.option('--file', type=click.File('r'))256 @click.option("--file", type=click.File("r"))257 def output(file):258 pass259260 with runner.isolated_filesystem():259 os.mkdir('example.txt')261 os.mkdir("example.txt")262263 do_io = True262 result_in = runner.invoke(input, ['--file=example.txt'])264 result_in = runner.invoke(input, ["--file=example.txt"])265 assert result_in.exit_code == 1266267 do_io = False266 result_in = runner.invoke(input, ['--file=example.txt'])268 result_in = runner.invoke(input, ["--file=example.txt"])269 assert result_in.exit_code == 0270269 result_out = runner.invoke(output, ['--file=example.txt'])271 result_out = runner.invoke(output, ["--file=example.txt"])272 assert result_out.exception273274 @click.command()273 @click.option('--file', type=click.File('w', lazy=False))275 @click.option("--file", type=click.File("w", lazy=False))276 def input_non_lazy(file):275 file.write('Hello World!\n')277 file.write("Hello World!\n")278279 with runner.isolated_filesystem():278 os.mkdir('example.txt')279 result_in = runner.invoke(input_non_lazy, ['--file=example.txt'])280 os.mkdir("example.txt")281 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])282 assert result_in.exit_code == 2281 assert 'Invalid value for "--file": Could not open file: example.txt' \283 assert (284 "Invalid value for '--file': Could not open file: example.txt"285 in result_in.output286 )287288289def test_path_option(runner):290 @click.command()287 @click.option('-O', type=click.Path(file_okay=False, exists=True,288 writable=True))291 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))292 def write_to_dir(o):290 with open(os.path.join(o, 'foo.txt'), 'wb') as f:291 f.write(b'meh\n')293 with open(os.path.join(o, "foo.txt"), "wb") as f:294 f.write(b"meh\n")295296 with runner.isolated_filesystem():294 os.mkdir('test')297 os.mkdir("test")298296 result = runner.invoke(write_to_dir, ['-O', 'test'])299 result = runner.invoke(write_to_dir, ["-O", "test"])300 assert not result.exception301299 with open('test/foo.txt', 'rb') as f:300 assert f.read() == b'meh\n'302 with open("test/foo.txt", "rb") as f:303 assert f.read() == b"meh\n"304302 result = runner.invoke(write_to_dir, ['-O', 'test/foo.txt'])303 assert 'Invalid value for "-O": Directory "test/foo.txt" is a file.' \304 in result.output305 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])306 assert "is a file" in result.output307308 @click.command()307 @click.option('-f', type=click.Path(exists=True))309 @click.option("-f", type=click.Path(exists=True))310 def showtype(f):309 click.echo('is_file=%s' % os.path.isfile(f))310 click.echo('is_dir=%s' % os.path.isdir(f))311 click.echo("is_file={}".format(os.path.isfile(f)))312 click.echo("is_dir={}".format(os.path.isdir(f)))313314 with runner.isolated_filesystem():313 result = runner.invoke(showtype, ['-f', 'xxx'])314 assert 'Error: Invalid value for "-f": Path "xxx" does not exist' \315 in result.output315 result = runner.invoke(showtype, ["-f", "xxx"])316 assert "does not exist" in result.output317317 result = runner.invoke(showtype, ['-f', '.'])318 assert 'is_file=False' in result.output319 assert 'is_dir=True' in result.output318 result = runner.invoke(showtype, ["-f", "."])319 assert "is_file=False" in result.output320 assert "is_dir=True" in result.output321322 @click.command()322 @click.option('-f', type=click.Path())323 @click.option("-f", type=click.Path())324 def exists(f):324 click.echo('exists=%s' % os.path.exists(f))325 click.echo("exists={}".format(os.path.exists(f)))326327 with runner.isolated_filesystem():327 result = runner.invoke(exists, ['-f', 'xxx'])328 assert 'exists=False' in result.output328 result = runner.invoke(exists, ["-f", "xxx"])329 assert "exists=False" in result.output330330 result = runner.invoke(exists, ['-f', '.'])331 assert 'exists=True' in result.output331 result = runner.invoke(exists, ["-f", "."])332 assert "exists=True" in result.output333334335def test_choice_option(runner):336 @click.command()336 @click.option('--method', type=click.Choice(['foo', 'bar', 'baz']))337 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))338 def cli(method):339 click.echo(method)340340 result = runner.invoke(cli, ['--method=foo'])341 result = runner.invoke(cli, ["--method=foo"])342 assert not result.exception342 assert result.output == 'foo\n'343 assert result.output == "foo\n"344344 result = runner.invoke(cli, ['--method=meh'])345 result = runner.invoke(cli, ["--method=meh"])346 assert result.exit_code == 2346 assert 'Invalid value for "--method": invalid choice: meh. ' \347 '(choose from foo, bar, baz)' in result.output347 assert (348 "Invalid value for '--method': invalid choice: meh."349 " (choose from foo, bar, baz)" in result.output350 )351349 result = runner.invoke(cli, ['--help'])350 assert '--method [foo|bar|baz]' in result.output352 result = runner.invoke(cli, ["--help"])353 assert "--method [foo|bar|baz]" in result.output354355356def test_datetime_option_default(runner):354357 @click.command()356 @click.option('--start_date', type=click.DateTime())358 @click.option("--start_date", type=click.DateTime())359 def cli(start_date):358 click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))360 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))361360 result = runner.invoke(cli, ['--start_date=2015-09-29'])362 result = runner.invoke(cli, ["--start_date=2015-09-29"])363 assert not result.exception362 assert result.output == '2015-09-29T00:00:00\n'364 assert result.output == "2015-09-29T00:00:00\n"365364 result = runner.invoke(cli, ['--start_date=2015-09-29T09:11:22'])366 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])367 assert not result.exception366 assert result.output == '2015-09-29T09:11:22\n'368 assert result.output == "2015-09-29T09:11:22\n"369368 result = runner.invoke(cli, ['--start_date=2015-09'])370 result = runner.invoke(cli, ["--start_date=2015-09"])371 assert result.exit_code == 2370 assert ('Invalid value for "--start_date": '371 'invalid datetime format: 2015-09. '372 '(choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)'373 ) in result.output372 assert (373 "Invalid value for '--start_date':"374 " invalid datetime format: 2015-09."375 " (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"376 ) in result.output377375 result = runner.invoke(cli, ['--help'])376 assert '--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]' in result.output378 result = runner.invoke(cli, ["--help"])379 assert (380 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output381 )382383384def test_datetime_option_custom(runner):385 @click.command()381 @click.option('--start_date',382 type=click.DateTime(formats=['%A %B %d, %Y']))386 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))387 def cli(start_date):384 click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))388 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))389386 result = runner.invoke(cli, ['--start_date=Wednesday June 05, 2010'])390 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])391 assert not result.exception388 assert result.output == '2010-06-05T00:00:00\n'392 assert result.output == "2010-06-05T00:00:00\n"393394395def test_int_range_option(runner):396 @click.command()393 @click.option('--x', type=click.IntRange(0, 5))397 @click.option("--x", type=click.IntRange(0, 5))398 def cli(x):399 click.echo(x)400397 result = runner.invoke(cli, ['--x=5'])401 result = runner.invoke(cli, ["--x=5"])402 assert not result.exception399 assert result.output == '5\n'403 assert result.output == "5\n"404401 result = runner.invoke(cli, ['--x=6'])405 result = runner.invoke(cli, ["--x=6"])406 assert result.exit_code == 2403 assert 'Invalid value for "--x": 6 is not in the valid range of 0 to 5.\n' \407 assert (408 "Invalid value for '--x': 6 is not in the valid range of 0 to 5.\n"409 in result.output410 )411412 @click.command()407 @click.option('--x', type=click.IntRange(0, 5, clamp=True))413 @click.option("--x", type=click.IntRange(0, 5, clamp=True))414 def clamp(x):415 click.echo(x)416411 result = runner.invoke(clamp, ['--x=5'])417 result = runner.invoke(clamp, ["--x=5"])418 assert not result.exception413 assert result.output == '5\n'419 assert result.output == "5\n"420415 result = runner.invoke(clamp, ['--x=6'])421 result = runner.invoke(clamp, ["--x=6"])422 assert not result.exception417 assert result.output == '5\n'423 assert result.output == "5\n"424419 result = runner.invoke(clamp, ['--x=-1'])425 result = runner.invoke(clamp, ["--x=-1"])426 assert not result.exception421 assert result.output == '0\n'427 assert result.output == "0\n"428429430def test_float_range_option(runner):431 @click.command()426 @click.option('--x', type=click.FloatRange(0, 5))432 @click.option("--x", type=click.FloatRange(0, 5))433 def cli(x):434 click.echo(x)435430 result = runner.invoke(cli, ['--x=5.0'])436 result = runner.invoke(cli, ["--x=5.0"])437 assert not result.exception432 assert result.output == '5.0\n'438 assert result.output == "5.0\n"439434 result = runner.invoke(cli, ['--x=6.0'])440 result = runner.invoke(cli, ["--x=6.0"])441 assert result.exit_code == 2436 assert 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n' \442 assert (443 "Invalid value for '--x': 6.0 is not in the valid range of 0 to 5.\n"444 in result.output445 )446447 @click.command()440 @click.option('--x', type=click.FloatRange(0, 5, clamp=True))448 @click.option("--x", type=click.FloatRange(0, 5, clamp=True))449 def clamp(x):450 click.echo(x)451444 result = runner.invoke(clamp, ['--x=5.0'])452 result = runner.invoke(clamp, ["--x=5.0"])453 assert not result.exception446 assert result.output == '5.0\n'454 assert result.output == "5.0\n"455448 result = runner.invoke(clamp, ['--x=6.0'])456 result = runner.invoke(clamp, ["--x=6.0"])457 assert not result.exception450 assert result.output == '5\n'458 assert result.output == "5\n"459452 result = runner.invoke(clamp, ['--x=-1.0'])460 result = runner.invoke(clamp, ["--x=-1.0"])461 assert not result.exception454 assert result.output == '0\n'462 assert result.output == "0\n"463464465def test_required_option(runner):466 @click.command()459 @click.option('--foo', required=True)467 @click.option("--foo", required=True)468 def cli(foo):469 click.echo(foo)470471 result = runner.invoke(cli, [])472 assert result.exit_code == 2465 assert 'Missing option "--foo"' in result.output473 assert "Missing option '--foo'" in result.output474475476def test_evaluation_order(runner):477 called = []
2 unmodified lines
480 called.append(value)481 return value482483 @click.command()476 @click.option('--missing', default='missing',477 is_eager=False, callback=memo)478 @click.option('--eager-flag1', flag_value='eager1',479 is_eager=True, callback=memo)480 @click.option('--eager-flag2', flag_value='eager2',481 is_eager=True, callback=memo)482 @click.option('--eager-flag3', flag_value='eager3',483 is_eager=True, callback=memo)484 @click.option('--normal-flag1', flag_value='normal1',485 is_eager=False, callback=memo)486 @click.option('--normal-flag2', flag_value='normal2',487 is_eager=False, callback=memo)488 @click.option('--normal-flag3', flag_value='normal3',489 is_eager=False, callback=memo)484 @click.option("--missing", default="missing", is_eager=False, callback=memo)485 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)486 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)487 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)488 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)489 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)490 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)491 def cli(**x):492 pass493493 result = runner.invoke(cli, ['--eager-flag2',494 '--eager-flag1',495 '--normal-flag2',496 '--eager-flag3',497 '--normal-flag3',498 '--normal-flag3',499 '--normal-flag1',500 '--normal-flag1'])494 result = runner.invoke(495 cli,496 [497 "--eager-flag2",498 "--eager-flag1",499 "--normal-flag2",500 "--eager-flag3",501 "--normal-flag3",502 "--normal-flag3",503 "--normal-flag1",504 "--normal-flag1",505 ],506 )507 assert not result.exception508 assert called == [503 'eager2',504 'eager1',505 'eager3',506 'normal2',507 'normal3',508 'normal1',509 'missing',509 "eager2",510 "eager1",511 "eager3",512 "normal2",513 "normal3",514 "normal1",515 "missing",516 ]517518519def test_hidden_option(runner):520 @click.command()515 @click.option('--nope', hidden=True)521 @click.option("--nope", hidden=True)522 def cli(nope):523 click.echo(nope)524519 result = runner.invoke(cli, ['--help'])525 result = runner.invoke(cli, ["--help"])526 assert result.exit_code == 0521 assert '--nope' not in result.output527 assert "--nope" not in result.output528529530def test_hidden_command(runner):531 @click.group()
3 unmodified lines
535 @cli.command(hidden=True)536 def nope():537 pass538533 result = runner.invoke(cli, ['--help'])539 result = runner.invoke(cli, ["--help"])540 assert result.exit_code == 0535 assert 'nope' not in result.output541 assert "nope" not in result.output542543544def test_hidden_group(runner):545 @click.group()
7 unmodified lines
553 @subgroup.command()554 def nope():555 pass556551 result = runner.invoke(cli, ['--help'])557 result = runner.invoke(cli, ["--help"])558 assert result.exit_code == 0553 assert 'subgroup' not in result.output554 assert 'nope' not in result.output559 assert "subgroup" not in result.output560 assert "nope" not in result.output
modified:tests/test_chain.py+70 added-92 removed
1import sys2import click23import pytest45import click678def debug():7 click.echo('%s=%s' % (8 sys._getframe(1).f_code.co_name,9 '|'.join(click.get_current_context().args),10 ))9 click.echo(10 "{}={}".format(11 sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args)12 )13 )141516def test_basic_chaining(runner):17 @click.group(chain=True)18 def cli():19 pass2018 @cli.command('sdist')21 @cli.command("sdist")22 def sdist():20 click.echo('sdist called')23 click.echo("sdist called")2422 @cli.command('bdist')25 @cli.command("bdist")26 def bdist():24 click.echo('bdist called')27 click.echo("bdist called")2826 result = runner.invoke(cli, ['bdist', 'sdist', 'bdist'])29 result = runner.invoke(cli, ["bdist", "sdist", "bdist"])30 assert not result.exception31 assert result.output.splitlines() == [29 'bdist called',30 'sdist called',31 'bdist called',32 "bdist called",33 "sdist called",34 "bdist called",35 ]363738def test_chaining_help(runner):
1 unmodified line
40 def cli():41 """ROOT HELP"""42 pass4341 @cli.command('sdist')44 @cli.command("sdist")45 def sdist():46 """SDIST HELP"""44 click.echo('sdist called')47 click.echo("sdist called")4846 @cli.command('bdist')49 @cli.command("bdist")50 def bdist():51 """BDIST HELP"""49 click.echo('bdist called')52 click.echo("bdist called")5351 result = runner.invoke(cli, ['--help'])54 result = runner.invoke(cli, ["--help"])55 assert not result.exception53 assert 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' in result.output54 assert 'ROOT HELP' in result.output56 assert "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." in result.output57 assert "ROOT HELP" in result.output5856 result = runner.invoke(cli, ['sdist', '--help'])59 result = runner.invoke(cli, ["sdist", "--help"])60 assert not result.exception58 assert 'SDIST HELP' in result.output61 assert "SDIST HELP" in result.output6260 result = runner.invoke(cli, ['bdist', '--help'])63 result = runner.invoke(cli, ["bdist", "--help"])64 assert not result.exception62 assert 'BDIST HELP' in result.output65 assert "BDIST HELP" in result.output6664 result = runner.invoke(cli, ['bdist', 'sdist', '--help'])67 result = runner.invoke(cli, ["bdist", "sdist", "--help"])68 assert not result.exception66 assert 'SDIST HELP' in result.output69 assert "SDIST HELP" in result.output707172def test_chaining_with_options(runner):73 @click.group(chain=True)74 def cli():75 pass7674 @cli.command('sdist')75 @click.option('--format')77 @cli.command("sdist")78 @click.option("--format")79 def sdist(format):77 click.echo('sdist called %s' % format)80 click.echo("sdist called {}".format(format))8179 @cli.command('bdist')80 @click.option('--format')82 @cli.command("bdist")83 @click.option("--format")84 def bdist(format):82 click.echo('bdist called %s' % format)85 click.echo("bdist called {}".format(format))8684 result = runner.invoke(cli, ['bdist', '--format=1', 'sdist', '--format=2'])87 result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"])88 assert not result.exception86 assert result.output.splitlines() == [87 'bdist called 1',88 'sdist called 2',89 ]89 assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]909192def test_chaining_with_arguments(runner):93 @click.group(chain=True)94 def cli():95 pass9697 @cli.command('sdist')98 @click.argument('format')97 @cli.command("sdist")98 @click.argument("format")99 def sdist(format):100 click.echo('sdist called %s' % format)100 click.echo("sdist called {}".format(format))101102 @cli.command('bdist')103 @click.argument('format')102 @cli.command("bdist")103 @click.argument("format")104 def bdist(format):105 click.echo('bdist called %s' % format)105 click.echo("bdist called {}".format(format))106107 result = runner.invoke(cli, ['bdist', '1', 'sdist', '2'])107 result = runner.invoke(cli, ["bdist", "1", "sdist", "2"])108 assert not result.exception109 assert result.output.splitlines() == [110 'bdist called 1',111 'sdist called 2',112 ]109 assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]110111112def test_pipeline(runner):113 @click.group(chain=True, invoke_without_command=True)117 @click.option('-i', '--input', type=click.File('r'))114 @click.option("-i", "--input", type=click.File("r"))115 def cli(input):116 pass117118 @cli.resultcallback()119 def process_pipeline(processors, input):123 iterator = (x.rstrip('\r\n') for x in input)120 iterator = (x.rstrip("\r\n") for x in input)121 for processor in processors:122 iterator = processor(iterator)123 for item in iterator:124 click.echo(item)125129 @cli.command('uppercase')126 @cli.command("uppercase")127 def make_uppercase():128 def processor(iterator):129 for line in iterator:130 yield line.upper()131132 return processor133136 @cli.command('strip')134 @cli.command("strip")135 def make_strip():136 def processor(iterator):137 for line in iterator:138 yield line.strip()139140 return processor141143 result = runner.invoke(cli, ['-i', '-'], input='foo\nbar')142 result = runner.invoke(cli, ["-i", "-"], input="foo\nbar")143 assert not result.exception145 assert result.output.splitlines() == [146 'foo',147 'bar',148 ]144 assert result.output.splitlines() == ["foo", "bar"]145150 result = runner.invoke(cli, ['-i', '-', 'strip'], input='foo \n bar')146 result = runner.invoke(cli, ["-i", "-", "strip"], input="foo \n bar")147 assert not result.exception152 assert result.output.splitlines() == [153 'foo',154 'bar',155 ]148 assert result.output.splitlines() == ["foo", "bar"]149157 result = runner.invoke(cli, ['-i', '-', 'strip', 'uppercase'],158 input='foo \n bar')150 result = runner.invoke(cli, ["-i", "-", "strip", "uppercase"], input="foo \n bar")151 assert not result.exception160 assert result.output.splitlines() == [161 'FOO',162 'BAR',163 ]152 assert result.output.splitlines() == ["FOO", "BAR"]153154155def test_args_and_chain(runner):156 @click.group(chain=True)
11 unmodified lines
168 @cli.command()169 def c():170 debug()171183 result = runner.invoke(cli, ['a', 'b', 'c'])172 result = runner.invoke(cli, ["a", "b", "c"])173 assert not result.exception185 assert result.output.splitlines() == [186 'cli=',187 'a=',188 'b=',189 'c=',190 ]174 assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]175176177def test_multicommand_arg_behavior(runner):178 with pytest.raises(RuntimeError):179180 @click.group(chain=True)196 @click.argument('forbidden', required=False)181 @click.argument("forbidden", required=False)182 def bad_cli():183 pass184185 with pytest.raises(RuntimeError):186187 @click.group(chain=True)202 @click.argument('forbidden', nargs=-1)188 @click.argument("forbidden", nargs=-1)189 def bad_cli2():190 pass191192 @click.group(chain=True)207 @click.argument('arg')193 @click.argument("arg")194 def cli(arg):209 click.echo('cli:%s' % arg)195 click.echo("cli:{}".format(arg))196197 @cli.command()198 def a():213 click.echo('a')199 click.echo("a")200215 result = runner.invoke(cli, ['foo', 'a'])201 result = runner.invoke(cli, ["foo", "a"])202 assert not result.exception217 assert result.output.splitlines() == [218 'cli:foo',219 'a',220 ]203 assert result.output.splitlines() == ["cli:foo", "a"]204205206@pytest.mark.xfail207def test_multicommand_chaining(runner):
16 unmodified lines
224 @cli.command()225 def l1b():226 debug()227245 result = runner.invoke(cli, ['l1a', 'l2a', 'l1b'])228 result = runner.invoke(cli, ["l1a", "l2a", "l1b"])229 assert not result.exception247 assert result.output.splitlines() == [248 'cli=',249 'l1a=',250 'l2a=',251 'l1b=',252 ]230 assert result.output.splitlines() == ["cli=", "l1a=", "l2a=", "l1b="]
modified:tests/test_commands.py+90 added-82 removed
1# -*- coding: utf-8 -*-2import re34import click5import pytest567def test_other_command_invoke(runner):8 @click.command()
1 unmodified line
10 def cli(ctx):11 return ctx.invoke(other_cmd, arg=42)1213 @click.command()15 @click.argument('arg', type=click.INT)14 @click.argument("arg", type=click.INT)15 def other_cmd(arg):16 click.echo(arg)1718 result = runner.invoke(cli, [])19 assert not result.exception21 assert result.output == '42\n'20 assert result.output == "42\n"212223def test_other_command_forward(runner):24 cli = click.Group()2526 @cli.command()28 @click.option('--count', default=1)27 @click.option("--count", default=1)28 def test(count):30 click.echo('Count: %d' % count)29 click.echo("Count: {:d}".format(count))3031 @cli.command()33 @click.option('--count', default=1)32 @click.option("--count", default=1)33 @click.pass_context34 def dist(ctx, count):35 ctx.forward(test)36 ctx.invoke(test, count=42)3739 result = runner.invoke(cli, ['dist'])38 result = runner.invoke(cli, ["dist"])39 assert not result.exception41 assert result.output == 'Count: 1\nCount: 42\n'40 assert result.output == "Count: 1\nCount: 42\n"414243def test_auto_shorthelp(runner):44 @click.group()
12 unmodified lines
57 def long():58 """This is a long text that is too long to show as short help59 and will be truncated instead."""6062 result = runner.invoke(cli, ['--help'])63 assert re.search(64 r'Commands:\n\s+'65 r'long\s+This is a long text that is too long to show as short help\.\.\.\n\s+'66 r'short\s+This is a short text\.\n\s+'67 r'special-chars\s+Login and store the token in ~/.netrc\.\s*',68 result.output) is not None61 result = runner.invoke(cli, ["--help"])62 assert (63 re.search(64 r"Commands:\n\s+"65 r"long\s+This is a long text that is too long to show as short help"66 r"\.\.\.\n\s+"67 r"short\s+This is a short text\.\n\s+"68 r"special-chars\s+Login and store the token in ~/.netrc\.\s*",69 result.output,70 )71 is not None72 )737475def test_no_args_is_help(runner):76 @click.command(no_args_is_help=True)
1 unmodified line
78 pass7980 result = runner.invoke(cli, [])81 assert result.exit_code == 078 assert 'Show this message and exit.' in result.output82 assert "Show this message and exit." in result.output838485def test_default_maps(runner):86 @click.group()87 def cli():88 pass8990 @cli.command()87 @click.option('--name', default='normal')91 @click.option("--name", default="normal")92 def foo(name):93 click.echo(name)9491 result = runner.invoke(cli, ['foo'], default_map={92 'foo': {'name': 'changed'}93 })95 result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})9697 assert not result.exception96 assert result.output == 'changed\n'98 assert result.output == "changed\n"99100101def test_group_with_args(runner):102 @click.group()101 @click.argument('obj')103 @click.argument("obj")104 def cli(obj):103 click.echo('obj=%s' % obj)105 click.echo("obj={}".format(obj))106107 @cli.command()108 def move():107 click.echo('move')109 click.echo("move")110111 result = runner.invoke(cli, [])112 assert result.exit_code == 0111 assert 'Show this message and exit.' in result.output113 assert "Show this message and exit." in result.output114113 result = runner.invoke(cli, ['obj1'])115 result = runner.invoke(cli, ["obj1"])116 assert result.exit_code == 2115 assert 'Error: Missing command.' in result.output117 assert "Error: Missing command." in result.output118117 result = runner.invoke(cli, ['obj1', '--help'])119 result = runner.invoke(cli, ["obj1", "--help"])120 assert result.exit_code == 0119 assert 'Show this message and exit.' in result.output121 assert "Show this message and exit." in result.output122121 result = runner.invoke(cli, ['obj1', 'move'])123 result = runner.invoke(cli, ["obj1", "move"])124 assert result.exit_code == 0123 assert result.output == 'obj=obj1\nmove\n'125 assert result.output == "obj=obj1\nmove\n"126127128def test_base_command(runner):129 import optparse
2 unmodified lines
132 def cli():133 pass134135 class OptParseCommand(click.BaseCommand):134136 def __init__(self, name, parser, callback):137 click.BaseCommand.__init__(self, name)138 self.parser = parser139 self.callback = callback
14 unmodified lines
154155 def invoke(self, ctx):156 ctx.invoke(self.callback, ctx.args, **ctx.params)157157 parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')158 parser.add_option("-f", "--file", dest="filename",159 help="write report to FILE", metavar="FILE")160 parser.add_option("-q", "--quiet",161 action="store_false", dest="verbose", default=True,162 help="don't print status messages to stdout")158 parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")159 parser.add_option(160 "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"161 )162 parser.add_option(163 "-q",164 "--quiet",165 action="store_false",166 dest="verbose",167 default=True,168 help="don't print status messages to stdout",169 )170171 def test_callback(args, filename, verbose):165 click.echo(' '.join(args))172 click.echo(" ".join(args))173 click.echo(filename)174 click.echo(verbose)168 cli.add_command(OptParseCommand('test', parser, test_callback))175170 result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',171 'whatever.txt', 'whateverelse.txt'])176 cli.add_command(OptParseCommand("test", parser, test_callback))177178 result = runner.invoke(179 cli, ["test", "-f", "test.txt", "-q", "whatever.txt", "whateverelse.txt"]180 )181 assert not result.exception182 assert result.output.splitlines() == [174 'whatever.txt whateverelse.txt',175 'test.txt',176 'False',183 "whatever.txt whateverelse.txt",184 "test.txt",185 "False",186 ]187179 result = runner.invoke(cli, ['test', '--help'])188 result = runner.invoke(cli, ["test", "--help"])189 assert not result.exception190 assert result.output.splitlines() == [182 'Usage: foo test [OPTIONS]',183 '',184 'Options:',185 ' -h, --help show this help message and exit',186 ' -f FILE, --file=FILE write report to FILE',187 ' -q, --quiet don\'t print status messages to stdout',191 "Usage: foo test [OPTIONS]",192 "",193 "Options:",194 " -h, --help show this help message and exit",195 " -f FILE, --file=FILE write report to FILE",196 " -q, --quiet don't print status messages to stdout",197 ]198199200def test_object_propagation(runner):201 for chain in False, True:202203 @click.group(chain=chain)194 @click.option('--debug/--no-debug', default=False)204 @click.option("--debug/--no-debug", default=False)205 @click.pass_context206 def cli(ctx, debug):207 if ctx.obj is None:208 ctx.obj = {}199 ctx.obj['DEBUG'] = debug209 ctx.obj["DEBUG"] = debug210211 @cli.command()212 @click.pass_context213 def sync(ctx):204 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))214 click.echo("Debug is {}".format("on" if ctx.obj["DEBUG"] else "off"))215206 result = runner.invoke(cli, ['sync'])216 result = runner.invoke(cli, ["sync"])217 assert result.exception is None208 assert result.output == 'Debug is off\n'218 assert result.output == "Debug is off\n"219220221def test_other_command_invoke_with_defaults(runner):222 @click.command()
1 unmodified line
224 def cli(ctx):225 return ctx.invoke(other_cmd)226227 @click.command()218 @click.option('--foo', type=click.INT, default=42)228 @click.option("--foo", type=click.INT, default=42)229 @click.pass_context230 def other_cmd(ctx, foo):221 assert ctx.info_name == 'other-cmd'231 assert ctx.info_name == "other-cmd"232 click.echo(foo)233234 result = runner.invoke(cli, [])235 assert not result.exception226 assert result.output == '42\n'236 assert result.output == "42\n"237238239def test_invoked_subcommand(runner):240 @click.group(invoke_without_command=True)241 @click.pass_context242 def cli(ctx):243 if ctx.invoked_subcommand is None:234 click.echo('no subcommand, use default')244 click.echo("no subcommand, use default")245 ctx.invoke(sync)246 else:237 click.echo('invoke subcommand')247 click.echo("invoke subcommand")248249 @cli.command()250 def sync():241 click.echo('in subcommand')251 click.echo("in subcommand")252243 result = runner.invoke(cli, ['sync'])253 result = runner.invoke(cli, ["sync"])254 assert not result.exception245 assert result.output == 'invoke subcommand\nin subcommand\n'255 assert result.output == "invoke subcommand\nin subcommand\n"256257 result = runner.invoke(cli)258 assert not result.exception249 assert result.output == 'no subcommand, use default\nin subcommand\n'259 assert result.output == "no subcommand, use default\nin subcommand\n"260261262def test_unprocessed_options(runner):253 @click.command(context_settings=dict(254 ignore_unknown_options=True255 ))256 @click.argument('args', nargs=-1, type=click.UNPROCESSED)257 @click.option('--verbose', '-v', count=True)263 @click.command(context_settings=dict(ignore_unknown_options=True))264 @click.argument("args", nargs=-1, type=click.UNPROCESSED)265 @click.option("--verbose", "-v", count=True)266 def cli(verbose, args):259 click.echo('Verbosity: %s' % verbose)260 click.echo('Args: %s' % '|'.join(args))267 click.echo("Verbosity: {}".format(verbose))268 click.echo("Args: {}".format("|".join(args)))269262 result = runner.invoke(cli, ['-foo', '-vvvvx', '--muhaha', 'x', 'y', '-x'])270 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])271 assert not result.exception272 assert result.output.splitlines() == [265 'Verbosity: 4',266 'Args: -foo|-x|--muhaha|x|y|-x',273 "Verbosity: 4",274 "Args: -foo|-x|--muhaha|x|y|-x",275 ]276277278def test_deprecated_in_help_messages(runner):
1 unmodified line
280 def cmd_with_help():281 """CLI HELP"""282 pass283276 result = runner.invoke(cmd_with_help, ['--help'])277 assert '(DEPRECATED)' in result.output284 result = runner.invoke(cmd_with_help, ["--help"])285 assert "(DEPRECATED)" in result.output286287 @click.command(deprecated=True)288 def cmd_without_help():289 pass290283 result = runner.invoke(cmd_without_help, ['--help'])284 assert '(DEPRECATED)' in result.output291 result = runner.invoke(cmd_without_help, ["--help"])292 assert "(DEPRECATED)" in result.output293294295def test_deprecated_in_invocation(runner):296 @click.command(deprecated=True)297 def deprecated_cmd():290 debug()298 pass299300 result = runner.invoke(deprecated_cmd)293 assert 'DeprecationWarning:' in result.output301 assert "DeprecationWarning:" in result.output
modified:tests/test_compat.py+17 added-13 removed
1import click1import pytest3from click._compat import should_strip_ansi, WIN23import click4from click._compat import should_strip_ansi5from click._compat import WIN678def test_legacy_callbacks(runner):9 def legacy_callback(ctx, value):10 return value.upper()1112 @click.command()11 @click.option('--foo', callback=legacy_callback)13 @click.option("--foo", callback=legacy_callback)14 def cli(foo):15 click.echo(foo)1615 with pytest.warns(Warning, match='Invoked legacy parameter callback'):16 result = runner.invoke(cli, ['--foo', 'wat'])17 with pytest.warns(Warning, match="Invoked legacy parameter callback"):18 result = runner.invoke(cli, ["--foo", "wat"])19 assert result.exit_code == 018 assert 'WAT' in result.output20 assert "WAT" in result.output212223def test_bash_func_name():24 from click._bashcomplete import get_completion_script23 script = get_completion_script('foo-bar baz_blah', '_COMPLETE_VAR', 'bash').strip()24 assert script.startswith('_foo_barbaz_blah_completion()')25 assert '_COMPLETE_VAR=complete $1' in script2526 script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip()27 assert script.startswith("_foo_barbaz_blah_completion()")28 assert "_COMPLETE_VAR=complete $1" in script293031def test_zsh_func_name():32 from click._bashcomplete import get_completion_script30 script = get_completion_script('foo-bar', '_COMPLETE_VAR', 'zsh').strip()31 assert script.startswith('#compdef foo-bar')32 assert 'compdef _foo_bar_completion foo-bar;' in script33 assert '(( ! $+commands[foo-bar] )) && return 1' in script3334 script = get_completion_script("foo-bar", "_COMPLETE_VAR", "zsh").strip()35 assert script.startswith("#compdef foo-bar")36 assert "compdef _foo_bar_completion foo-bar;" in script37 assert "(( ! $+commands[foo-bar] )) && return 1" in script383940@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")41def test_is_jupyter_kernel_output():42 class JupyterKernelFakeStream(object):43 pass
4 unmodified lines
modified:tests/test_context.py+53 added-45 removed
1# -*- coding: utf-8 -*-2import click2import pytest34import click5from click.core import ParameterSource678def test_ensure_context_objects(runner):9 class Foo(object):10 def __init__(self):8 self.title = 'default'11 self.title = "default"1213 pass_foo = click.make_pass_decorator(Foo, ensure=True)1415 @click.group()
5 unmodified lines
21 @pass_foo22 def test(foo):23 click.echo(foo.title)2422 result = runner.invoke(cli, ['test'])25 result = runner.invoke(cli, ["test"])26 assert not result.exception24 assert result.output == 'default\n'27 assert result.output == "default\n"282930def test_get_context_objects(runner):31 class Foo(object):32 def __init__(self):30 self.title = 'default'33 self.title = "default"3435 pass_foo = click.make_pass_decorator(Foo, ensure=True)3637 @click.group()38 @click.pass_context39 def cli(ctx):40 ctx.obj = Foo()38 ctx.obj.title = 'test'41 ctx.obj.title = "test"4243 @cli.command()44 @pass_foo45 def test(foo):46 click.echo(foo.title)4745 result = runner.invoke(cli, ['test'])48 result = runner.invoke(cli, ["test"])49 assert not result.exception47 assert result.output == 'test\n'50 assert result.output == "test\n"515253def test_get_context_objects_no_ensuring(runner):54 class Foo(object):55 def __init__(self):53 self.title = 'default'56 self.title = "default"5758 pass_foo = click.make_pass_decorator(Foo)5960 @click.group()61 @click.pass_context62 def cli(ctx):63 ctx.obj = Foo()61 ctx.obj.title = 'test'64 ctx.obj.title = "test"6566 @cli.command()67 @pass_foo68 def test(foo):69 click.echo(foo.title)7068 result = runner.invoke(cli, ['test'])71 result = runner.invoke(cli, ["test"])72 assert not result.exception70 assert result.output == 'test\n'73 assert result.output == "test\n"747576def test_get_context_objects_missing(runner):77 class Foo(object):
10 unmodified lines
88 @pass_foo89 def test(foo):90 click.echo(foo.title)9189 result = runner.invoke(cli, ['test'])92 result = runner.invoke(cli, ["test"])93 assert result.exception is not None94 assert isinstance(result.exception, RuntimeError)92 assert "Managed to invoke callback without a context object " \93 "of type 'Foo' existing" in str(result.exception)95 assert (96 "Managed to invoke callback without a context object of type"97 " 'Foo' existing" in str(result.exception)98 )99100101def test_multi_enter(runner):102 called = []
2 unmodified lines
105 @click.pass_context106 def cli(ctx):107 def callback():108 called.append(True)109110 ctx.call_on_close(callback)111112 with ctx:113 pass
8 unmodified lines
122 @click.command()123 @click.pass_context124 def cli(ctx):125 assert click.get_current_context() is ctx120 ctx.obj = 'FOOBAR'121 assert click.get_current_context().obj == 'FOOBAR'126 ctx.obj = "FOOBAR"127 assert click.get_current_context().obj == "FOOBAR"128129 assert click.get_current_context(silent=True) is None130 runner.invoke(cli, [], catch_exceptions=False)131 assert click.get_current_context(silent=True) is None132133134def test_context_meta(runner):129 LANG_KEY = __name__ + '.lang'135 LANG_KEY = "{}.lang".format(__name__)136137 def set_language(value):138 click.get_current_context().meta[LANG_KEY] = value139140 def get_language():135 return click.get_current_context().meta.get(LANG_KEY, 'en_US')141 return click.get_current_context().meta.get(LANG_KEY, "en_US")142143 @click.command()144 @click.pass_context145 def cli(ctx):140 assert get_language() == 'en_US'141 set_language('de_DE')142 assert get_language() == 'de_DE'146 assert get_language() == "en_US"147 set_language("de_DE")148 assert get_language() == "de_DE"149150 runner.invoke(cli, [], catch_exceptions=False)151152
26 unmodified lines
179def test_pass_obj(runner):180 @click.group()181 @click.pass_context182 def cli(ctx):177 ctx.obj = 'test'183 ctx.obj = "test"184185 @cli.command()186 @click.pass_obj187 def test(obj):188 click.echo(obj)189184 result = runner.invoke(cli, ['test'])190 result = runner.invoke(cli, ["test"])191 assert not result.exception186 assert result.output == 'test\n'192 assert result.output == "test\n"193194195def test_close_before_pop(runner):196 called = []197198 @click.command()199 @click.pass_context200 def cli(ctx):195 ctx.obj = 'test'201 ctx.obj = "test"202203 @ctx.call_on_close204 def foo():199 assert click.get_current_context().obj == 'test'205 assert click.get_current_context().obj == "test"206 called.append(True)201 click.echo('aha!')207208 click.echo("aha!")209210 result = runner.invoke(cli, [])211 assert not result.exception205 assert result.output == 'aha!\n'212 assert result.output == "aha!\n"213 assert called == [True]214215216def test_make_pass_decorator_args(runner):217 """218 Test to check that make_pass_decorator doesn't consume arguments based on219 invocation order.220 """221222 class Foo(object):215 title = 'foocmd'223 title = "foocmd"224225 pass_foo = click.make_pass_decorator(Foo)226227 @click.group()
12 unmodified lines
240 @click.pass_context241 def test2(ctx, foo):242 click.echo(foo.title)243236 result = runner.invoke(cli, ['test1'])244 result = runner.invoke(cli, ["test1"])245 assert not result.exception238 assert result.output == 'foocmd\n'246 assert result.output == "foocmd\n"247240 result = runner.invoke(cli, ['test2'])248 result = runner.invoke(cli, ["test2"])249 assert not result.exception242 assert result.output == 'foocmd\n'250 assert result.output == "foocmd\n"251252253def test_exit_not_standalone():254 @click.command()255 @click.pass_context256 def cli(ctx):257 ctx.exit(1)258251 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 1259 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1260261 @click.command()262 @click.pass_context263 def cli(ctx):264 ctx.exit(0)265258 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0266 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0267268269def test_parameter_source_default(runner):270 @click.command()
2 unmodified lines
273 def cli(ctx, option):274 click.echo(ctx.get_parameter_source("option"))275276 rv = runner.invoke(cli)269 assert rv.output.rstrip() == click.ParameterSource.DEFAULT277 assert rv.output.rstrip() == ParameterSource.DEFAULT278279280def test_parameter_source_default_map(runner):281 @click.command()
2 unmodified lines
284 def cli(ctx, option):285 click.echo(ctx.get_parameter_source("option"))286287 rv = runner.invoke(cli, default_map={"option": 1})280 assert rv.output.rstrip() == click.ParameterSource.DEFAULT_MAP281 288 assert rv.output.rstrip() == ParameterSource.DEFAULT_MAP289290291def test_parameter_source_commandline(runner):292 @click.command()293 @click.pass_context294 @click.option("-o", "--option", default=1)295 def cli(ctx, option):296 click.echo(ctx.get_parameter_source("option"))297298 rv = runner.invoke(cli, ["-o", "1"])291 assert rv.output.rstrip() == click.ParameterSource.COMMANDLINE299 assert rv.output.rstrip() == ParameterSource.COMMANDLINE300 rv = runner.invoke(cli, ["--option", "1"])293 assert rv.output.rstrip() == click.ParameterSource.COMMANDLINE301 assert rv.output.rstrip() == ParameterSource.COMMANDLINE302303304def test_parameter_source_environment(runner):305 @click.command()
2 unmodified lines
308 def cli(ctx, option):309 click.echo(ctx.get_parameter_source("option"))310311 rv = runner.invoke(cli, auto_envvar_prefix="TEST", env={"TEST_OPTION": "1"})304 assert rv.output.rstrip() == click.ParameterSource.ENVIRONMENT312 assert rv.output.rstrip() == ParameterSource.ENVIRONMENT313314315def test_parameter_source_environment_variable_specified(runner):316 @click.command()317 @click.pass_context318 @click.option("-o", "--option", default=1, envvar="NAME")319 def cli(ctx, option):320 click.echo(ctx.get_parameter_source("option"))313 321322 rv = runner.invoke(cli, env={"NAME": "1"})315 assert rv.output.rstrip() == click.ParameterSource.ENVIRONMENT323 assert rv.output.rstrip() == ParameterSource.ENVIRONMENT324325326def test_validate_parameter_source():327 with pytest.raises(ValueError):320 click.ParameterSource.validate("NOT_A_VALID_PARAMETER_SOURCE")328 ParameterSource.validate("NOT_A_VALID_PARAMETER_SOURCE")
modified:tests/test_defaults.py+10 added-16 removed
1 unmodified line
234def test_basic_defaults(runner):5 @click.command()6 @click.option('--foo', default=42, type=click.FLOAT)6 @click.option("--foo", default=42, type=click.FLOAT)7 def cli(foo):8 assert type(foo) is float9 click.echo('FOO:[%s]' % foo)9 click.echo("FOO:[{}]".format(foo))1011 result = runner.invoke(cli, [])12 assert not result.exception13 assert 'FOO:[42.0]' in result.output13 assert "FOO:[42.0]" in result.output141516def test_multiple_defaults(runner):17 @click.command()18 @click.option('--foo', default=[23, 42], type=click.FLOAT,19 multiple=True)18 @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True)19 def cli(foo):20 for item in foo:21 assert type(item) is float22 click.echo(item)2324 result = runner.invoke(cli, [])25 assert not result.exception27 assert result.output.splitlines() == [28 '23.0',29 '42.0',30 ]26 assert result.output.splitlines() == ["23.0", "42.0"]272829def test_nargs_plus_multiple(runner):30 @click.command()35 @click.option('--arg', default=((1, 2), (3, 4)),36 nargs=2, multiple=True, type=click.INT)31 @click.option(32 "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT33 )34 def cli(arg):35 for item in arg:39 click.echo('<%d|%d>' % item)36 click.echo("<{0[0]:d}|{0[1]:d}>".format(item))3738 result = runner.invoke(cli, [])39 assert not result.exception43 assert result.output.splitlines() == [44 '<1|2>',45 '<3|4>',46 ]40 assert result.output.splitlines() == ["<1|2>", "<3|4>"]
modified:tests/test_formatting.py+138 added-136 removed
23 unmodified lines
24 And this is a paragraph25 that will be rewrapped again.26 """2728 result = runner.invoke(cli, ['--help'], terminal_width=60)28 result = runner.invoke(cli, ["--help"], terminal_width=60)29 assert not result.exception30 assert result.output.splitlines() == [31 'Usage: cli [OPTIONS]',32 '',33 ' First paragraph.',34 '',35 ' This is a very long second paragraph and not correctly',36 ' wrapped but it will be rewrapped.',37 '',38 ' This is',39 ' a paragraph',40 ' without rewrapping.',41 '',42 ' 1',43 ' 2',44 ' 3',45 '',46 ' And this is a paragraph that will be rewrapped again.',47 '',48 'Options:',49 ' --help Show this message and exit.',31 "Usage: cli [OPTIONS]",32 "",33 " First paragraph.",34 "",35 " This is a very long second paragraph and not correctly",36 " wrapped but it will be rewrapped.",37 "",38 " This is",39 " a paragraph",40 " without rewrapping.",41 "",42 " 1",43 " 2",44 " 3",45 "",46 " And this is a paragraph that will be rewrapped again.",47 "",48 "Options:",49 " --help Show this message and exit.",50 ]515253def test_wrapping_long_options_strings(runner):
7 unmodified lines
61 """Second level62 """6364 @a_very_long.command()65 @click.argument('first')66 @click.argument('second')67 @click.argument('third')68 @click.argument('fourth')69 @click.argument('fifth')70 @click.argument('sixth')65 @click.argument("first")66 @click.argument("second")67 @click.argument("third")68 @click.argument("fourth")69 @click.argument("fifth")70 @click.argument("sixth")71 def command():72 """A command.73 """7475 # 54 is chosen as a length where the second line is one character76 # longer than the maximum length.77 result = runner.invoke(cli, ['a-very-long', 'command', '--help'],78 terminal_width=54)77 result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54)78 assert not result.exception79 assert result.output.splitlines() == [81 'Usage: cli a-very-long command [OPTIONS] FIRST SECOND',82 ' THIRD FOURTH FIFTH',83 ' SIXTH',84 '',85 ' A command.',86 '',87 'Options:',88 ' --help Show this message and exit.',80 "Usage: cli a-very-long command [OPTIONS] FIRST SECOND",81 " THIRD FOURTH FIFTH",82 " SIXTH",83 "",84 " A command.",85 "",86 "Options:",87 " --help Show this message and exit.",88 ]899091def test_wrapping_long_command_name(runner):
7 unmodified lines
99 """Second level100 """101102 @a_very_very_very_long.command()104 @click.argument('first')105 @click.argument('second')106 @click.argument('third')107 @click.argument('fourth')108 @click.argument('fifth')109 @click.argument('sixth')103 @click.argument("first")104 @click.argument("second")105 @click.argument("third")106 @click.argument("fourth")107 @click.argument("fifth")108 @click.argument("sixth")109 def command():110 """A command.111 """112114 result = runner.invoke(cli, ['a-very-very-very-long', 'command', '--help'],115 terminal_width=54)113 result = runner.invoke(114 cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54115 )116 assert not result.exception117 assert result.output.splitlines() == [118 'Usage: cli a-very-very-very-long command ',119 ' [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH',120 ' SIXTH',121 '',122 ' A command.',123 '',124 'Options:',125 ' --help Show this message and exit.',118 "Usage: cli a-very-very-very-long command ",119 " [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH",120 " SIXTH",121 "",122 " A command.",123 "",124 "Options:",125 " --help Show this message and exit.",126 ]127128129def test_formatting_empty_help_lines(runner):
2 unmodified lines
132 """Top level command133134 """135136 result = runner.invoke(cli, ['--help'])136 result = runner.invoke(cli, ["--help"])137 assert not result.exception138 assert result.output.splitlines() == [139 'Usage: cli [OPTIONS]',140 '',141 ' Top level command',142 '',143 '',144 '',145 'Options:',146 ' --help Show this message and exit.',139 "Usage: cli [OPTIONS]",140 "",141 " Top level command",142 "",143 "",144 "",145 "Options:",146 " --help Show this message and exit.",147 ]148149150def test_formatting_usage_error(runner):151 @click.command()152 @click.argument('arg')152 @click.argument("arg")153 def cmd(arg):154 click.echo('arg:' + arg)154 click.echo("arg:{}".format(arg))155156 result = runner.invoke(cmd, [])157 assert result.exit_code == 2158 assert result.output.splitlines() == [159 'Usage: cmd [OPTIONS] ARG',160 'Try "cmd --help" for help.',161 '',162 'Error: Missing argument "ARG".'159 "Usage: cmd [OPTIONS] ARG",160 "Try 'cmd --help' for help.",161 "",162 "Error: Missing argument 'ARG'.",163 ]164165166def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171172 @click.command()172 @click.argument('arg', metavar='metavar')173 @click.argument("arg", metavar="metavar")174 def cmd(arg):175 pass176177 result = runner.invoke(cmd, [])178 assert result.exit_code == 2179 assert result.output.splitlines() == [179 'Usage: cmd [OPTIONS] metavar',180 'Try "cmd --help" for help.',181 '',182 'Error: Missing argument "metavar".'180 "Usage: cmd [OPTIONS] metavar",181 "Try 'cmd --help' for help.",182 "",183 "Error: Missing argument 'metavar'.",184 ]185186187def test_formatting_usage_error_metavar_bad_arg(runner):188 @click.command()188 @click.argument('arg', type=click.INT, metavar='metavar')189 @click.argument("arg", type=click.INT, metavar="metavar")190 def cmd(arg):191 pass192192 result = runner.invoke(cmd, ['3.14'])193 result = runner.invoke(cmd, ["3.14"])194 assert result.exit_code == 2195 assert result.output.splitlines() == [195 'Usage: cmd [OPTIONS] metavar',196 'Try "cmd --help" for help.',197 '',198 'Error: Invalid value for "metavar": 3.14 is not a valid integer'196 "Usage: cmd [OPTIONS] metavar",197 "Try 'cmd --help' for help.",198 "",199 "Error: Invalid value for 'metavar': 3.14 is not a valid integer",200 ]201202203def test_formatting_usage_error_nested(runner):
1 unmodified line
205 def cmd():206 pass207208 @cmd.command()208 @click.argument('bar')209 @click.argument("bar")210 def foo(bar):210 click.echo('foo:' + bar)211 click.echo("foo:{}".format(bar))212212 result = runner.invoke(cmd, ['foo'])213 result = runner.invoke(cmd, ["foo"])214 assert result.exit_code == 2215 assert result.output.splitlines() == [215 'Usage: cmd foo [OPTIONS] BAR',216 'Try "cmd foo --help" for help.',217 '',218 'Error: Missing argument "BAR".'216 "Usage: cmd foo [OPTIONS] BAR",217 "Try 'cmd foo --help' for help.",218 "",219 "Error: Missing argument 'BAR'.",220 ]221222223def test_formatting_usage_error_no_help(runner):224 @click.command(add_help_option=False)224 @click.argument('arg')225 @click.argument("arg")226 def cmd(arg):226 click.echo('arg:' + arg)227 click.echo("arg:{}".format(arg))228229 result = runner.invoke(cmd, [])230 assert result.exit_code == 2231 assert result.output.splitlines() == [231 'Usage: cmd [OPTIONS] ARG',232 '',233 'Error: Missing argument "ARG".'232 "Usage: cmd [OPTIONS] ARG",233 "",234 "Error: Missing argument 'ARG'.",235 ]236237238def test_formatting_usage_custom_help(runner):238 @click.command(context_settings=dict(help_option_names=['--man']))239 @click.argument('arg')239 @click.command(context_settings=dict(help_option_names=["--man"]))240 @click.argument("arg")241 def cmd(arg):241 click.echo('arg:' + arg)242 click.echo("arg:{}".format(arg))243244 result = runner.invoke(cmd, [])245 assert result.exit_code == 2246 assert result.output.splitlines() == [246 'Usage: cmd [OPTIONS] ARG',247 'Try "cmd --man" for help.',248 '',249 'Error: Missing argument "ARG".'247 "Usage: cmd [OPTIONS] ARG",248 "Try 'cmd --man' for help.",249 "",250 "Error: Missing argument 'ARG'.",251 ]252253254def test_formatting_custom_type_metavar(runner):255 class MyType(click.ParamType):256 def get_metavar(self, param):257 return "MY_TYPE"
3 unmodified lines
261 @click.argument("param", type=MyType())262 def cmd(param):263 pass264263 result = runner.invoke(cmd, '--help')265 result = runner.invoke(cmd, "--help")266 assert not result.exception267 assert result.output.splitlines() == [266 'Usage: foo [OPTIONS] MY_TYPE',267 '',268 'Options:',269 ' --help Show this message and exit.'268 "Usage: foo [OPTIONS] MY_TYPE",269 "",270 "Options:",271 " --help Show this message and exit.",272 ]273274275def test_truncating_docstring(runner):
9 unmodified lines
285286 :param click.core.Context ctx: Click context.287 """288287 result = runner.invoke(cli, ['--help'], terminal_width=60)289 result = runner.invoke(cli, ["--help"], terminal_width=60)290 assert not result.exception291 assert result.output.splitlines() == [290 'Usage: cli [OPTIONS]',291 '',292 ' First paragraph.',293 '',294 ' This is a very long second paragraph and not correctly',295 ' wrapped but it will be rewrapped.',296 '',297 'Options:',298 ' --help Show this message and exit.',292 "Usage: cli [OPTIONS]",293 "",294 " First paragraph.",295 "",296 " This is a very long second paragraph and not correctly",297 " wrapped but it will be rewrapped.",298 "",299 "Options:",300 " --help Show this message and exit.",301 ]302303304def test_global_show_default(runner):
1 unmodified line
306 @click.option("-f", "in_file", default="out.txt", help="Output file name")307 def cli():308 pass309308 result = runner.invoke(cli, ['--help'],)310 result = runner.invoke(cli, ["--help"],)311 assert result.output.splitlines() == [310 'Usage: cli [OPTIONS]',311 '',312 'Options:',313 ' -f TEXT Output file name [default: out.txt]',314 ' --help Show this message and exit. [default: False]'312 "Usage: cli [OPTIONS]",313 "",314 "Options:",315 " -f TEXT Output file name [default: out.txt]",316 " --help Show this message and exit. [default: False]",317 ]318319320def test_formatting_usage_multiline_option_padding(runner):319 @click.command('foo')320 @click.option('--bar', help='This help message will be padded if it wraps.')321 @click.command("foo")322 @click.option("--bar", help="This help message will be padded if it wraps.")323 def cli():324 pass325324 result = runner.invoke(cli, '--help', terminal_width=45)326 result = runner.invoke(cli, "--help", terminal_width=45)327 assert not result.exception328 assert result.output.splitlines() == [327 'Usage: foo [OPTIONS]',328 '',329 'Options:',330 ' --bar TEXT This help message will be',331 ' padded if it wraps.',332 '',333 ' --help Show this message and exit.'329 "Usage: foo [OPTIONS]",330 "",331 "Options:",332 " --bar TEXT This help message will be",333 " padded if it wraps.",334 "",335 " --help Show this message and exit.",336 ]337338339def test_formatting_usage_no_option_padding(runner):338 @click.command('foo')339 @click.option('--bar', help='This help message will be padded if it wraps.')340 @click.command("foo")341 @click.option("--bar", help="This help message will be padded if it wraps.")342 def cli():343 pass344343 result = runner.invoke(cli, '--help', terminal_width=80)345 result = runner.invoke(cli, "--help", terminal_width=80)346 assert not result.exception347 assert result.output.splitlines() == [346 'Usage: foo [OPTIONS]',347 '',348 'Options:',349 ' --bar TEXT This help message will be padded if it wraps.',350 ' --help Show this message and exit.'348 "Usage: foo [OPTIONS]",349 "",350 "Options:",351 " --bar TEXT This help message will be padded if it wraps.",352 " --help Show this message and exit.",353 ]
modified:tests/test_imports.py+31 added-14 removed
1import sys1import json2import subprocess3import sys45from click._compat import WIN678IMPORT_TEST = b'''\8IMPORT_TEST = b"""\9try:10 import __builtin__ as builtins11except ImportError:12 import builtins
13 unmodified lines
26import click27rv = list(found_imports)28import json29click.echo(json.dumps(rv))30'''30"""3132ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35 'threading', 'colorama', 'errno', 'fcntl', 'datetime', 'pipes', 'shlex'36])32ALLOWED_IMPORTS = {33 "weakref",34 "os",35 "struct",36 "collections",37 "sys",38 "contextlib",39 "functools",40 "stat",41 "re",42 "codecs",43 "inspect",44 "itertools",45 "io",46 "threading",47 "colorama",48 "errno",49 "fcntl",50 "datetime",51 "pipes",52 "shlex",53}5455if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',40 'zlib'])56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])575859def test_light_imports():44 c = subprocess.Popen([sys.executable, '-'], stdin=subprocess.PIPE,45 stdout=subprocess.PIPE)60 c = subprocess.Popen(61 [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE62 )63 rv = c.communicate(IMPORT_TEST)[0]6465 if sys.version_info[0] != 2:49 rv = rv.decode('utf-8')66 rv = rv.decode("utf-8")67 imported = json.loads(rv)6869 for module in imported:53 if module == 'click' or module.startswith('click.'):70 if module == "click" or module.startswith("click."):71 continue72 assert module in ALLOWED_IMPORTS
modified:tests/test_normalization.py+10 added-10 removed
4 unmodified lines
567def test_option_normalization(runner):8 @click.command(context_settings=CONTEXT_SETTINGS)9 @click.option('--foo')10 @click.option('-x')9 @click.option("--foo")10 @click.option("-x")11 def cli(foo, x):12 click.echo(foo)13 click.echo(x)1415 result = runner.invoke(cli, ['--FOO', '42', '-X', 23])16 assert result.output == '42\n23\n'15 result = runner.invoke(cli, ["--FOO", "42", "-X", 23])16 assert result.output == "42\n23\n"171819def test_choice_normalization(runner):20 @click.command(context_settings=CONTEXT_SETTINGS)21 @click.option('--choice', type=click.Choice(['Foo', 'Bar']))21 @click.option("--choice", type=click.Choice(["Foo", "Bar"]))22 def cli(choice):23 click.echo(choice)2425 result = runner.invoke(cli, ['--CHOICE', 'FOO'])26 assert result.output == 'Foo\n'25 result = runner.invoke(cli, ["--CHOICE", "FOO"])26 assert result.output == "Foo\n"272829def test_command_normalization(runner):30 @click.group(context_settings=CONTEXT_SETTINGS)
1 unmodified line
32 pass3334 @cli.command()35 def foo():36 click.echo('here!')36 click.echo("here!")3738 result = runner.invoke(cli, ['FOO'])39 assert result.output == 'here!\n'38 result = runner.invoke(cli, ["FOO"])39 assert result.output == "here!\n"
modified:tests/test_options.py+213 added-211 removed
1# -*- coding: utf-8 -*-2import re2import os4import click3import re45import pytest67import click8from click._compat import text_type91011def test_prefixes(runner):12 @click.command()12 @click.option('++foo', is_flag=True, help='das foo')13 @click.option('--bar', is_flag=True, help='das bar')13 @click.option("++foo", is_flag=True, help="das foo")14 @click.option("--bar", is_flag=True, help="das bar")15 def cli(foo, bar):15 click.echo('foo=%s bar=%s' % (foo, bar))16 click.echo("foo={} bar={}".format(foo, bar))1717 result = runner.invoke(cli, ['++foo', '--bar'])18 result = runner.invoke(cli, ["++foo", "--bar"])19 assert not result.exception19 assert result.output == 'foo=True bar=True\n'20 assert result.output == "foo=True bar=True\n"2121 result = runner.invoke(cli, ['--help'])22 assert re.search(r'\+\+foo\s+das foo', result.output) is not None23 assert re.search(r'--bar\s+das bar', result.output) is not None22 result = runner.invoke(cli, ["--help"])23 assert re.search(r"\+\+foo\s+das foo", result.output) is not None24 assert re.search(r"--bar\s+das bar", result.output) is not None252627def test_invalid_option(runner):27 try:28 with pytest.raises(TypeError, match="name was passed"):2930 @click.command()29 @click.option('foo')31 @click.option("foo")32 def cli(foo):33 pass32 except TypeError as e:33 assert 'No options defined but a name was passed (foo).' \34 in str(e)35 else:36 assert False, 'Expected a type error because of an invalid option.'343536def test_invalid_nargs(runner):40 try:37 with pytest.raises(TypeError, match="nargs < 0"):3839 @click.command()42 @click.option('--foo', nargs=-1)40 @click.option("--foo", nargs=-1)41 def cli(foo):42 pass45 except TypeError as e:46 assert 'Options cannot have nargs < 0' in str(e)47 else:48 assert False, 'Expected a type error because of an invalid option.'434445def test_nargs_tup_composite_mult(runner):46 @click.command()53 @click.option('--item', type=(str, int), multiple=True)47 @click.option("--item", type=(str, int), multiple=True)48 def copy(item):49 for item in item:56 click.echo('name=%s id=%d' % item)50 click.echo("name={0[0]} id={0[1]:d}".format(item))5158 result = runner.invoke(copy, ['--item', 'peter', '1', '--item', 'max', '2'])52 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])53 assert not result.exception60 assert result.output.splitlines() == [61 'name=peter id=1',62 'name=max id=2',63 ]54 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]555657def test_counting(runner):58 @click.command()68 @click.option('-v', count=True, help='Verbosity',69 type=click.IntRange(0, 3))59 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))60 def cli(v):71 click.echo('verbosity=%d' % v)61 click.echo("verbosity={:d}".format(v))6273 result = runner.invoke(cli, ['-vvv'])63 result = runner.invoke(cli, ["-vvv"])64 assert not result.exception75 assert result.output == 'verbosity=3\n'65 assert result.output == "verbosity=3\n"6677 result = runner.invoke(cli, ['-vvvv'])67 result = runner.invoke(cli, ["-vvvv"])68 assert result.exception79 assert 'Invalid value for "-v": 4 is not in the valid range of 0 to 3.' \69 assert (70 "Invalid value for '-v': 4 is not in the valid range of 0 to 3."71 in result.output72 )7374 result = runner.invoke(cli, [])75 assert not result.exception84 assert result.output == 'verbosity=0\n'76 assert result.output == "verbosity=0\n"7786 result = runner.invoke(cli, ['--help'])87 assert re.search(r'-v\s+Verbosity', result.output) is not None78 result = runner.invoke(cli, ["--help"])79 assert re.search(r"-v\s+Verbosity", result.output) is not None808190@pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])82@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])83def test_unknown_options(runner, unknown_flag):84 @click.command()85 def cli():86 pass8788 result = runner.invoke(cli, [unknown_flag])89 assert result.exception98 assert 'no such option: {0}'.format(unknown_flag) in result.output90 assert "no such option: {}".format(unknown_flag) in result.output919293def test_multiple_required(runner):94 @click.command()103 @click.option('-m', '--message', multiple=True, required=True)95 @click.option("-m", "--message", multiple=True, required=True)96 def cli(message):105 click.echo('\n'.join(message))97 click.echo("\n".join(message))98107 result = runner.invoke(cli, ['-m', 'foo', '-mbar'])99 result = runner.invoke(cli, ["-m", "foo", "-mbar"])100 assert not result.exception109 assert result.output == 'foo\nbar\n'101 assert result.output == "foo\nbar\n"102103 result = runner.invoke(cli, [])104 assert result.exception113 assert 'Error: Missing option "-m" / "--message".' in result.output105 assert "Error: Missing option '-m' / '--message'." in result.output106107108def test_empty_envvar(runner):109 @click.command()118 @click.option('--mypath', type=click.Path(exists=True), envvar='MYPATH')110 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")111 def cli(mypath):120 click.echo('mypath: %s' % mypath)112 click.echo("mypath: {}".format(mypath))113122 result = runner.invoke(cli, [], env={'MYPATH': ''})114 result = runner.invoke(cli, [], env={"MYPATH": ""})115 assert result.exit_code == 0124 assert result.output == 'mypath: None\n'116 assert result.output == "mypath: None\n"117118119def test_multiple_envvar(runner):120 @click.command()129 @click.option('--arg', multiple=True)121 @click.option("--arg", multiple=True)122 def cmd(arg):131 click.echo('|'.join(arg))123 click.echo("|".join(arg))124133 result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',134 env={'TEST_ARG': 'foo bar baz'})125 result = runner.invoke(126 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}127 )128 assert not result.exception136 assert result.output == 'foo|bar|baz\n'129 assert result.output == "foo|bar|baz\n"130131 @click.command()139 @click.option('--arg', multiple=True, envvar='X')132 @click.option("--arg", multiple=True, envvar="X")133 def cmd(arg):141 click.echo('|'.join(arg))134 click.echo("|".join(arg))135143 result = runner.invoke(cmd, [], env={'X': 'foo bar baz'})136 result = runner.invoke(cmd, [], env={"X": "foo bar baz"})137 assert not result.exception145 assert result.output == 'foo|bar|baz\n'138 assert result.output == "foo|bar|baz\n"139140 @click.command()148 @click.option('--arg', multiple=True, type=click.Path())141 @click.option("--arg", multiple=True, type=click.Path())142 def cmd(arg):150 click.echo('|'.join(arg))143 click.echo("|".join(arg))144152 result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',153 env={'TEST_ARG': 'foo%sbar' % os.path.pathsep})145 result = runner.invoke(146 cmd,147 [],148 auto_envvar_prefix="TEST",149 env={"TEST_ARG": "foo{}bar".format(os.path.pathsep)},150 )151 assert not result.exception155 assert result.output == 'foo|bar\n'152 assert result.output == "foo|bar\n"153154155def test_multiple_default_help(runner):156 @click.command()160 @click.option('--arg1', multiple=True, default=('foo', 'bar'),161 show_default=True)162 @click.option('--arg2', multiple=True, default=(1, 2), type=int,163 show_default=True)157 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)158 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)159 def cmd(arg, arg2):160 pass161167 result = runner.invoke(cmd, ['--help'])162 result = runner.invoke(cmd, ["--help"])163 assert not result.exception169 assert 'foo, bar' in result.output170 assert '1, 2' in result.output164 assert "foo, bar" in result.output165 assert "1, 2" in result.output166167168def test_multiple_default_type(runner):169 @click.command()175 @click.option('--arg1', multiple=True, default=('foo', 'bar'))176 @click.option('--arg2', multiple=True, default=(1, 'a'))170 @click.option("--arg1", multiple=True, default=("foo", "bar"))171 @click.option("--arg2", multiple=True, default=(1, "a"))172 def cmd(arg1, arg2):173 assert all(isinstance(e[0], text_type) for e in arg1)174 assert all(isinstance(e[1], text_type) for e in arg1)175176 assert all(isinstance(e[0], int) for e in arg2)177 assert all(isinstance(e[1], text_type) for e in arg2)178184 result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '185 'two --arg2 4 four'.split())179 result = runner.invoke(180 cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()181 )182 assert not result.exception183184185def test_dynamic_default_help_unset(runner):186 @click.command()187 @click.option(188 "--username",190 @click.option('--username', prompt=True,191 default=lambda: os.environ.get('USER', ''),192 show_default=True)189 prompt=True,190 default=lambda: os.environ.get("USER", ""),191 show_default=True,192 )193 def cmd(username):194 print("Hello,", username)195196 result = runner.invoke(cmd, ['--help'])196 result = runner.invoke(cmd, ["--help"])197 assert result.exit_code == 0198 assert '--username' in result.output199 assert 'lambda' not in result.output200 assert '(dynamic)' in result.output198 assert "--username" in result.output199 assert "lambda" not in result.output200 assert "(dynamic)" in result.output201202203def test_dynamic_default_help_text(runner):204 @click.command()204 @click.option('--username', prompt=True,205 default=lambda: os.environ.get('USER', ''),206 show_default='current user')205 @click.option(206 "--username",207 prompt=True,208 default=lambda: os.environ.get("USER", ""),209 show_default="current user",210 )211 def cmd(username):212 print("Hello,", username)213210 result = runner.invoke(cmd, ['--help'])214 result = runner.invoke(cmd, ["--help"])215 assert result.exit_code == 0212 assert '--username' in result.output213 assert 'lambda' not in result.output214 assert '(current user)' in result.output216 assert "--username" in result.output217 assert "lambda" not in result.output218 assert "(current user)" in result.output219220221def test_toupper_envvar_prefix(runner):222 @click.command()219 @click.option('--arg')223 @click.option("--arg")224 def cmd(arg):225 click.echo(arg)226223 result = runner.invoke(cmd, [], auto_envvar_prefix='test',224 env={'TEST_ARG': 'foo'})227 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})228 assert not result.exception226 assert result.output == 'foo\n'229 assert result.output == "foo\n"230231232def test_nargs_envvar(runner):233 @click.command()231 @click.option('--arg', nargs=2)234 @click.option("--arg", nargs=2)235 def cmd(arg):233 click.echo('|'.join(arg))236 click.echo("|".join(arg))237235 result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',236 env={'TEST_ARG': 'foo bar'})238 result = runner.invoke(239 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}240 )241 assert not result.exception238 assert result.output == 'foo|bar\n'242 assert result.output == "foo|bar\n"243244 @click.command()241 @click.option('--arg', nargs=2, multiple=True)245 @click.option("--arg", nargs=2, multiple=True)246 def cmd(arg):247 for item in arg:244 click.echo('|'.join(item))248 click.echo("|".join(item))249246 result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',247 env={'TEST_ARG': 'x 1 y 2'})250 result = runner.invoke(251 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}252 )253 assert not result.exception249 assert result.output == 'x|1\ny|2\n'254 assert result.output == "x|1\ny|2\n"255256257def test_show_envvar(runner):258 @click.command()254 @click.option('--arg1', envvar='ARG1',255 show_envvar=True)259 @click.option("--arg1", envvar="ARG1", show_envvar=True)260 def cmd(arg):261 pass262259 result = runner.invoke(cmd, ['--help'])263 result = runner.invoke(cmd, ["--help"])264 assert not result.exception261 assert 'ARG1' in result.output265 assert "ARG1" in result.output266267268def test_show_envvar_auto_prefix(runner):269 @click.command()266 @click.option('--arg1', show_envvar=True)270 @click.option("--arg1", show_envvar=True)271 def cmd(arg):272 pass273270 result = runner.invoke(cmd, ['--help'],271 auto_envvar_prefix='TEST')274 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")275 assert not result.exception273 assert 'TEST_ARG1' in result.output276 assert "TEST_ARG1" in result.output277278279def test_show_envvar_auto_prefix_dash_in_command(runner):280 @click.group()281 def cli():282 pass283284 @cli.command()282 @click.option('--baz', show_envvar=True)285 @click.option("--baz", show_envvar=True)286 def foo_bar(baz):287 pass288286 result = runner.invoke(cli, ['foo-bar', '--help'],287 auto_envvar_prefix='TEST')289 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")290 assert not result.exception289 assert 'TEST_FOO_BAR_BAZ' in result.output291 assert "TEST_FOO_BAR_BAZ" in result.output292293294def test_custom_validation(runner):295 def validate_pos_int(ctx, param, value):296 if value < 0:295 raise click.BadParameter('Value needs to be positive')297 raise click.BadParameter("Value needs to be positive")298 return value299300 @click.command()299 @click.option('--foo', callback=validate_pos_int, default=1)301 @click.option("--foo", callback=validate_pos_int, default=1)302 def cmd(foo):303 click.echo(foo)304303 result = runner.invoke(cmd, ['--foo', '-1'])304 assert 'Invalid value for "--foo": Value needs to be positive' \305 in result.output305 result = runner.invoke(cmd, ["--foo", "-1"])306 assert "Invalid value for '--foo': Value needs to be positive" in result.output307307 result = runner.invoke(cmd, ['--foo', '42'])308 assert result.output == '42\n'308 result = runner.invoke(cmd, ["--foo", "42"])309 assert result.output == "42\n"310311312def test_winstyle_options(runner):313 @click.command()313 @click.option('/debug;/no-debug', help='Enables or disables debug mode.')314 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")315 def cmd(debug):316 click.echo(debug)317317 result = runner.invoke(cmd, ['/debug'], help_option_names=['/?'])318 assert result.output == 'True\n'319 result = runner.invoke(cmd, ['/no-debug'], help_option_names=['/?'])320 assert result.output == 'False\n'321 result = runner.invoke(cmd, [], help_option_names=['/?'])322 assert result.output == 'False\n'323 result = runner.invoke(cmd, ['/?'], help_option_names=['/?'])324 assert '/debug; /no-debug Enables or disables debug mode.' in result.output325 assert '/? Show this message and exit.' in result.output318 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])319 assert result.output == "True\n"320 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])321 assert result.output == "False\n"322 result = runner.invoke(cmd, [], help_option_names=["/?"])323 assert result.output == "False\n"324 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])325 assert "/debug; /no-debug Enables or disables debug mode." in result.output326 assert "/? Show this message and exit." in result.output327328329def test_legacy_options(runner):330 @click.command()330 @click.option('-whatever')331 @click.option("-whatever")332 def cmd(whatever):333 click.echo(whatever)334334 result = runner.invoke(cmd, ['-whatever', '42'])335 assert result.output == '42\n'336 result = runner.invoke(cmd, ['-whatever=23'])337 assert result.output == '23\n'335 result = runner.invoke(cmd, ["-whatever", "42"])336 assert result.output == "42\n"337 result = runner.invoke(cmd, ["-whatever=23"])338 assert result.output == "23\n"339340341def test_missing_option_string_cast():342 ctx = click.Context(click.Command(""))343344 with pytest.raises(click.MissingParameter) as excinfo:344 click.Option(['-a'], required=True).full_process_value(ctx, None)345 click.Option(["-a"], required=True).full_process_value(ctx, None)346347 assert str(excinfo.value) == "missing parameter: a"348349350def test_missing_choice(runner):351 @click.command()351 @click.option('--foo', type=click.Choice(['foo', 'bar']),352 required=True)352 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)353 def cmd(foo):354 click.echo(foo)355356 result = runner.invoke(cmd)357 assert result.exit_code == 2358 error, separator, choices = result.output.partition('Choose from')359 assert 'Error: Missing option "--foo". ' in error360 assert 'Choose from' in separator361 assert 'foo' in choices362 assert 'bar' in choices358 error, separator, choices = result.output.partition("Choose from")359 assert "Error: Missing option '--foo'. " in error360 assert "Choose from" in separator361 assert "foo" in choices362 assert "bar" in choices363364365def test_case_insensitive_choice(runner):366 @click.command()367 @click.option('--foo', type=click.Choice(368 ['Orange', 'Apple'], case_sensitive=False))367 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))368 def cmd(foo):369 click.echo(foo)370372 result = runner.invoke(cmd, ['--foo', 'apple'])371 result = runner.invoke(cmd, ["--foo", "apple"])372 assert result.exit_code == 0374 assert result.output == 'Apple\n'373 assert result.output == "Apple\n"374376 result = runner.invoke(cmd, ['--foo', 'oRANGe'])375 result = runner.invoke(cmd, ["--foo", "oRANGe"])376 assert result.exit_code == 0378 assert result.output == 'Orange\n'377 assert result.output == "Orange\n"378380 result = runner.invoke(cmd, ['--foo', 'Apple'])379 result = runner.invoke(cmd, ["--foo", "Apple"])380 assert result.exit_code == 0382 assert result.output == 'Apple\n'381 assert result.output == "Apple\n"382383 @click.command()385 @click.option('--foo', type=click.Choice(['Orange', 'Apple']))384 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))385 def cmd2(foo):386 click.echo(foo)387389 result = runner.invoke(cmd2, ['--foo', 'apple'])388 result = runner.invoke(cmd2, ["--foo", "apple"])389 assert result.exit_code == 2390392 result = runner.invoke(cmd2, ['--foo', 'oRANGe'])391 result = runner.invoke(cmd2, ["--foo", "oRANGe"])392 assert result.exit_code == 2393395 result = runner.invoke(cmd2, ['--foo', 'Apple'])394 result = runner.invoke(cmd2, ["--foo", "Apple"])395 assert result.exit_code == 0396397398def test_case_insensitive_choice_returned_exactly(runner):399 @click.command()401 @click.option('--foo', type=click.Choice(402 ['Orange', 'Apple'], case_sensitive=False))400 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))401 def cmd(foo):402 click.echo(foo)403406 result = runner.invoke(cmd, ['--foo', 'apple'])404 result = runner.invoke(cmd, ["--foo", "apple"])405 assert result.exit_code == 0408 assert result.output == 'Apple\n'406 assert result.output == "Apple\n"407408409def test_option_help_preserve_paragraphs(runner):410 @click.command()
1 unmodified line
412 "-C",413 "--config",414 type=click.Path(),415 help="""Configuration file to use.418 416417 If not given, the environment variable CONFIG_FILE is consulted418 and used if set. If neither are given, a default configuration419 file is loaded.""",420 )421 def cmd(config):422 pass423426 result = runner.invoke(cmd, ['--help'], )424 result = runner.invoke(cmd, ["--help"],)425 assert result.exit_code == 0426 assert (427 " -C, --config PATH Configuration file to use.\n"428 "{i}\n"
1 unmodified line
430 "{i}consulted and used if set. If neither are given, a default\n"431 "{i}configuration file is loaded.".format(i=" " * 21)432 ) in result.output433434435def test_argument_custom_class(runner):436 class CustomArgument(click.Argument):437 def get_default(self, ctx):439 '''a dumb override of a default value for testing'''440 return 'I am a default'438 """a dumb override of a default value for testing"""439 return "I am a default"440441 @click.command()443 @click.argument('testarg', cls=CustomArgument, default='you wont see me')442 @click.argument("testarg", cls=CustomArgument, default="you wont see me")443 def cmd(testarg):444 click.echo(testarg)445446 result = runner.invoke(cmd)448 assert 'I am a default' in result.output449 assert 'you wont see me' not in result.output447 assert "I am a default" in result.output448 assert "you wont see me" not in result.output449450451def test_option_custom_class(runner):452 class CustomOption(click.Option):453 def get_help_record(self, ctx):455 '''a dumb override of a help text for testing'''456 return ('--help', 'I am a help text')454 """a dumb override of a help text for testing"""455 return ("--help", "I am a help text")456457 @click.command()459 @click.option('--testoption', cls=CustomOption, help='you wont see me')458 @click.option("--testoption", cls=CustomOption, help="you wont see me")459 def cmd(testoption):460 click.echo(testoption)461463 result = runner.invoke(cmd, ['--help'])464 assert 'I am a help text' in result.output465 assert 'you wont see me' not in result.output462 result = runner.invoke(cmd, ["--help"])463 assert "I am a help text" in result.output464 assert "you wont see me" not in result.output465466467def test_option_custom_class_reusable(runner):468 """Ensure we can reuse a custom class option. See Issue #926"""469470 class CustomOption(click.Option):471 def get_help_record(self, ctx):473 '''a dumb override of a help text for testing'''474 return ('--help', 'I am a help text')472 """a dumb override of a help text for testing"""473 return ("--help", "I am a help text")474475 # Assign to a variable to re-use the decorator.477 testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')476 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")477478 @click.command()479 @testoption480 def cmd1(testoption):
6 unmodified lines
487488 # Both of the commands should have the --help option now.489 for cmd in (cmd1, cmd2):490492 result = runner.invoke(cmd, ['--help'])493 assert 'I am a help text' in result.output494 assert 'you wont see me' not in result.output491 result = runner.invoke(cmd, ["--help"])492 assert "I am a help text" in result.output493 assert "you wont see me" not in result.output494495496def test_bool_flag_with_type(runner):497 @click.command()499 @click.option('--shout/--no-shout', default=False, type=bool)498 @click.option("--shout/--no-shout", default=False, type=bool)499 def cmd(shout):500 pass501502 result = runner.invoke(cmd)
1 unmodified line
504505506def test_aliases_for_flags(runner):507 @click.command()509 @click.option('--warnings/--no-warnings', ' /-W', default=True)508 @click.option("--warnings/--no-warnings", " /-W", default=True)509 def cli(warnings):510 click.echo(warnings)511513 result = runner.invoke(cli, ['--warnings'])514 assert result.output == 'True\n'515 result = runner.invoke(cli, ['--no-warnings'])516 assert result.output == 'False\n'517 result = runner.invoke(cli, ['-W'])518 assert result.output == 'False\n'512 result = runner.invoke(cli, ["--warnings"])513 assert result.output == "True\n"514 result = runner.invoke(cli, ["--no-warnings"])515 assert result.output == "False\n"516 result = runner.invoke(cli, ["-W"])517 assert result.output == "False\n"518519 @click.command()521 @click.option('--warnings/--no-warnings', '-w', default=True)520 @click.option("--warnings/--no-warnings", "-w", default=True)521 def cli_alt(warnings):522 click.echo(warnings)523525 result = runner.invoke(cli_alt, ['--warnings'])526 assert result.output == 'True\n'527 result = runner.invoke(cli_alt, ['--no-warnings'])528 assert result.output == 'False\n'529 result = runner.invoke(cli_alt, ['-w'])530 assert result.output == 'True\n'524 result = runner.invoke(cli_alt, ["--warnings"])525 assert result.output == "True\n"526 result = runner.invoke(cli_alt, ["--no-warnings"])527 assert result.output == "False\n"528 result = runner.invoke(cli_alt, ["-w"])529 assert result.output == "True\n"530532@pytest.mark.parametrize('option_args,expected', [533 (['--aggressive', '--all', '-a'], 'aggressive'),534 (['--first', '--second', '--third', '-a', '-b', '-c'], 'first'),535 (['--apple', '--banana', '--cantaloupe', '-a', '-b', '-c'], 'apple'),536 (['--cantaloupe', '--banana', '--apple', '-c', '-b', '-a'], 'cantaloupe'),537 (['-a', '-b', '-c'], 'a'),538 (['-c', '-b', '-a'], 'c'),539 (['-a', '--apple', '-b', '--banana', '-c', '--cantaloupe'], 'apple'),540 (['-c', '-a', '--cantaloupe', '-b', '--banana', '--apple'], 'cantaloupe'),541 (['--from', '-f', '_from'], '_from'),542 (['--return', '-r', '_ret'], '_ret'),543])544def test_option_names(runner, option_args, expected):531532@pytest.mark.parametrize(533 "option_args,expected",534 [535 (["--aggressive", "--all", "-a"], "aggressive"),536 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),537 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),538 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),539 (["-a", "-b", "-c"], "a"),540 (["-c", "-b", "-a"], "c"),541 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),542 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),543 (["--from", "-f", "_from"], "_from"),544 (["--return", "-r", "_ret"], "_ret"),545 ],546)547def test_option_names(runner, option_args, expected):548 @click.command()549 @click.option(*option_args, is_flag=True)550 def cmd(**kwargs):551 click.echo(str(kwargs[expected]))552553 assert cmd.params[0].name == expected554555 for form in option_args:554 if form.startswith('-'):556 if form.startswith("-"):557 result = runner.invoke(cmd, [form])556 assert result.output == 'True\n'558 assert result.output == "True\n"
modified:tests/test_termui.py+139 added-126 removed
1# -*- coding: utf-8 -*-2import pytest34import click2import time34import pytest56import click._termui_impl7from click._compat import WIN89
17 unmodified lines
272829def test_progressbar_strip_regression(runner, monkeypatch):30 fake_clock = FakeClock()32 label = ' padded line'31 label = " padded line"3233 @click.command()34 def cli():35 with _create_progress(label=label) as progress:37 for thing in progress:36 for _ in progress:37 fake_clock.advance_time()3840 monkeypatch.setattr(time, 'time', fake_clock.time)41 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)39 monkeypatch.setattr(time, "time", fake_clock.time)40 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)41 assert label in runner.invoke(cli, []).output424344def test_progressbar_length_hint(runner, monkeypatch):
18 unmodified lines
63 fake_clock = FakeClock()6465 @click.command()66 def cli():68 with click.progressbar(Hinted(10), label='test') as progress:69 for thing in progress:67 with click.progressbar(Hinted(10), label="test") as progress:68 for _ in progress:69 fake_clock.advance_time()7072 monkeypatch.setattr(time, 'time', fake_clock.time)73 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)71 monkeypatch.setattr(time, "time", fake_clock.time)72 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)73 result = runner.invoke(cli, [])74 assert result.exception is None757677def test_progressbar_hidden(runner, monkeypatch):78 fake_clock = FakeClock()80 label = 'whatever'79 label = "whatever"8081 @click.command()82 def cli():83 with _create_progress(label=label) as progress:85 for thing in progress:84 for _ in progress:85 fake_clock.advance_time()8688 monkeypatch.setattr(time, 'time', fake_clock.time)89 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)90 assert runner.invoke(cli, []).output == ''87 monkeypatch.setattr(time, "time", fake_clock.time)88 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)89 assert runner.invoke(cli, []).output == ""909193@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])92@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])93def test_progressbar_time_per_iteration(runner, avg, expected):94 with _create_progress(2, avg=avg) as progress:95 assert progress.time_per_iteration == expected969799@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])98@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])99def test_progressbar_eta(runner, finished, expected):100 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:101 assert progress.eta == expected102103105@pytest.mark.parametrize('eta, expected',106 [(0, '00:00:00'), (30, '00:00:30'), (90, '00:01:30'), (900, '00:15:00'),107 (9000, '02:30:00'), (99999999999, '1157407d 09:46:39'), (None, '')])104@pytest.mark.parametrize(105 "eta, expected",106 [107 (0, "00:00:00"),108 (30, "00:00:30"),109 (90, "00:01:30"),110 (900, "00:15:00"),111 (9000, "02:30:00"),112 (99999999999, "1157407d 09:46:39"),113 (None, ""),114 ],115)116def test_progressbar_format_eta(runner, eta, expected):117 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:118 assert progress.format_eta() == expected119120113@pytest.mark.parametrize('pos, length', [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])121@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])122def test_progressbar_format_pos(runner, pos, length):123 with _create_progress(length, length_known=length != 0, pos=pos) as progress:124 result = progress.format_pos()125 if progress.length_known:118 assert result == '%s/%s' % (pos, length)126 assert result == "{}/{}".format(pos, length)127 else:128 assert result == str(pos)129130123@pytest.mark.parametrize('length, finished, pos, avg, expected',124 [(8, False, 7, 0, '#######-'),125 (0, True, 8, 0, '########'),126 (0, False, 8, 0, '--------'),127 (0, False, 5, 3, '#-------')128 ])131@pytest.mark.parametrize(132 "length, finished, pos, avg, expected",133 [134 (8, False, 7, 0, "#######-"),135 (0, True, 8, 0, "########"),136 (0, False, 8, 0, "--------"),137 (0, False, 5, 3, "#-------"),138 ],139)140def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):130 with _create_progress(length,131 length_known=length != 0,132 width=8,133 pos=pos,134 finished=finished,135 avg=[avg]) as progress:141 with _create_progress(142 length, length_known=length != 0, width=8, pos=pos, finished=finished, avg=[avg]143 ) as progress:144 assert progress.format_bar() == expected145146139@pytest.mark.parametrize('length, length_known, show_percent, show_pos, pos, expected',140 [(0, True, True, True, 0, ' [--------] 0/0 0%'),141 (0, True, False, True, 0, ' [--------] 0/0'),142 (0, True, False, False, 0, ' [--------]'),143 (0, False, False, False, 0, ' [--------]'),144 (8, True, True, True, 8, ' [########] 8/8 100%')145 ])146def test_progressbar_format_progress_line(runner, length, length_known, show_percent, show_pos, pos, expected):147 with _create_progress(length,148 length_known,149 width=8,150 show_percent=show_percent,151 pos=pos,152 show_pos=show_pos) as progress:147@pytest.mark.parametrize(148 "length, length_known, show_percent, show_pos, pos, expected",149 [150 (0, True, True, True, 0, " [--------] 0/0 0%"),151 (0, True, False, True, 0, " [--------] 0/0"),152 (0, True, False, False, 0, " [--------]"),153 (0, False, False, False, 0, " [--------]"),154 (8, True, True, True, 8, " [########] 8/8 100%"),155 ],156)157def test_progressbar_format_progress_line(158 runner, length, length_known, show_percent, show_pos, pos, expected159):160 with _create_progress(161 length,162 length_known,163 width=8,164 show_percent=show_percent,165 pos=pos,166 show_pos=show_pos,167 ) as progress:168 assert progress.format_progress_line() == expected169170156@pytest.mark.parametrize('test_item', ['test', None])171@pytest.mark.parametrize("test_item", ["test", None])172def test_progressbar_format_progress_line_with_show_func(runner, test_item):158173 def item_show_func(item):174 return item175162 with _create_progress(item_show_func=item_show_func, current_item=test_item) as progress:176 with _create_progress(177 item_show_func=item_show_func, current_item=test_item178 ) as progress:179 if test_item:180 assert progress.format_progress_line().endswith(test_item)181 else:182 assert progress.format_progress_line().endswith(progress.format_pct())183184185def test_progressbar_init_exceptions(runner):170 try:186 with pytest.raises(TypeError, match="iterable or length is required"):187 click.progressbar()172 except TypeError as e:173 assert str(e) == 'iterable or length is required'174 else:175 assert False, 'Expected an exception because unspecified arguments'188189190def test_progressbar_iter_outside_with_exceptions(runner):179 try:191 with pytest.raises(RuntimeError, match="with block"):192 progress = click.progressbar(length=2)193 iter(progress)182 except RuntimeError as e:183 assert str(e) == 'You need to use progress bars in a with block.'184 else:185 assert False, 'Expected an exception because of abort-related inputs.'194195196def test_progressbar_is_iterator(runner, monkeypatch):197 fake_clock = FakeClock()198199 @click.command()200 def cli():193 with click.progressbar(range(10), label='test') as progress:201 with click.progressbar(range(10), label="test") as progress:202 while True:203 try:204 next(progress)205 fake_clock.advance_time()206 except StopIteration:207 break208201 monkeypatch.setattr(time, 'time', fake_clock.time)202 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)209 monkeypatch.setattr(time, "time", fake_clock.time)210 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)211212 result = runner.invoke(cli, [])213 assert result.exception is None214215216def test_choices_list_in_prompt(runner, monkeypatch):217 @click.command()210 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),211 prompt=True)218 @click.option(219 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True220 )221 def cli_with_choices(g):222 pass223224 @click.command()216 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),217 prompt=True, show_choices=False)225 @click.option(226 "-g",227 type=click.Choice(["none", "day", "week", "month"]),228 prompt=True,229 show_choices=False,230 )231 def cli_without_choices(g):232 pass233221 result = runner.invoke(cli_with_choices, [], input='none')222 assert '(none, day, week, month)' in result.output234 result = runner.invoke(cli_with_choices, [], input="none")235 assert "(none, day, week, month)" in result.output236224 result = runner.invoke(cli_without_choices, [], input='none')225 assert '(none, day, week, month)' not in result.output237 result = runner.invoke(cli_without_choices, [], input="none")238 assert "(none, day, week, month)" not in result.output239240241@pytest.mark.parametrize(229 "file_kwargs",230 [231 {"mode": "rt"},232 {"mode": "rb"},233 {"lazy": True},234 ]242 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]243)244def test_file_prompt_default_format(runner, file_kwargs):245 @click.command()246 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))
7 unmodified lines
254def test_secho(runner):255 with runner.isolation() as outstreams:256 click.secho(None, nl=False)257 bytes = outstreams[0].getvalue()250 assert bytes == b''258 assert bytes == b""259260261def test_progressbar_yields_all_items(runner):262 with click.progressbar(range(3)) as progress:
9 unmodified lines
272 for _ in progress:273 fake_clock.advance_time()274 print("")275268 monkeypatch.setattr(time, 'time', fake_clock.time)269 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)276 monkeypatch.setattr(time, "time", fake_clock.time)277 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)278 output = runner.invoke(cli, []).output279272 lines = [line for line in output.split('\n') if '[' in line]280 lines = [line for line in output.split("\n") if "[" in line]281274 assert ' 25% 00:00:03' in lines[0]275 assert ' 50% 00:00:02' in lines[1]276 assert ' 75% 00:00:01' in lines[2]277 assert '100% ' in lines[3]282 assert " 25% 00:00:03" in lines[0]283 assert " 50% 00:00:02" in lines[1]284 assert " 75% 00:00:01" in lines[2]285 assert "100% " in lines[3]286287288def test_progressbar_item_show_func(runner, monkeypatch):289 fake_clock = FakeClock()290291 @click.command()292 def cli():285 with click.progressbar(range(4), item_show_func=lambda x: "Custom {}".format(x)) as progress:293 with click.progressbar(294 range(4), item_show_func=lambda x: "Custom {}".format(x)295 ) as progress:296 for _ in progress:297 fake_clock.advance_time()298 print("")299290 monkeypatch.setattr(time, 'time', fake_clock.time)291 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)300 monkeypatch.setattr(time, "time", fake_clock.time)301 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)302 output = runner.invoke(cli, []).output303294 lines = [line for line in output.split('\n') if '[' in line]304 lines = [line for line in output.split("\n") if "[" in line]305296 assert 'Custom 0' in lines[0]297 assert 'Custom 1' in lines[1]298 assert 'Custom 2' in lines[2]299 assert 'Custom None' in lines[3]306 assert "Custom 0" in lines[0]307 assert "Custom 1" in lines[1]308 assert "Custom 2" in lines[2]309 assert "Custom None" in lines[3]310311312def test_progressbar_update_with_item_show_func(runner, monkeypatch):313 fake_clock = FakeClock()314315 @click.command()316 def cli():307 with click.progressbar(length=6, item_show_func=lambda x: "Custom {}".format(x)) as progress:317 with click.progressbar(318 length=6, item_show_func=lambda x: "Custom {}".format(x)319 ) as progress:320 while not progress.finished:321 fake_clock.advance_time()322 progress.update(2, progress.pos)323 print("")324313 monkeypatch.setattr(time, 'time', fake_clock.time)314 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)325 monkeypatch.setattr(time, "time", fake_clock.time)326 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)327 output = runner.invoke(cli, []).output328317 lines = [line for line in output.split('\n') if '[' in line]329 lines = [line for line in output.split("\n") if "[" in line]330319 assert 'Custom 0' in lines[0]320 assert 'Custom 2' in lines[1]321 assert 'Custom 4' in lines[2]331 assert "Custom 0" in lines[0]332 assert "Custom 2" in lines[1]333 assert "Custom 4" in lines[2]334335324@pytest.mark.parametrize(325 'key_char', (u'h', u'H', u'é', u'À', u' ', u'字', u'àH', u'àR')326)327@pytest.mark.parametrize('echo', [True, False])328@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')336@pytest.mark.parametrize("key_char", (u"h", u"H", u"é", u"À", u" ", u"字", u"àH", u"àR"))337@pytest.mark.parametrize("echo", [True, False])338@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")339def test_getchar_windows(runner, monkeypatch, key_char, echo):330 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwche', lambda: key_char)331 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)332 monkeypatch.setattr(click.termui, '_getchar', None)340 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)341 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)342 monkeypatch.setattr(click.termui, "_getchar", None)343 assert click.getchar(echo) == key_char344345336@pytest.mark.parametrize('special_key_char, key_char', [(u'\x00', 'a'), (u'\x00', 'b'), (u'\xe0', 'c')])337@pytest.mark.skipif(not WIN, reason='Tests special character inputs using the msvcrt module.')346@pytest.mark.parametrize(347 "special_key_char, key_char", [(u"\x00", "a"), (u"\x00", "b"), (u"\xe0", "c")]348)349@pytest.mark.skipif(350 not WIN, reason="Tests special character inputs using the msvcrt module."351)352def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):353 ordered_inputs = [key_char, special_key_char]340 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: ordered_inputs.pop())341 monkeypatch.setattr(click.termui, '_getchar', None)354 monkeypatch.setattr(355 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()356 )357 monkeypatch.setattr(click.termui, "_getchar", None)358 assert click.getchar() == special_key_char + key_char359360345@pytest.mark.parametrize('key_char', [u'\x03', u'\x1a'])346@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')347def test_getchar_windows_exceptions(runner, monkeypatch, key_char):348 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)349 monkeypatch.setattr(click.termui, '_getchar', None)350 try:361@pytest.mark.parametrize(362 ("key_char", "exc"), [(u"\x03", KeyboardInterrupt), (u"\x1a", EOFError)],363)364@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")365def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):366 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)367 monkeypatch.setattr(click.termui, "_getchar", None)368369 with pytest.raises(exc):370 click.getchar()352 except KeyboardInterrupt:353 assert key_char == u'\x03'354 except EOFError:355 assert key_char == u'\x1a'356 else:357 assert False, 'Expected an exception because of abort-specific inputs.'
modified:tests/test_testing.py+70 added-68 removed
1import os2import sys34import pytest5import click56import click7from click._compat import PY28from click._compat import WIN9from click.testing import CliRunner109from click._compat import PY2, WIN1011# Use the most reasonable io that users would use for the python version.12if PY2:13 from cStringIO import StringIO as ReasonableBytesIO14else:
2 unmodified lines
1718def test_runner():19 @click.command()20 def test():21 i = click.get_binary_stream('stdin')22 o = click.get_binary_stream('stdout')21 i = click.get_binary_stream("stdin")22 o = click.get_binary_stream("stdout")23 while 1:24 chunk = i.read(4096)25 if not chunk:26 break27 o.write(chunk)28 o.flush()2930 runner = CliRunner()31 result = runner.invoke(test, input='Hello World!\n')31 result = runner.invoke(test, input="Hello World!\n")32 assert not result.exception33 assert result.output == 'Hello World!\n'33 assert result.output == "Hello World!\n"3435 runner = CliRunner(echo_stdin=True)36 result = runner.invoke(test, input='Hello World!\n')36 result = runner.invoke(test, input="Hello World!\n")37 assert not result.exception38 assert result.output == 'Hello World!\nHello World!\n'38 assert result.output == "Hello World!\nHello World!\n"394041def test_runner_with_stream():42 @click.command()43 def test():44 i = click.get_binary_stream('stdin')45 o = click.get_binary_stream('stdout')44 i = click.get_binary_stream("stdin")45 o = click.get_binary_stream("stdout")46 while 1:47 chunk = i.read(4096)48 if not chunk:49 break50 o.write(chunk)51 o.flush()5253 runner = CliRunner()54 result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))54 result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))55 assert not result.exception56 assert result.output == 'Hello World!\n'56 assert result.output == "Hello World!\n"5758 runner = CliRunner(echo_stdin=True)59 result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))59 result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))60 assert not result.exception61 assert result.output == 'Hello World!\nHello World!\n'61 assert result.output == "Hello World!\nHello World!\n"626364def test_prompts():65 @click.command()66 @click.option('--foo', prompt=True)66 @click.option("--foo", prompt=True)67 def test(foo):68 click.echo('foo=%s' % foo)68 click.echo("foo={}".format(foo))6970 runner = CliRunner()71 result = runner.invoke(test, input='wau wau\n')71 result = runner.invoke(test, input="wau wau\n")72 assert not result.exception73 assert result.output == 'Foo: wau wau\nfoo=wau wau\n'73 assert result.output == "Foo: wau wau\nfoo=wau wau\n"7475 @click.command()76 @click.option('--foo', prompt=True, hide_input=True)76 @click.option("--foo", prompt=True, hide_input=True)77 def test(foo):78 click.echo('foo=%s' % foo)78 click.echo("foo={}".format(foo))7980 runner = CliRunner()81 result = runner.invoke(test, input='wau wau\n')81 result = runner.invoke(test, input="wau wau\n")82 assert not result.exception83 assert result.output == 'Foo: \nfoo=wau wau\n'83 assert result.output == "Foo: \nfoo=wau wau\n"848586def test_getchar():87 @click.command()88 def continue_it():89 click.echo(click.getchar())9091 runner = CliRunner()92 result = runner.invoke(continue_it, input='y')92 result = runner.invoke(continue_it, input="y")93 assert not result.exception94 assert result.output == 'y\n'94 assert result.output == "y\n"959697def test_catch_exceptions():98 class CustomError(Exception):
18 unmodified lines
117 result = runner.invoke(cli)118 assert result.exit_code == 1119120121@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')121@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")122def test_with_color():123 @click.command()124 def cli():125 click.secho('hello world', fg='blue')125 click.secho("hello world", fg="blue")126127 runner = CliRunner()128129 result = runner.invoke(cli)130 assert result.output == 'hello world\n'130 assert result.output == "hello world\n"131 assert not result.exception132133 result = runner.invoke(cli, color=True)134 assert result.output == click.style('hello world', fg='blue') + '\n'134 assert result.output == "{}\n".format(click.style("hello world", fg="blue"))135 assert not result.exception136137138def test_with_color_but_pause_not_blocking():
3 unmodified lines
142143 runner = CliRunner()144 result = runner.invoke(cli, color=True)145 assert not result.exception146 assert result.output == ''146 assert result.output == ""147148149def test_exit_code_and_output_from_sys_exit():150 # See issue #362151 @click.command()152 def cli_string():153 click.echo('hello world')154 sys.exit('error')153 click.echo("hello world")154 sys.exit("error")155156 @click.command()157 @click.pass_context158 def cli_string_ctx_exit(ctx):159 click.echo('hello world')160 ctx.exit('error')159 click.echo("hello world")160 ctx.exit("error")161162 @click.command()163 def cli_int():164 click.echo('hello world')164 click.echo("hello world")165 sys.exit(1)166167 @click.command()168 @click.pass_context169 def cli_int_ctx_exit(ctx):170 click.echo('hello world')170 click.echo("hello world")171 ctx.exit(1)172173 @click.command()174 def cli_float():175 click.echo('hello world')175 click.echo("hello world")176 sys.exit(1.0)177178 @click.command()179 @click.pass_context180 def cli_float_ctx_exit(ctx):181 click.echo('hello world')181 click.echo("hello world")182 ctx.exit(1.0)183184 @click.command()185 def cli_no_error():186 click.echo('hello world')186 click.echo("hello world")187188 runner = CliRunner()189190 result = runner.invoke(cli_string)191 assert result.exit_code == 1192 assert result.output == 'hello world\nerror\n'192 assert result.output == "hello world\nerror\n"193194 result = runner.invoke(cli_string_ctx_exit)195 assert result.exit_code == 1196 assert result.output == 'hello world\nerror\n'196 assert result.output == "hello world\nerror\n"197198 result = runner.invoke(cli_int)199 assert result.exit_code == 1200 assert result.output == 'hello world\n'200 assert result.output == "hello world\n"201202 result = runner.invoke(cli_int_ctx_exit)203 assert result.exit_code == 1204 assert result.output == 'hello world\n'204 assert result.output == "hello world\n"205206 result = runner.invoke(cli_float)207 assert result.exit_code == 1208 assert result.output == 'hello world\n1.0\n'208 assert result.output == "hello world\n1.0\n"209210 result = runner.invoke(cli_float_ctx_exit)211 assert result.exit_code == 1212 assert result.output == 'hello world\n1.0\n'212 assert result.output == "hello world\n1.0\n"213214 result = runner.invoke(cli_no_error)215 assert result.exit_code == 0216 assert result.output == 'hello world\n'216 assert result.output == "hello world\n"217218219def test_env():220 @click.command()221 def cli_env():222 click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])222 click.echo("ENV={}".format(os.environ["TEST_CLICK_ENV"]))223224 runner = CliRunner()225226 env_orig = dict(os.environ)227 env = dict(env_orig)228 assert 'TEST_CLICK_ENV' not in env229 env['TEST_CLICK_ENV'] = 'some_value'228 assert "TEST_CLICK_ENV" not in env229 env["TEST_CLICK_ENV"] = "some_value"230 result = runner.invoke(cli_env, env=env)231 assert result.exit_code == 0232 assert result.output == 'ENV=some_value\n'232 assert result.output == "ENV=some_value\n"233234 assert os.environ == env_orig235236
6 unmodified lines
243 runner = CliRunner(mix_stderr=False)244245 result = runner.invoke(cli_stderr)246247 assert result.output == 'stdout\n'248 assert result.stdout == 'stdout\n'249 assert result.stderr == 'stderr\n'247 assert result.output == "stdout\n"248 assert result.stdout == "stdout\n"249 assert result.stderr == "stderr\n"250251 runner_mix = CliRunner(mix_stderr=True)252 result_mix = runner_mix.invoke(cli_stderr)253254 assert result_mix.output == 'stdout\nstderr\n'255 assert result_mix.stdout == 'stdout\nstderr\n'254 assert result_mix.output == "stdout\nstderr\n"255 assert result_mix.stdout == "stdout\nstderr\n"256257 with pytest.raises(ValueError):258 result_mix.stderr259
4 unmodified lines
264 runner = CliRunner(mix_stderr=False)265266 result = runner.invoke(cli_empty_stderr)267268 assert result.output == 'stdout\n'269 assert result.stdout == 'stdout\n'270 assert result.stderr == ''268 assert result.output == "stdout\n"269 assert result.stdout == "stdout\n"270 assert result.stderr == ""271272273@pytest.mark.parametrize('args, expected_output', [274 (None, 'bar\n'),275 ([], 'bar\n'),276 ('', 'bar\n'),277 (['--foo', 'one two'], 'one two\n'),278 ('--foo "one two"', 'one two\n'),279])273@pytest.mark.parametrize(274 "args, expected_output",275 [276 (None, "bar\n"),277 ([], "bar\n"),278 ("", "bar\n"),279 (["--foo", "one two"], "one two\n"),280 ('--foo "one two"', "one two\n"),281 ],282)283def test_args(args, expected_output):281284 @click.command()283 @click.option('--foo', default='bar')285 @click.option("--foo", default="bar")286 def cli_args(foo):287 click.echo(foo)288289 runner = CliRunner()
9 unmodified lines
299300 runner = CliRunner()301 result = runner.invoke(cli, prog_name="foobar")302 assert not result.exception301 assert result.output == 'ok\n'303 assert result.output == "ok\n"
modified:tests/test_utils.py+139 added-143 removed
2 unmodified lines
3import sys45import pytest67import click8import click.utils7import click._termui_impl8import click.utils10from click._compat import WIN, PY29from click._compat import WIN101112def test_echo(runner):13 with runner.isolation() as outstreams:15 click.echo(u'\N{SNOWMAN}')16 click.echo(b'\x44\x44')14 click.echo(u"\N{SNOWMAN}")15 click.echo(b"\x44\x44")16 click.echo(42, nl=False)18 click.echo(b'a', nl=False)19 click.echo('\x1b[31mx\x1b[39m', nl=False)20 bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')21 assert bytes == b'\xe2\x98\x83\nDD\n42ax'17 click.echo(b"a", nl=False)18 click.echo("\x1b[31mx\x1b[39m", nl=False)19 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")20 assert bytes == b"\xe2\x98\x83\nDD\n42ax"2122 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 324 if sys.version_info[0] == 2:25 import StringIO2627 sys.stdout = x = StringIO.StringIO()28 try:29 click.echo('\xf6')29 click.echo("\xf6")30 finally:31 sys.stdout = sys.__stdout__32 assert x.getvalue() == '\xf6\n'32 assert x.getvalue() == "\xf6\n"3334 # And in any case, if wrapped, we expect bytes to survive.35 @click.command()36 def cli():37 click.echo(b'\xf6')37 click.echo(b"\xf6")3839 result = runner.invoke(cli, [])39 assert result.stdout_bytes == b'\xf6\n'40 assert result.stdout_bytes == b"\xf6\n"4142 # Ensure we do not strip for bytes.43 with runner.isolation() as outstreams:43 click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)44 assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'44 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)45 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"464748def test_echo_custom_file():49 import io5051 f = io.StringIO()50 click.echo(u'hello', file=f)51 assert f.getvalue() == u'hello\n'52 click.echo(u"hello", file=f)53 assert f.getvalue() == u"hello\n"545556@pytest.mark.parametrize(57 ("styles", "ref"),
24 unmodified lines
82 assert click.style("x y", **styles) == ref83 assert click.unstyle(ref) == "x y"848584@pytest.mark.parametrize(85 ("text", "expect"),86 [87 ("\x1b[?25lx y\x1b[?25h", "x y"),88 ]89)86@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])87def test_unstyle_other_ansi(text, expect):88 assert click.unstyle(text) == expect89909491def test_filename_formatting():96 assert click.format_filename(b'foo.txt') == 'foo.txt'97 assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'98 assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'99 assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt'92 assert click.format_filename(b"foo.txt") == "foo.txt"93 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"94 assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"95 assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt"9697 # filesystem encoding on windows permits this.98 if not WIN:103 assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \104 == u'foo\ufffd.txt'99 assert (100 click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"101 )102103104def test_prompts(runner):105 @click.command()106 def test():110 if click.confirm('Foo'):111 click.echo('yes!')107 if click.confirm("Foo"):108 click.echo("yes!")109 else:113 click.echo('no :(')110 click.echo("no :(")111115 result = runner.invoke(test, input='y\n')112 result = runner.invoke(test, input="y\n")113 assert not result.exception117 assert result.output == 'Foo [y/N]: y\nyes!\n'114 assert result.output == "Foo [y/N]: y\nyes!\n"115119 result = runner.invoke(test, input='\n')116 result = runner.invoke(test, input="\n")117 assert not result.exception121 assert result.output == 'Foo [y/N]: \nno :(\n'118 assert result.output == "Foo [y/N]: \nno :(\n"119123 result = runner.invoke(test, input='n\n')120 result = runner.invoke(test, input="n\n")121 assert not result.exception125 assert result.output == 'Foo [y/N]: n\nno :(\n'122 assert result.output == "Foo [y/N]: n\nno :(\n"123124 @click.command()125 def test_no():129 if click.confirm('Foo', default=True):130 click.echo('yes!')126 if click.confirm("Foo", default=True):127 click.echo("yes!")128 else:132 click.echo('no :(')129 click.echo("no :(")130134 result = runner.invoke(test_no, input='y\n')131 result = runner.invoke(test_no, input="y\n")132 assert not result.exception136 assert result.output == 'Foo [Y/n]: y\nyes!\n'133 assert result.output == "Foo [Y/n]: y\nyes!\n"134138 result = runner.invoke(test_no, input='\n')135 result = runner.invoke(test_no, input="\n")136 assert not result.exception140 assert result.output == 'Foo [Y/n]: \nyes!\n'137 assert result.output == "Foo [Y/n]: \nyes!\n"138142 result = runner.invoke(test_no, input='n\n')139 result = runner.invoke(test_no, input="n\n")140 assert not result.exception144 assert result.output == 'Foo [Y/n]: n\nno :(\n'141 assert result.output == "Foo [Y/n]: n\nno :(\n"142143147@pytest.mark.skipif(WIN, reason='Different behavior on windows.')144@pytest.mark.skipif(WIN, reason="Different behavior on windows.")145def test_prompts_abort(monkeypatch, capsys):146 def f(_):147 raise KeyboardInterrupt()148152 monkeypatch.setattr('click.termui.hidden_prompt_func', f)149 monkeypatch.setattr("click.termui.hidden_prompt_func", f)150151 try:155 click.prompt('Password', hide_input=True)152 click.prompt("Password", hide_input=True)153 except click.Abort:157 click.echo('Screw you.')154 click.echo("Screw you.")155156 out, err = capsys.readouterr()160 assert out == 'Password: \nScrew you.\n'157 assert out == "Password: \nScrew you.\n"158159160def _test_gen_func():164 yield 'a'165 yield 'b'166 yield 'c'167 yield 'abc'161 yield "a"162 yield "b"163 yield "c"164 yield "abc"165166170@pytest.mark.skipif(WIN, reason='Different behavior on windows.')171@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])172@pytest.mark.parametrize('test', [173 # We need lambda here, because pytest will174 # reuse the parameters, and then the generators175 # are already used and will not yield anymore176 ('just text\n', lambda: 'just text'),177 ('iterable\n', lambda: ["itera", "ble"]),178 ('abcabc\n', lambda: _test_gen_func),179 ('abcabc\n', lambda: _test_gen_func()),180 ('012345\n', lambda: (c for c in range(6))),181])167@pytest.mark.skipif(WIN, reason="Different behavior on windows.")168@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])169@pytest.mark.parametrize(170 "test",171 [172 # We need lambda here, because pytest will173 # reuse the parameters, and then the generators174 # are already used and will not yield anymore175 ("just text\n", lambda: "just text"),176 ("iterable\n", lambda: ["itera", "ble"]),177 ("abcabc\n", lambda: _test_gen_func),178 ("abcabc\n", lambda: _test_gen_func()),179 ("012345\n", lambda: (c for c in range(6))),180 ],181)182def test_echo_via_pager(monkeypatch, capfd, cat, test):183 monkeypatch.setitem(os.environ, 'PAGER', cat)184 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)183 monkeypatch.setitem(os.environ, "PAGER", cat)184 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)185186 expected_output = test[0]187 test_input = test[1]()188
2 unmodified lines
191 out, err = capfd.readouterr()192 assert out == expected_output193194195@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')195@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")196def test_echo_color_flag(monkeypatch, capfd):197 isatty = True198 monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)198 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)199200 text = 'foo'201 styled_text = click.style(text, fg='red')202 assert styled_text == '\x1b[31mfoo\x1b[0m'200 text = "foo"201 styled_text = click.style(text, fg="red")202 assert styled_text == "\x1b[31mfoo\x1b[0m"203204 click.echo(styled_text, color=False)205 out, err = capfd.readouterr()206 assert out == text + '\n'206 assert out == "{}\n".format(text)207208 click.echo(styled_text, color=True)209 out, err = capfd.readouterr()210 assert out == styled_text + '\n'210 assert out == "{}\n".format(styled_text)211212 isatty = True213 click.echo(styled_text)214 out, err = capfd.readouterr()215 assert out == styled_text + '\n'215 assert out == "{}\n".format(styled_text)216217 isatty = False218 click.echo(styled_text)219 out, err = capfd.readouterr()220 assert out == text + '\n'220 assert out == "{}\n".format(text)221222223@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')223@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")224def test_echo_writing_to_standard_error(capfd, monkeypatch):225 def emulate_input(text):226 """Emulate keyboard input."""227 if sys.version_info[0] == 2:228 from StringIO import StringIO229 else:230 from io import StringIO231 monkeypatch.setattr(sys, 'stdin', StringIO(text))231 monkeypatch.setattr(sys, "stdin", StringIO(text))232233 click.echo('Echo to standard output')233 click.echo("Echo to standard output")234 out, err = capfd.readouterr()235 assert out == 'Echo to standard output\n'236 assert err == ''235 assert out == "Echo to standard output\n"236 assert err == ""237238 click.echo('Echo to standard error', err=True)238 click.echo("Echo to standard error", err=True)239 out, err = capfd.readouterr()240 assert out == ''241 assert err == 'Echo to standard error\n'240 assert out == ""241 assert err == "Echo to standard error\n"242243 emulate_input('asdlkj\n')244 click.prompt('Prompt to stdin')243 emulate_input("asdlkj\n")244 click.prompt("Prompt to stdin")245 out, err = capfd.readouterr()246 assert out == 'Prompt to stdin: '247 assert err == ''246 assert out == "Prompt to stdin: "247 assert err == ""248249 emulate_input('asdlkj\n')250 click.prompt('Prompt to stderr', err=True)249 emulate_input("asdlkj\n")250 click.prompt("Prompt to stderr", err=True)251 out, err = capfd.readouterr()252 assert out == ''253 assert err == 'Prompt to stderr: '252 assert out == ""253 assert err == "Prompt to stderr: "254255 emulate_input('y\n')256 click.confirm('Prompt to stdin')255 emulate_input("y\n")256 click.confirm("Prompt to stdin")257 out, err = capfd.readouterr()258 assert out == 'Prompt to stdin [y/N]: '259 assert err == ''258 assert out == "Prompt to stdin [y/N]: "259 assert err == ""260261 emulate_input('y\n')262 click.confirm('Prompt to stderr', err=True)261 emulate_input("y\n")262 click.confirm("Prompt to stderr", err=True)263 out, err = capfd.readouterr()264 assert out == ''265 assert err == 'Prompt to stderr [y/N]: '264 assert out == ""265 assert err == "Prompt to stderr [y/N]: "266267 monkeypatch.setattr(click.termui, 'isatty', lambda x: True)268 monkeypatch.setattr(click.termui, 'getchar', lambda: ' ')267 monkeypatch.setattr(click.termui, "isatty", lambda x: True)268 monkeypatch.setattr(click.termui, "getchar", lambda: " ")269270 click.pause('Pause to stdout')270 click.pause("Pause to stdout")271 out, err = capfd.readouterr()272 assert out == 'Pause to stdout\n'273 assert err == ''272 assert out == "Pause to stdout\n"273 assert err == ""274275 click.pause('Pause to stderr', err=True)275 click.pause("Pause to stderr", err=True)276 out, err = capfd.readouterr()277 assert out == ''278 assert err == 'Pause to stderr\n'277 assert out == ""278 assert err == "Pause to stderr\n"279280281def test_open_file(runner):282 @click.command()283 @click.argument('filename')283 @click.argument("filename")284 def cli(filename):285 with click.open_file(filename) as f:286 click.echo(f.read())287288 click.echo('meep')288 click.echo("meep")289290 with runner.isolated_filesystem():291 with open('hello.txt', 'w') as f:292 f.write('Cool stuff')291 with open("hello.txt", "w") as f:292 f.write("Cool stuff")293294 result = runner.invoke(cli, ['hello.txt'])294 result = runner.invoke(cli, ["hello.txt"])295 assert result.exception is None296 assert result.output == 'Cool stuff\nmeep\n'296 assert result.output == "Cool stuff\nmeep\n"297298 result = runner.invoke(cli, ['-'], input='foobar')298 result = runner.invoke(cli, ["-"], input="foobar")299 assert result.exception is None300 assert result.output == 'foobar\nmeep\n'300 assert result.output == "foobar\nmeep\n"301302303def test_open_file_ignore_errors_stdin(runner):304 @click.command()
32 unmodified lines
337 with click.open_file("test.bin", errors="ignore") as f:338 f.read()339340341@pytest.mark.skipif(WIN, reason='os.chmod() is not fully supported on Windows.')342@pytest.mark.parametrize('permissions', [343 0o400,344 0o444,345 0o600,346 0o644,347 ])341@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")342@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])343def test_open_file_atomic_permissions_existing_file(runner, permissions):344 with runner.isolated_filesystem():350 with open('existing.txt', 'w') as f:351 f.write('content')352 os.chmod('existing.txt', permissions)345 with open("existing.txt", "w") as f:346 f.write("content")347 os.chmod("existing.txt", permissions)348349 @click.command()355 @click.argument('filename')350 @click.argument("filename")351 def cli(filename):357 click.open_file(filename, 'w', atomic=True).close()352 click.open_file(filename, "w", atomic=True).close()353359 result = runner.invoke(cli, ['existing.txt'])354 result = runner.invoke(cli, ["existing.txt"])355 assert result.exception is None361 assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions356 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions357358364@pytest.mark.skipif(WIN, reason='os.stat() is not fully supported on Windows.')359@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")360def test_open_file_atomic_permissions_new_file(runner):361 with runner.isolated_filesystem():362363 @click.command()368 @click.argument('filename')364 @click.argument("filename")365 def cli(filename):370 click.open_file(filename, 'w', atomic=True).close()366 click.open_file(filename, "w", atomic=True).close()367368 # Create a test file to get the expected permissions for new files369 # according to the current umask.374 with open('test.txt', 'w'):370 with open("test.txt", "w"):371 pass376 permissions = stat.S_IMODE(os.stat('test.txt').st_mode)372 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)373378 result = runner.invoke(cli, ['new.txt'])374 result = runner.invoke(cli, ["new.txt"])375 assert result.exception is None380 assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions376 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions377378379def test_iter_keepopenfile(tmpdir):380 expected = list(map(str, range(10)))385 p = tmpdir.mkdir('testdir').join('testfile')381 p = tmpdir.mkdir("testdir").join("testfile")382 p.write("\n".join(expected))383 with p.open() as f:384 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):385 assert e_line == a_line.strip()386387388def test_iter_lazyfile(tmpdir):389 expected = list(map(str, range(10)))394 p = tmpdir.mkdir('testdir').join('testfile')390 p = tmpdir.mkdir("testdir").join("testfile")391 p.write("\n".join(expected))392 with p.open() as f:393 with click.utils.LazyFile(f.name) as lf:394 for e_line, a_line in zip(expected, lf):
1 unmodified line
modified:.azure-pipelines.yml+3 added-15 removed
28 unmodified lines
29 vmImage: windows-latest30 python.version: '2.7'31 Docs:32 TOXENV: docs33 Style:34 TOXENV: style3536pool:37 vmImage: $(vmImage)38
5 unmodified lines
4445 - script: pip --disable-pip-version-check install -U tox46 displayName: Install tox4746 - script: tox -s false -- --junit-xml=test-results.xml48 - script: tox49 displayName: Run tox4849 - task: PublishTestResults@250 inputs:51 testResultsFiles: test-results.xml52 testRunTitle: $(Agent.JobName)53 condition: eq(variables['hasTestResults'], 'true')54 displayName: Publish test results5556 - task: PublishCodeCoverageResults@157 inputs:58 codeCoverageTool: Cobertura59 summaryFileLocation: coverage.xml60 condition: eq(variables['hasTestResults'], 'true')61 displayName: Publish coverage results
added:.pre-commit-config.yaml+27 added
1repos:2 - repo: https://github.com/asottile/pyupgrade3 rev: v2.1.04 hooks:5 - id: pyupgrade6 - repo: https://github.com/asottile/reorder_python_imports7 rev: v2.0.08 hooks:9 - id: reorder-python-imports10 args: ["--application-directories", "src"]11 - repo: https://github.com/ambv/black12 rev: 19.10b013 hooks:14 - id: black15 - repo: https://gitlab.com/pycqa/flake816 rev: 3.7.917 hooks:18 - id: flake819 additional_dependencies:20 - flake8-bugbear21 - flake8-implicit-str-concat22 - repo: https://github.com/pre-commit/pre-commit-hooks23 rev: v2.5.024 hooks:25 - id: check-byte-order-marker26 - id: trailing-whitespace27 - id: end-of-file-fixer
modified:CONTRIBUTING.rst+1 added-1 removed
9 unmodified lines
10Please, don't use the issue tracker for this. Check whether the11``#pocoo`` IRC channel on Freenode can help with your issue. If your problem12is not strictly Click-specific, ``#python`` on Freenode is generally more13active. Also try searching or asking on `Stack Overflow`_ with the14``python-click`` tag. 14``python-click`` tag.1516.. _Stack Overflow: https://stackoverflow.com/questions/tagged/python-click?sort=votes1718Reporting issues
48 unmodified lines
modified:README.rst+2 added-3 removed
36 unmodified lines
37 import click3839 @click.command()40 @click.option("--count", default=1, help="Number of greetings.")41 @click.option("--name", prompt="Your name",42 help="The person to greet.")41 @click.option("--name", prompt="Your name", help="The person to greet.")42 def hello(count, name):43 """Simple program that greets NAME for a total of COUNT times."""44 for _ in range(count):46 click.echo("Hello, %s!" % name)45 click.echo(f"Hello, {name}!")4647 if __name__ == '__main__':48 hello()49
30 unmodified lines
modified:setup.cfg+24 added-1 removed
10 unmodified lines
1112[coverage:run]13branch = True14source =15 click15 src16 tests1718[coverage:paths]19source =20 click21 */site-packages2223[flake8]24# B = bugbear25# E = pycodestyle errors26# F = flake8 pyflakes27# W = pycodestyle warnings28# B9 = bugbear opinions,29# ISC = implicit str concat30select = B, E, F, W, B9, ISC31ignore =32 # slice notation whitespace, invalid33 E20334 # line length, handled by bugbear B95035 E50136 # bare except, handled by bugbear B00137 E72238 # bin op line break, invalid39 W50340# up to 88 allowed by bugbear B95041max-line-length = 8042per-file-ignores =43 # __init__ module exports names44 src/click/__init__.py: F401
modified:setup.py+6 added-3 removed
1import io2import re34from setuptools import find_packages5from setuptools import setup67with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()98with io.open("click/__init__.py", "rt", encoding="utf8") as f:9 version = re.search(r"__version__ = '(.*?)'", f.read()).group(1)10with io.open("src/click/__init__.py", "rt", encoding="utf8") as f:11 version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)1213setup(14 name="click",15 version=version,
7 unmodified lines
23 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
modified:tox.ini+6 added
1[tox]2envlist =3 py{38,37,36,35,27,py3,py}4 style5 docs6skip_missing_interpreters = true78[testenv]
1 unmodified line
10 pytest11 colorama12commands = pytest --tb=short --basetemp={envtmpdir} {posargs}1314[testenv:style]15deps = pre-commit16skip_install = true17commands = pre-commit run --all-files --show-diff-on-failure1819[testenv:docs]20deps = -r docs/requirements.txt21commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html