Commit f09f3e10 authored by Igor Makarov's avatar Igor Makarov Committed by Commit Bot

Reformat python code in third_party/blink/tools/blinkpy/formatter for PEP8

- added .style.yapf file
- reformat *.py files

Bug: 1051750
Change-Id: I902200e328a800ec23a4c34ce7896b5d25122b19
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2132791Reviewed-by: default avatarKent Tamura <tkent@chromium.org>
Commit-Queue: Kent Tamura <tkent@chromium.org>
Cr-Commit-Position: refs/heads/master@{#758451}
parent 6820d712
...@@ -6,6 +6,5 @@ import sys ...@@ -6,6 +6,5 @@ import sys
from blinkpy.formatter.main import main from blinkpy.formatter.main import main
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())
# Copyright 2016 The Chromium Authors. All rights reserved. # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
"""A 2to3 fixer that reformats docstrings. """A 2to3 fixer that reformats docstrings.
This should transform docstrings to be closer to the conventions in pep-0257; This should transform docstrings to be closer to the conventions in pep-0257;
...@@ -33,9 +32,8 @@ class FixDocstrings(BaseFix): ...@@ -33,9 +32,8 @@ class FixDocstrings(BaseFix):
""" """
# Pylint incorrectly warns that there's no member simple_stmt on python_symbols # Pylint incorrectly warns that there's no member simple_stmt on python_symbols
# because the attribute is set dynamically. pylint: disable=no-member # because the attribute is set dynamically. pylint: disable=no-member
return (node.value.startswith('"""') and return (node.value.startswith('"""') and node.prev_sibling is None
node.prev_sibling is None and and node.parent.type == python_symbols.simple_stmt)
node.parent.type == python_symbols.simple_stmt)
def transform(self, node, results): def transform(self, node, results):
# First, strip whitespace at the beginning and end. # First, strip whitespace at the beginning and end.
......
# Copyright 2014 The Chromium Authors. All rights reserved. # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
"""A 2to3 fixer that converts all string literals to use double quotes. """A 2to3 fixer that converts all string literals to use double quotes.
Strings that contain double quotes will not be modified. Prefixed string Strings that contain double quotes will not be modified. Prefixed string
......
# Copyright 2014 The Chromium Authors. All rights reserved. # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
"""A 2to3 fixer that converts all string literals to use single quotes. """A 2to3 fixer that converts all string literals to use single quotes.
Strings that contain single quotes will not be modified. Prefixed string Strings that contain single quotes will not be modified. Prefixed string
...@@ -19,7 +18,8 @@ class FixSingleQuoteStrings(BaseFix): ...@@ -19,7 +18,8 @@ class FixSingleQuoteStrings(BaseFix):
_accept_type = token.STRING _accept_type = token.STRING
def match(self, node): def match(self, node):
res = node.value.startswith('"') and not node.value.startswith('"""') and "'" not in node.value[1:-1] res = (node.value.startswith('"') and not node.value.startswith('"""')
and "'" not in node.value[1:-1])
return res return res
def transform(self, node, results): def transform(self, node, results):
......
...@@ -15,20 +15,51 @@ from blinkpy.third_party import autopep8 ...@@ -15,20 +15,51 @@ from blinkpy.third_party import autopep8
def parse_args(args=None): def parse_args(args=None):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--chromium', action='store_const', dest='style', const='chromium', default='blink', parser.add_argument(
help="Format according to Chromium's Python coding styles instead of Blink's.") '--chromium',
parser.add_argument('--no-backups', action='store_false', default=True, dest='backup', action='store_const',
dest='style',
const='chromium',
default='blink',
help=
"Format according to Chromium's Python coding styles instead of Blink's."
)
parser.add_argument(
'--no-backups',
action='store_false',
default=True,
dest='backup',
help='Do not back up files before overwriting them.') help='Do not back up files before overwriting them.')
parser.add_argument('-j', '--jobs', metavar='n', type=int, default=0, parser.add_argument(
'-j',
'--jobs',
metavar='n',
type=int,
default=0,
help='Number of parallel jobs; match CPU count if less than 1.') help='Number of parallel jobs; match CPU count if less than 1.')
parser.add_argument('files', nargs='*', default=['-'], parser.add_argument(
'files',
nargs='*',
default=['-'],
help="files to format or '-' for standard in") help="files to format or '-' for standard in")
parser.add_argument('--double-quote-strings', action='store_const', dest='quoting', const='double', default='single', parser.add_argument(
help='Rewrite string literals to use double quotes instead of single quotes.') '--double-quote-strings',
parser.add_argument('--no-autopep8', action='store_true', action='store_const',
dest='quoting',
const='double',
default='single',
help=
'Rewrite string literals to use double quotes instead of single quotes.'
)
parser.add_argument(
'--no-autopep8',
action='store_true',
help='Skip the autopep8 code-formatting step.') help='Skip the autopep8 code-formatting step.')
parser.add_argument('--leave-strings-alone', action='store_true', parser.add_argument(
help='Do not reformat string literals to use a consistent quote style.') '--leave-strings-alone',
action='store_true',
help='Do not reformat string literals to use a consistent quote style.'
)
return parser.parse_args(args=args) return parser.parse_args(args=args)
...@@ -46,13 +77,17 @@ def main(host=None, args=None): ...@@ -46,13 +77,17 @@ def main(host=None, args=None):
if options.files == ['-']: if options.files == ['-']:
host = host or SystemHost() host = host or SystemHost()
host.print_(reformat_source(host.stdin.read(), autopep8_options, fixers, '<stdin>'), end='') host.print_(
reformat_source(host.stdin.read(), autopep8_options, fixers,
'<stdin>'),
end='')
return return
# We create the arglist before checking if we need to create a Host, because a # We create the arglist before checking if we need to create a Host, because a
# real host is non-picklable and can't be passed to host.executive.map(). # real host is non-picklable and can't be passed to host.executive.map().
arglist = [(host, name, autopep8_options, fixers, options.backup) for name in options.files] arglist = [(host, name, autopep8_options, fixers, options.backup)
for name in options.files]
host = host or SystemHost() host = host or SystemHost()
host.executive.map(_reformat_thunk, arglist, processes=options.jobs) host.executive.map(_reformat_thunk, arglist, processes=options.jobs)
...@@ -61,18 +96,24 @@ def main(host=None, args=None): ...@@ -61,18 +96,24 @@ def main(host=None, args=None):
def _autopep8_options_for_style(style): def _autopep8_options_for_style(style):
return { return {
None: [], None: [],
'blink': autopep8.parse_args([ 'blink':
autopep8.parse_args([
'--aggressive', '--aggressive',
'--max-line-length', '132', '--max-line-length',
'132',
'--ignore=E309', '--ignore=E309',
'--indent-size', '4', '--indent-size',
'4',
'', '',
]), ]),
'chromium': autopep8.parse_args([ 'chromium':
autopep8.parse_args([
'--aggressive', '--aggressive',
'--max-line-length', '80', '--max-line-length',
'80',
'--ignore=E309', '--ignore=E309',
'--indent-size', '2', '--indent-size',
'2',
'', '',
]), ]),
}.get(style) }.get(style)
...@@ -107,8 +148,8 @@ def reformat_source(source, autopep8_options, fixers, name): ...@@ -107,8 +148,8 @@ def reformat_source(source, autopep8_options, fixers, name):
tmp_str = autopep8.fix_code(tmp_str, autopep8_options) tmp_str = autopep8.fix_code(tmp_str, autopep8_options)
if fixers: if fixers:
tool = lib2to3.refactor.RefactoringTool(fixer_names=fixers, tool = lib2to3.refactor.RefactoringTool(
explicit=fixers) fixer_names=fixers, explicit=fixers)
tmp_str = unicode(tool.refactor_string(tmp_str, name=name)) tmp_str = unicode(tool.refactor_string(tmp_str, name=name))
return tmp_str return tmp_str
...@@ -8,7 +8,6 @@ import unittest ...@@ -8,7 +8,6 @@ import unittest
from blinkpy.common.system.system_host_mock import MockSystemHost from blinkpy.common.system.system_host_mock import MockSystemHost
from blinkpy.formatter.main import main from blinkpy.formatter.main import main
ACTUAL_INPUT = ''' ACTUAL_INPUT = '''
def foo(): def foo():
"""triple-quoted docstring""" """triple-quoted docstring"""
...@@ -20,7 +19,6 @@ def foo(): ...@@ -20,7 +19,6 @@ def foo():
pass pass
''' '''
EXPECTED_BLINK_OUTPUT = ''' EXPECTED_BLINK_OUTPUT = '''
def foo(): def foo():
"""triple-quoted docstring""" """triple-quoted docstring"""
...@@ -35,7 +33,6 @@ def foo(): ...@@ -35,7 +33,6 @@ def foo():
pass pass
''' '''
EXPECTED_CHROMIUM_OUTPUT = ''' EXPECTED_CHROMIUM_OUTPUT = '''
def foo(): def foo():
"""triple-quoted docstring""" """triple-quoted docstring"""
...@@ -69,32 +66,33 @@ class TestMain(unittest.TestCase): ...@@ -69,32 +66,33 @@ class TestMain(unittest.TestCase):
def test_files_blink(self): def test_files_blink(self):
host = MockSystemHost() host = MockSystemHost()
host.filesystem.files = { host.filesystem.files = {'test.py': ACTUAL_INPUT}
'test.py': ACTUAL_INPUT}
main(host, ['test.py']) main(host, ['test.py'])
self.assertEqual(host.filesystem.files, { self.assertEqual(host.filesystem.files, {
'test.py': EXPECTED_BLINK_OUTPUT, 'test.py': EXPECTED_BLINK_OUTPUT,
'test.py.bak': ACTUAL_INPUT}) 'test.py.bak': ACTUAL_INPUT
})
def test_files_blink_no_backup(self): def test_files_blink_no_backup(self):
host = MockSystemHost() host = MockSystemHost()
host.filesystem.files = { host.filesystem.files = {'test.py': ACTUAL_INPUT}
'test.py': ACTUAL_INPUT}
main(host, ['--no-backups', 'test.py']) main(host, ['--no-backups', 'test.py'])
self.assertEqual(host.filesystem.files, { self.assertEqual(host.filesystem.files,
'test.py': EXPECTED_BLINK_OUTPUT}) {'test.py': EXPECTED_BLINK_OUTPUT})
def test_stdin_blink(self): def test_stdin_blink(self):
host = MockSystemHost() host = MockSystemHost()
host.stdin = StringIO.StringIO(ACTUAL_INPUT) host.stdin = StringIO.StringIO(ACTUAL_INPUT)
main(host, ['-']) main(host, ['-'])
self.assertMultiLineEqual(host.stdout.getvalue(), EXPECTED_BLINK_OUTPUT) self.assertMultiLineEqual(host.stdout.getvalue(),
EXPECTED_BLINK_OUTPUT)
def test_stdin_chromium(self): def test_stdin_chromium(self):
host = MockSystemHost() host = MockSystemHost()
host.stdin = StringIO.StringIO(ACTUAL_INPUT) host.stdin = StringIO.StringIO(ACTUAL_INPUT)
main(host, ['--chromium', '-']) main(host, ['--chromium', '-'])
self.assertMultiLineEqual(host.stdout.getvalue(), EXPECTED_CHROMIUM_OUTPUT) self.assertMultiLineEqual(host.stdout.getvalue(),
EXPECTED_CHROMIUM_OUTPUT)
def test_stdin_no_changes(self): def test_stdin_no_changes(self):
host = MockSystemHost() host = MockSystemHost()
...@@ -106,7 +104,8 @@ class TestMain(unittest.TestCase): ...@@ -106,7 +104,8 @@ class TestMain(unittest.TestCase):
host = MockSystemHost() host = MockSystemHost()
host.stdin = StringIO.StringIO(ACTUAL_INPUT) host.stdin = StringIO.StringIO(ACTUAL_INPUT)
main(host, ['--no-autopep8', '--double-quote-strings', '-']) main(host, ['--no-autopep8', '--double-quote-strings', '-'])
self.assertMultiLineEqual(host.stdout.getvalue(), EXPECTED_ONLY_DOUBLE_QUOTED_OUTPUT) self.assertMultiLineEqual(host.stdout.getvalue(),
EXPECTED_ONLY_DOUBLE_QUOTED_OUTPUT)
def test_format_docstrings(self): def test_format_docstrings(self):
host = MockSystemHost() host = MockSystemHost()
...@@ -123,7 +122,8 @@ def f(): ...@@ -123,7 +122,8 @@ def f():
return x return x
''') ''')
main(host, ['-']) main(host, ['-'])
self.assertMultiLineEqual(host.stdout.getvalue(), ''' self.assertMultiLineEqual(
host.stdout.getvalue(), '''
def f(): def f():
"""triple-quoted docstring """triple-quoted docstring
with multiple lines with multiple lines
...@@ -144,7 +144,8 @@ def f(): ...@@ -144,7 +144,8 @@ def f():
""" """
''') ''')
main(host, ['-']) main(host, ['-'])
self.assertMultiLineEqual(host.stdout.getvalue(), ''' self.assertMultiLineEqual(
host.stdout.getvalue(), '''
def f(): def f():
"""This is a docstring """This is a docstring
With extra indentation on this line. With extra indentation on this line.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment