iannucci@chromium.org | 3665cd2 | 2013-11-07 09:37:03 +0000 | [diff] [blame] | 1 | """HTML reporting for Coverage.""" |
| 2 | |
| 3 | import os, re, shutil, sys |
| 4 | |
| 5 | import coverage |
| 6 | from coverage.backward import pickle |
| 7 | from coverage.misc import CoverageException, Hasher |
| 8 | from coverage.phystokens import source_token_lines, source_encoding |
| 9 | from coverage.report import Reporter |
| 10 | from coverage.results import Numbers |
| 11 | from coverage.templite import Templite |
| 12 | |
| 13 | |
| 14 | # Static files are looked for in a list of places. |
| 15 | STATIC_PATH = [ |
| 16 | # The place Debian puts system Javascript libraries. |
| 17 | "/usr/share/javascript", |
| 18 | |
| 19 | # Our htmlfiles directory. |
| 20 | os.path.join(os.path.dirname(__file__), "htmlfiles"), |
| 21 | ] |
| 22 | |
| 23 | def data_filename(fname): |
| 24 | """Return the path to a data file of ours. |
| 25 | |
| 26 | The file is searched for on `STATIC_PATH`, and the first place it's found, |
| 27 | is returned. |
| 28 | |
| 29 | """ |
| 30 | for static_dir in STATIC_PATH: |
| 31 | static_filename = os.path.join(static_dir, fname) |
| 32 | if os.path.exists(static_filename): |
| 33 | return static_filename |
| 34 | raise CoverageException("Couldn't find static file %r" % fname) |
| 35 | |
| 36 | def data(fname): |
| 37 | """Return the contents of a data file of ours.""" |
| 38 | data_file = open(data_filename(fname)) |
| 39 | try: |
| 40 | return data_file.read() |
| 41 | finally: |
| 42 | data_file.close() |
| 43 | |
| 44 | |
| 45 | class HtmlReporter(Reporter): |
| 46 | """HTML reporting.""" |
| 47 | |
| 48 | # These files will be copied from the htmlfiles dir to the output dir. |
| 49 | STATIC_FILES = [ |
| 50 | "style.css", |
| 51 | "jquery.min.js", |
| 52 | "jquery.hotkeys.js", |
| 53 | "jquery.isonscreen.js", |
| 54 | "jquery.tablesorter.min.js", |
| 55 | "coverage_html.js", |
| 56 | "keybd_closed.png", |
| 57 | "keybd_open.png", |
| 58 | ] |
| 59 | |
| 60 | def __init__(self, cov, config): |
| 61 | super(HtmlReporter, self).__init__(cov, config) |
| 62 | self.directory = None |
| 63 | self.template_globals = { |
| 64 | 'escape': escape, |
| 65 | 'title': self.config.html_title, |
| 66 | '__url__': coverage.__url__, |
| 67 | '__version__': coverage.__version__, |
| 68 | } |
| 69 | self.source_tmpl = Templite( |
| 70 | data("pyfile.html"), self.template_globals |
| 71 | ) |
| 72 | |
| 73 | self.coverage = cov |
| 74 | |
| 75 | self.files = [] |
| 76 | self.arcs = self.coverage.data.has_arcs() |
| 77 | self.status = HtmlStatus() |
| 78 | self.extra_css = None |
| 79 | self.totals = Numbers() |
| 80 | |
| 81 | def report(self, morfs): |
| 82 | """Generate an HTML report for `morfs`. |
| 83 | |
| 84 | `morfs` is a list of modules or filenames. |
| 85 | |
| 86 | """ |
| 87 | assert self.config.html_dir, "must give a directory for html reporting" |
| 88 | |
| 89 | # Read the status data. |
| 90 | self.status.read(self.config.html_dir) |
| 91 | |
| 92 | # Check that this run used the same settings as the last run. |
| 93 | m = Hasher() |
| 94 | m.update(self.config) |
| 95 | these_settings = m.digest() |
| 96 | if self.status.settings_hash() != these_settings: |
| 97 | self.status.reset() |
| 98 | self.status.set_settings_hash(these_settings) |
| 99 | |
| 100 | # The user may have extra CSS they want copied. |
| 101 | if self.config.extra_css: |
| 102 | self.extra_css = os.path.basename(self.config.extra_css) |
| 103 | |
| 104 | # Process all the files. |
| 105 | self.report_files(self.html_file, morfs, self.config.html_dir) |
| 106 | |
| 107 | if not self.files: |
| 108 | raise CoverageException("No data to report.") |
| 109 | |
| 110 | # Write the index file. |
| 111 | self.index_file() |
| 112 | |
| 113 | self.make_local_static_report_files() |
| 114 | |
| 115 | return self.totals.pc_covered |
| 116 | |
| 117 | def make_local_static_report_files(self): |
| 118 | """Make local instances of static files for HTML report.""" |
| 119 | # The files we provide must always be copied. |
| 120 | for static in self.STATIC_FILES: |
| 121 | shutil.copyfile( |
| 122 | data_filename(static), |
| 123 | os.path.join(self.directory, static) |
| 124 | ) |
| 125 | |
| 126 | # The user may have extra CSS they want copied. |
| 127 | if self.extra_css: |
| 128 | shutil.copyfile( |
| 129 | self.config.extra_css, |
| 130 | os.path.join(self.directory, self.extra_css) |
| 131 | ) |
| 132 | |
| 133 | def write_html(self, fname, html): |
| 134 | """Write `html` to `fname`, properly encoded.""" |
| 135 | fout = open(fname, "wb") |
| 136 | try: |
| 137 | fout.write(html.encode('ascii', 'xmlcharrefreplace')) |
| 138 | finally: |
| 139 | fout.close() |
| 140 | |
| 141 | def file_hash(self, source, cu): |
| 142 | """Compute a hash that changes if the file needs to be re-reported.""" |
| 143 | m = Hasher() |
| 144 | m.update(source) |
| 145 | self.coverage.data.add_to_hash(cu.filename, m) |
| 146 | return m.digest() |
| 147 | |
| 148 | def html_file(self, cu, analysis): |
| 149 | """Generate an HTML file for one source file.""" |
| 150 | source_file = cu.source_file() |
| 151 | try: |
| 152 | source = source_file.read() |
| 153 | finally: |
| 154 | source_file.close() |
| 155 | |
| 156 | # Find out if the file on disk is already correct. |
| 157 | flat_rootname = cu.flat_rootname() |
| 158 | this_hash = self.file_hash(source, cu) |
| 159 | that_hash = self.status.file_hash(flat_rootname) |
| 160 | if this_hash == that_hash: |
| 161 | # Nothing has changed to require the file to be reported again. |
| 162 | self.files.append(self.status.index_info(flat_rootname)) |
| 163 | return |
| 164 | |
| 165 | self.status.set_file_hash(flat_rootname, this_hash) |
| 166 | |
| 167 | # If need be, determine the encoding of the source file. We use it |
| 168 | # later to properly write the HTML. |
| 169 | if sys.version_info < (3, 0): |
| 170 | encoding = source_encoding(source) |
| 171 | # Some UTF8 files have the dreaded UTF8 BOM. If so, junk it. |
| 172 | if encoding.startswith("utf-8") and source[:3] == "\xef\xbb\xbf": |
| 173 | source = source[3:] |
| 174 | encoding = "utf-8" |
| 175 | |
| 176 | # Get the numbers for this file. |
| 177 | nums = analysis.numbers |
| 178 | |
| 179 | missing_branch_arcs = analysis.missing_branch_arcs() |
| 180 | |
| 181 | # These classes determine which lines are highlighted by default. |
| 182 | c_run = "run hide_run" |
| 183 | c_exc = "exc" |
| 184 | c_mis = "mis" |
| 185 | c_par = "par " + c_run |
| 186 | |
| 187 | lines = [] |
| 188 | |
| 189 | for lineno, line in enumerate(source_token_lines(source)): |
| 190 | lineno += 1 # 1-based line numbers. |
| 191 | # Figure out how to mark this line. |
| 192 | line_class = [] |
| 193 | annotate_html = "" |
| 194 | annotate_title = "" |
| 195 | if lineno in analysis.statements: |
| 196 | line_class.append("stm") |
| 197 | if lineno in analysis.excluded: |
| 198 | line_class.append(c_exc) |
| 199 | elif lineno in analysis.missing: |
| 200 | line_class.append(c_mis) |
| 201 | elif self.arcs and lineno in missing_branch_arcs: |
| 202 | line_class.append(c_par) |
| 203 | annlines = [] |
| 204 | for b in missing_branch_arcs[lineno]: |
| 205 | if b < 0: |
| 206 | annlines.append("exit") |
| 207 | else: |
| 208 | annlines.append(str(b)) |
| 209 | annotate_html = " ".join(annlines) |
| 210 | if len(annlines) > 1: |
| 211 | annotate_title = "no jumps to these line numbers" |
| 212 | elif len(annlines) == 1: |
| 213 | annotate_title = "no jump to this line number" |
| 214 | elif lineno in analysis.statements: |
| 215 | line_class.append(c_run) |
| 216 | |
| 217 | # Build the HTML for the line |
| 218 | html = [] |
| 219 | for tok_type, tok_text in line: |
| 220 | if tok_type == "ws": |
| 221 | html.append(escape(tok_text)) |
| 222 | else: |
| 223 | tok_html = escape(tok_text) or ' ' |
| 224 | html.append( |
| 225 | "<span class='%s'>%s</span>" % (tok_type, tok_html) |
| 226 | ) |
| 227 | |
| 228 | lines.append({ |
| 229 | 'html': ''.join(html), |
| 230 | 'number': lineno, |
| 231 | 'class': ' '.join(line_class) or "pln", |
| 232 | 'annotate': annotate_html, |
| 233 | 'annotate_title': annotate_title, |
| 234 | }) |
| 235 | |
| 236 | # Write the HTML page for this file. |
| 237 | html = spaceless(self.source_tmpl.render({ |
| 238 | 'c_exc': c_exc, 'c_mis': c_mis, 'c_par': c_par, 'c_run': c_run, |
| 239 | 'arcs': self.arcs, 'extra_css': self.extra_css, |
| 240 | 'cu': cu, 'nums': nums, 'lines': lines, |
| 241 | })) |
| 242 | |
| 243 | if sys.version_info < (3, 0): |
| 244 | html = html.decode(encoding) |
| 245 | |
| 246 | html_filename = flat_rootname + ".html" |
| 247 | html_path = os.path.join(self.directory, html_filename) |
| 248 | self.write_html(html_path, html) |
| 249 | |
| 250 | # Save this file's information for the index file. |
| 251 | index_info = { |
| 252 | 'nums': nums, |
| 253 | 'html_filename': html_filename, |
| 254 | 'name': cu.name, |
| 255 | } |
| 256 | self.files.append(index_info) |
| 257 | self.status.set_index_info(flat_rootname, index_info) |
| 258 | |
| 259 | def index_file(self): |
| 260 | """Write the index.html file for this report.""" |
| 261 | index_tmpl = Templite( |
| 262 | data("index.html"), self.template_globals |
| 263 | ) |
| 264 | |
| 265 | self.totals = sum([f['nums'] for f in self.files]) |
| 266 | |
| 267 | html = index_tmpl.render({ |
| 268 | 'arcs': self.arcs, |
| 269 | 'extra_css': self.extra_css, |
| 270 | 'files': self.files, |
| 271 | 'totals': self.totals, |
| 272 | }) |
| 273 | |
| 274 | if sys.version_info < (3, 0): |
| 275 | html = html.decode("utf-8") |
| 276 | self.write_html( |
| 277 | os.path.join(self.directory, "index.html"), |
| 278 | html |
| 279 | ) |
| 280 | |
| 281 | # Write the latest hashes for next time. |
| 282 | self.status.write(self.directory) |
| 283 | |
| 284 | |
| 285 | class HtmlStatus(object): |
| 286 | """The status information we keep to support incremental reporting.""" |
| 287 | |
| 288 | STATUS_FILE = "status.dat" |
| 289 | STATUS_FORMAT = 1 |
| 290 | |
| 291 | def __init__(self): |
| 292 | self.reset() |
| 293 | |
| 294 | def reset(self): |
| 295 | """Initialize to empty.""" |
| 296 | self.settings = '' |
| 297 | self.files = {} |
| 298 | |
| 299 | def read(self, directory): |
| 300 | """Read the last status in `directory`.""" |
| 301 | usable = False |
| 302 | try: |
| 303 | status_file = os.path.join(directory, self.STATUS_FILE) |
| 304 | fstatus = open(status_file, "rb") |
| 305 | try: |
| 306 | status = pickle.load(fstatus) |
| 307 | finally: |
| 308 | fstatus.close() |
| 309 | except (IOError, ValueError): |
| 310 | usable = False |
| 311 | else: |
| 312 | usable = True |
| 313 | if status['format'] != self.STATUS_FORMAT: |
| 314 | usable = False |
| 315 | elif status['version'] != coverage.__version__: |
| 316 | usable = False |
| 317 | |
| 318 | if usable: |
| 319 | self.files = status['files'] |
| 320 | self.settings = status['settings'] |
| 321 | else: |
| 322 | self.reset() |
| 323 | |
| 324 | def write(self, directory): |
| 325 | """Write the current status to `directory`.""" |
| 326 | status_file = os.path.join(directory, self.STATUS_FILE) |
| 327 | status = { |
| 328 | 'format': self.STATUS_FORMAT, |
| 329 | 'version': coverage.__version__, |
| 330 | 'settings': self.settings, |
| 331 | 'files': self.files, |
| 332 | } |
| 333 | fout = open(status_file, "wb") |
| 334 | try: |
| 335 | pickle.dump(status, fout) |
| 336 | finally: |
| 337 | fout.close() |
| 338 | |
| 339 | def settings_hash(self): |
| 340 | """Get the hash of the coverage.py settings.""" |
| 341 | return self.settings |
| 342 | |
| 343 | def set_settings_hash(self, settings): |
| 344 | """Set the hash of the coverage.py settings.""" |
| 345 | self.settings = settings |
| 346 | |
| 347 | def file_hash(self, fname): |
| 348 | """Get the hash of `fname`'s contents.""" |
| 349 | return self.files.get(fname, {}).get('hash', '') |
| 350 | |
| 351 | def set_file_hash(self, fname, val): |
| 352 | """Set the hash of `fname`'s contents.""" |
| 353 | self.files.setdefault(fname, {})['hash'] = val |
| 354 | |
| 355 | def index_info(self, fname): |
| 356 | """Get the information for index.html for `fname`.""" |
| 357 | return self.files.get(fname, {}).get('index', {}) |
| 358 | |
| 359 | def set_index_info(self, fname, info): |
| 360 | """Set the information for index.html for `fname`.""" |
| 361 | self.files.setdefault(fname, {})['index'] = info |
| 362 | |
| 363 | |
| 364 | # Helpers for templates and generating HTML |
| 365 | |
| 366 | def escape(t): |
| 367 | """HTML-escape the text in `t`.""" |
| 368 | return (t |
| 369 | # Convert HTML special chars into HTML entities. |
| 370 | .replace("&", "&").replace("<", "<").replace(">", ">") |
| 371 | .replace("'", "'").replace('"', """) |
| 372 | # Convert runs of spaces: "......" -> " . . ." |
| 373 | .replace(" ", " ") |
| 374 | # To deal with odd-length runs, convert the final pair of spaces |
| 375 | # so that "....." -> " . ." |
| 376 | .replace(" ", " ") |
| 377 | ) |
| 378 | |
| 379 | def spaceless(html): |
| 380 | """Squeeze out some annoying extra space from an HTML string. |
| 381 | |
| 382 | Nicely-formatted templates mean lots of extra space in the result. |
| 383 | Get rid of some. |
| 384 | |
| 385 | """ |
| 386 | html = re.sub(r">\s+<p ", ">\n<p ", html) |
| 387 | return html |