1import Foundation
2
3/// Coverage cards and every module, each folding out its files.
4public struct IndexPage: Sendable {
5 public static let sitePath = "index.html"
6 private let title: String
7 private let modules: [ModuleTotals]
8 private let tests: TestRun?
9 private let run: ReportHeader
10 private let comparison: BaselineComparison?
11 private let hasRegions: Bool
12 private let hasBranches: Bool
13 private let trend: CoverageTrend
14 private let hasConditions: Bool
15
16 /// - Parameters:
17 /// - title: the site's name, shown as given in the page's title and heading.
18 /// - tests: results add the Tests tab; counts alone do not create a page.
19 /// - commit: the commit the report was built from, shortened in the header.
20 /// - subject: the commit's first message line.
21 /// - historyPath: the History destination relative to the report root, if available.
22 /// - trend: the line series shown in the coverage card.
23 /// - baseline: an earlier run to compare with; with it, the table gets a change
24 /// column.
25 public init(
26 title: String, files: [FileTotals], tests: TestRun?, commit: String?,
27 baseline: RunTotals? = nil, subject: String? = nil, historyPath: String? = nil,
28 trend: CoverageTrend = CoverageTrend(runs: [])
2978 ) {
3078 self.trend = trend
3178 self.comparison = baseline.map(BaselineComparison.init)
3278 self.title = title
3378 self.modules = ModuleTotals.grouping(files)
34161 self.hasRegions = files.contains { $0.regions != nil }
35164 self.hasBranches = files.contains { $0.branches != nil }
36166 self.hasConditions = files.contains { $0.conditions != nil }
3778 self.tests = tests
3878 self.run = ReportHeader(commit: commit, subject: subject, historyPath: historyPath)
3978 }
40
4178 public var html: String {
4278 """
4378 <!doctype html>
4478 <html lang="en">
4578 <head>
4678 <meta charset="utf-8">
4778 <meta name="viewport" content="width=device-width, initial-scale=1">
4878 <title>\(escapingHTML(title))</title>
4978 <link rel="stylesheet" href="\(SiteStylesheet.fileName)">
5078 </head>
5178 <body class="\(bodyClasses)">
5278 <header class="page-header">
5378 \(SiteHeader(title: title, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: "", run: run).html)
5478 </header>
5578 <main>
5678 \(cardsMarkup)
5778 <p class="legend"><span class="key high"></span>90% and up \
5878 <span class="key medium"></span>75% and up <span class="key low"></span>below 75%</p>
5978 <div class="toolbar" data-needs-script hidden>
6078 <input id="filter" type="search" placeholder="Filter files" aria-label="Filter files">\(compactToggle)
6178 </div>
6278 \(groupHeadings)<div class="row columns" data-needs-script hidden>\
6378 <button type="button" data-sort="name" data-first="ascending">File</button>\(barHeading)\
6478 <button type="button" data-sort="percent" data-first="ascending">\(lineShareTitle)</button>\
6578 <button type="button" data-sort="missed" data-first="descending">Missed</button>\
6678 \(comparison == nil ? "" : Self.sortButton("change", title: "Change", cell: "change"))\
6778 \(regionHeadings)\
6878 \(hasBranches ? #"<span class="branches">Branches</span>"# : "")\
6978 \(hasConditions ? #"<span class="conditions">Conditions</span>"# : "")</div>
7078 <div class="modules">
71193 \(modules.map(moduleMarkup).joined(separator: "\n"))
7278 </div>
7378 </main>
7478 <script>\(Self.sortAndFilterScript)</script>
7578 </body>
7678 </html>
7778
7878 """
7978 }
80
81 /// Whether rows have more to sum up than their lines.
82640 private var hasOtherMetrics: Bool { hasRegions || hasBranches || hasConditions }
83
8478 private var barHeading: String {
8578 hasOtherMetrics
8678 ? Self.sortButton("overall", title: "Overall", cell: "bar")
8778 : #"<span class="bar"></span>"#
8878 }
89
90 /// The row over the column headings that says which columns are lines' and which
91 /// regions'. Lines alone need none.
9278 private var groupHeadings: String {
9378 guard hasRegions else { return "" }
9429 return #"<div class="row groups" data-needs-script hidden><span class="name"></span>"#
9529 + #"<span class="bar"></span><span class="group">Lines</span>"#
9629 + #"<span class="group regions">Regions</span>"#
9729 + (hasBranches ? #"<span class="branches"></span>"# : "")
9829 + (hasConditions ? #"<span class="conditions"></span>"# : "")
9929 + "</div>\n"
10078 }
101
102 /// Switches the table to one column per metric. Lines alone already have just one.
10378 private var compactToggle: String {
10478 guard hasRegions else { return "" }
10529 return "\n"
10629 + #"<label class="compact-toggle"><input id="compact" type="checkbox"> Compact</label>"#
10778 }
108
10978 private var lineShareTitle: String { hasRegions ? Self.shareTitle("Lines") : "Lines" }
110
111 /// "Cover" under the metric's group heading, and the metric itself in the compact
112 /// view, which has no group headings. The stylesheet shows one of the two.
11358 private static func shareTitle(_ metric: String) -> String {
11458 #"<span class="normal-only">Cover</span><span class="compact-only">\#(metric)</span>"#
11558 }
116
11778 private var regionHeadings: String {
11878 guard hasRegions else { return "" }
11929 let change =
12029 comparison == nil
12129 ? "" : Self.sortButton("regionChange", title: "Change", cell: "regions-change")
12229 return Self.sortButton("regionPercent", title: Self.shareTitle("Regions"), cell: "regions")
12329 + #"<button type="button" class="regions-missed" data-sort="regionMissed" data-first="descending">Missed</button>"#
12429 + change
12578 }
126
127 /// A heading that sorts by a share or change, the worst rows first.
12889 private static func sortButton(_ key: String, title: String, cell: String) -> String {
12989 #"<button type="button" class="\#(cell)" data-sort="\#(key)" data-first="ascending">\#(title)</button>"#
13089 }
131
132 /// The classes the stylesheet keys its extra columns on.
13378 private var bodyClasses: String {
13478 var classes = ["index-page"]
13578 if comparison != nil { classes.append("has-baseline") }
13678 if hasRegions { classes.append("has-regions") }
13778 if hasBranches { classes.append("has-branches") }
13878 if hasConditions { classes.append("has-conditions") }
13978 return classes.joined(separator: " ")
14078 }
141
14278 private var hasTestsPage: Bool {
14378 if case .results = tests { true } else { false }
14478 }
145
146 /// Lines alone fill one row of cards. With regions, the two coverage cards share
147 /// the first row and their missed counts the second, so neither metric leads.
14878 private var cardsMarkup: String {
149115 let total = LineSummary(adding: modules.map(\.lines))
150115 let files = modules.flatMap(\.files)
15178 let lineCard = lineCard(total)
15278 let missedLines = Self.card(
15378 title: "Missed lines", value: groupingDigits(total.count - total.covered),
15478 detail: comparison.map { Self.missedChangeSpan($0.missedLineChange(now: total)) } ?? "")
15578 let newFiles = comparison.map { "\($0.newFileCount(in: files)) new since baseline" } ?? ""
15678 let fileCard = Self.card(
15778 title: "Files", value: groupingDigits(files.count), detail: newFiles)
15878 let rows =
159166 if let regions = CoverageCount(addingPresent: files.map(\.regions)) {
16029 Self.cardRow(
16129 [lineCard, regionCard(regions)], classes: "cards pair",
16229 label: "Coverage summary")
16329 + Self.cardRow(
16429 [missedLines, missedRegionCard(regions), fileCard], classes: "cards counts",
16529 label: "Coverage counts")
16649 } else {
16749 Self.cardRow(
16849 [lineCard, missedLines, fileCard], classes: "cards", label: "Coverage summary")
16949 }
17078 return rows + otherMetricCards(files)
17178 }
172
17378 private func lineCard(_ total: LineSummary) -> String {
17478 let change =
17578 comparison.map { Self.changeSpan($0.changeOfTotal(now: total)) + " since baseline · " }
17678 ?? ""
17778 return Self.card(
17878 title: "Line coverage", value: total.percentText,
17978 detail: change
18078 + "\(groupingDigits(total.covered)) of \(groupingDigits(total.count)) lines"
18178 + trend.sparkline)
18278 }
183
18429 private func regionCard(_ regions: CoverageCount) -> String {
18529 Self.card(
18629 title: "Region coverage", value: regions.percentText,
18729 detail: metricDetail(
18829 regions, noun: "regions", change: comparison?.regionChange(now: regions))
18929 + trend.regionSparkline)
19029 }
191
19229 private func missedRegionCard(_ regions: CoverageCount) -> String {
19329 let detail =
19429 comparison.map { baseline in
19510 baseline.missedRegionChange(now: regions).map(Self.missedChangeSpan)
19610 ?? Self.changeSpan(.new) + " since baseline"
19719 } ?? ""
19829 return Self.card(
19929 title: "Missed regions", value: groupingDigits(regions.total - regions.covered),
20029 detail: detail)
20129 }
202
203 /// Fewer missed is the improvement, so a fall is styled as `up`.
20423 private static func missedChangeSpan(_ difference: Int) -> String {
20523 let style = difference < 0 ? "up" : difference > 0 ? "down" : "flat"
20623 let sign = difference > 0 ? "+" : ""
20723 return
20823 #"<span class="change \#(style)">\#(sign)\#(groupingDigits(difference)) since baseline</span>"#
20923 }
210
211 /// Branch and condition cards, for the exports that count them.
21278 private func otherMetricCards(_ files: [FileTotals]) -> String {
21378 var cards = [String]()
214166 if let branches = CoverageCount(addingPresent: files.map(\.branches)) {
2156 cards.append(
2166 Self.card(
2176 title: "Branch coverage", value: branches.percentText,
2186 detail: metricDetail(
2196 branches, noun: "outcomes", change: comparison?.branchChange(now: branches))
2206 ))
2216 }
222166 if let conditions = CoverageCount(addingPresent: files.map(\.conditions)) {
2233 cards.append(
2243 Self.card(
2253 title: "Condition coverage", value: conditions.percentText,
2263 detail: metricDetail(
2273 conditions, noun: "conditions",
2283 change: comparison?.conditionChange(now: conditions))))
2293 }
23078 return cards.isEmpty
23178 ? "" : Self.cardRow(cards, classes: "cards secondary", label: "Additional coverage")
23278 }
233
234113 private static func cardRow(_ cards: [String], classes: String, label: String) -> String {
235113 #"<section class="\#(classes)" aria-label="\#(label)">"# + cards.joined() + "</section>"
236113 }
237
238301 private static func card(title: String, value: String, detail: String) -> String {
239301 #"<article class="card"><h2>\#(title)</h2><p class="value">\#(value)</p><p class="detail">\#(detail)</p></article>"#
240301 }
241
242 private func metricDetail(
243 _ count: CoverageCount, noun: String, change: CoverageChange?
24438 ) -> String {
24538 let delta = change.map { Self.changeSpan($0) + " since baseline · " } ?? ""
24638 return delta + "\(groupingDigits(count.covered)) of \(groupingDigits(count.total)) \(noun)"
24738 }
248
249 /// Shows the controls, sorts modules and the files inside each by the clicked column
250 /// (a second click reverses it), and filters files by path, opening the modules
251 /// that still have matches. Without scripts the modules still fold out by hand.
252 private static let sortAndFilterScript = """
253 (() => {
254 const list = document.querySelector(".modules");
255 const modules = [...list.querySelectorAll("details.module")];
256 const buttons = [...document.querySelectorAll("button[data-sort]")];
257 const filter = document.getElementById("filter");
258 document.querySelectorAll("[data-needs-script]").forEach(element => element.hidden = false);
259 let key = "name";
260 let ascending = true;
261 const value = row => key === "name" ? row.dataset.name.toLowerCase() : parseFloat(row.dataset[key]);
262 const order = (a, b) => {
263 const [x, y] = [value(a), value(b)];
264 // Rows without the value go last, whichever way the rest are sorted.
265 if (Number.isNaN(x) || Number.isNaN(y)) return Number.isNaN(x) - Number.isNaN(y);
266 return (x < y ? -1 : x > y ? 1 : 0) * (ascending ? 1 : -1);
267 };
268 const sort = () => {
269 for (const module of modules.sort(order)) {
270 module.append(...[...module.querySelectorAll("a.file")].sort(order));
271 list.append(module);
272 }
273 for (const button of buttons) {
274 button.dataset.direction = button.dataset.sort === key ? (ascending ? "ascending" : "descending") : "";
275 }
276 };
277 for (const button of buttons) {
278 button.addEventListener("click", () => {
279 ascending = button.dataset.sort === key ? !ascending : button.dataset.first === "ascending";
280 key = button.dataset.sort;
281 sort();
282 });
283 }
284 filter.addEventListener("input", () => {
285 const query = filter.value.trim().toLowerCase();
286 for (const module of modules) {
287 let hasMatch = false;
288 for (const file of module.querySelectorAll("a.file")) {
289 const path = (module.dataset.name + "/" + file.dataset.name).toLowerCase();
290 file.hidden = query !== "" && !path.includes(query);
291 hasMatch = hasMatch || !file.hidden;
292 }
293 module.hidden = !hasMatch;
294 module.open = query !== "" && hasMatch;
295 }
296 });
297 const compact = document.getElementById("compact");
298 if (compact) {
299 const storageKey = "covane.compact";
300 // Browsers may refuse storage; the view then just starts out normal.
301 try { compact.checked = localStorage.getItem(storageKey) === "true"; } catch {}
302 const shareColumns = { missed: "percent", change: "percent", regionMissed: "regionPercent", regionChange: "regionPercent" };
303 const apply = () => {
304 document.body.classList.toggle("compact", compact.checked);
305 // Never leave the rows ordered by a column the compact view hides.
306 if (compact.checked && key in shareColumns) {
307 key = shareColumns[key];
308 ascending = true;
309 }
310 sort();
311 };
312 compact.addEventListener("change", () => {
313 try { localStorage.setItem(storageKey, compact.checked); } catch {}
314 apply();
315 });
316 apply();
317 } else {
318 sort();
319 }
320 })();
321 """
322
323 /// A `<details>` per module, so its files fold out without any script.
324115 private func moduleMarkup(_ module: ModuleTotals) -> String {
325166 let files = module.files.map { file in
326166 let values = RowValues(
327166 name: String(file.relativePath.dropFirst(module.name.count + 1)),
328166 lines: file.lines,
329166 change: comparison?.change(ofFile: file.relativePath, now: file.lines),
330166 regions: file.regions,
331166 regionChange: file.regions.flatMap { now in
33231 comparison?.regionChange(ofFile: file.relativePath, now: now)
33331 },
334166 branches: file.branches, conditions: file.conditions)
335166 return
336166 #"<a class="row file" href="\#(escapingHTML(SourcePage.sitePath(for: file.relativePath)))""#
337166 + "\(sortKeys(values))>\(cells(values))</a>"
338166 }
339115 let values = RowValues(
340115 name: module.name, lines: module.lines,
341115 change: comparison?.change(ofModule: module.name, now: module.lines),
342115 regions: module.regions,
343115 regionChange: module.regions.flatMap { now in
34429 comparison?.regionChange(ofModule: module.name, now: now)
34529 },
346115 branches: module.branches, conditions: module.conditions)
347115 return """
348115 <details class="module"\(sortKeys(values))>
349115 <summary class="row">\(cells(values))</summary>
350115 \(files.joined(separator: "\n"))
351115 </details>
352115 """
353115 }
354
355 /// The values the index's sort script orders rows by, unformatted, so it compares
356 /// numbers rather than the text shown. A value a row lacks, or a change from
357 /// nothing, has no key.
358281 private func sortKeys(_ row: RowValues) -> String {
359281 var keys =
360281 #" data-name="\#(escapingHTML(row.name))""#
361281 + #" data-percent="\#(Self.sortNumber(row.lines.percent))""#
362281 + #" data-missed="\#(row.lines.count - row.lines.covered)" data-lines="\#(row.lines.count)""#
363281 if case .points(let points) = row.change {
36434 keys += #" data-change="\#(Self.sortNumber(points))""#
36534 }
366281 if let regions = row.regions {
36760 let share = LineSummary(count: regions.total, covered: regions.covered)
36860 keys +=
36960 #" data-region-percent="\#(Self.sortNumber(share.percent))""#
37060 + #" data-region-missed="\#(regions.total - regions.covered)""#
37160 }
372281 if case .points(let points) = row.regionChange {
37312 keys += #" data-region-change="\#(Self.sortNumber(points))""#
37412 }
375281 if let overall = overall(of: row) {
37673 keys += #" data-overall="\#(Self.sortNumber(overall.percent))""#
37773 }
378281 return keys
379281 }
380
381460 private static func sortNumber(_ value: Double) -> String {
382460 String(format: "%.2f", value)
383460 }
384
385110 private static func changeSpan(_ change: CoverageChange) -> String {
386110 #"<span class="change \#(change.styleName)">\#(change.text)</span>"#
387110 }
388
389 /// What one module's or file's row shows. The changes are nil without a baseline.
390 private struct RowValues {
391 let name: String
392 let lines: LineSummary
393 let change: CoverageChange?
394 let regions: CoverageCount?
395 let regionChange: CoverageChange?
396 let branches: CoverageCount?
397 let conditions: CoverageCount?
398 }
399
400281 private func cells(_ row: RowValues) -> String {
401281 let tier = row.lines.tier.rawValue
402281 let changeCell = row.change.map(Self.changeSpan) ?? ""
403281 let branchCell = hasBranches ? Self.countCell(row.branches, className: "branches") : ""
404281 let conditionCell =
405281 hasConditions ? Self.countCell(row.conditions, className: "conditions") : ""
406281 return #"<span class="name">\#(escapingHTML(row.name))</span>"#
407281 + barMarkup(row)
408281 + #"<span class="percent \#(tier)">\#(row.lines.percentText)</span>"#
409281 + #"<span class="missed">\#(groupingDigits(row.lines.count - row.lines.covered))</span>"#
410281 + changeCell
411281 + (hasRegions ? regionCells(row) : "")
412281 + branchCell + conditionCell
413281 }
414
415 /// The row summed up across its metrics; nil on a page of lines alone, whose bar
416 /// needs no summing up.
417562 private func overall(of row: RowValues) -> OverallCoverage? {
418562 guard hasOtherMetrics else { return nil }
419146 return OverallCoverage(
420146 lines: row.lines, regions: row.regions, branches: row.branches,
421146 conditions: row.conditions)
422562 }
423
424281 private func barMarkup(_ row: RowValues) -> String {
425281 let overall = overall(of: row)
426281 let tier = overall?.tier ?? row.lines.tier
427281 let width = overall?.percentText ?? row.lines.percentText
428281 let tooltip = overall.map { #" title="\#($0.breakdown)""# } ?? ""
429281 return
430281 #"<span class="bar"\#(tooltip)><span class="fill \#(tier.rawValue)" style="width: \#(width)"></span></span>"#
431281 }
432
433 /// Share, missed and, with a baseline, change, as for lines; dashes where this row
434 /// has no region data while others do.
43563 private func regionCells(_ row: RowValues) -> String {
43663 let share =
43763 row.regions.map { regions in
43860 #"<span class="percent \#(regions.tier.rawValue)">\#(regions.percentText)</span>"#
43960 } ?? "–"
44063 let missed = row.regions.map { groupingDigits($0.total - $0.covered) } ?? "–"
44163 let change =
44263 comparison == nil
44363 ? ""
44463 : #"<span class="regions-change">\#(row.regionChange.map(Self.changeSpan) ?? "–")</span>"#
44563 return #"<span class="regions">\#(share)</span>"#
44663 + #"<span class="regions-missed">\#(missed)</span>"# + change
44763 }
448
449 /// The share in its tier colour and the counts it comes from; a dash where this
450 /// file or module has no data while others do.
45120 private static func countCell(_ count: CoverageCount?, className: String) -> String {
45220 guard let count else { return #"<span class="\#(className)">–</span>"# }
45319 return #"<span class="\#(className)"><span class="percent \#(count.tier.rawValue)">"#
45419 + "\(count.percentText)</span> \(groupingDigits(count.covered))/"
45519 + "\(groupingDigits(count.total))</span>"
45620 }
457}