1# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
3
4"""Reporter foundation for coverage.py."""
5import sys
6
7from coverage import env
8from coverage.files import prep_patterns, FnmatchMatcher
9from coverage.misc import CoverageException, NoSource, NotPython, ensure_dir_for_file, file_be_gone
10
11
12def render_report(output_path, reporter, morfs):
13    """Run the provided reporter ensuring any required setup and cleanup is done
14
15    At a high level this method ensures the output file is ready to be written to. Then writes the
16    report to it. Then closes the file and deletes any garbage created if necessary.
17    """
18    file_to_close = None
19    delete_file = False
20    if output_path:
21        if output_path == '-':
22            outfile = sys.stdout
23        else:
24            # Ensure that the output directory is created; done here
25            # because this report pre-opens the output file.
26            # HTMLReport does this using the Report plumbing because
27            # its task is more complex, being multiple files.
28            ensure_dir_for_file(output_path)
29            open_kwargs = {}
30            if env.PY3:
31                open_kwargs['encoding'] = 'utf8'
32            outfile = open(output_path, "w", **open_kwargs)
33            file_to_close = outfile
34    try:
35        return reporter.report(morfs, outfile=outfile)
36    except CoverageException:
37        delete_file = True
38        raise
39    finally:
40        if file_to_close:
41            file_to_close.close()
42            if delete_file:
43                file_be_gone(output_path)
44
45
46def get_analysis_to_report(coverage, morfs):
47    """Get the files to report on.
48
49    For each morf in `morfs`, if it should be reported on (based on the omit
50    and include configuration options), yield a pair, the `FileReporter` and
51    `Analysis` for the morf.
52
53    """
54    file_reporters = coverage._get_file_reporters(morfs)
55    config = coverage.config
56
57    if config.report_include:
58        matcher = FnmatchMatcher(prep_patterns(config.report_include))
59        file_reporters = [fr for fr in file_reporters if matcher.match(fr.filename)]
60
61    if config.report_omit:
62        matcher = FnmatchMatcher(prep_patterns(config.report_omit))
63        file_reporters = [fr for fr in file_reporters if not matcher.match(fr.filename)]
64
65    if not file_reporters:
66        raise CoverageException("No data to report.")
67
68    for fr in sorted(file_reporters):
69        try:
70            analysis = coverage._analyze(fr)
71        except NoSource:
72            if not config.ignore_errors:
73                raise
74        except NotPython:
75            # Only report errors for .py files, and only if we didn't
76            # explicitly suppress those errors.
77            # NotPython is only raised by PythonFileReporter, which has a
78            # should_be_python() method.
79            if fr.should_be_python():
80                if config.ignore_errors:
81                    msg = "Couldn't parse Python file '{}'".format(fr.filename)
82                    coverage._warn(msg, slug="couldnt-parse")
83                else:
84                    raise
85        else:
86            yield (fr, analysis)
87