1import Foundation
2
3/// The coverage page of one source file: its code, line by line, marked with what ran.
4public struct SourcePage: Sendable {
5 /// The file's path below the sources folder, such as `Kit/File.swift`.
6 public let relativePath: String
7 private let run: ReportHeader
8 private let siteTitle: String
9 private let hasTestsPage: Bool
10 private let sourceLines: [Substring]
11 private let coverage: [LineCoverage]
12
13 /// - Parameters:
14 /// - siteTitle: the site's name, shown as given after the path in the page's title.
15 /// - hasTestsPage: whether the site has a test results page, so the header shows its tab.
16 /// - run: shared commit, subject and optional History destination.
17 /// - source: the file's text as it was when the tests ran.
18 /// - coverage: one entry per line of `source`, from `LineCoverage.lines(from:lineCount:)`
19 /// with `SourcePage.lineCount(of: source)`. Lines without an entry show as not code.
20 public init(
21 relativePath: String, siteTitle: String, hasTestsPage: Bool, source: String,
22 coverage: [LineCoverage], run: ReportHeader = ReportHeader()
2349 ) {
2449 self.run = run
2549 self.relativePath = relativePath
2649 self.siteTitle = siteTitle
2749 self.hasTestsPage = hasTestsPage
2849 self.sourceLines = Self.lines(of: source)
2949 self.coverage = coverage
3049 }
31
32 /// The number of lines in `source`; a final line break doesn't start another line.
3337 public static func lineCount(of source: String) -> Int {
3437 lines(of: source).count
3537 }
36
3786 private static func lines(of source: String) -> [Substring] {
3886 var lines = source.split(separator: "\n", omittingEmptySubsequences: false)
3986 if lines.last?.isEmpty == true {
4085 lines.removeLast()
4185 }
4286 return lines
4386 }
44
45 /// Where the page goes, relative to the site's root: `coverage/<relativePath>.html`.
4690 public var sitePath: String {
4790 Self.sitePath(for: relativePath)
4890 }
49
50216 static func sitePath(for relativePath: String) -> String {
51216 "coverage/\(relativePath).html"
52216 }
53
54 /// The whole page. Links to the stylesheet and the tabs are relative, so the site
55 /// works from any folder or host.
5657 public var html: String {
5757 let root = String(repeating: "../", count: sitePath.split(separator: "/").count - 1)
5857 let path = escapingHTML(relativePath)
5957 return """
6057 <!doctype html>
6157 <html lang="en">
6257 <head>
6357 <meta charset="utf-8">
6457 <meta name="viewport" content="width=device-width, initial-scale=1">
6557 <title>\(path) · \(escapingHTML(siteTitle))</title>
6657 <link rel="stylesheet" href="\(root)\(SiteStylesheet.fileName)">
6757 </head>
6857 <body class="source-page">
6957 <header class="page-header">
7057 \(SiteHeader(title: siteTitle, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: root, run: run).html)
7157 <p class="path">\(path)</p>
7257 \(totalsMarkup)
7357 </header>
7457 <main>
7557 <table class="source">
7657 <tbody>
7757 \(rowsMarkup)
7857 </tbody>
7957 </table>
8057 </main>
8157 \(minimapMarkup)
8257 <script>\(Self.missNavigationScript)</script>
8357 </body>
8457 </html>
8557
8657 """
8757 }
88
8957 private var totalsMarkup: String {
9057 let summary = LineSummary(lines: coverage)
91170 let missed = coverage.count { $0.state == .missed }
92170 let partly = coverage.count { $0.state == .partlyCovered }
9357 return """
9457 <p class="totals"><span class="percent \(summary.tier.rawValue)">\
9557 \(summary.percentText)</span> \(groupingDigits(summary.covered)) of \
9657 \(groupingDigits(summary.count)) lines · \(groupingDigits(missed)) missed · \
9757 \(groupingDigits(partly)) partly covered</p>
9857 """
9957 }
100
10157 private var rowsMarkup: String {
102174 sourceLines.indices.map { index in
103174 let line = lineCoverage(at: index)
104174 let number = index + 1
105174 return """
106174 <tr id="L\(number)" class="\(Self.rowClass(of: line.state))">\
107174 <td class="number"><a href="#L\(number)">\(number)</a></td>\
108174 \(Self.countCell(line.count))\
109174 <td class="code"><code>\(Self.codeMarkup(sourceLines[index], missedSpans: line.missedSpans))</code></td></tr>
110174 """
111174 }.joined(separator: "\n")
11257 }
113
114383 private func lineCoverage(at index: Int) -> LineCoverage {
115383 index < coverage.count ? coverage[index] : LineCoverage(state: .notCode, count: nil)
116383 }
117
118 /// A mark down the right edge for each run of missed or partly covered lines, placed
119 /// and sized by where the run sits in the file; red if any line in it never ran.
12057 private var minimapMarkup: String {
12157 let total = sourceLines.count
12257 var marks: [String] = []
12357 var index = 0
124221 while index < total {
125164 let start = index
126164 var isAnyLineMissed = false
127188 while index < total, lineCoverage(at: index).isMiss {
12824 isAnyLineMissed = isAnyLineMissed || lineCoverage(at: index).state == .missed
12924 index += 1
130164 }
131164 guard index > start else {
132150 index += 1
133150 continue
134150 }
13514 let position = String(
13614 format: "top: %.2f%%; height: %.2f%%", Double(start) * 100 / Double(total),
13714 Double(index - start) * 100 / Double(total))
13814 let state = isAnyLineMissed ? "missed" : "partly"
13914 marks.append(
14014 ##"<a class="mark \##(state)" href="#L\##(start + 1)" style="\##(position)"></a>"##)
14157 }
14257 guard !marks.isEmpty else { return "" }
14312 return #"<nav class="minimap" aria-label="Missed lines">"# + marks.joined() + "</nav>"
14457 }
145
146 /// Measures the sticky header so linked lines land below it, and makes `n` and `p`
147 /// scroll to the next and previous run of misses. Without scripts the page still
148 /// reads; linked lines may sit under a wrapped header and the keys are lost.
149 private static let missNavigationScript = """
150 (() => {
151 const header = document.querySelector(".page-header");
152 const measureHeader = () =>
153 document.documentElement.style.setProperty("--header-height", header.offsetHeight + "px");
154 measureHeader();
155 addEventListener("resize", measureHeader);
156 if (location.hash) document.querySelector(location.hash)?.scrollIntoView();
157 const isMiss = row => row && (row.classList.contains("missed") || row.classList.contains("partly"));
158 const runs = [...document.querySelectorAll("tr.missed, tr.partly")]
159 .filter(row => !isMiss(row.previousElementSibling));
160 document.addEventListener("keydown", event => {
161 if (event.metaKey || event.ctrlKey || event.altKey || (event.key !== "n" && event.key !== "p")) return;
162 // Rows land a little below the sticky header, and "next" means below that spot,
163 // so pressing n again moves on instead of finding the same row.
164 const spot = header.getBoundingClientRect().bottom + 24;
165 const target = event.key === "n"
166 ? runs.find(row => row.getBoundingClientRect().top > spot + 2)
167 : runs.findLast(row => row.getBoundingClientRect().top < spot - 2);
168 if (!target) return;
169 event.preventDefault();
170 window.scrollBy(0, target.getBoundingClientRect().top - spot);
171 history.replaceState(null, "", "#" + target.id);
172 });
173 })();
174 """
175
176174 private static func rowClass(of state: LineState) -> String {
177174 switch state {
178174 case .notCode: "plain"
179174 case .covered: "covered"
180174 case .partlyCovered: "partly"
181174 case .missed: "missed"
182174 }
183174 }
184
185 /// llvm-cov clamps a counter that wrapped around to `Int64.max` (docs/DESIGN.md,
186 /// D2); printing it would only mislead.
187174 private static func countCell(_ count: UInt64?) -> String {
188174 guard let count else { return #"<td class="count"></td>"# }
189162 guard count < UInt64(Int64.max) else {
1901 return #"<td class="count" title="The counter overflowed"></td>"#
191161 }
192161 return #"<td class="count">\#(shortened(count))</td>"#
193174 }
194
195161 private static func shortened(_ count: UInt64) -> String {
196161 guard count >= 10_000 else { return String(count) }
1976 for (scale, unit) in [(1e9, "G"), (1e6, "M"), (1e3, "k")] where Double(count) >= scale {
1986 let value = Double(count) / scale
1996 return String(format: value < 100 ? "%.1f%@" : "%.0f%@", value, unit)
2006 }
2010 return String(count)
202161 }
203
204 /// llvm-cov's columns count UTF-8 bytes, so spans are cut in bytes, not characters.
205174 private static func codeMarkup(_ line: Substring, missedSpans: [ColumnSpan]) -> String {
206174 let bytes = Array(line.utf8)
207202 func text(_ range: Range<Int>) -> String {
208202 escapingHTML(String(decoding: bytes[range], as: UTF8.self))
209202 }
210174 var markup = ""
211174 var cursor = 0
212174 for span in missedSpans {
21314 let start = min(max(span.start - 1, cursor), bytes.count)
21414 let end = min(max((span.end ?? bytes.count + 1) - 1, start), bytes.count)
21514 markup +=
21614 text(cursor..<start) + #"<span class="unrun">"# + text(start..<end) + "</span>"
21714 cursor = end
218174 }
219174 return markup + text(cursor..<bytes.count)
220174 }
221}
222
223extension LineCoverage {
224185 fileprivate var isMiss: Bool { state == .missed || state == .partlyCovered }
225}