summaryrefslogtreecommitdiff
path: root/coverage/report.py
blob: 1e14eb78ee53061fff5f388f33b10db314ee4cfe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt

"""Reporter foundation for coverage.py."""

from __future__ import annotations

import os
import sys

from typing import Callable, Iterable, Iterator, IO, Optional, Tuple, TYPE_CHECKING

from coverage.exceptions import NoDataError, NotPython
from coverage.files import prep_patterns, GlobMatcher
from coverage.misc import ensure_dir_for_file, file_be_gone
from coverage.plugin import FileReporter
from coverage.results import Analysis
from coverage.types import Protocol, TMorf

if TYPE_CHECKING:
    from coverage import Coverage


class Reporter(Protocol):
    """What we expect of reporters."""

    report_type: str

    def report(self, morfs: Optional[Iterable[TMorf]], outfile: IO[str]) -> float:
        """Generate a report of `morfs`, written to `outfile`."""


def render_report(
    output_path: str,
    reporter: Reporter,
    morfs: Optional[Iterable[TMorf]],
    msgfn: Callable[[str], None],
) -> float:
    """Run a one-file report generator, managing the output file.

    This function ensures the output file is ready to be written to. Then writes
    the report to it. Then closes the file and cleans up.

    """
    file_to_close = None
    delete_file = False

    if output_path == "-":
        outfile = sys.stdout
    else:
        # Ensure that the output directory is created; done here because this
        # report pre-opens the output file.  HtmlReporter does this on its own
        # because its task is more complex, being multiple files.
        ensure_dir_for_file(output_path)
        outfile = open(output_path, "w", encoding="utf-8")
        file_to_close = outfile
        delete_file = True

    try:
        ret = reporter.report(morfs, outfile=outfile)
        if file_to_close is not None:
            if sys.stdout.isatty():
                file_path = f"file://{os.path.abspath(output_path)}"
                print_path = f"\033]8;;{file_path}\a{output_path}\033]8;;\a"
            else:
                print_path = output_path
            msgfn(f"Wrote {reporter.report_type} to {print_path}")
        delete_file = False
        return ret
    finally:
        if file_to_close is not None:
            file_to_close.close()
            if delete_file:
                file_be_gone(output_path)           # pragma: part covered (doesn't return)


def get_analysis_to_report(
    coverage: Coverage,
    morfs: Optional[Iterable[TMorf]],
) -> Iterator[Tuple[FileReporter, Analysis]]:
    """Get the files to report on.

    For each morf in `morfs`, if it should be reported on (based on the omit
    and include configuration options), yield a pair, the `FileReporter` and
    `Analysis` for the morf.

    """
    file_reporters = coverage._get_file_reporters(morfs)
    config = coverage.config

    if config.report_include:
        matcher = GlobMatcher(prep_patterns(config.report_include), "report_include")
        file_reporters = [fr for fr in file_reporters if matcher.match(fr.filename)]

    if config.report_omit:
        matcher = GlobMatcher(prep_patterns(config.report_omit), "report_omit")
        file_reporters = [fr for fr in file_reporters if not matcher.match(fr.filename)]

    if not file_reporters:
        raise NoDataError("No data to report.")

    for fr in sorted(file_reporters):
        try:
            analysis = coverage._analyze(fr)
        except NotPython:
            # Only report errors for .py files, and only if we didn't
            # explicitly suppress those errors.
            # NotPython is only raised by PythonFileReporter, which has a
            # should_be_python() method.
            if fr.should_be_python():       # type: ignore[attr-defined]
                if config.ignore_errors:
                    msg = f"Couldn't parse Python file '{fr.filename}'"
                    coverage._warn(msg, slug="couldnt-parse")
                else:
                    raise
        except Exception as exc:
            if config.ignore_errors:
                msg = f"Couldn't parse '{fr.filename}': {exc}".rstrip()
                coverage._warn(msg, slug="couldnt-parse")
            else:
                raise
        else:
            yield (fr, analysis)