Debian Codegraph @

ansible_collections/community/general/.azure-pipelines/scripts/publish-codecov.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # Copyright (c) Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 """
7 Upload code coverage reports to codecov.io.
8 Multiple coverage files from multiple languages are accepted and aggregated after upload.
9 Python coverage, as well as PowerShell and Python stubs can all be uploaded.
10 """
11
12 import argparse
13 import dataclasses
14 import pathlib
15 import shutil
16 import subprocess
17 import tempfile
18 import urllib.request
19
20
21 @dataclasses.dataclass(frozen=True)
22 class CoverageFile:
23 name: str
24 path: pathlib.Path
25 flags: list[str]
26
27
28 @dataclasses.dataclass(frozen=True)
29 class Args:
30 dry_run: bool
31 path: pathlib.Path
32
33
34 def parse_args() -> Args:
35 parser = argparse.ArgumentParser()
36 parser.add_argument("-n", "--dry-run", action="store_true")
37 parser.add_argument("path", type=pathlib.Path)
38
39 args = parser.parse_args()
40
41 # Store arguments in a typed dataclass
42 fields = dataclasses.fields(Args)
43 kwargs = {field.name: getattr(args, field.name) for field in fields}
44
45 return Args(**kwargs)
46
47
48 def process_files(directory: pathlib.Path) -> tuple[CoverageFile, ...]:
49 processed = []
50 for file in directory.joinpath("reports").glob("coverage*.xml"):
51 name = file.stem.replace("coverage=", "")
52
53 # Get flags from name
54 flags = name.replace("-powershell", "").split("=") # Drop '-powershell' suffix
55 flags = [
56 flag if not flag.startswith("stub") else flag.split("-")[0] for flag in flags
57 ] # Remove "-01" from stub files
58
59 processed.append(CoverageFile(name, file, flags))
60
61 return tuple(processed)
62
63
64 def upload_files(codecov_bin: pathlib.Path, files: tuple[CoverageFile, ...], dry_run: bool = False) -> None:
65 for file in files:
66 cmd = [
67 str(codecov_bin),
68 "--name",
69 file.name,
70 "--file",
71 str(file.path),
72 ]
73 for flag in file.flags:
74 cmd.extend(["--flags", flag])
75
76 if dry_run:
77 print(f"DRY-RUN: Would run command: {cmd}")
78 continue
79
80 subprocess.run(cmd, check=True)
81
82
83 def download_file(url: str, dest: pathlib.Path, flags: int, dry_run: bool = False) -> None:
84 if dry_run:
85 print(f"DRY-RUN: Would download {url} to {dest} and set mode to {flags:o}")
86 return
87
88 with urllib.request.urlopen(url) as resp:
89 with dest.open("w+b") as f:
90 # Read data in chunks rather than all at once
91 shutil.copyfileobj(resp, f, 64 * 1024)
92
93 dest.chmod(flags)
94
95
96 def main():
97 args = parse_args()
98 url = "https://ansible-ci-files.s3.amazonaws.com/codecov/linux/codecov"
99 with tempfile.TemporaryDirectory(prefix="codecov-") as tmpdir:
100 codecov_bin = pathlib.Path(tmpdir) / "codecov"
101 download_file(url, codecov_bin, 0o755, args.dry_run)
102
103 files = process_files(args.path)
104 upload_files(codecov_bin, files, args.dry_run)
105
106
107 if __name__ == "__main__":
108 main()