-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathopa_coverage_to_sonarcloud.py
executable file
·104 lines (88 loc) · 3.04 KB
/
opa_coverage_to_sonarcloud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import argparse
from dataclasses import dataclass, field
from typing import List
import json
import xml.etree.ElementTree as ET
import os
import time
import math
@dataclass
class RowInfo:
row: int
@dataclass
class LineCoverage:
start: RowInfo
end: RowInfo
@dataclass
class BaseCoverage:
coverage: int
covered_lines: int = 0
not_covered_lines: int = 0
@dataclass
class FileCoverage(BaseCoverage):
covered: List[LineCoverage] = field(default_factory=list)
not_covered: List[LineCoverage] = field(default_factory=list)
@dataclass
class OPACoverage(BaseCoverage):
files: dict[str, FileCoverage] = field(default_factory=dict)
@property
def lines_valid(self):
return self.covered_lines + self.not_covered_lines
def generate_sonarcloud_xml(coverage: OPACoverage) -> ET.Element:
coverage_xml = ET.Element("coverage", attrib={
"version": "1",
})
for path, data in coverage.files.items():
if isinstance(data, dict):
if not "coverage" in data:
data["coverage"] = 0
data = FileCoverage(**data)
file_data = ET.Element("file", attrib={
"path": path,
})
coverage_xml.append(file_data)
cover_map = {}
max_line = 1
for c in data.covered:
if isinstance(c, dict):
c = LineCoverage(**c)
if isinstance(c.start, dict):
c.start = RowInfo(**c.start)
if isinstance(c.end, dict):
c.end = RowInfo(**c.end)
max_line = max(max_line, c.end.row)
for i in range(c.start.row, c.end.row+1):
cover_map[i] = 1
for c in data.not_covered:
if isinstance(c, dict):
c = LineCoverage(**c)
if isinstance(c.start, dict):
c.start = RowInfo(**c.start)
if isinstance(c.end, dict):
c.end = RowInfo(**c.end)
max_line = max(max_line, c.end.row)
for i in range(c.start.row, c.end.row+1):
cover_map[i] = 0
for i in range(1, max_line+1):
if cover_map.get(i) is None:
continue
ET.SubElement(file_data, "lineToCover", attrib={
"lineNumber": str(i),
"covered": "true" if (cover_map[i] == 1) else "false",
})
return coverage_xml
if __name__ == "__main__":
# init args
parser = argparse.ArgumentParser(
prog='opa-coverage-to-sonarcloud',
description='Convert opa coverage report to SonarCloud format')
parser.add_argument("input", help='input json file')
parser.add_argument("output", help='output xml file')
args = parser.parse_args()
with open(args.input, encoding="utf-8") as fp:
content = json.load(fp)
overall_coverage = OPACoverage(**content)
sonarcloud_xml = generate_sonarcloud_xml(overall_coverage)
tree = ET.ElementTree(sonarcloud_xml)
ET.indent(tree)
tree.write(args.output, encoding="utf-8", xml_declaration=True)