Skip to content

Commit 047b683

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 0ff7651 commit 047b683

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

bears/js/JSComplexityBear.py

Lines changed: 21 additions & 1 deletion
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

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

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

tests/js/JSComplexityBearTest.py

Lines changed: 3 additions & 1 deletion
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)