Skip to content

livery.extensions.coverage._render

livery.extensions.coverage._render

Draw one package's coverage pages from its files' readings in the line format.

livery.extensions.coverage._render.render writes a package's tree: an index of its files, an index of its functions and one of its classes, a page per file with its source highlighted line by line, and the stylesheet and script every page shares, which ship in this extension's content/assets. The numbers are coverage.py's (livery.extensions.coverage._format.numbers): the statements, branches and percentages its report shows, and the category it draws each line in. Beyond them, a page shows how many times each line ran for a measurer that counts runs, a measurer's numbered branches and its counts of a line's branches, the code of a line that ran which never did for a measurer that reads columns, who measured each file, where the measurement comes from, and the package's floor. The pages depend on the readings alone: drawing the same readings again writes the same tree.

Classes:

Name Description
Drawn

One file to draw.

Report

One package's pages: what to draw, and what to say about it.

Functions:

Name Description
render

Write report's pages into into, replacing what was there; the totals.

page_name

The page drawn for the file at name: its name, and its directory's digest.

line_categories

The category of each line from 1 to count, as coverage.py draws it.

jumps

The jumps from line that never ran: each one's short and long annotation.

unrun_marks

The characters of each line that ran whose code never did, by the ranges.

highlighted

text as HTML, line by line, highlighted by Pygments' lexer for name.

source_lines

text's lines, numbered as coverage.py numbers them.

Attributes:

Name Type Description
ASSETS
STYLE
SCRIPT
REGION_KINDS
CATEGORIES
ANYWHERE
EMPTY_CONTEXT
ARROW

ASSETS module-attribute

ASSETS = Path(__file__).resolve().parent / 'content' / 'assets'

STYLE module-attribute

STYLE = 'coverage.css'

SCRIPT module-attribute

SCRIPT = 'coverage.js'

REGION_KINDS module-attribute

REGION_KINDS = (('function', 'functions'), ('class', 'classes'))

CATEGORIES module-attribute

CATEGORIES = ('exc', 'mis', 'par', 'run', 'exc2', 'mis2', 'par2', 'run2')

ANYWHERE module-attribute

ANYWHERE = "line {line} didn't jump anywhere: it always raised an exception."

EMPTY_CONTEXT module-attribute

EMPTY_CONTEXT = '(empty)'

ARROW module-attribute

ARROW = '\u202f↛\u202f'

Drawn dataclass

Drawn(name: str, merged: Merged, text: str | None, digest: str = '')

One file to draw.

Attributes:

Name Type Description
name str

The file's path from the workspace root.

merged Merged

Its merged reading.

text str | None

The checkout's text of the file when it is the content measured; None when the checkout holds other content.

digest str

The checkout's git blob id of the file.

name instance-attribute

name: str

merged instance-attribute

merged: Merged

text instance-attribute

text: str | None

digest class-attribute instance-attribute

digest: str = ''

Report dataclass

Report(title: str, files: tuple[Drawn, ...], contexts: tuple[str, ...] = (), notes: tuple[str, ...] = (), absent: tuple[str, ...] = (), precision: int = 0, floor: str = '')

One package's pages: what to draw, and what to say about it.

Attributes:

Name Type Description
title str

What the pages cover: packages/workshop.

files tuple[Drawn, ...]

The files to draw.

contexts tuple[str, ...]

The contexts a reading's reached indexes name.

notes tuple[str, ...]

Lines the index states under its heading: where the measurement comes from, and the commit drawn.

absent tuple[str, ...]

The measured files the checkout no longer has.

precision int

The decimals a percentage shows.

floor str

The line each index states under its heading about the package's floor; empty for none.

title instance-attribute

title: str

files instance-attribute

files: tuple[Drawn, ...]

contexts class-attribute instance-attribute

contexts: tuple[str, ...] = ()

notes class-attribute instance-attribute

notes: tuple[str, ...] = ()

absent class-attribute instance-attribute

absent: tuple[str, ...] = ()

precision class-attribute instance-attribute

precision: int = 0

floor class-attribute instance-attribute

floor: str = ''

render

render(into: Path, report: Report) -> Numbers

Write report's pages into into, replacing what was there; the totals.

into is removed and written afresh, so a file that left the report leaves no page behind. Each page is written with LF line endings, so one report gives the same bytes on every platform.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def render(into: Path, report: Report) -> Numbers:
    """Write *report*'s pages into *into*, replacing what was there; the totals.

    *into* is removed and written afresh, so a file that left the
    report leaves no page behind. Each page is written with LF line
    endings, so one report gives the same bytes on every platform.
    """
    shutil.rmtree(into, ignore_errors=True)
    into.mkdir(parents=True)
    assets = {name: _copy_asset(into, name) for name in (STYLE, SCRIPT)}
    files = sorted(report.files, key=lambda drawn: drawn.name)
    pages = [page_name(drawn.name) for drawn in files]
    totals = Numbers()
    rows: list[tuple[Drawn, Numbers]] = []
    for drawn in files:
        counted = numbers(drawn.merged.entry, drawn.merged.measurer)
        rows.append((drawn, counted))
        totals += counted
    kinds = [
        (noun, plural)
        for noun, plural in REGION_KINDS
        if any(noun in drawn.merged.measurer.regions for drawn in files)
    ]
    branched = any(_has_branches(drawn) for drawn in files)
    page = _Pages(report, assets, branched, kinds)
    for index, (drawn, counted) in enumerate(rows):
        before = pages[index - 1] if index else "index.html"
        after = pages[index + 1] if index + 1 < len(pages) else "index.html"
        _write(into / pages[index], page.file(drawn, counted, before, after))
    first = pages[0] if pages else "index.html"
    last = pages[-1] if pages else "index.html"
    index_rows = [
        _Row(drawn.name, pages[index], "", "", counted)
        for index, (drawn, counted) in enumerate(rows)
    ]
    _write(into / "index.html", page.index("file", index_rows, totals, last, first))
    for noun, _plural in kinds:
        region_index: list[_Row] = []
        for index, (drawn, _counted) in enumerate(rows):
            if noun not in drawn.merged.measurer.regions:
                continue
            for region, narrowed in region_rows(drawn.merged.entry, noun):
                counted = numbers(narrowed, drawn.merged.measurer)
                if region is None:
                    region_index.append(
                        _Row(drawn.name, pages[index], f"(no {noun})", "", counted)
                    )
                    continue
                region_index.append(
                    _Row(
                        drawn.name,
                        f"{pages[index]}#t{region.start}",
                        region.name,
                        region.name.rpartition(".")[2].lstrip("_"),
                        counted,
                    )
                )
        _write(
            into / f"{noun}_index.html",
            page.index(noun, region_index, totals, last, first),
        )
    return totals

page_name

page_name(name: str) -> str

The page drawn for the file at name: its name, and its directory's digest.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def page_name(name: str) -> str:
    """The page drawn for the file at *name*: its name, and its directory's digest."""
    path = PurePosixPath(name)
    folder = hashlib.sha1(
        str(path.parent).encode("utf-8"), usedforsecurity=False
    ).hexdigest()[:8]
    stem = re.sub(r"[^A-Za-z0-9_-]", "_", path.name)
    return f"f_{folder}_{stem}.html"

line_categories

line_categories(entry: Entry, count: int) -> list[str]

The category of each line from 1 to count, as coverage.py draws it.

Excluded first, then missing, then partial, then run; a later line of a statement written over several lines takes its first line's category with a 2, and any other line has none, an empty string.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def line_categories(entry: Entry, count: int) -> list[str]:
    """The category of each line from 1 to *count*, as coverage.py draws it.

    Excluded first, then missing, then partial, then run; a later line
    of a statement written over several lines takes its first line's
    category with a ``2``, and any other line has none, an empty string.
    """
    missing = entry.missing
    partial = entry.partial
    first_of = {
        line: first for first, last in entry.spans for line in range(first, last + 1)
    }
    found: list[str] = []
    for line in range(1, count + 1):
        own = _category(line, entry, missing, partial)
        if own:
            found.append(own)
            continue
        first = first_of.get(line)
        if first is None:
            found.append("")
            continue
        of_first = _category(first, entry, missing, partial)
        found.append(f"{of_first}2" if of_first else "")
    return found

jumps

jumps(merged: Merged, line: int) -> list[tuple[str, str]]

The jumps from line that never ran: each one's short and long annotation.

coverage.py's wording: 12 ↛ 15 and 12 ↛ exit beside the sentence that says why, or 12 ↛ anywhere when no branch of the line ran. A measurer that numbers branches names them branch 1, an exception's path branch 1 (throw), and one that counts a line's branches says how many of them ran.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def jumps(merged: Merged, line: int) -> list[tuple[str, str]]:
    """The jumps from *line* that never ran: each one's short and long annotation.

    coverage.py's wording: ``12 ↛ 15`` and ``12 ↛ exit`` beside the
    sentence that says why, or ``12 ↛ anywhere`` when no branch of the
    line ran. A measurer that numbers branches names them ``branch 1``,
    an exception's path ``branch 1 (throw)``, and one that counts a
    line's branches says how many of them ran.
    """
    entry = merged.entry
    own = [branch for branch in entry.branches if branch.source == line]
    untaken = [branch for branch in own if branch.taken == 0]
    found: list[tuple[str, str]] = []
    if untaken and merged.measurer.branches == TARGETS and len(untaken) == len(own):
        found.append((f"{line}{ARROW}anywhere", ANYWHERE.format(line=line)))
    else:
        found.extend(_jump(branch, merged.measurer.branches) for branch in untaken)
    for at, total, ran in entry.branch_counts:
        if at == line and ran < total:
            found.append(
                (f"{ran} of {total}", f"{ran} of line {line}'s {total} branches ran")
            )
    return found

unrun_marks

unrun_marks(entry: Entry, text: str) -> dict[int, list[tuple[int, int]]]

The characters of each line that ran whose code never did, by the ranges.

Per line of text, each stretch from its first character's index to the index after its last. A range's columns count bytes, so a line with characters beyond ASCII has its stretches moved to the characters those bytes belong to. A line that never ran is drawn missing whole and has none.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def unrun_marks(entry: Entry, text: str) -> dict[int, list[tuple[int, int]]]:
    """The characters of each line that ran whose code never did, by the ranges.

    Per line of *text*, each stretch from its first character's index
    to the index after its last. A range's columns count bytes, so a
    line with characters beyond ASCII has its stretches moved to the
    characters those bytes belong to. A line that never ran is drawn
    missing whole and has none.
    """
    lines = source_lines(text)
    executed = entry.executed
    found: dict[int, list[tuple[int, int]]] = {}
    for line, spans in unrun_columns(entry).items():
        if line not in executed or line > len(lines):
            continue
        starts: list[int] = []
        width = 0
        for char in lines[line - 1]:
            starts.append(width)
            width += len(char.encode("utf-8"))
        marked = [
            (
                bisect.bisect_left(starts, start - 1),
                bisect.bisect_left(starts, width if end is None else end - 1),
            )
            for start, end in spans
        ]
        kept = [(start, end) for start, end in marked if start < end]
        if kept:
            found[line] = kept
    return found

highlighted

highlighted(name: str, text: str, marks: Mapping[int, Sequence[tuple[int, int]]] | None = None) -> list[str]

text as HTML, line by line, highlighted by Pygments' lexer for name.

A name no lexer claims is drawn as plain text. Each line is HTML without its line ending; a token over several lines is split at each, and a CRLF or a lone CR ends a line as LF does (livery.extensions.coverage._render.source_lines). marks names, by line, the stretches of characters that never ran, as unrun_marks gives them: each piece of a token inside one is drawn with the class nr beside the token's own.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def highlighted(
    name: str, text: str, marks: Mapping[int, Sequence[tuple[int, int]]] | None = None
) -> list[str]:
    """*text* as HTML, line by line, highlighted by Pygments' lexer for *name*.

    A name no lexer claims is drawn as plain text. Each line is HTML
    without its line ending; a token over several lines is split at
    each, and a CRLF or a lone CR ends a line as LF does
    ([livery.extensions.coverage._render.source_lines][]). *marks*
    names, by line, the stretches of characters that never ran, as
    `unrun_marks` gives them: each piece of a token inside one is drawn
    with the class ``nr`` beside the token's own.
    """
    from pygments.lexers import get_lexer_for_filename
    from pygments.lexers.special import TextLexer
    from pygments.util import ClassNotFound

    text = _newlines(text)
    try:
        lexer = get_lexer_for_filename(name, text, stripnl=False, ensurenl=False)
    except ClassNotFound:
        lexer = TextLexer(stripnl=False, ensurenl=False)
    lines: list[list[str]] = [[]]
    offset = 0
    for kind, value in lexer.get_tokens(text):
        css = _token_class(kind)
        for index, piece in enumerate(value.split("\n")):
            if index:
                lines.append([])
                offset = 0
            if not piece:
                continue
            marked = (marks or {}).get(len(lines), ())
            for start, end, unrun in _pieces(offset, len(piece), marked):
                escaped = html.escape(piece[start - offset : end - offset], quote=False)
                classes = f"{css} nr".strip() if unrun else css
                lines[-1].append(
                    f'<span class="{classes}">{escaped}</span>' if classes else escaped
                )
            offset += len(piece)
    drawn = ["".join(line) for line in lines]
    count = len(source_lines(text))
    return (drawn + [""] * count)[:count]

source_lines

source_lines(text: str) -> list[str]

text's lines, numbered as coverage.py numbers them.

coverage.py reads a source's CRLF and lone CR line endings as LF, so a file checked out with CRLF on Windows has the lines it has elsewhere, and none of them ends in a carriage return.

Source code in packages/extensions/coverage/src/livery/extensions/coverage/_render.py
def source_lines(text: str) -> list[str]:
    """*text*'s lines, numbered as coverage.py numbers them.

    coverage.py reads a source's CRLF and lone CR line endings as LF,
    so a file checked out with CRLF on Windows has the lines it has
    elsewhere, and none of them ends in a carriage return.
    """
    lines = _newlines(text).split("\n")
    if lines and lines[-1] == "":
        lines.pop()
    return lines