Skip to content

Commit

Permalink
JSStandardBear: Add fixing capabilities
Browse files Browse the repository at this point in the history
The corrected code is retrieved by piping to JSStandard. If there
several issues in a single line, the messages are displayed together to
make it easy to understand the proposed fix.

Closes coala#1952
  • Loading branch information
Alexander-N committed Aug 7, 2017
1 parent 92b1f28 commit acbb8f0
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 14 deletions.
71 changes: 68 additions & 3 deletions bears/js/JSStandardBear.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from collections import defaultdict
import re
from subprocess import Popen, PIPE
from typing import List, Iterable, Tuple

from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.NpmRequirement import NpmRequirement
from coalib.results.Result import Result
from coalib.results.Diff import Diff


@linter(executable='standard',
output_format='regex',
output_regex=r'\s*[^:]+:(?P<line>\d+):(?P<column>\d+):'
r'\s*(?P<message>.+)')
use_stdin=True,
use_stderr=True)
class JSStandardBear:
"""
One JavaScript Style to Rule Them All.
Expand All @@ -24,5 +30,64 @@ class JSStandardBear:
CAN_FIX = {'Formatting'}
SEE_MORE = 'https://standardjs.com/rules.html'

issue_regex = re.compile(
r'\s*[^:]+:(?P<line>\d+):(?P<column>\d+):'
r'\s*(?P<message>.+)')

def create_arguments(self, filename, file, config_file):
return (filename, '--verbose')

@staticmethod
def _get_corrected_code(old_code: List[str]) -> List[str]:
"""
Pipes the code to JSStandard and returns the corrected code.
"""
p = Popen(
('standard', '--stdin', '--fix'),
stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.write(bytes(''.join(old_code), 'UTF-8'))
out, err = p.communicate()
return out.decode('UTF-8').splitlines(True)

def _get_issues(self, stdout: str) -> Iterable[Tuple[int, str]]:
"""
Gets the issues from the output of JSStandard.
The issues get parsed with ``self.issue_regex`` and merged if they
concern the same line.
:param stdout: Output from which the issues get parsed.
:return: List of tuples containing the line number and the message.
"""
match_objects = (
self.issue_regex.match(line) for line in stdout.splitlines())
issues = (
match_object.groupdict()
for match_object in match_objects if match_object is not None)
line_number_to_messages = defaultdict(list)
for issue in issues:
line_number = int(issue['line'])
line_number_to_messages[line_number].append(issue['message'])
return (
(line_number, '\n'.join(messages))
for line_number, messages in line_number_to_messages.items())

def process_output(self, output, filename, file):
stdout, stderr = output
corrected_code = None
if '--fix' in stderr:
corrected_code = self._get_corrected_code(file)
if len(file) != len(corrected_code):
corrected_code = None

for line_number, message in self._get_issues(stdout):
diff = None
if corrected_code:
diff = Diff(file)
diff.modify_line(line_number, corrected_code[line_number-1])
yield Result.from_values(
origin=self,
message=message,
file=filename,
line=line_number,
diffs={filename: diff})
60 changes: 49 additions & 11 deletions tests/js/JSStandardBearTest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from coalib.testing.LocalBearTestHelper import verify_local_bear
from queue import Queue

from coalib.settings.Section import Section
from coalib.testing.BearTestHelper import generate_skip_decorator
from coalib.testing.LocalBearTestHelper import verify_local_bear
from coalib.testing.LocalBearTestHelper import LocalBearTestHelper
from bears.js.JSStandardBear import JSStandardBear


good_file = """
var foo = {
bar: 1,
Expand Down Expand Up @@ -68,12 +71,47 @@
}
"""

JSStandardBearTest = verify_local_bear(JSStandardBear,
valid_files=(good_file,),
invalid_files=(bad_file_indent,
bad_file_quote,
bad_file_semicolon,
bad_file_infix,
bad_file_undef,
bad_file_ifelse,
bad_file_func_name,))

JSStandardBearTest = verify_local_bear(
JSStandardBear,
valid_files=(good_file,),
invalid_files=(bad_file_indent,
bad_file_quote,
bad_file_semicolon,
bad_file_infix,
bad_file_undef,
bad_file_ifelse,
bad_file_func_name,))


@generate_skip_decorator(JSStandardBear)
class JSStandardBearTestClass(LocalBearTestHelper):
bad_code = """
(function () {
console.log('wrong indentation')
console.log('wrong indentation and semicolon');
}())
""".splitlines(True)

def setUp(self):
section = Section('name')
self.js_standard_bear = JSStandardBear(section, Queue())

def test_messages(self):
results = self.check_invalidity(
self.js_standard_bear,
self.bad_code)
self.assertIn('(indent)', results[0].message)
# Check that messages for lines with multiple issues get merged.
self.assertIn('(indent)', results[1].message)
self.assertIn('(semi)', results[1].message)

def test_corrected_code(self):
"""
Check that the corrected code is valid.
"""
corrected_code = self.js_standard_bear._get_corrected_code(
self.bad_code)
self.check_validity(
self.js_standard_bear,
corrected_code)

0 comments on commit acbb8f0

Please sign in to comment.