Skip to content

Commit 79a6b15

Browse files
committed
YapfBear: Catch parse errors and give result
The YapfBear earlier raised an error when the file was not parseable. Now, that error is caught and a Result is given out mentioning that the file has syntax errors and cannot be parsed. Fixes #750
1 parent 0d0c0a7 commit 79a6b15

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

bears/python/YapfBear.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,22 @@ def run(self, filename, file,
122122
options += 'use_tabs = ' + str(not use_spaces)
123123
options = options.format(**locals())
124124

125-
with prepare_file(options.splitlines(keepends=True),
126-
None) as (file_, fname):
127-
corrected = FormatFile(filename,
128-
style_config=fname,
129-
verify=False)[0].splitlines(True)
125+
try:
126+
with prepare_file(options.splitlines(keepends=True),
127+
None) as (file_, fname):
128+
corrected = FormatFile(filename,
129+
style_config=fname,
130+
verify=False)[0].splitlines(True)
131+
except SyntaxError as err:
132+
if isinstance(err, IndentationError):
133+
error_type = "indentation errors (" + err.args[0] + ')'
134+
else:
135+
error_type = "syntax errors"
136+
yield Result.from_values(
137+
self,
138+
"The code cannot be parsed due to {0}.".format(error_type),
139+
filename, line=err.lineno, column=err.offset)
140+
return
130141
diffs = Diff.from_string_arrays(file, corrected).split_diff()
131142
for diff in diffs:
132143
yield Result(self,

tests/python/YapfBearTest.py

+17
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@ def test_eof_handling(self):
3131
self.check_validity(self.uut, ['a = 2'], valid=True)
3232
self.check_validity(self.uut, ['\n'], valid=True)
3333

34+
def test_invalid_python(self):
35+
results = self.check_validity(
36+
self.uut, ['def a():', ' b=1', ' bad indent'], valid=False)
37+
self.assertEqual(len(results), 1, str(results))
38+
self.assertIn('unexpected indent', results[0].message)
39+
40+
results = self.check_validity(
41+
self.uut, ['def a():', ' b=1', '\ttab error'], valid=False)
42+
self.assertEqual(len(results), 1, str(results))
43+
self.assertIn('inconsistent use of tabs and spaces in indentation',
44+
results[0].message)
45+
46+
results = self.check_validity(
47+
self.uut, ['def a(:', ' b=1', '\ttab error'], valid=False)
48+
self.assertEqual(len(results), 1, str(results))
49+
self.assertIn('syntax errors', results[0].message)
50+
3451
def test_valid_python_2(self):
3552
self.check_validity(self.uut, ['print 1\n'], valid=True)
3653

0 commit comments

Comments
 (0)