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 private let regions: CoverageCount?
13
14 /// - Parameters:
15 /// - siteTitle: the site's name, shown as given after the path in the page's title.
16 /// - hasTestsPage: whether the site has a test results page, so the header shows its tab.
17 /// - regions: the file's region counts, shown in the header; nil when the export
18 /// has none.
19 /// - run: shared commit, subject and optional History destination.
20 /// - source: the file's text as it was when the tests ran.
21 /// - coverage: one entry per line of `source`, from `LineCoverage.lines(from:lineCount:)`
22 /// with `SourcePage.lineCount(of: source)`. Lines without an entry show as not code.
23 public init(
24 relativePath: String, siteTitle: String, hasTestsPage: Bool, source: String,
25 coverage: [LineCoverage], regions: CoverageCount? = nil, run: ReportHeader = ReportHeader()
2659 ) {
2759 self.run = run
2859 self.regions = regions
2959 self.relativePath = relativePath
3059 self.siteTitle = siteTitle
3159 self.hasTestsPage = hasTestsPage
3259 self.sourceLines = Self.lines(of: source)
3359 self.coverage = coverage
3459 }
35
36 /// The number of lines in `source`; a final line break doesn't start another line.
3745 public static func lineCount(of source: String) -> Int {
3845 lines(of: source).count
3945 }
40
41104 private static func lines(of source: String) -> [Substring] {
42104 var lines = source.split(separator: "\n", omittingEmptySubsequences: false)
43104 if lines.last?.isEmpty == true {
44103 lines.removeLast()
45103 }
46104 return lines
47104 }
48
49 /// Where the page goes, relative to the site's root: `coverage/<relativePath>.html`.
50108 public var sitePath: String {
51108 Self.sitePath(for: relativePath)
52108 }
53
54251 static func sitePath(for relativePath: String) -> String {
55251 "coverage/\(relativePath).html"
56251 }
57
58 /// The whole page. Links to the stylesheet and the tabs are relative, so the site
59 /// works from any folder or host.
6067 public var html: String {
6167 let root = String(repeating: "../", count: sitePath.split(separator: "/").count - 1)
6267 let path = escapingHTML(relativePath)
6367 return """
6467 <!doctype html>
6567 <html lang="en">
6667 <head>
6767 <meta charset="utf-8">
6867 <meta name="viewport" content="width=device-width, initial-scale=1">
6967 <title>\(path) · \(escapingHTML(siteTitle))</title>
7067 <link rel="stylesheet" href="\(root)\(SiteStylesheet.fileName)">
7167 </head>
7267 <body class="source-page">
7367 <header class="page-header">
7467 \(SiteHeader(title: siteTitle, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: root, run: run).html)
7567 <p class="path">\(path)</p>
7667 \(totalsMarkup)
7767 </header>
7867 <main>
7967 <table class="source">
8067 <tbody>
8167 \(rowsMarkup)
8267 </tbody>
8367 </table>
8467 </main>
8567 \(minimapMarkup)
8667 <script>\(Self.missNavigationScript)</script>
8767 </body>
8867 </html>
8967
9067 """
9167 }
92
9367 private var totalsMarkup: String {
9467 let summary = LineSummary(lines: coverage)
95170 let missed = coverage.count { $0.state == .missed }
96170 let partly = coverage.count { $0.state == .partlyCovered }
9767 return """
9867 <p class="totals"><span class="percent \(summary.tier.rawValue)">\
9967 \(summary.percentText)</span> \(groupingDigits(summary.covered)) of \
10067 \(groupingDigits(summary.count)) lines · \(groupingDigits(missed)) missed · \
10167 \(groupingDigits(partly)) partly covered\(regionsMarkup)</p>
10267 """
10367 }
104
10567 private var regionsMarkup: String {
10667 guard let regions else { return "" }
1077 return
1087 #" · <span class="percent \#(regions.tier.rawValue)">\#(regions.percentText)</span> "#
1097 + "\(groupingDigits(regions.covered)) of \(groupingDigits(regions.total)) regions"
11067 }
111
11267 private var rowsMarkup: String {
113174 sourceLines.indices.map { index in
114174 let line = lineCoverage(at: index)
115174 let number = index + 1
116174 return """
117174 <tr id="L\(number)" class="\(Self.rowClass(of: line.state))">\
118174 <td class="number"><a href="#L\(number)">\(number)</a></td>\
119174 \(Self.countCell(line.count))\
120174 <td class="code"><code>\(Self.codeMarkup(sourceLines[index], missedSpans: line.missedSpans))</code></td></tr>
121174 """
122174 }.joined(separator: "\n")
12367 }
124
125383 private func lineCoverage(at index: Int) -> LineCoverage {
126383 index < coverage.count ? coverage[index] : LineCoverage(state: .notCode, count: nil)
127383 }
128
129 /// A mark down the right edge for each run of missed or partly covered lines, placed
130 /// and sized by where the run sits in the file; red if any line in it never ran.
13167 private var minimapMarkup: String {
13267 let total = sourceLines.count
13367 var marks: [String] = []
13467 var index = 0
135231 while index < total {
136164 let start = index
137164 var isAnyLineMissed = false
138188 while index < total, lineCoverage(at: index).isMiss {
13924 isAnyLineMissed = isAnyLineMissed || lineCoverage(at: index).state == .missed
14024 index += 1
141164 }
142164 guard index > start else {
143150 index += 1
144150 continue
145150 }
14614 let position = String(
14714 format: "top: %.2f%%; height: %.2f%%", Double(start) * 100 / Double(total),
14814 Double(index - start) * 100 / Double(total))
14914 let state = isAnyLineMissed ? "missed" : "partly"
15014 marks.append(
15114 ##"<a class="mark \##(state)" href="#L\##(start + 1)" style="\##(position)"></a>"##)
15267 }
15367 guard !marks.isEmpty else { return "" }
15412 return #"<nav class="minimap" aria-label="Missed lines">"# + marks.joined() + "</nav>"
15567 }
156
157 /// Measures the sticky header so linked lines land below it, and makes `n` and `p`
158 /// scroll to the next and previous run of misses. Without scripts the page still
159 /// reads; linked lines may sit under a wrapped header and the keys are lost.
160 private static let missNavigationScript = """
161 (() => {
162 const header = document.querySelector(".page-header");
163 const measureHeader = () =>
164 document.documentElement.style.setProperty("--header-height", header.offsetHeight + "px");
165 measureHeader();
166 addEventListener("resize", measureHeader);
167 if (location.hash) document.querySelector(location.hash)?.scrollIntoView();
168 const isMiss = row => row && (row.classList.contains("missed") || row.classList.contains("partly"));
169 const runs = [...document.querySelectorAll("tr.missed, tr.partly")]
170 .filter(row => !isMiss(row.previousElementSibling));
171 document.addEventListener("keydown", event => {
172 if (event.metaKey || event.ctrlKey || event.altKey || (event.key !== "n" && event.key !== "p")) return;
173 // Rows land a little below the sticky header, and "next" means below that spot,
174 // so pressing n again moves on instead of finding the same row.
175 const spot = header.getBoundingClientRect().bottom + 24;
176 const target = event.key === "n"
177 ? runs.find(row => row.getBoundingClientRect().top > spot + 2)
178 : runs.findLast(row => row.getBoundingClientRect().top < spot - 2);
179 if (!target) return;
180 event.preventDefault();
181 window.scrollBy(0, target.getBoundingClientRect().top - spot);
182 history.replaceState(null, "", "#" + target.id);
183 });
184 })();
185 """
186
187174 private static func rowClass(of state: LineState) -> String {
188174 switch state {
189174 case .notCode: "plain"
190174 case .covered: "covered"
191174 case .partlyCovered: "partly"
192174 case .missed: "missed"
193174 }
194174 }
195
196 /// llvm-cov clamps a counter that wrapped around to `Int64.max` (docs/DESIGN.md,
197 /// D2); printing it would only mislead.
198174 private static func countCell(_ count: UInt64?) -> String {
199174 guard let count else { return #"<td class="count"></td>"# }
200162 guard count < UInt64(Int64.max) else {
2011 return #"<td class="count" title="The counter overflowed"></td>"#
202161 }
203161 return #"<td class="count">\#(shortened(count))</td>"#
204174 }
205
206161 private static func shortened(_ count: UInt64) -> String {
207161 guard count >= 10_000 else { return String(count) }
2086 for (scale, unit) in [(1e9, "G"), (1e6, "M"), (1e3, "k")] where Double(count) >= scale {
2096 let value = Double(count) / scale
2106 return String(format: value < 100 ? "%.1f%@" : "%.0f%@", value, unit)
2116 }
2120 return String(count)
213161 }
214
215 /// llvm-cov's columns count UTF-8 bytes, so spans are cut in bytes, not characters.
216174 private static func codeMarkup(_ line: Substring, missedSpans: [ColumnSpan]) -> String {
217174 let bytes = Array(line.utf8)
218202 func text(_ range: Range<Int>) -> String {
219202 escapingHTML(String(decoding: bytes[range], as: UTF8.self))
220202 }
221174 var markup = ""
222174 var cursor = 0
223174 for span in missedSpans {
22414 let start = min(max(span.start - 1, cursor), bytes.count)
22514 let end = min(max((span.end ?? bytes.count + 1) - 1, start), bytes.count)
22614 markup +=
22714 text(cursor..<start) + #"<span class="unrun">"# + text(start..<end) + "</span>"
22814 cursor = end
229174 }
230174 return markup + text(cursor..<bytes.count)
231174 }
232}
233
234extension LineCoverage {
235185 fileprivate var isMiss: Bool { state == .missed || state == .partlyCovered }
236}