Skip to content

Commit b73a3d1

Browse files
author
exarkun
committed
Merge pyflakes-encoding-problem-2842-2
Author: chaica, exarkun Reviewer: radix Fixes: #2842 Handle errors in the encoding of a source file.
1 parent 0fbfe73 commit b73a3d1

File tree

2 files changed

+45
-7
lines changed

2 files changed

+45
-7
lines changed

pyflakes/scripts/pyflakes.py

+27-7
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,19 @@
99
checker = __import__('pyflakes.checker').checker
1010

1111
def check(codeString, filename):
12+
"""
13+
Check the Python source given by C{codeString} for flakes.
14+
15+
@param codeString: The Python source to check.
16+
@type codeString: C{str}
17+
18+
@param filename: The name of the file the source came from, used to report
19+
errors.
20+
@type filename: C{str}
21+
22+
@return: The number of warnings emitted.
23+
@rtype: C{int}
24+
"""
1225
# Since compiler.parse does not reliably report syntax errors, use the
1326
# built in compiler first to detect those.
1427
try:
@@ -18,16 +31,23 @@ def check(codeString, filename):
1831

1932
(lineno, offset, text) = value.lineno, value.offset, value.text
2033

21-
line = text.splitlines()[-1]
34+
# If there's an encoding problem with the file, the text is None.
35+
if text is None:
36+
# Avoid using msg, since for the only known case, it contains a
37+
# bogus message that claims the encoding the file declared was
38+
# unknown.
39+
print >> sys.stderr, "%s: problem decoding source" % (filename, )
40+
else:
41+
line = text.splitlines()[-1]
2242

23-
if offset is not None:
24-
offset = offset - (len(text) - len(line))
43+
if offset is not None:
44+
offset = offset - (len(text) - len(line))
2545

26-
print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)
27-
print >> sys.stderr, line
46+
print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)
47+
print >> sys.stderr, line
2848

29-
if offset is not None:
30-
print >> sys.stderr, " " * offset, "^"
49+
if offset is not None:
50+
print >> sys.stderr, " " * offset, "^"
3151

3252
return 1
3353
else:

pyflakes/test/test_script.py

+18
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,21 @@ def test_permissionDenied(self):
165165
self.assertEquals(count, 1)
166166
self.assertEquals(
167167
err.getvalue(), "%s: Permission denied\n" % (sourcePath.path,))
168+
169+
170+
def test_misencodedFile(self):
171+
"""
172+
If a source file contains bytes which cannot be decoded, this is
173+
reported on stderr.
174+
"""
175+
source = u"""\
176+
# coding: ascii
177+
x = "\N{SNOWMAN}"
178+
""".encode('utf-8')
179+
sourcePath = FilePath(self.mktemp())
180+
sourcePath.setContent(source)
181+
err = StringIO()
182+
count = withStderrTo(err, lambda: checkPath(sourcePath.path))
183+
self.assertEquals(count, 1)
184+
self.assertEquals(
185+
err.getvalue(), "%s: problem decoding source\n" % (sourcePath.path,))

0 commit comments

Comments
 (0)