diff options
Diffstat (limited to 'coverage')
-rw-r--r-- | coverage/backward.py | 21 | ||||
-rw-r--r-- | coverage/html.py | 22 |
2 files changed, 32 insertions, 11 deletions
diff --git a/coverage/backward.py b/coverage/backward.py index f0a34ac4..31668e7f 100644 --- a/coverage/backward.py +++ b/coverage/backward.py @@ -101,6 +101,27 @@ else: """Convert bytes `b` to a string (no-op in 2.x).""" return b +# A few details about writing encoded text are different in 2.x and 3.x. +if sys.version_info >= (3, 0): + def write_encoded(fname, text, encoding='utf8', errors='strict'): + '''Write string `text` to file names `fname`, with encoding.''' + # Don't use "with", so that this file is still good for old 2.x. + f = open(fname, 'w', encoding=encoding, errors=errors) + try: + f.write(text) + finally: + f.close() +else: + # It's not clear that using utf8 strings in 2.x is the right thing to do. + def write_encoded(fname, text, encoding='utf8', errors='strict'): + '''Write utf8 string `text` to file names `fname`, with encoding.''' + import codecs + f = codecs.open(fname, 'w', encoding=encoding, errors=errors) + try: + f.write(text.decode('utf8')) + finally: + f.close() + # Md5 is available in different places. try: import hashlib diff --git a/coverage/html.py b/coverage/html.py index 9b951002..be6ff084 100644 --- a/coverage/html.py +++ b/coverage/html.py @@ -3,7 +3,7 @@ import os, re, shutil import coverage -from coverage.backward import pickle +from coverage.backward import pickle, write_encoded from coverage.misc import CoverageException, Hasher from coverage.phystokens import source_token_lines from coverage.report import Reporter @@ -98,6 +98,10 @@ class HtmlReporter(Reporter): os.path.join(self.directory, static) ) + def write_html(self, fname, html): + """Write `html` to `fname`, properly encoded.""" + write_encoded(fname, html, 'ascii', 'xmlcharrefreplace') + def file_hash(self, source, cu): """Compute a hash that changes if the file needs to be re-reported.""" m = Hasher() @@ -189,12 +193,9 @@ class HtmlReporter(Reporter): # Write the HTML page for this file. html_filename = flat_rootname + ".html" html_path = os.path.join(self.directory, html_filename) + html = spaceless(self.source_tmpl.render(locals())) - fhtml = open(html_path, 'w') - try: - fhtml.write(html) - finally: - fhtml.close() + self.write_html(html_path, html) # Save this file's information for the index file. index_info = { @@ -217,11 +218,10 @@ class HtmlReporter(Reporter): totals = sum([f['nums'] for f in files]) - fhtml = open(os.path.join(self.directory, "index.html"), "w") - try: - fhtml.write(index_tmpl.render(locals())) - finally: - fhtml.close() + self.write_html( + os.path.join(self.directory, "index.html"), + index_tmpl.render(locals()) + ) # Write the latest hashes for next time. self.status.write(self.directory) |