Debian Codegraph @

.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
8 from __future__ import annotations
9
10 import argparse
11 import dataclasses
12 import pathlib
13 import shlex
14 import subprocess
15 import tempfile
16 import typing as t
17 import venv
18
19 SCRIPTS_DIR = pathlib.Path(__file__).parent.resolve()
20 DEPS_DIR = SCRIPTS_DIR / 'dependencies'
21
22
23 @dataclasses.dataclass(frozen=True)
24 class CoverageFile:
25 name: str
26 path: pathlib.Path
27 flags: t.List[str]
28
29
30 @dataclasses.dataclass(frozen=True)
31 class Args:
32 dry_run: bool
33 path: pathlib.Path
34
35
36 def parse_args() -> Args:
37 parser = argparse.ArgumentParser()
38 parser.add_argument('-n', '--dry-run', action='store_true')
39 parser.add_argument('path', type=pathlib.Path)
40
41 args = parser.parse_args()
42
43 # Store arguments in a typed dataclass
44 fields = dataclasses.fields(Args)
45 kwargs = {field.name: getattr(args, field.name) for field in fields}
46
47 return Args(**kwargs)
48
49
50 def run(
51 *args: str | pathlib.Path,
52 dry_run: bool = False,
53 ) -> None:
54 """
55 Log and run given command.
56
57 The command is not actually executed if ``dry_run`` is truthy.
58 """
59 cmd = [str(arg) for arg in args]
60
61 dry_prefix = '[would run] ' if dry_run else ''
62 print(f'==> {dry_prefix}{shlex.join(cmd)}', flush=True)
63
64 if not dry_run:
65 subprocess.run(cmd, check=True)
66
67
68 def install_codecov(dest: pathlib.Path, dry_run: bool = False) -> pathlib.Path:
69 """Populate a transitively pinned venv with ``codecov-cli``."""
70 requirement_file = DEPS_DIR / 'codecov.in'
71 constraint_file = requirement_file.with_suffix('.txt')
72
73 venv_dir = dest / 'venv'
74 python_bin = venv_dir / 'bin' / 'python'
75 codecov_bin = venv_dir / 'bin' / 'codecovcli'
76
77 venv.create(venv_dir, with_pip=True)
78
79 run(
80 python_bin,
81 '-m',
82 'pip',
83 'install',
84 f'--constraint={constraint_file!s}',
85 f'--requirement={requirement_file!s}',
86 '--disable-pip-version-check',
87 dry_run=dry_run,
88 )
89
90 return codecov_bin
91
92
93 def process_files(directory: pathlib.Path) -> t.Tuple[CoverageFile, ...]:
94 processed = []
95 for file in directory.joinpath('reports').glob('coverage*.xml'):
96 name = file.stem.replace('coverage=', '')
97
98 # Get flags from name
99 flags = name.replace('-powershell', '').split('=') # Drop '-powershell' suffix
100 flags = [flag if not flag.startswith('stub') else flag.split('-')[0] for flag in flags] # Remove "-01" from stub files
101
102 processed.append(CoverageFile(name, file, flags))
103
104 return tuple(processed)
105
106
107 def upload_files(codecov_bin: pathlib.Path, config_file: pathlib.Path, files: t.Tuple[CoverageFile, ...], dry_run: bool = False) -> None:
108 for file in files:
109 cmd = [
110 codecov_bin,
111 '--disable-telem',
112 '--codecov-yml-path',
113 config_file,
114 'upload-process',
115 '--disable-search',
116 '--disable-file-fixes',
117 '--plugin',
118 'noop',
119 '--name',
120 file.name,
121 '--file',
122 file.path,
123 ]
124
125 for flag in file.flags:
126 cmd.extend(['--flag', flag])
127
128 if dry_run:
129 cmd.append('--dry-run')
130
131 run(*cmd)
132
133
134 def report_upload_completion(
135 codecov_bin: pathlib.Path,
136 config_file: pathlib.Path,
137 dry_run: bool = False,
138 ) -> None:
139 """Notify Codecov backend that all reports we wanted are in."""
140 cmd = [
141 codecov_bin,
142 '--disable-telem',
143 f'--codecov-yml-path={config_file}',
144 'send-notifications',
145 ]
146
147 run(*cmd, dry_run=dry_run)
148
149
150 def main() -> None:
151 args = parse_args()
152
153 with tempfile.TemporaryDirectory(prefix='codecov-') as tmpdir:
154 config_file = pathlib.Path(tmpdir) / 'config.yml'
155 # Refs:
156 # * https://docs.codecov.com/docs/codecovyml-reference#codecovnotifymanual_trigger
157 # * https://docs.codecov.com/docs/notifications#preventing-notifications-until-youre-ready-to-send-notifications
158 config_file.write_text('codecov:\n notify:\n manual_trigger: true')
159
160 codecov_bin = install_codecov(
161 pathlib.Path(tmpdir),
162 dry_run=args.dry_run,
163 )
164 files = process_files(args.path)
165 upload_files(codecov_bin, config_file, files, args.dry_run)
166 # Ref: https://docs.codecov.com/docs/cli-options#send-notifications
167 report_upload_completion(codecov_bin, config_file, args.dry_run)
168
169
170 if __name__ == '__main__':
171 main()