-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoverage.js
186 lines (158 loc) · 5.53 KB
/
coverage.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
const fs = require('fs');
const path = require('path');
const { table } = require('table');
const dir = process.cwd();
function divideCalculate(numerator, denominator) {
if (denominator === 0 || isNaN(denominator)) {
return 0;
} else {
return (numerator / denominator) * 100;
}
}
function calculatePercentage(numerator, denominator, digits = 2, percentsign = true) {
const result = divideCalculate(numerator, denominator);
return percentsign ? result.toFixed(digits) + '%' : result.toFixed(digits);
}
function getTransformedContractFiles(contractFiles) {
const results = Object.entries(contractFiles).map(([address, contents]) =>
contents.reduce((result, value) => {
if (value.length > 0) {
const [filename, code] = value;
result[`${address}__${filename}`] = code;
}
return result;
}, {}),
);
return Object.assign({}, ...results);
}
function getTransformedCoverageJson(coverageJson, transformedContractFiles) {
const results = {};
if (!coverageJson.coverage) return results;
for (const [key, value] of Object.entries(coverageJson.coverage)) {
for (const item of value.covered_code) {
const contractAddress = key.match(/0x([a-fA-F0-9]+)/)?.[0];
const combinedKey = `${contractAddress}__${item.file}`;
const code = transformedContractFiles[combinedKey];
if (!code) continue;
if (!results.hasOwnProperty(combinedKey)) {
results[combinedKey] = [];
}
const word = code.slice(item.offset, item.offset + item.length);
results[combinedKey].push({ ...item, word });
}
}
return results;
}
function getHighlightLineCount(arr, code) {
let lineWords = {};
for (let item of arr) {
let lineNumber = (code.substring(0, item.offset + item.length).match(/\n/g) || []).length + 1;
if (!lineWords[lineNumber]) {
lineWords[lineNumber] = [];
}
lineWords[lineNumber].push(item.word);
}
return Object.keys(lineWords).length;
}
function generateHTML(table) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contract coverage</title>
<style>
table {
width: 100%;
border-collapse: collapse;
border-spacing: 0px;
}
table,
th,
td {
padding: 5px;
border: 1px solid black;
text-align: center;
}
</style>
</head>
<body>
<table>
<tr>
<th>Contract Address</th>
<th>File Name</th>
<th>Coverage</th>
</tr>
${table}
</table>
</body>
</html>
`;
}
function buildCoveragePage() {
let data = [['Contract Address', 'File Name', 'Coverage']];
let output = '';
let files;
try {
files = fs.readFileSync(path.join(dir, 'workdir/files.json'));
} catch (err) {
console.log('files.json not found, skipping coverage page generation');
return;
}
const filesJson = JSON.parse(files.toString());
let coverage;
try {
coverage = fs.readFileSync(path.join(dir, 'workdir/coverage.json'));
} catch (err) {
console.log('coverage.json not found, skipping coverage page generation');
return;
}
const coverageJson = JSON.parse(coverage.toString());
const transformedContractFiles = getTransformedContractFiles(filesJson);
const transformedCoverageJson = getTransformedCoverageJson(coverageJson, transformedContractFiles);
Object.entries(transformedCoverageJson)
.sort((a, b) => {
const [keyA, valueA] = a;
const [keyB, valueB] = b;
const highlighLineCountA = getHighlightLineCount(valueA, transformedContractFiles[keyA]);
const highlightBlockCountA = highlighLineCountA / transformedContractFiles[keyA].split('\n').length;
const highlighLineCountB = getHighlightLineCount(valueB, transformedContractFiles[keyB]);
const highlightBlockCountB = highlighLineCountB / transformedContractFiles[keyB].split('\n').length;
return highlightBlockCountB - highlightBlockCountA;
})
.map(([key, value]) => {
const [address, filename] = key.split('__');
const code = transformedContractFiles[key];
const lineCount = (code.match(/\n/g) || []).length + 1;
const highlightLineCount = getHighlightLineCount(value, code);
const coverage = calculatePercentage(highlightLineCount, lineCount);
output += `<tr>
<td>${address}</td>
<td>${filename}</td>
<td>${coverage}</td>
</tr>`;
data.push([address, filename, coverage]);
});
console.log(table(data));
try {
fs.writeFileSync('./workdir/coverage.html', generateHTML(output));
} catch (err) {
console.error('save file error: ', err);
}
}
function handleBuildCoverage() {
const directoryToWatch = './workdir';
const filesToCheck = ['files.json', 'coverage.json'];
const checkFilesExistence = () => {
const filesExist = filesToCheck.every((file) => fs.existsSync(`${directoryToWatch}/${file}`));
if (filesExist) {
buildCoveragePage();
fs.unwatchFile(directoryToWatch);
}
};
fs.watchFile(directoryToWatch, checkFilesExistence);
}
module.exports = {
handleBuildCoverage,
};