Skip to content

Commit 20bc3ad

Browse files
committed
Add another way to open source files, that works on 3.1
1 parent b3e807b commit 20bc3ad

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

coverage/backward.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,29 @@ def exec_code_object(code, global_map):
7373
import ConfigParser as configparser
7474

7575
# Python 3.2 provides `tokenize.open`, the best way to open source files.
76+
import tokenize
7677
try:
77-
import tokenize
7878
open_source = tokenize.open # pylint: disable=E1101
7979
except AttributeError:
80-
def open_source(fname):
81-
"""Open a source file the best way."""
82-
return open(fname, "rU")
80+
try:
81+
detect_encoding = tokenize.detect_encoding
82+
except AttributeError:
83+
def open_source(fname):
84+
"""Open a source file the best way."""
85+
return open(fname, "rU")
86+
else:
87+
from io import TextIOWrapper
88+
# Copied from the 3.2 stdlib:
89+
def open_source(fname):
90+
"""Open a file in read only mode using the encoding detected by
91+
detect_encoding().
92+
"""
93+
buffer = open(fname, 'rb')
94+
encoding, lines = detect_encoding(buffer.readline)
95+
buffer.seek(0)
96+
text = TextIOWrapper(buffer, encoding, line_buffering=True)
97+
text.mode = 'r'
98+
return text
8399

84100
# Python 3.x is picky about bytes and strings, so provide methods to
85101
# get them right, and make them no-ops in 2.x

0 commit comments

Comments
 (0)