Debian Codegraph @

ansible_collections/microsoft/ad/.azure-pipelines/scripts/publish-codecov.py

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