Debian Codegraph @

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

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