Skip to content

Commit a281c6d

Browse files
AbdealiLoKosils
authored andcommitted
JSComplexityBear: Handle invalid syntax better
Ths commits adds the feature to this bear to give a result when the tool is unable to parse the code at all. This is given as a MAJOR error as this a fault in the javascript code in itself. Fixes #729
1 parent bfb1165 commit a281c6d

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

bears/js/JSComplexityBear.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import json
2+
import re
23

34
from coalib.bearlib.abstractions.Linter import linter
45
from coalib.bears.requirements.NpmRequirement import NpmRequirement
6+
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
57
from coalib.results.Result import Result
68

79

@@ -19,6 +21,11 @@ class JSComplexityBear:
1921
ASCIINEMA_URL = 'https://asciinema.org/a/39250'
2022
CAN_DETECT = {'Complexity'}
2123

24+
try:
25+
DecodeError = json.decoder.JSONDecodeError
26+
except AttributeError:
27+
DecodeError = ValueError
28+
2229
@staticmethod
2330
def create_arguments(filename, file, config_file):
2431
return '--format', 'json', filename
@@ -29,7 +36,20 @@ def process_output(self, output, filename, file, cc_threshold: int=10):
2936
"""
3037
message = "{} has a cyclomatic complexity of {}."
3138
if output:
32-
output = json.loads(output)
39+
try:
40+
output = json.loads(output)
41+
except self.DecodeError:
42+
output_regex = (r'Fatal error \[getReports\]: .+: '
43+
r'Line (?P<line>\d+): (?P<message>.*)')
44+
for match in re.finditer(output_regex, output):
45+
groups = match.groupdict()
46+
yield Result.from_values(
47+
origin=self,
48+
message=groups["message"].strip(),
49+
file=filename,
50+
severity=RESULT_SEVERITY.MAJOR,
51+
line=int(groups["line"]))
52+
return
3353
for function in output["reports"][0]["functions"]:
3454
if function["cyclomatic"] >= cc_threshold:
3555
yield Result.from_values(

tests/js/JSComplexityBearTest.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,12 @@
3636
})()
3737
"""
3838

39+
test_syntax_error = '{<!@3@^ yeah!/\n'
40+
3941
JSComplexityBearTest = verify_local_bear(
4042
JSComplexityBear,
4143
valid_files=(complexity_4,),
42-
invalid_files=(complexity_12,),
44+
invalid_files=(complexity_12, test_syntax_error),
4345
tempfile_kwargs={"suffix": ".js"})
4446

4547
JSComplexityBearThresholdTest = verify_local_bear(

0 commit comments

Comments
 (0)