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
Provenance
- Commit
5f75f9e- Tree
aa8b7c6- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
93ba3ba
27 files changed+91 added−100 removed
modified:examples/aliases/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/bashcompletion/bashcompletion.py+2 added-1 removed
29 unmodified lines30 def 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]]37 38 39 @group.command(help="Choose a user")6 unmodified linesmodified:examples/bashcompletion/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/complex/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/imagepipe/imagepipe.py+1 added-1 removed
233 unmodified lines234 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 image241 242 49 unmodified linesmodified:examples/imagepipe/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/inout/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/naval/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/repo/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:examples/validation/setup.py+1 added-1 removed
3 unmodified lines4 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 linemodified:src/click/_bashcomplete.py+26 added-16 removed
28 unmodified lines29 %(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 fi37 38 complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s36 unmodified lines75 76 compdef %(complete_func)s %(script_names)s77 """78 78-COMPLETION_SCRIPT_FISH = """79-complete --no-files --command %(script_names)s --arguments "(env %(autocomplete_var)s=complete_fish COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(script_names)s)"80-"""79+COMPLETION_SCRIPT_FISH = (80+ "complete --no-files --command %(script_names)s --arguments"81+ ' "(env %(autocomplete_var)s=complete_fish'82+ " COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t)"83+ ' %(script_names)s)"'84+)85 86 _completion_scripts = {87 "bash": COMPLETION_SCRIPT_BASH,88 "zsh": COMPLETION_SCRIPT_ZSH,16 unmodified lines105 ).strip() + ";"106 107 108 def 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.111+112 :param cli: command definition113 :param prog_name: the program that is running114 :param args: full list of args115 :return: the final context/command parsed34 unmodified lines150 151 def 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] == "-"158 159 160 def is_incomplete_option(all_args, cmd_param):161 """162 :param all_args: the full original list of args supplied163 :param cmd_param: the current command 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 lines183 184 185 def 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 lines253 for c in get_visible_commands_starting_with(ctx, incomplete)254 ]255 )256 248- # 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 lines284 return []285 286 has_double_dash = "--" in all_args287 278- # 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 linesmodified:src/click/_compat.py+1 added
1+# flake8: noqa2 import codecs3 import io4 import os5 import re787 unmodified linesmodified:src/click/core.py+8 added-10 removed
40 unmodified lines41 SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."42 SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."43 44 DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45-DEPRECATED_INVOKE_NOTICE = (46- "DeprecationWarning: " + "The command %(name)s is deprecated."47-)45+DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."46 47 48 def _maybe_show_deprecated_notice(cmd):49 if cmd.deprecated:525 unmodified lines575 context and command.576 """577 return self.command.get_help(self)578 581- 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:582 583 1. the first argument can be a callback and all other arguments and31 unmodified lines615 with augment_usage_errors(self):616 with ctx:617 return callback(*args, **kwargs)618 621- 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 lines982 self.format_help(ctx, formatter)983 return formatter.getvalue().rstrip("\n")984 985 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 lines1361 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 command1366 1367 def decorator(f):1368 cmd = command(*args, **kwargs)(f)1369 self.add_command(cmd)6 unmodified lines1376 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 group1381 1382 def decorator(f):1383 cmd = group(*args, **kwargs)(f)1384 self.add_command(cmd)653 unmodified lines2038 return '"%s"' % self.make_metavar()2039 2040 def add_to_parser(self, parser, ctx):2041 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)2040-2041-2042-# Circular dependency between decorators and core2043-from .decorators import command, groupmodified:src/click/decorators.py+6 added-6 removed
2 unmodified lines3 from functools import update_wrapper4 5 from ._compat import iteritems6 from ._unicodefun import _check_for_unicode_literals7+from .core import Argument8+from .core import Command9+from .core import Group10+from .core import Option11 from .globals import get_current_context12 from .utils import echo13 14 271 unmodified lines286 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()298 299 attrs.setdefault("is_flag", True)300 attrs.setdefault("expose_value", False)29 unmodified lines330 attrs["callback"] = callback331 return option(*(param_decls or ("--help",)), **attrs)(f)332 333 return decorator330-331-332-# Circular dependencies between core and decorators333-from .core import Command, Group, Argument, Optionmodified:src/click/exceptions.py+2 added
246 unmodified lines247 248 :param code: the status code to exit with.249 """250 251+ __slots__ = ("exit_code",)252+253 def __init__(self, code=0):254 self.exit_code = codemodified:src/click/globals.py+1 added-1 removed
17 unmodified lines18 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 linesmodified:src/click/termui.py+1 added-1 removed
154 unmodified lines155 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 linesmodified:src/click/testing.py+1 added-1 removed
380 unmodified lines381 finally:382 os.chdir(cwd)383 try:384 shutil.rmtree(t)385- except (OSError, IOError):385+ except (OSError, IOError): # noqa: B014386 passmodified:src/click/types.py+4 added-4 removed
259 unmodified lines260 261 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)266 267 def __repr__(self):268 return "INT"59 unmodified lines328 329 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)334 335 def __repr__(self):336 return "FLOAT"80 unmodified lines417 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)423 424 def __repr__(self):425 return "UUID"75 unmodified lines501 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 linesmodified:src/click/utils.py+1 added-1 removed
124 unmodified lines125 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 FileError131 132 raise FileError(self.name, hint=get_streerror(e))133 self._f = rv322 unmodified linesmodified:tests/test_arguments.py+1 added-6 removed
23 unmodified lines24 ]25 26 27 def test_nargs_default(runner):28- try:28+ with pytest.raises(TypeError, match="nargs=-1"):29 30 @click.command()31 @click.argument("src", nargs=-1, default=42)32 def copy(src):33 pass34 35- except TypeError as e:36- assert "nargs=-1" in str(e)37- else:38- assert False35 40-36 def test_nargs_tup(runner):37 @click.command()38 @click.argument("name", nargs=1)39 @click.argument("point", nargs=2, type=click.INT)296 unmodified linesmodified:tests/test_basic.py+1 added-1 removed
47 unmodified lines48 return 4249 50 with cli.make_context("foo", []) as ctx:51 rv = cli.invoke(ctx)52- assert rv is 4252+ assert rv == 4253 54 55 def test_basic_group(runner):56 @click.group()509 unmodified linesmodified:tests/test_commands.py+3 added-2 removed
60 unmodified lines61 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 lines294 295 def test_deprecated_in_invocation(runner):296 @click.command(deprecated=True)297 def deprecated_cmd():297- debug()298+ pass299 300 result = runner.invoke(deprecated_cmd)301 assert "DeprecationWarning:" in result.outputmodified:tests/test_options.py+3 added-13 removed
23 unmodified lines24 assert re.search(r"--bar\s+das bar", result.output) is not None25 26 27 def test_invalid_option(runner):28- try:28+ with pytest.raises(TypeError, match="name was passed"):29 30 @click.command()31 @click.option("foo")32 def cli(foo):33 pass34 35- 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."35 40-36 def test_invalid_nargs(runner):42- try:37+ with pytest.raises(TypeError, match="nargs < 0"):38 39 @click.command()40 @click.option("--foo", nargs=-1)41 def cli(foo):42 pass43 49- 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."44 54-45 def test_nargs_tup_composite_mult(runner):46 @click.command()47 @click.option("--item", type=(str, int), multiple=True)48 def copy(item):366 unmodified lines415 "-C",416 "--config",417 type=click.Path(),418 help="""Configuration file to use.429- 419+420 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 linesmodified:tests/test_termui.py+16 added-23 removed
31 unmodified lines32 33 @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()38 39 monkeypatch.setattr(time, "time", fake_clock.time)40 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)23 unmodified lines64 65 @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()70 71 monkeypatch.setattr(time, "time", fake_clock.time)72 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)7 unmodified lines80 81 @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()86 87 monkeypatch.setattr(time, "time", fake_clock.time)88 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)93 unmodified lines182 assert progress.format_progress_line().endswith(progress.format_pct())183 184 185 def 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"188 189 190 def 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."194 195 196 def test_progressbar_is_iterator(runner, monkeypatch):197 fake_clock = FakeClock()40 unmodified lines238 assert "(none, day, week, month)" not in result.output239 240 241 @pytest.mark.parametrize(250- "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True},]242+ "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]243 )244 def test_file_prompt_default_format(runner, file_kwargs):245 @click.command()246 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))62 unmodified lines309 monkeypatch.setattr(click.termui, "_getchar", None)310 assert click.getchar() == special_key_char + key_char311 312 321-@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.")323-def test_getchar_windows_exceptions(runner, monkeypatch, key_char):321+def 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:324+325+ 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 lines5 import pytest6 7 import click._termui_impl8 import click.utils9-from click._compat import PY29 from click._compat import WIN10 11 12 def test_echo(runner):69 unmodified lines82 assert click.style("x y", **styles) == ref83 assert click.unstyle(ref) == "x y"84 85 87-@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")])87 def test_unstyle_other_ansi(text, expect):88 assert click.unstyle(text) == expect89 90 247 unmodified lines338 f.read()339 340 341 @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])343 def 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 linesmodified:setup.cfg+3 added-2 removed
23 unmodified lines24 # B = bugbear25 # E = pycodestyle errors26 # F = flake8 pyflakes27 # W = pycodestyle warnings28-# B9 = bugbear opinions29-select = B, E, F, W, B928+# B9 = bugbear opinions,29+# ISC = implicit str concat30+select = B, E, F, W, B9, ISC31 ignore =32 # slice notation whitespace, invalid33 E20334 # line length, handled by bugbear B95010 unmodified lines