Skip to content
Myr

apply flake8

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

authored by David Lord · committed by David Lord · parent 93ba3ba · Browse files · 27 files+91 added−100 removed
This commit

State

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

Diff stats

27 files+91 added−100 removed

  • tests:+26 added−48 removed
  • other:+65 added−52 removed

27 files+91 added−100 removed

modified:examples/aliases/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-aliases",5 version="1.0",6 py_modules=["aliases"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 aliases=aliases:cli12 """,
1 unmodified line
modified:examples/bashcompletion/bashcompletion.py+2 added-1 removed
29 unmodified lines
30def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).33 users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34 # Ths will allow completion matches based on matches within the description string too!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")
6 unmodified lines
modified:examples/bashcompletion/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-bashcompletion",5 version="1.0",6 py_modules=["bashcompletion"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 bashcompletion=bashcompletion:cli12 """,
1 unmodified line
modified:examples/complex/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-complex",5 version="1.0",6 packages=["complex", "complex.commands"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 complex=complex.cli:cli12 """,
1 unmodified line
modified:examples/imagepipe/imagepipe.py+1 added-1 removed
233 unmodified lines
234 click.echo(235 'Smoothening "%s" %d time%s'236 % (image.filename, iterations, iterations != 1 and "s" or "",)237 )238 for x in xrange(iterations):238 for _ in range(iterations):239 image = copy_filename(image.filter(ImageFilter.BLUR), image)240 yield image241242
49 unmodified lines
modified:examples/imagepipe/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-imagepipe",5 version="1.0",6 py_modules=["imagepipe"],7 include_package_data=True,8 install_requires=["click", "pillow",],8 install_requires=["click", "pillow"],9 entry_points="""10 [console_scripts]11 imagepipe=imagepipe:cli12 """,
1 unmodified line
modified:examples/inout/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-inout",5 version="0.1",6 py_modules=["inout"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 inout=inout:cli12 """,
1 unmodified line
modified:examples/naval/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-naval",5 version="2.0",6 py_modules=["naval"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 naval=naval:cli12 """,
1 unmodified line
modified:examples/repo/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-repo",5 version="0.1",6 py_modules=["repo"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 repo=repo:cli12 """,
1 unmodified line
modified:examples/validation/setup.py+1 added-1 removed
3 unmodified lines
4 name="click-example-validation",5 version="1.0",6 py_modules=["validation"],7 include_package_data=True,8 install_requires=["click",],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 validation=validation:cli12 """,
1 unmodified line
modified:src/click/_bashcomplete.py+26 added-16 removed
28 unmodified lines
29%(complete_func)setup() {30 local COMPLETION_OPTIONS=""31 local BASH_VERSION_ARR=(${BASH_VERSION//./ })32 # Only BASH version 4.4 and later have the nosort option.33 if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] && [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then33 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)s
36 unmodified lines
7576compdef %(complete_func)s %(script_names)s77"""7878COMPLETION_SCRIPT_FISH = """79complete --no-files --command %(script_names)s --arguments "(env %(autocomplete_var)s=complete_fish COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(script_names)s)"80"""79COMPLETION_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,
16 unmodified lines
105 ).strip() + ";"106107108def resolve_ctx(cli, prog_name, args):105 """106 Parse into a hierarchy of contexts. Contexts are connected through the parent variable.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 parsed
34 unmodified lines
150151def start_of_option(param_str):152 """153 :param param_str: param_str to check149 :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")154 :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 paramter158 :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and159 corresponds to this cmd_param. In other words whether this cmd_param option can still accept160 values164 :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:
11 unmodified lines
183184185def is_incomplete_argument(current_params, cmd_param):186 """180 :param current_params: the current params and values for this argument as already entered187 :param current_params: the current params and values for this188 argument as already entered189 :param cmd_param: the current command parameter182 :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In183 other words whether or not the this cmd_param argument can still accept values190 :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]
56 unmodified lines
253 for c in get_visible_commands_starting_with(ctx, incomplete)254 ]255 )256248 # Walk up the context list and add any other completion possibilities from chained commands257 # 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 = [
21 unmodified lines
284 return []285286 has_double_dash = "--" in all_args287278 # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse279 # without the '='288 # In newer versions of bash long opts with '='s are partitioned, but289 # it's easier to parse without the '='290 if start_of_option(incomplete) and WORDBREAK in incomplete:291 partition_incomplete = incomplete.partition(WORDBREAK)292 all_args.append(partition_incomplete[0])293 incomplete = partition_incomplete[2]
82 unmodified lines
modified:src/click/_compat.py+1 added
1# flake8: noqa2import codecs3import io4import os5import re
787 unmodified lines
modified:src/click/core.py+8 added-10 removed
40 unmodified lines
41SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."42SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."4344DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45DEPRECATED_INVOKE_NOTICE = (46 "DeprecationWarning: " + "The command %(name)s is deprecated."47)45DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."464748def _maybe_show_deprecated_notice(cmd):49 if cmd.deprecated:
525 unmodified lines
575 context and command.576 """577 return self.command.get_help(self)578581 def invoke(*args, **kwargs):579 def invoke(*args, **kwargs): # noqa: B902580 """Invokes a command callback in exactly the way it expects. There581 are two ways to invoke this method:582583 1. the first argument can be a callback and all other arguments and
31 unmodified lines
615 with augment_usage_errors(self):616 with ctx:617 return callback(*args, **kwargs)618621 def forward(*args, **kwargs):619 def forward(*args, **kwargs): # noqa: B902620 """Similar to :meth:`invoke` but fills in default keyword621 arguments from the current context if the other command expects622 it. This cannot invoke callbacks directly, only other commands.623 """
358 unmodified lines
982 self.format_help(ctx, formatter)983 return formatter.getvalue().rstrip("\n")984985 def get_short_help_str(self, limit=45):988 """Gets short help for the command or makes it by shortening the long help string."""986 """Gets short help for the command or makes it by shortening the987 long help string.988 """989 return (990 self.short_help991 or self.help992 and make_default_short_help(self.help, limit)
368 unmodified lines
1361 the group. This takes the same arguments as :func:`command` but1362 immediately registers the created command with this instance by1363 calling into :meth:`add_command`.1364 """1365 from .decorators import command13661367 def decorator(f):1368 cmd = command(*args, **kwargs)(f)1369 self.add_command(cmd)
6 unmodified lines
1376 the group. This takes the same arguments as :func:`group` but1377 immediately registers the created command with this instance by1378 calling into :meth:`add_command`.1379 """1380 from .decorators import group13811382 def decorator(f):1383 cmd = group(*args, **kwargs)(f)1384 self.add_command(cmd)
653 unmodified lines
2038 return '"%s"' % self.make_metavar()20392040 def add_to_parser(self, parser, ctx):2041 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)204020412042# Circular dependency between decorators and core2043from .decorators import command, group
modified:src/click/decorators.py+6 added-6 removed
2 unmodified lines
3from 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 echo1314
271 unmodified lines
286 pass287 else:288 for dist in pkg_resources.working_set:289 scripts = dist.get_entry_map().get("console_scripts") or {}286 for script_name, entry_point in iteritems(scripts):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")292 echo(message % {"prog": prog, "version": ver,}, color=ctx.color)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)
29 unmodified lines
330 attrs["callback"] = callback331 return option(*(param_decls or ("--help",)), **attrs)(f)332333 return decorator330331332# Circular dependencies between core and decorators333from .core import Command, Group, Argument, Option
modified:src/click/exceptions.py+2 added
246 unmodified lines
247248 :param code: the status code to exit with.249 """250251 __slots__ = ("exit_code",)252253 def __init__(self, code=0):254 self.exit_code = code
modified:src/click/globals.py+1 added-1 removed
17 unmodified lines
18 is available. The default behavior is to raise a19 :exc:`RuntimeError`.20 """21 try:22 return getattr(_local, "stack")[-1]22 return _local.stack[-1]23 except (AttributeError, IndexError):24 if not silent:25 raise RuntimeError("There is no active click context.")26
21 unmodified lines
modified:src/click/termui.py+1 added-1 removed
154 unmodified lines
155 return default156 try:157 result = value_proc(value)158 except UsageError as e:159 echo("Error: %s" % e.message, err=err)159 echo("Error: %s" % e.message, err=err) # noqa: B306160 continue161 if not confirmation_prompt:162 return result163 while 1:
518 unmodified lines
modified:src/click/testing.py+1 added-1 removed
380 unmodified lines
381 finally:382 os.chdir(cwd)383 try:384 shutil.rmtree(t)385 except (OSError, IOError):385 except (OSError, IOError): # noqa: B014386 pass
modified:src/click/types.py+4 added-4 removed
259 unmodified lines
260261 def convert(self, value, param, ctx):262 try:263 return int(value)264 except (ValueError, UnicodeError):264 except ValueError:265 self.fail("%s is not a valid integer" % value, param, ctx)266267 def __repr__(self):268 return "INT"
59 unmodified lines
328329 def convert(self, value, param, ctx):330 try:331 return float(value)332 except (UnicodeError, ValueError):332 except ValueError:333 self.fail("%s is not a valid floating point value" % value, param, ctx)334335 def __repr__(self):336 return "FLOAT"
80 unmodified lines
417 try:418 if PY2 and isinstance(value, text_type):419 value = value.encode("ascii")420 return uuid.UUID(value)421 except (UnicodeError, ValueError):421 except ValueError:422 self.fail("%s is not a valid UUID value" % value, param, ctx)423424 def __repr__(self):425 return "UUID"
75 unmodified lines
501 ctx.call_on_close(safecall(f.close))502 else:503 ctx.call_on_close(safecall(f.flush))504 return f505 except (IOError, OSError) as e:505 except (IOError, OSError) as e: # noqa: B014506 self.fail(507 "Could not open file: %s: %s"508 % (filename_to_ui(value), get_streerror(e),),509 param,
234 unmodified lines
modified:src/click/utils.py+1 added-1 removed
124 unmodified lines
125 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:129 except (IOError, OSError) as e: # noqa: E402130 from .exceptions import FileError131132 raise FileError(self.name, hint=get_streerror(e))133 self._f = rv
322 unmodified lines
modified:tests/test_arguments.py+1 added-6 removed
23 unmodified lines
24 ]252627def test_nargs_default(runner):28 try:28 with pytest.raises(TypeError, match="nargs=-1"):2930 @click.command()31 @click.argument("src", nargs=-1, default=42)32 def copy(src):33 pass3435 except TypeError as e:36 assert "nargs=-1" in str(e)37 else:38 assert False354036def test_nargs_tup(runner):37 @click.command()38 @click.argument("name", nargs=1)39 @click.argument("point", nargs=2, type=click.INT)
296 unmodified lines
modified:tests/test_basic.py+1 added-1 removed
47 unmodified lines
48 return 424950 with cli.make_context("foo", []) as ctx:51 rv = cli.invoke(ctx)52 assert rv is 4252 assert rv == 42535455def test_basic_group(runner):56 @click.group()
509 unmodified lines
modified:tests/test_commands.py+3 added-2 removed
60 unmodified lines
61 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\.\.\.\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 )
223 unmodified lines
294295def test_deprecated_in_invocation(runner):296 @click.command(deprecated=True)297 def deprecated_cmd():297 debug()298 pass299300 result = runner.invoke(deprecated_cmd)301 assert "DeprecationWarning:" in result.output
modified:tests/test_options.py+3 added-13 removed
23 unmodified lines
24 assert re.search(r"--bar\s+das bar", result.output) is not None252627def test_invalid_option(runner):28 try:28 with pytest.raises(TypeError, match="name was passed"):2930 @click.command()31 @click.option("foo")32 def cli(foo):33 pass3435 except TypeError as e:36 assert "No options defined but a name was passed (foo)." in str(e)37 else:38 assert False, "Expected a type error because of an invalid option."354036def test_invalid_nargs(runner):42 try:37 with pytest.raises(TypeError, match="nargs < 0"):3839 @click.command()40 @click.option("--foo", nargs=-1)41 def cli(foo):42 pass4349 except TypeError as e:50 assert "Options cannot have nargs < 0" in str(e)51 else:52 assert False, "Expected a type error because of an invalid option."445445def test_nargs_tup_composite_mult(runner):46 @click.command()47 @click.option("--item", type=(str, int), multiple=True)48 def copy(item):
366 unmodified lines
415 "-C",416 "--config",417 type=click.Path(),418 help="""Configuration file to use.429 419420 If not given, the environment variable CONFIG_FILE is consulted421 and used if set. If neither are given, a default configuration422 file is loaded.""",423 )
138 unmodified lines
modified:tests/test_termui.py+16 added-23 removed
31 unmodified lines
3233 @click.command()34 def cli():35 with _create_progress(label=label) as progress:36 for thing in progress:36 for _ in progress:37 fake_clock.advance_time()3839 monkeypatch.setattr(time, "time", fake_clock.time)40 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
23 unmodified lines
6465 @click.command()66 def cli():67 with click.progressbar(Hinted(10), label="test") as progress:68 for thing in progress:68 for _ in progress:69 fake_clock.advance_time()7071 monkeypatch.setattr(time, "time", fake_clock.time)72 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
7 unmodified lines
8081 @click.command()82 def cli():83 with _create_progress(label=label) as progress:84 for thing in progress:84 for _ in progress:85 fake_clock.advance_time()8687 monkeypatch.setattr(time, "time", fake_clock.time)88 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)
93 unmodified lines
182 assert progress.format_progress_line().endswith(progress.format_pct())183184185def test_progressbar_init_exceptions(runner):186 try:186 with pytest.raises(TypeError, match="iterable or length is required"):187 click.progressbar()188 except TypeError as e:189 assert str(e) == "iterable or length is required"190 else:191 assert False, "Expected an exception because unspecified arguments"188189190def test_progressbar_iter_outside_with_exceptions(runner):195 try:191 with pytest.raises(RuntimeError, match="with block"):192 progress = click.progressbar(length=2)193 iter(progress)198 except RuntimeError as e:199 assert str(e) == "You need to use progress bars in a with block."200 else:201 assert False, "Expected an exception because of abort-related inputs."194195196def test_progressbar_is_iterator(runner, monkeypatch):197 fake_clock = FakeClock()
40 unmodified lines
238 assert "(none, day, week, month)" not in result.output239240241@pytest.mark.parametrize(250 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True},]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))
62 unmodified lines
309 monkeypatch.setattr(click.termui, "_getchar", None)310 assert click.getchar() == special_key_char + key_char311312321@pytest.mark.parametrize("key_char", [u"\x03", u"\x1a"])313@pytest.mark.parametrize(314 ("key_char", "exc"),315 [316 (u"\x03", KeyboardInterrupt),317 (u"\x1a", EOFError),318 ],319)320@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")323def test_getchar_windows_exceptions(runner, monkeypatch, key_char):321def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):322 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)323 monkeypatch.setattr(click.termui, "_getchar", None)326 try:324325 with pytest.raises(exc):326 click.getchar()328 except KeyboardInterrupt:329 assert key_char == u"\x03"330 except EOFError:331 assert key_char == u"\x1a"332 else:333 assert False, "Expected an exception because of abort-specific inputs."
modified:tests/test_utils.py+2 added-3 removed
4 unmodified lines
5import pytest67import click._termui_impl8import click.utils9from click._compat import PY29from click._compat import WIN101112def test_echo(runner):
69 unmodified lines
82 assert click.style("x y", **styles) == ref83 assert click.unstyle(ref) == "x y"848587@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y"),])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) == expect8990
247 unmodified lines
338 f.read()339340341@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")343@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644,])342@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])343def test_open_file_atomic_permissions_existing_file(runner, permissions):344 with runner.isolated_filesystem():345 with open("existing.txt", "w") as f:346 f.write("content")
49 unmodified lines
modified:setup.cfg+3 added-2 removed
23 unmodified lines
24# B = bugbear25# E = pycodestyle errors26# F = flake8 pyflakes27# W = pycodestyle warnings28# B9 = bugbear opinions29select = B, E, F, W, B928# 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 B950
10 unmodified lines