-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProcessCoverage.swift
More file actions
executable file
·390 lines (355 loc) · 11.6 KB
/
Copy pathProcessCoverage.swift
File metadata and controls
executable file
·390 lines (355 loc) · 11.6 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/swift
//
// Postprocesses an LLVM coverage report, as output by `swift test --enable-coverage`.
//
// - Filters files out of the report that are not interesting (tests, package
// dependencies)
// - Generates an HTML report of the coverage, with annotated source code
// - Prints a summary report to standard output
// - Generates an SVG of a coverage badge that can be used in the README
//
import Foundation
let inputPath = CommandLine.arguments[1]
let outputPath = CommandLine.arguments[2]
let htmlOutputPath = CommandLine.arguments[3]
let badgeOutputPath = CommandLine.arguments[4]
var report = try JSONDecoder().decode(
CoverageReport.self,
from: try Data(contentsOf: URL(fileURLWithPath: inputPath))
)
// Filter out data we don't need
// Ideally, this wouldn't be necessary, and we could specify not to record coverage for
// these files
for di in report.data.indices {
report.data[di].files.removeAll(where: { f in
f.filename.contains("Tests/") || f.filename.contains(".build/")
})
// Update (some) totals
(report.data[di].totals.lines.covered, report.data[di].totals.lines.count) =
report.data[di].files.reduce(
(0, 0),
{ acc, next in
(
acc.0 + next.summary.lines.covered,
acc.1 + next.summary.lines.count
)
})
report.data[di].totals.lines.percent =
100 * Float(report.data[di].totals.lines.covered) / Float(report.data[di].totals.lines.count)
}
// Write out filtered report
FileManager.default.createFile(
atPath: outputPath,
contents: try JSONEncoder().encode(report)
)
////////////////////////////////////////////////////////////////////////////////
// Summary report
////////////////////////////////////////////////////////////////////////////////
var totalCovered = 0
var totalCount = 0
print("Code coverage (lines):")
for d in report.data {
for f in d.files {
let filename = f.filename.stripPrefix(FileManager.default.currentDirectoryPath + "/")
let lines = String(format: "%d/%d", f.summary.lines.covered, f.summary.lines.count)
let percent = String(
format: "(%.01f%%)", Float(f.summary.lines.covered * 100) / Float(f.summary.lines.count))
print(
" \(filename.rightPadded(toLength: 24)) \(lines.leftPadded(toLength: 10)) \(percent.leftPadded(toLength: 8))"
)
}
totalCovered += d.totals.lines.covered
totalCount += d.totals.lines.count
}
let lines = String(format: "%d/%d", totalCovered, totalCount)
let percent = String(
format: "(%.01f%%)", Float(totalCovered * 100) / Float(totalCount))
print(" ---")
print(
" \("TOTAL".rightPadded(toLength: 24)) \(lines.leftPadded(toLength: 10)) \(percent.leftPadded(toLength: 8))"
)
////////////////////////////////////////////////////////////////////////////////
// Coverage badge
////////////////////////////////////////////////////////////////////////////////
let percentRounded = Int((Float(totalCovered * 100) / Float(totalCount)).rounded())
FileManager.default.createFile(
atPath: badgeOutputPath,
contents: Data(
"""
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Coverage - \(percent)%</title>
<defs>
<linearGradient id="workflow-fill" x1="50%" y1="0%" x2="50%" y2="100%">
<stop stop-color="#444D56" offset="0%"></stop>
<stop stop-color="#24292E" offset="100%"></stop>
</linearGradient>
<linearGradient id="state-fill" x1="50%" y1="0%" x2="50%" y2="100%">
<stop stop-color="#34D058" offset="0%"></stop>
<stop stop-color="#28A745" offset="100%"></stop>
</linearGradient>
</defs>
<g fill="none" fill-rule="evenodd">
<g font-family="'DejaVu Sans',Verdana,Geneva,sans-serif" font-size="11">
<path id="workflow-bg" d="M0,3 C0,1.3431 1.3552,0 3.02702703,0 L65,0 L65,20 L3.02702703,20 C1.3552,20 0,18.6569 0,17 L0,3 Z" fill="url(#workflow-fill)" fill-rule="nonzero"></path>
<text fill="#010101" fill-opacity=".3">
<tspan x="6" y="15" aria-hidden="true">Coverage</tspan>
</text>
<text fill="#FFFFFF">
<tspan x="6" y="14">Coverage</tspan>
</text>
</g>
<g transform="translate(65)" font-family="'DejaVu Sans',Verdana,Geneva,sans-serif" font-size="11">
<path d="M0 0h46.939C48.629 0 40 1.343 40 3v14c0 1.657-1.37 3-3.061 3H0V0z" id="state-bg" fill="url(#state-fill)" fill-rule="nonzero"></path>
<text fill="#010101" fill-opacity=".3" aria-hidden="true">
<tspan x="7" y="15">\(percentRounded)%</tspan>
</text>
<text fill="#FFFFFF">
<tspan x="7" y="14">\(percentRounded)%</tspan>
</text>
</g>
</g>
</svg>
""".utf8
))
////////////////////////////////////////////////////////////////////////////////
// HTML Report
////////////////////////////////////////////////////////////////////////////////
var out = ""
var files = ""
var fileID = 0
for d in report.data {
for f in d.files {
let filename = f.filename.stripPrefix(FileManager.default.currentDirectoryPath + "/")
let percent = String(
format: "%.01f", Float(f.summary.lines.covered * 100) / Float(f.summary.lines.count))
files += "<option value=\"f\(fileID)\">\(filename.htmlEscaped) (\(percent)%)</option>"
out += "<pre id=\"f\(fileID)\" style=\"display: none\"><span>"
var segments = f.segments
for (index, line) in try
(String(contentsOfFile: f.filename, encoding: .utf8).split(omittingEmptySubsequences: false) {
$0.isNewline
})
.enumerated()
{
var l = line
var columnOffset = 0
while let segment = segments.first {
if segment.line != index + 1 {
break
}
var endIndex = l.utf8.index(l.startIndex, offsetBy: segment.column - 1 - columnOffset)
if endIndex > l.endIndex {
endIndex = l.endIndex
}
columnOffset = segment.column - 1
let spanClass = !segment.hasCount ? "" : segment.count > 0 ? "c" : "nc"
out +=
String(l[l.startIndex..<endIndex]).htmlEscaped
+ "</span><span class=\"\(spanClass)\">"
l = l[endIndex..<l.endIndex]
segments.removeFirst(1)
}
out += String(l).htmlEscaped + "\n"
}
out += "</span></pre>"
fileID += 1
}
}
out =
"""
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Coverage</title>
<style>
body {
background: #111;
color: #888;
font-family: monospace;
font-size: 15px;
}
nav { position: fixed; top: 0; }
pre { margin-top: 25px; }
.c { color: green; }
.nc { color: red; }
</style>
</head>
<body>
<nav>
<select id="files">
\(files)
</select>
</nav>
""" + out + """
<script>
(function() {
var filesEl = document.getElementById('files');
var selectedEl;
function select(fileID) {
if (selectedEl != null) {
selectedEl.style.display = 'none';
}
selectedEl = document.getElementById(fileID);
if (selectedEl == null) {
return;
}
filesEl.value = fileID;
selectedEl.style.display = 'block';
location.hash = fileID;
}
if (location.hash !== "") {
select(location.hash.substr(1));
}
if (selectedEl == null) {
select("f0");
}
filesEl.addEventListener('change', function() {
select(filesEl.value);
window.scrollTo(0, 0);
} , false);
})();
</script>
</body></html>
"""
FileManager.default.createFile(
atPath: htmlOutputPath,
contents: Data(out.utf8)
)
////////////////////////////////////////////////////////////////////////////////
// LLVM Coverage Export JSON Format
// See https://github.com/llvm/llvm-project/blob/main/llvm/tools/llvm-cov/CoverageExporterJson.cpp
////////////////////////////////////////////////////////////////////////////////
struct CoverageReport: Codable {
var type: String
var version: String
var data: [CoverageExport]
}
struct CoverageExport: Codable {
var totals: CoverageSummary
var files: [CoverageFile]
var functions: [CoverageFunction]
}
struct CoverageFile: Codable {
var filename: String
var summary: CoverageSummary
var segments: [CoverageSegment]
var branches: [CoverageBranch]
var expansions: [CoverageExpansion]
}
struct CoverageFunction: Codable {
var count: Int
var filenames: [String]
var name: String
var regions: [CoverageRegion]
var branches: [CoverageBranch]
}
struct CoverageSummary: Codable {
var lines: CoverageSummaryEntry
var branches: CoverageSummaryEntry
var functions: CoverageSummaryEntry
var instantiations: CoverageSummaryEntry
var regions: CoverageSummaryEntry
}
struct CoverageSummaryEntry: Codable {
var count: Int
var covered: Int
var percent: Float
var notcovered: Int?
}
struct CoverageSegment {
var line: Int
var column: Int
var count: Int
var hasCount: Bool
var isRegionEntry: Bool
var isGapRegion: Bool
}
extension CoverageSegment: Decodable {
init(from decoder: Decoder) throws {
var c = try decoder.unkeyedContainer()
line = try c.decode(Int.self)
column = try c.decode(Int.self)
count = try c.decode(Int.self)
hasCount = try c.decode(Bool.self)
isRegionEntry = try c.decode(Bool.self)
isGapRegion = try c.decode(Bool.self)
}
}
extension CoverageSegment: Encodable {
func encode(to encoder: Encoder) throws {
var c = encoder.unkeyedContainer()
try c.encode(line)
try c.encode(column)
try c.encode(count)
try c.encode(hasCount)
try c.encode(isRegionEntry)
try c.encode(isGapRegion)
}
}
struct CoverageRegion {
var lineStart: Int
var columnStart: Int
var lineEnd: Int
var columnEnd: Int
var executionCount: Int
var fileID: Int
var expandedFileID: Int
var regionKind: Int
}
extension CoverageRegion: Decodable {
init(from decoder: Decoder) throws {
var c = try decoder.unkeyedContainer()
lineStart = try c.decode(Int.self)
columnStart = try c.decode(Int.self)
lineEnd = try c.decode(Int.self)
columnEnd = try c.decode(Int.self)
executionCount = try c.decode(Int.self)
fileID = try c.decode(Int.self)
expandedFileID = try c.decode(Int.self)
regionKind = try c.decode(Int.self)
}
}
extension CoverageRegion: Encodable {
func encode(to encoder: Encoder) throws {
var c = encoder.unkeyedContainer()
try c.encode(lineStart)
try c.encode(columnStart)
try c.encode(lineEnd)
try c.encode(columnEnd)
try c.encode(executionCount)
try c.encode(fileID)
try c.encode(expandedFileID)
try c.encode(regionKind)
}
}
struct CoverageBranch: Codable {}
struct CoverageExpansion: Codable {}
////////////////////////////////////////////////////////////////////////////////
// Misc utility
////////////////////////////////////////////////////////////////////////////////
extension String {
func leftPadded(toLength: Int) -> String {
if count < toLength {
return String(repeating: " ", count: toLength - count) + self
} else {
return self
}
}
func rightPadded(toLength: Int) -> String {
if count < toLength {
return self + String(repeating: " ", count: toLength - count)
} else {
return self
}
}
func stripPrefix(_ prefix: String) -> String {
return self.hasPrefix(prefix) ? String(self.dropFirst(prefix.count)) : self
}
var htmlEscaped: String {
return self.replacingOccurrences(of: "&", with: "&").replacingOccurrences(
of: "<", with: "<"
).replacingOccurrences(
of: ">", with: ">")
}
}