coverage 7.11.3__cp314-cp314-musllinux_1_2_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of coverage might be problematic. Click here for more details.

Files changed (59) hide show
  1. coverage/__init__.py +40 -0
  2. coverage/__main__.py +12 -0
  3. coverage/annotate.py +114 -0
  4. coverage/bytecode.py +196 -0
  5. coverage/cmdline.py +1184 -0
  6. coverage/collector.py +486 -0
  7. coverage/config.py +731 -0
  8. coverage/context.py +74 -0
  9. coverage/control.py +1481 -0
  10. coverage/core.py +139 -0
  11. coverage/data.py +227 -0
  12. coverage/debug.py +669 -0
  13. coverage/disposition.py +59 -0
  14. coverage/env.py +135 -0
  15. coverage/exceptions.py +85 -0
  16. coverage/execfile.py +329 -0
  17. coverage/files.py +553 -0
  18. coverage/html.py +856 -0
  19. coverage/htmlfiles/coverage_html.js +733 -0
  20. coverage/htmlfiles/favicon_32.png +0 -0
  21. coverage/htmlfiles/index.html +164 -0
  22. coverage/htmlfiles/keybd_closed.png +0 -0
  23. coverage/htmlfiles/pyfile.html +149 -0
  24. coverage/htmlfiles/style.css +377 -0
  25. coverage/htmlfiles/style.scss +824 -0
  26. coverage/inorout.py +614 -0
  27. coverage/jsonreport.py +188 -0
  28. coverage/lcovreport.py +219 -0
  29. coverage/misc.py +373 -0
  30. coverage/multiproc.py +120 -0
  31. coverage/numbits.py +146 -0
  32. coverage/parser.py +1213 -0
  33. coverage/patch.py +166 -0
  34. coverage/phystokens.py +197 -0
  35. coverage/plugin.py +617 -0
  36. coverage/plugin_support.py +299 -0
  37. coverage/py.typed +1 -0
  38. coverage/python.py +269 -0
  39. coverage/pytracer.py +369 -0
  40. coverage/regions.py +127 -0
  41. coverage/report.py +298 -0
  42. coverage/report_core.py +117 -0
  43. coverage/results.py +471 -0
  44. coverage/sqldata.py +1153 -0
  45. coverage/sqlitedb.py +239 -0
  46. coverage/sysmon.py +482 -0
  47. coverage/templite.py +306 -0
  48. coverage/tomlconfig.py +210 -0
  49. coverage/tracer.cpython-314-x86_64-linux-musl.so +0 -0
  50. coverage/tracer.pyi +43 -0
  51. coverage/types.py +206 -0
  52. coverage/version.py +35 -0
  53. coverage/xmlreport.py +264 -0
  54. coverage-7.11.3.dist-info/METADATA +221 -0
  55. coverage-7.11.3.dist-info/RECORD +59 -0
  56. coverage-7.11.3.dist-info/WHEEL +5 -0
  57. coverage-7.11.3.dist-info/entry_points.txt +4 -0
  58. coverage-7.11.3.dist-info/licenses/LICENSE.txt +177 -0
  59. coverage-7.11.3.dist-info/top_level.txt +1 -0
coverage/html.py ADDED
@@ -0,0 +1,856 @@
1
+ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2
+ # For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
3
+
4
+ """HTML reporting for coverage.py."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import collections
9
+ import dataclasses
10
+ import datetime
11
+ import functools
12
+ import json
13
+ import os
14
+ import re
15
+ import string
16
+ from collections.abc import Iterable
17
+ from dataclasses import dataclass, field
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ import coverage
21
+ from coverage.data import CoverageData, add_data_to_hash
22
+ from coverage.exceptions import NoDataError
23
+ from coverage.files import flat_rootname
24
+ from coverage.misc import (
25
+ Hasher,
26
+ ensure_dir,
27
+ file_be_gone,
28
+ format_local_datetime,
29
+ human_sorted,
30
+ isolate_module,
31
+ plural,
32
+ stdout_link,
33
+ )
34
+ from coverage.report_core import get_analysis_to_report
35
+ from coverage.results import Analysis, AnalysisNarrower, Numbers
36
+ from coverage.templite import Templite
37
+ from coverage.types import TLineNo, TMorf
38
+ from coverage.version import __url__
39
+
40
+ if TYPE_CHECKING:
41
+ from coverage import Coverage
42
+ from coverage.plugins import FileReporter
43
+
44
+
45
+ os = isolate_module(os)
46
+
47
+
48
+ def data_filename(fname: str) -> str:
49
+ """Return the path to an "htmlfiles" data file of ours."""
50
+ static_dir = os.path.join(os.path.dirname(__file__), "htmlfiles")
51
+ static_filename = os.path.join(static_dir, fname)
52
+ return static_filename
53
+
54
+
55
+ def read_data(fname: str) -> str:
56
+ """Return the contents of a data file of ours."""
57
+ with open(data_filename(fname), encoding="utf-8") as data_file:
58
+ return data_file.read()
59
+
60
+
61
+ def write_html(fname: str, html: str) -> None:
62
+ """Write `html` to `fname`, properly encoded."""
63
+ html = re.sub(r"(\A\s+)|(\s+$)", "", html, flags=re.MULTILINE) + "\n"
64
+ with open(fname, "wb") as fout:
65
+ fout.write(html.encode("ascii", "xmlcharrefreplace"))
66
+
67
+
68
+ @dataclass
69
+ class LineData:
70
+ """The data for each source line of HTML output."""
71
+
72
+ tokens: list[tuple[str, str]]
73
+ number: TLineNo
74
+ category: str
75
+ contexts: list[str]
76
+ contexts_label: str
77
+ context_list: list[str]
78
+ short_annotations: list[str]
79
+ long_annotations: list[str]
80
+ html: str = ""
81
+ context_str: str | None = None
82
+ annotate: str | None = None
83
+ annotate_long: str | None = None
84
+ css_class: str = ""
85
+
86
+
87
+ @dataclass
88
+ class FileData:
89
+ """The data for each source file of HTML output."""
90
+
91
+ relative_filename: str
92
+ nums: Numbers
93
+ lines: list[LineData]
94
+
95
+
96
+ @dataclass
97
+ class IndexItem:
98
+ """Information for each index entry, to render an index page."""
99
+
100
+ url: str = ""
101
+ file: str = ""
102
+ description: str = ""
103
+ nums: Numbers = field(default_factory=Numbers)
104
+
105
+
106
+ @dataclass
107
+ class IndexPage:
108
+ """Data for each index page."""
109
+
110
+ noun: str
111
+ plural: str
112
+ filename: str
113
+ summaries: list[IndexItem]
114
+ totals: Numbers
115
+ skipped_covered_count: int
116
+ skipped_empty_count: int
117
+
118
+
119
+ class HtmlDataGeneration:
120
+ """Generate structured data to be turned into HTML reports."""
121
+
122
+ EMPTY = "(empty)"
123
+
124
+ def __init__(self, cov: Coverage) -> None:
125
+ self.coverage = cov
126
+ self.config = self.coverage.config
127
+ self.data = self.coverage.get_data()
128
+ self.has_arcs = self.data.has_arcs()
129
+ if self.config.show_contexts:
130
+ if self.data.measured_contexts() == {""}:
131
+ self.coverage._warn("No contexts were measured")
132
+ self.data.set_query_contexts(self.config.report_contexts)
133
+
134
+ def data_for_file(self, fr: FileReporter, analysis: Analysis) -> FileData:
135
+ """Produce the data needed for one file's report."""
136
+ if self.has_arcs:
137
+ missing_branch_arcs = analysis.missing_branch_arcs()
138
+ arcs_executed = analysis.arcs_executed
139
+ else:
140
+ missing_branch_arcs = {}
141
+ arcs_executed = []
142
+
143
+ if self.config.show_contexts:
144
+ contexts_by_lineno = self.data.contexts_by_lineno(analysis.filename)
145
+
146
+ lines = []
147
+ branch_stats = analysis.branch_stats()
148
+ multiline_map = {}
149
+ if hasattr(fr, "multiline_map"):
150
+ multiline_map = fr.multiline_map()
151
+
152
+ for lineno, tokens in enumerate(fr.source_token_lines(), start=1):
153
+ # Figure out how to mark this line.
154
+ category = category2 = ""
155
+ short_annotations = []
156
+ long_annotations = []
157
+
158
+ if lineno in analysis.excluded:
159
+ category = "exc"
160
+ elif lineno in analysis.missing:
161
+ category = "mis"
162
+ elif self.has_arcs and lineno in missing_branch_arcs:
163
+ category = "par"
164
+ mba = missing_branch_arcs[lineno]
165
+ if len(mba) == branch_stats[lineno][0]:
166
+ # None of the branches were taken from this line.
167
+ short_annotations.append("anywhere")
168
+ long_annotations.append(
169
+ f"line {lineno} didn't jump anywhere: it always raised an exception."
170
+ )
171
+ else:
172
+ for b in missing_branch_arcs[lineno]:
173
+ if b < 0:
174
+ short_annotations.append("exit")
175
+ else:
176
+ short_annotations.append(str(b))
177
+ long_annotations.append(
178
+ fr.missing_arc_description(lineno, b, arcs_executed)
179
+ )
180
+ elif lineno in analysis.statements:
181
+ category = "run"
182
+ elif first_line := multiline_map.get(lineno):
183
+ if first_line in analysis.excluded:
184
+ category2 = "exc2"
185
+ elif first_line in analysis.missing:
186
+ category2 = "mis2"
187
+ elif self.has_arcs and first_line in missing_branch_arcs:
188
+ category2 = "par2"
189
+ # I don't understand why this last condition is marked as
190
+ # partial. If I add an else with an exception, the exception
191
+ # is raised.
192
+ elif first_line in analysis.statements: # pragma: part covered
193
+ category2 = "run2"
194
+
195
+ contexts = []
196
+ contexts_label = ""
197
+ context_list = []
198
+ if category and self.config.show_contexts:
199
+ contexts = human_sorted(c or self.EMPTY for c in contexts_by_lineno.get(lineno, ()))
200
+ if contexts == [self.EMPTY]:
201
+ contexts_label = self.EMPTY
202
+ else:
203
+ contexts_label = f"{len(contexts)} ctx"
204
+ context_list = contexts
205
+
206
+ lines.append(
207
+ LineData(
208
+ tokens=tokens,
209
+ number=lineno,
210
+ category=category or category2,
211
+ contexts=contexts,
212
+ contexts_label=contexts_label,
213
+ context_list=context_list,
214
+ short_annotations=short_annotations,
215
+ long_annotations=long_annotations,
216
+ )
217
+ )
218
+
219
+ file_data = FileData(
220
+ relative_filename=fr.relative_filename(),
221
+ nums=analysis.numbers,
222
+ lines=lines,
223
+ )
224
+
225
+ return file_data
226
+
227
+
228
+ class FileToReport:
229
+ """A file we're considering reporting."""
230
+
231
+ def __init__(self, fr: FileReporter, analysis: Analysis) -> None:
232
+ self.fr = fr
233
+ self.analysis = analysis
234
+ self.rootname = flat_rootname(fr.relative_filename())
235
+ self.html_filename = self.rootname + ".html"
236
+ self.prev_html = self.next_html = ""
237
+
238
+
239
+ HTML_SAFE = string.ascii_letters + string.digits + "!#$%'()*+,-./:;=?@[]^_`{|}~"
240
+
241
+
242
+ @functools.cache
243
+ def encode_int(n: int) -> str:
244
+ """Create a short HTML-safe string from an integer, using HTML_SAFE."""
245
+ if n == 0:
246
+ return HTML_SAFE[0]
247
+
248
+ r = []
249
+ while n:
250
+ n, t = divmod(n, len(HTML_SAFE))
251
+ r.append(HTML_SAFE[t])
252
+ return "".join(r)
253
+
254
+
255
+ def copy_with_cache_bust(src: str, dest_dir: str) -> str:
256
+ """Copy `src` to `dest_dir`, adding a hash to the name.
257
+
258
+ Returns the updated destination file name with hash.
259
+ """
260
+ with open(src, "rb") as f:
261
+ text = f.read()
262
+ h = Hasher()
263
+ h.update(text)
264
+ cache_bust = h.hexdigest()[:8]
265
+ src_base = os.path.basename(src)
266
+ dest = src_base.replace(".", f"_cb_{cache_bust}.")
267
+ with open(os.path.join(dest_dir, dest), "wb") as f:
268
+ f.write(text)
269
+ return dest
270
+
271
+
272
+ class HtmlReporter:
273
+ """HTML reporting."""
274
+
275
+ # These files will be copied from the htmlfiles directory to the output
276
+ # directory.
277
+ STATIC_FILES = [
278
+ "style.css",
279
+ "coverage_html.js",
280
+ "keybd_closed.png",
281
+ "favicon_32.png",
282
+ ]
283
+
284
+ def __init__(self, cov: Coverage) -> None:
285
+ self.coverage = cov
286
+ self.config = self.coverage.config
287
+ self.directory = self.config.html_dir
288
+
289
+ self.skip_covered = self.config.html_skip_covered
290
+ if self.skip_covered is None:
291
+ self.skip_covered = self.config.skip_covered
292
+ self.skip_empty = self.config.html_skip_empty
293
+ if self.skip_empty is None:
294
+ self.skip_empty = self.config.skip_empty
295
+
296
+ title = self.config.html_title
297
+
298
+ self.extra_css = bool(self.config.extra_css)
299
+
300
+ self.data = self.coverage.get_data()
301
+ self.has_arcs = self.data.has_arcs()
302
+
303
+ self.index_pages: dict[str, IndexPage] = {
304
+ "file": self.new_index_page("file", "files"),
305
+ }
306
+ self.incr = IncrementalChecker(self.directory)
307
+ self.datagen = HtmlDataGeneration(self.coverage)
308
+ self.directory_was_empty = False
309
+ self.first_fr = None
310
+ self.final_fr = None
311
+
312
+ self.template_globals = {
313
+ # Functions available in the templates.
314
+ "escape": escape,
315
+ "pair": pair,
316
+ "len": len,
317
+ # Constants for this report.
318
+ "__url__": __url__,
319
+ "__version__": coverage.__version__,
320
+ "title": title,
321
+ "time_stamp": format_local_datetime(datetime.datetime.now()),
322
+ "extra_css": self.extra_css,
323
+ "has_arcs": self.has_arcs,
324
+ "show_contexts": self.config.show_contexts,
325
+ "statics": {},
326
+ # Constants for all reports.
327
+ # These css classes determine which lines are highlighted by default.
328
+ "category": {
329
+ "exc": "exc show_exc",
330
+ "mis": "mis show_mis",
331
+ "par": "par run show_par",
332
+ "run": "run",
333
+ "exc2": "exc exc2 show_exc",
334
+ "mis2": "mis mis2 show_mis",
335
+ "par2": "par par2 ru2 show_par",
336
+ "run2": "run run2",
337
+ },
338
+ }
339
+ self.index_tmpl = Templite(read_data("index.html"), self.template_globals)
340
+ self.pyfile_html_source = read_data("pyfile.html")
341
+ self.source_tmpl = Templite(self.pyfile_html_source, self.template_globals)
342
+
343
+ def new_index_page(self, noun: str, plural_noun: str) -> IndexPage:
344
+ """Create an IndexPage for a kind of region."""
345
+ return IndexPage(
346
+ noun=noun,
347
+ plural=plural_noun,
348
+ filename="index.html" if noun == "file" else f"{noun}_index.html",
349
+ summaries=[],
350
+ totals=Numbers(precision=self.config.precision),
351
+ skipped_covered_count=0,
352
+ skipped_empty_count=0,
353
+ )
354
+
355
+ def report(self, morfs: Iterable[TMorf] | None) -> float:
356
+ """Generate an HTML report for `morfs`.
357
+
358
+ `morfs` is a list of modules or file names.
359
+
360
+ """
361
+ # Read the status data and check that this run used the same
362
+ # global data as the last run.
363
+ self.incr.read()
364
+ self.incr.check_global_data(self.config, self.pyfile_html_source)
365
+
366
+ # Process all the files. For each page we need to supply a link
367
+ # to the next and previous page.
368
+ files_to_report = []
369
+
370
+ have_data = False
371
+ for fr, analysis in get_analysis_to_report(self.coverage, morfs):
372
+ have_data = True
373
+ ftr = FileToReport(fr, analysis)
374
+ if self.should_report(analysis, self.index_pages["file"]):
375
+ files_to_report.append(ftr)
376
+ else:
377
+ file_be_gone(os.path.join(self.directory, ftr.html_filename))
378
+
379
+ if not have_data:
380
+ raise NoDataError("No data to report.")
381
+
382
+ self.make_directory()
383
+ self.make_local_static_report_files()
384
+
385
+ if files_to_report:
386
+ for ftr1, ftr2 in zip(files_to_report[:-1], files_to_report[1:]):
387
+ ftr1.next_html = ftr2.html_filename
388
+ ftr2.prev_html = ftr1.html_filename
389
+ files_to_report[0].prev_html = "index.html"
390
+ files_to_report[-1].next_html = "index.html"
391
+
392
+ for ftr in files_to_report:
393
+ self.write_html_page(ftr)
394
+ for noun, plural_noun in ftr.fr.code_region_kinds():
395
+ if noun not in self.index_pages:
396
+ self.index_pages[noun] = self.new_index_page(noun, plural_noun)
397
+
398
+ # Write the index page.
399
+ if files_to_report:
400
+ first_html = files_to_report[0].html_filename
401
+ final_html = files_to_report[-1].html_filename
402
+ else:
403
+ first_html = final_html = "index.html"
404
+ self.write_file_index_page(first_html, final_html)
405
+
406
+ # Write function and class index pages.
407
+ self.write_region_index_pages(files_to_report)
408
+
409
+ return (
410
+ self.index_pages["file"].totals.n_statements
411
+ and self.index_pages["file"].totals.pc_covered
412
+ )
413
+
414
+ def make_directory(self) -> None:
415
+ """Make sure our htmlcov directory exists."""
416
+ ensure_dir(self.directory)
417
+ if not os.listdir(self.directory):
418
+ self.directory_was_empty = True
419
+
420
+ def copy_static_file(self, src: str, slug: str = "") -> None:
421
+ """Copy a static file into the output directory with cache busting."""
422
+ dest = copy_with_cache_bust(src, self.directory)
423
+ if not slug:
424
+ slug = os.path.basename(src).replace(".", "_")
425
+ self.template_globals["statics"][slug] = dest # type: ignore
426
+
427
+ def make_local_static_report_files(self) -> None:
428
+ """Make local instances of static files for HTML report."""
429
+
430
+ # The files we provide must always be copied.
431
+ for static in self.STATIC_FILES:
432
+ self.copy_static_file(data_filename(static))
433
+
434
+ # The user may have extra CSS they want copied.
435
+ if self.extra_css:
436
+ assert self.config.extra_css is not None
437
+ self.copy_static_file(self.config.extra_css, slug="extra_css")
438
+
439
+ # Only write the .gitignore file if the directory was originally empty.
440
+ # .gitignore can't be copied from the source tree because if it was in
441
+ # the source tree, it would stop the static files from being checked in.
442
+ if self.directory_was_empty:
443
+ with open(os.path.join(self.directory, ".gitignore"), "w", encoding="utf-8") as fgi:
444
+ fgi.write("# Created by coverage.py\n*\n")
445
+
446
+ def should_report(self, analysis: Analysis, index_page: IndexPage) -> bool:
447
+ """Determine if we'll report this file or region."""
448
+ # Get the numbers for this file.
449
+ nums = analysis.numbers
450
+ index_page.totals += nums
451
+
452
+ if self.skip_covered:
453
+ # Don't report on 100% files.
454
+ no_missing_lines = (nums.n_missing == 0) # fmt: skip
455
+ no_missing_branches = (nums.n_partial_branches == 0) # fmt: skip
456
+ if no_missing_lines and no_missing_branches:
457
+ index_page.skipped_covered_count += 1
458
+ return False
459
+
460
+ if self.skip_empty:
461
+ # Don't report on empty files.
462
+ if nums.n_statements == 0:
463
+ index_page.skipped_empty_count += 1
464
+ return False
465
+
466
+ return True
467
+
468
+ def write_html_page(self, ftr: FileToReport) -> None:
469
+ """Generate an HTML page for one source file.
470
+
471
+ If the page on disk is already correct based on our incremental status
472
+ checking, then the page doesn't have to be generated, and this function
473
+ only does page summary bookkeeping.
474
+
475
+ """
476
+ # Find out if the page on disk is already correct.
477
+ if self.incr.can_skip_file(self.data, ftr.fr, ftr.rootname):
478
+ self.index_pages["file"].summaries.append(self.incr.index_info(ftr.rootname))
479
+ return
480
+
481
+ # Write the HTML page for this source file.
482
+ file_data = self.datagen.data_for_file(ftr.fr, ftr.analysis)
483
+
484
+ contexts = collections.Counter(c for cline in file_data.lines for c in cline.contexts)
485
+ context_codes = {y: i for (i, y) in enumerate(x[0] for x in contexts.most_common())}
486
+ if context_codes:
487
+ contexts_json = json.dumps(
488
+ {encode_int(v): k for (k, v) in context_codes.items()},
489
+ indent=2,
490
+ )
491
+ else:
492
+ contexts_json = None
493
+
494
+ for ldata in file_data.lines:
495
+ # Build the HTML for the line.
496
+ html_parts = []
497
+ for tok_type, tok_text in ldata.tokens:
498
+ if tok_type == "ws":
499
+ html_parts.append(escape(tok_text))
500
+ else:
501
+ tok_html = escape(tok_text) or "&nbsp;"
502
+ html_parts.append(f'<span class="{tok_type}">{tok_html}</span>')
503
+ ldata.html = "".join(html_parts)
504
+ if ldata.context_list:
505
+ encoded_contexts = [
506
+ encode_int(context_codes[c_context]) for c_context in ldata.context_list
507
+ ]
508
+ code_width = max(len(ec) for ec in encoded_contexts)
509
+ ldata.context_str = str(code_width) + "".join(
510
+ ec.ljust(code_width) for ec in encoded_contexts
511
+ )
512
+ else:
513
+ ldata.context_str = ""
514
+
515
+ if ldata.short_annotations:
516
+ # 202F is NARROW NO-BREAK SPACE.
517
+ # 219B is RIGHTWARDS ARROW WITH STROKE.
518
+ ldata.annotate = ",&nbsp;&nbsp; ".join(
519
+ f"{ldata.number}&#x202F;&#x219B;&#x202F;{d}" for d in ldata.short_annotations
520
+ )
521
+ else:
522
+ ldata.annotate = None
523
+
524
+ if ldata.long_annotations:
525
+ longs = ldata.long_annotations
526
+ # A line can only have two branch destinations. If there were
527
+ # two missing, we would have written one as "always raised."
528
+ assert len(longs) == 1, (
529
+ f"Had long annotations in {ftr.fr.relative_filename()}: {longs}"
530
+ )
531
+ ldata.annotate_long = longs[0]
532
+ else:
533
+ ldata.annotate_long = None
534
+
535
+ css_classes = []
536
+ if ldata.category:
537
+ css_classes.append(
538
+ self.template_globals["category"][ldata.category], # type: ignore[index]
539
+ )
540
+ ldata.css_class = " ".join(css_classes) or "pln"
541
+
542
+ html_path = os.path.join(self.directory, ftr.html_filename)
543
+ html = self.source_tmpl.render(
544
+ {
545
+ **file_data.__dict__,
546
+ "contexts_json": contexts_json,
547
+ "prev_html": ftr.prev_html,
548
+ "next_html": ftr.next_html,
549
+ }
550
+ )
551
+ write_html(html_path, html)
552
+
553
+ # Save this file's information for the index page.
554
+ index_info = IndexItem(
555
+ url=ftr.html_filename,
556
+ file=escape(ftr.fr.relative_filename()),
557
+ nums=ftr.analysis.numbers,
558
+ )
559
+ self.index_pages["file"].summaries.append(index_info)
560
+ self.incr.set_index_info(ftr.rootname, index_info)
561
+
562
+ def write_file_index_page(self, first_html: str, final_html: str) -> None:
563
+ """Write the file index page for this report."""
564
+ index_file = self.write_index_page(
565
+ self.index_pages["file"],
566
+ first_html=first_html,
567
+ final_html=final_html,
568
+ )
569
+
570
+ print_href = stdout_link(index_file, f"file://{os.path.abspath(index_file)}")
571
+ self.coverage._message(f"Wrote HTML report to {print_href}")
572
+
573
+ # Write the latest hashes for next time.
574
+ self.incr.write()
575
+
576
+ def write_region_index_pages(self, files_to_report: Iterable[FileToReport]) -> None:
577
+ """Write the other index pages for this report."""
578
+ for ftr in files_to_report:
579
+ region_nouns = [pair[0] for pair in ftr.fr.code_region_kinds()]
580
+ num_lines = len(ftr.fr.source().splitlines())
581
+ regions = ftr.fr.code_regions()
582
+
583
+ for noun in region_nouns:
584
+ page_data = self.index_pages[noun]
585
+
586
+ outside_lines = set(range(1, num_lines + 1))
587
+ for region in regions:
588
+ if region.kind != noun:
589
+ continue
590
+ outside_lines -= region.lines
591
+
592
+ narrower = AnalysisNarrower(ftr.analysis)
593
+ narrower.add_regions(r.lines for r in regions if r.kind == noun)
594
+ narrower.add_regions([outside_lines])
595
+
596
+ for region in regions:
597
+ if region.kind != noun:
598
+ continue
599
+ analysis = narrower.narrow(region.lines)
600
+ if not self.should_report(analysis, page_data):
601
+ continue
602
+ sorting_name = region.name.rpartition(".")[-1].lstrip("_")
603
+ page_data.summaries.append(
604
+ IndexItem(
605
+ url=f"{ftr.html_filename}#t{region.start}",
606
+ file=escape(ftr.fr.relative_filename()),
607
+ description=(
608
+ f"<data value='{escape(sorting_name)}'>"
609
+ + escape(region.name)
610
+ + "</data>"
611
+ ),
612
+ nums=analysis.numbers,
613
+ )
614
+ )
615
+
616
+ analysis = narrower.narrow(outside_lines)
617
+ if self.should_report(analysis, page_data):
618
+ page_data.summaries.append(
619
+ IndexItem(
620
+ url=ftr.html_filename,
621
+ file=escape(ftr.fr.relative_filename()),
622
+ description=(
623
+ "<data value=''>"
624
+ + f"<span class='no-noun'>(no {escape(noun)})</span>"
625
+ + "</data>"
626
+ ),
627
+ nums=analysis.numbers,
628
+ )
629
+ )
630
+
631
+ for noun, index_page in self.index_pages.items():
632
+ if noun != "file":
633
+ self.write_index_page(index_page)
634
+
635
+ def write_index_page(self, index_page: IndexPage, **kwargs: str) -> str:
636
+ """Write an index page specified by `index_page`.
637
+
638
+ Returns the filename created.
639
+ """
640
+ skipped_covered_msg = skipped_empty_msg = ""
641
+ if n := index_page.skipped_covered_count:
642
+ word = plural(n, index_page.noun, index_page.plural)
643
+ skipped_covered_msg = f"{n} {word} skipped due to complete coverage."
644
+ if n := index_page.skipped_empty_count:
645
+ word = plural(n, index_page.noun, index_page.plural)
646
+ skipped_empty_msg = f"{n} empty {word} skipped."
647
+
648
+ index_buttons = [
649
+ {
650
+ "label": ip.plural.title(),
651
+ "url": ip.filename if ip.noun != index_page.noun else "",
652
+ "current": ip.noun == index_page.noun,
653
+ }
654
+ for ip in self.index_pages.values()
655
+ ]
656
+ render_data = {
657
+ "regions": index_page.summaries,
658
+ "totals": index_page.totals,
659
+ "noun": index_page.noun,
660
+ "region_noun": index_page.noun if index_page.noun != "file" else "",
661
+ "skip_covered": self.skip_covered,
662
+ "skipped_covered_msg": skipped_covered_msg,
663
+ "skipped_empty_msg": skipped_empty_msg,
664
+ "first_html": "",
665
+ "final_html": "",
666
+ "index_buttons": index_buttons,
667
+ }
668
+ render_data.update(kwargs)
669
+ html = self.index_tmpl.render(render_data)
670
+
671
+ index_file = os.path.join(self.directory, index_page.filename)
672
+ write_html(index_file, html)
673
+ return index_file
674
+
675
+
676
+ @dataclass
677
+ class FileInfo:
678
+ """Summary of the information from last rendering, to avoid duplicate work."""
679
+
680
+ hash: str = ""
681
+ index: IndexItem = field(default_factory=IndexItem)
682
+
683
+
684
+ class IncrementalChecker:
685
+ """Logic and data to support incremental reporting.
686
+
687
+ When generating an HTML report, often only a few of the source files have
688
+ changed since the last time we made the HTML report. This means previously
689
+ created HTML pages can be reused without generating them again, speeding
690
+ the command.
691
+
692
+ This class manages a JSON data file that captures enough information to
693
+ know whether an HTML page for a .py file needs to be regenerated or not.
694
+ The data file also needs to store all the information needed to create the
695
+ entry for the file on the index page so that if the HTML page is reused,
696
+ the index page can still be created to refer to it.
697
+
698
+ The data looks like::
699
+
700
+ {
701
+ "note": "This file is an internal implementation detail ...",
702
+ // A fixed number indicating the data format. STATUS_FORMAT
703
+ "format": 5,
704
+ // The version of coverage.py
705
+ "version": "7.4.4",
706
+ // A hash of a number of global things, including the configuration
707
+ // settings and the pyfile.html template itself.
708
+ "globals": "540ee119c15d52a68a53fe6f0897346d",
709
+ "files": {
710
+ // An entry for each source file keyed by the flat_rootname().
711
+ "z_7b071bdc2a35fa80___init___py": {
712
+ // Hash of the source, the text of the .py file.
713
+ "hash": "e45581a5b48f879f301c0f30bf77a50c",
714
+ // Information for the index.html file.
715
+ "index": {
716
+ "url": "z_7b071bdc2a35fa80___init___py.html",
717
+ "file": "cogapp/__init__.py",
718
+ "description": "",
719
+ // The Numbers for this file.
720
+ "nums": { "precision": 2, "n_files": 1, "n_statements": 43, ... }
721
+ }
722
+ },
723
+ ...
724
+ }
725
+ }
726
+
727
+ """
728
+
729
+ STATUS_FILE = "status.json"
730
+ STATUS_FORMAT = 5
731
+ NOTE = (
732
+ "This file is an internal implementation detail to speed up HTML report"
733
+ + " generation. Its format can change at any time. You might be looking"
734
+ + " for the JSON report: https://coverage.rtfd.io/cmd.html#cmd-json"
735
+ )
736
+
737
+ def __init__(self, directory: str) -> None:
738
+ self.directory = directory
739
+ self._reset()
740
+
741
+ def _reset(self) -> None:
742
+ """Initialize to empty. Causes all files to be reported."""
743
+ self.globals = ""
744
+ self.files: dict[str, FileInfo] = {}
745
+
746
+ def read(self) -> None:
747
+ """Read the information we stored last time."""
748
+ try:
749
+ status_file = os.path.join(self.directory, self.STATUS_FILE)
750
+ with open(status_file, encoding="utf-8") as fstatus:
751
+ status = json.load(fstatus)
752
+ except (OSError, ValueError):
753
+ # Status file is missing or malformed.
754
+ usable = False
755
+ else:
756
+ if status["format"] != self.STATUS_FORMAT:
757
+ usable = False
758
+ elif status["version"] != coverage.__version__:
759
+ usable = False
760
+ else:
761
+ usable = True
762
+
763
+ if usable:
764
+ self.files = {}
765
+ for filename, filedict in status["files"].items():
766
+ indexdict = filedict["index"]
767
+ index_item = IndexItem(**indexdict)
768
+ index_item.nums = Numbers(**indexdict["nums"])
769
+ fileinfo = FileInfo(
770
+ hash=filedict["hash"],
771
+ index=index_item,
772
+ )
773
+ self.files[filename] = fileinfo
774
+ self.globals = status["globals"]
775
+ else:
776
+ self._reset()
777
+
778
+ def write(self) -> None:
779
+ """Write the current status."""
780
+ status_file = os.path.join(self.directory, self.STATUS_FILE)
781
+ status_data = {
782
+ "note": self.NOTE,
783
+ "format": self.STATUS_FORMAT,
784
+ "version": coverage.__version__,
785
+ "globals": self.globals,
786
+ "files": {fname: dataclasses.asdict(finfo) for fname, finfo in self.files.items()},
787
+ }
788
+ with open(status_file, "w", encoding="utf-8") as fout:
789
+ json.dump(status_data, fout, separators=(",", ":"))
790
+
791
+ def check_global_data(self, *data: Any) -> None:
792
+ """Check the global data that can affect incremental reporting.
793
+
794
+ Pass in whatever global information could affect the content of the
795
+ HTML pages. If the global data has changed since last time, this will
796
+ clear the data so that all files are regenerated.
797
+
798
+ """
799
+ m = Hasher()
800
+ for d in data:
801
+ m.update(d)
802
+ these_globals = m.hexdigest()
803
+ if self.globals != these_globals:
804
+ self._reset()
805
+ self.globals = these_globals
806
+
807
+ def can_skip_file(self, data: CoverageData, fr: FileReporter, rootname: str) -> bool:
808
+ """Can we skip reporting this file?
809
+
810
+ `data` is a CoverageData object, `fr` is a `FileReporter`, and
811
+ `rootname` is the name being used for the file.
812
+
813
+ Returns True if the HTML page is fine as-is, False if we need to recreate
814
+ the HTML page.
815
+
816
+ """
817
+ m = Hasher()
818
+ m.update(fr.source().encode("utf-8"))
819
+ add_data_to_hash(data, fr.filename, m)
820
+ this_hash = m.hexdigest()
821
+
822
+ file_info = self.files.setdefault(rootname, FileInfo())
823
+
824
+ if this_hash == file_info.hash:
825
+ # Nothing has changed to require the file to be reported again.
826
+ return True
827
+ else:
828
+ # File has changed, record the latest hash and force regeneration.
829
+ file_info.hash = this_hash
830
+ return False
831
+
832
+ def index_info(self, fname: str) -> IndexItem:
833
+ """Get the information for index.html for `fname`."""
834
+ return self.files.get(fname, FileInfo()).index
835
+
836
+ def set_index_info(self, fname: str, info: IndexItem) -> None:
837
+ """Set the information for index.html for `fname`."""
838
+ self.files.setdefault(fname, FileInfo()).index = info
839
+
840
+
841
+ # Helpers for templates and generating HTML
842
+
843
+
844
+ def escape(t: str) -> str:
845
+ """HTML-escape the text in `t`.
846
+
847
+ This is only suitable for HTML text, not attributes.
848
+
849
+ """
850
+ # Convert HTML special chars into HTML entities.
851
+ return t.replace("&", "&amp;").replace("<", "&lt;")
852
+
853
+
854
+ def pair(ratio: tuple[int, int]) -> str:
855
+ """Format a pair of numbers so JavaScript can read them in an attribute."""
856
+ return "{} {}".format(*ratio)