summaryrefslogtreecommitdiff
path: root/coverage/backward.py
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2011-08-28 15:05:45 -0400
committerNed Batchelder <ned@nedbatchelder.com>2011-08-28 15:05:45 -0400
commit20bc3ad07de296fa960dc68d0e3d2a580fcd55da (patch)
tree6c551c9002b62f8d332ebfc53fcf4f950e56141a /coverage/backward.py
parentb3e807b4126f52cf0abffe7ddb497cc22eef4433 (diff)
downloadpython-coveragepy-git-20bc3ad07de296fa960dc68d0e3d2a580fcd55da.tar.gz
Add another way to open source files, that works on 3.1
Diffstat (limited to 'coverage/backward.py')
-rw-r--r--coverage/backward.py24
1 files changed, 20 insertions, 4 deletions
diff --git a/coverage/backward.py b/coverage/backward.py
index 31668e7f..ef2a7743 100644
--- a/coverage/backward.py
+++ b/coverage/backward.py
@@ -73,13 +73,29 @@ except ImportError:
import ConfigParser as configparser
# Python 3.2 provides `tokenize.open`, the best way to open source files.
+import tokenize
try:
- import tokenize
open_source = tokenize.open # pylint: disable=E1101
except AttributeError:
- def open_source(fname):
- """Open a source file the best way."""
- return open(fname, "rU")
+ try:
+ detect_encoding = tokenize.detect_encoding
+ except AttributeError:
+ def open_source(fname):
+ """Open a source file the best way."""
+ return open(fname, "rU")
+ else:
+ from io import TextIOWrapper
+ # Copied from the 3.2 stdlib:
+ def open_source(fname):
+ """Open a file in read only mode using the encoding detected by
+ detect_encoding().
+ """
+ buffer = open(fname, 'rb')
+ encoding, lines = detect_encoding(buffer.readline)
+ buffer.seek(0)
+ text = TextIOWrapper(buffer, encoding, line_buffering=True)
+ text.mode = 'r'
+ return text
# Python 3.x is picky about bytes and strings, so provide methods to
# get them right, and make them no-ops in 2.x