From 8bfb76a5f28a0ba6030082c5f5fd331eb0194ccd Mon Sep 17 00:00:00 2001 From: Stephen Finucane Date: Wed, 22 Jul 2020 20:03:04 +0100 Subject: [PATCH] Switch to black Signed-off-by: Stephen Finucane --- .pre-commit-config.yaml | 33 ++++++++-- pyproject.toml | 16 +++++ setup.cfg | 4 ++ setup.py | 3 +- sphinx_click/ext.py | 83 ++++++++++++++----------- tests/test_formatter.py | 133 +++++++++++++++++++++++++++++----------- tox.ini | 4 -- 7 files changed, 192 insertions(+), 84 deletions(-) create mode 100644 pyproject.toml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 14c68a7..ea996a4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,29 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +--- +default_language_version: + # force all unspecified python hooks to run python3 + python: python3 repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.2.3 - hooks: - - id: flake8 - - id: trailing-whitespace + - repo: https://github.com/ambv/black + rev: stable + hooks: + - id: black + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.1.0 + hooks: + - id: trailing-whitespace + - id: mixed-line-ending + args: ['--fix', 'lf'] + - id: check-byte-order-marker + - id: check-executables-have-shebangs + - id: check-merge-conflict + - id: debug-statements + - id: end-of-file-fixer + - id: check-yaml + files: .*\.(yaml|yml)$ + - id: check-added-large-files + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.3 + hooks: + - id: flake8 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e0d775c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,16 @@ +[tool.black] +line-length = 88 +target-version = ['py36'] +skip-string-normalization = true +exclude = ''' +( + /( + \.eggs + | \.git + | \.tox + | \.venv + | build + | dist + ) +) +''' diff --git a/setup.cfg b/setup.cfg index 5dee086..0094a0f 100644 --- a/setup.cfg +++ b/setup.cfg @@ -25,3 +25,7 @@ packages = [wheel] universal = 1 + +[flake8] +max-line-length = 88 +ignore = E203,E501,E741,W503 diff --git a/setup.py b/setup.py index 26f5ba6..bae36e2 100644 --- a/setup.py +++ b/setup.py @@ -3,6 +3,5 @@ from setuptools import setup setup( - setup_requires=['pbr>=2.0'], - pbr=True, + setup_requires=['pbr>=2.0'], pbr=True, ) diff --git a/sphinx_click/ext.py b/sphinx_click/ext.py index d3064ff..6b95372 100644 --- a/sphinx_click/ext.py +++ b/sphinx_click/ext.py @@ -38,6 +38,7 @@ def _get_help_record(opt): [1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option """ + def _write_opts(opts): rv, _ = click.formatting.join_options(opts) if not opt.is_flag and not opt.count: @@ -57,9 +58,14 @@ def _write_opts(opts): # documentation thus needs a manually written string. extra.append('default: %s' % opt.show_default) else: - extra.append('default: %s' % - (', '.join('%s' % d for d in opt.default) if isinstance( - opt.default, (list, tuple)) else opt.default, )) + extra.append( + 'default: %s' + % ( + ', '.join('%s' % d for d in opt.default) + if isinstance(opt.default, (list, tuple)) + else opt.default, + ) + ) if opt.required: extra.append('required') if extra: @@ -84,9 +90,9 @@ def _format_description(ctx): return bar_enabled = False - for line in statemachine.string2lines(help_string, - tab_width=4, - convert_whitespace=True): + for line in statemachine.string2lines( + help_string, tab_width=4, convert_whitespace=True + ): if line == '\b': bar_enabled = True continue @@ -113,9 +119,9 @@ def _format_option(opt): yield '.. option:: {}'.format(opt[0]) if opt[1]: yield '' - for line in statemachine.string2lines(opt[1], - tab_width=4, - convert_whitespace=True): + for line in statemachine.string2lines( + opt[1], tab_width=4, convert_whitespace=True + ): yield _indent(line) @@ -123,8 +129,9 @@ def _format_options(ctx): """Format all `click.Option` for a `click.Command`.""" # the hidden attribute is part of click 7.x only hence use of getattr params = [ - x for x in ctx.command.params - if isinstance(x, click.Option) and not getattr(x, 'hidden', False) + param + for param in ctx.command.params + if isinstance(param, click.Option) and not getattr(param, 'hidden', False) ] for param in params: @@ -137,9 +144,11 @@ def _format_argument(arg): """Format the output of a `click.Argument`.""" yield '.. option:: {}'.format(arg.human_readable_name) yield '' - yield _indent('{} argument{}'.format( - 'Required' if arg.required else 'Optional', - '(s)' if arg.nargs != 1 else '')) + yield _indent( + '{} argument{}'.format( + 'Required' if arg.required else 'Optional', '(s)' if arg.nargs != 1 else '' + ) + ) def _format_arguments(ctx): @@ -195,9 +204,9 @@ def _format_subcommand(command): if short_help: yield '' - for line in statemachine.string2lines(short_help, - tab_width=4, - convert_whitespace=True): + for line in statemachine.string2lines( + short_help, tab_width=4, convert_whitespace=True + ): yield _indent(line) @@ -311,39 +320,39 @@ def _load_module(self, module_path): module_name, attr_name = module_path.split(':', 1) except ValueError: # noqa raise self.error( - '"{}" is not of format "module:parser"'.format(module_path)) + '"{}" is not of format "module:parser"'.format(module_path) + ) try: mod = __import__(module_name, globals(), locals(), [attr_name]) except (Exception, SystemExit) as exc: # noqa - err_msg = 'Failed to import "{}" from "{}". '.format( - attr_name, module_name) + err_msg = 'Failed to import "{}" from "{}". '.format(attr_name, module_name) if isinstance(exc, SystemExit): err_msg += 'The module appeared to call sys.exit()' else: err_msg += 'The following exception was raised:\n{}'.format( - traceback.format_exc()) + traceback.format_exc() + ) raise self.error(err_msg) if not hasattr(mod, attr_name): - raise self.error('Module "{}" has no attribute "{}"'.format( - module_name, attr_name)) + raise self.error( + 'Module "{}" has no attribute "{}"'.format(module_name, attr_name) + ) parser = getattr(mod, attr_name) if not isinstance(parser, click.BaseCommand): - raise self.error('"{}" of type "{}" is not derived from ' - '"click.BaseCommand"'.format( - type(parser), module_path)) + raise self.error( + '"{}" of type "{}" is not derived from ' + '"click.BaseCommand"'.format(type(parser), module_path) + ) return parser - def _generate_nodes(self, - name, - command, - parent=None, - show_nested=False, - commands=None): + def _generate_nodes( + self, name, command, parent=None, show_nested=False, commands=None + ): """Generate the relevant Sphinx nodes. Format a `click.Group` or `click.Command`. @@ -367,7 +376,8 @@ def _generate_nodes(self, '', nodes.title(text=name), ids=[nodes.make_id(ctx.command_path)], - names=[nodes.fully_normalize_name(ctx.command_path)]) + names=[nodes.fully_normalize_name(ctx.command_path)], + ) # Summary @@ -387,8 +397,8 @@ def _generate_nodes(self, commands = _filter_commands(ctx, commands) for command in commands: section.extend( - self._generate_nodes(command.name, command, ctx, - show_nested)) + self._generate_nodes(command.name, command, ctx, show_nested) + ) return [section] @@ -404,8 +414,7 @@ def run(self): show_nested = 'show-nested' in self.options commands = self.options.get('commands') - return self._generate_nodes(prog_name, command, None, show_nested, - commands) + return self._generate_nodes(prog_name, command, None, show_nested, commands) def setup(app): diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 6bd60cd..8df862e 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -22,14 +22,18 @@ def foobar(): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command. .. program:: foobar .. code-block:: shell foobar [OPTIONS] - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) def test_basic_parameters(self): """Validate a combination of parameters. @@ -40,8 +44,11 @@ def test_basic_parameters(self): @click.command() @click.option('--param', envvar='PARAM', help='A sample option') - @click.option('--choice', help='A sample option with choices', - type=click.Choice(['Option1', 'Option2'])) + @click.option( + '--choice', + help='A sample option with choices', + type=click.Choice(['Option1', 'Option2']), + ) @click.argument('ARG', envvar='ARG') def foobar(bar): """A sample command.""" @@ -51,7 +58,8 @@ def foobar(bar): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command. .. program:: foobar @@ -92,17 +100,26 @@ def foobar(bar): :noindex: Provide a default for :option:`ARG` - """).lstrip(), '\n'.join(output)) - - @unittest.skipIf(ext.CLICK_VERSION < (7, 0), - 'Allowing show_default to be a string was added in Click 7.0') + """ + ).lstrip(), + '\n'.join(output), + ) + + @unittest.skipIf( + ext.CLICK_VERSION < (7, 0), + 'Allowing show_default to be a string was added in Click 7.0', + ) def test_defaults(self): """Validate formatting of user documented defaults. """ @click.command() @click.option('--num-param', type=int, default=42, show_default=True) - @click.option('--param', default=lambda: None, show_default='Something computed at runtime') + @click.option( + '--param', + default=lambda: None, + show_default='Something computed at runtime', + ) def foobar(bar): """A sample command.""" pass @@ -111,7 +128,8 @@ def foobar(bar): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command. .. program:: foobar @@ -128,10 +146,14 @@ def foobar(bar): .. option:: --param [default: Something computed at runtime] - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) - @unittest.skipIf(ext.CLICK_VERSION < (7, 0), - 'The hidden flag was added in Click 7.0') + @unittest.skipIf( + ext.CLICK_VERSION < (7, 0), 'The hidden flag was added in Click 7.0' + ) def test_hidden(self): """Validate a `click.Command` with the `hidden` flag.""" @@ -163,14 +185,18 @@ def cli(): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. .. program:: cli .. code-block:: shell cli [OPTIONS] COMMAND [ARGS]... - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) def test_basic_parameters(self): """Validate a combination of parameters. @@ -190,7 +216,8 @@ def cli(): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. .. program:: cli @@ -225,7 +252,10 @@ def cli(): :noindex: Provide a default for :option:`ARG` - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) def test_no_line_wrapping(self): r"""Validate behavior when a \b character is present. @@ -251,7 +281,8 @@ def cli(): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. | This is @@ -265,7 +296,10 @@ def cli(): .. code-block:: shell cli [OPTIONS] COMMAND [ARGS]... - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) class NestedCommandsTestCase(unittest.TestCase): @@ -293,7 +327,8 @@ def test_hide_nested(self): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. .. program:: cli @@ -306,7 +341,10 @@ def test_hide_nested(self): .. object:: hello A sample command. - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) def test_show_nested(self): """Validate a nested command with show_nested. @@ -318,14 +356,18 @@ def test_show_nested(self): output = list(ext._format_command(ctx, show_nested=True)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. .. program:: cli .. code-block:: shell cli [OPTIONS] COMMAND [ARGS]... - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) class CommandFilterTestCase(unittest.TestCase): @@ -352,24 +394,30 @@ def test_no_commands(self): output = list(ext._format_command(ctx, show_nested=False, commands='')) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. .. program:: cli .. code-block:: shell cli [OPTIONS] COMMAND [ARGS]... - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) def test_order_of_commands(self): """Validate the order of commands.""" ctx = self._get_ctx() - output = list(ext._format_command(ctx, show_nested=False, - commands='world, hello')) + output = list( + ext._format_command(ctx, show_nested=False, commands='world, hello') + ) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample command group. .. program:: cli @@ -386,7 +434,10 @@ def test_order_of_commands(self): .. object:: hello A sample command. - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) class CustomMultiCommandTestCase(unittest.TestCase): @@ -422,7 +473,8 @@ def get_command(self, ctx, name): output = list(ext._format_command(ctx, show_nested=False)) self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample custom multicommand. .. program:: cli @@ -439,12 +491,17 @@ def get_command(self, ctx, name): .. object:: world A world command. - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) - @unittest.skipIf(ext.CLICK_VERSION < (7, 0), - 'The hidden flag was added in Click 7.0') + @unittest.skipIf( + ext.CLICK_VERSION < (7, 0), 'The hidden flag was added in Click 7.0' + ) def test_hidden(self): """Ensure 'hidden' subcommands are not shown.""" + @click.command() def hello(): """A sample command.""" @@ -476,7 +533,8 @@ def get_command(self, ctx, name): # Note that we do NOT expect this to show the 'hidden' command self.assertEqual( - textwrap.dedent(""" + textwrap.dedent( + """ A sample custom multicommand. .. program:: cli @@ -493,4 +551,7 @@ def get_command(self, ctx, name): .. object:: world A world command. - """).lstrip(), '\n'.join(output)) + """ + ).lstrip(), + '\n'.join(output), + ) diff --git a/tox.ini b/tox.ini index 3061841..241bffb 100644 --- a/tox.ini +++ b/tox.ini @@ -20,12 +20,8 @@ commands = [testenv:style] deps = - isort - yapf flake8 commands = - isort -rc -c -df {toxinidir}/sphinx_click/ - yapf -ri {toxinidir}/sphinx_click/ flake8 {toxinidir}/sphinx_click/ [coverage:run]