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 siteTitle: String
8 private let hasTestsPage: Bool
9 private let sourceLines: [Substring]
10 private let coverage: [LineCoverage]
11
12 /// - Parameters:
13 /// - siteTitle: the site's name, shown as given after the path in the page's title.
14 /// - hasTestsPage: whether the site has a test results page, so the header shows its tab.
15 /// - source: the file's text as it was when the tests ran.
16 /// - coverage: one entry per line of `source`, from `LineCoverage.lines(from:lineCount:)`
17 /// with `SourcePage.lineCount(of: source)`. Lines without an entry show as not code.
18 public init(
19 relativePath: String, siteTitle: String, hasTestsPage: Bool, source: String,
20 coverage: [LineCoverage]
2143 ) {
2243 self.relativePath = relativePath
2343 self.siteTitle = siteTitle
2443 self.hasTestsPage = hasTestsPage
2543 self.sourceLines = Self.lines(of: source)
2643 self.coverage = coverage
2743 }
28
29 /// The number of lines in `source`; a final line break doesn't start another line.
3031 public static func lineCount(of source: String) -> Int {
3131 lines(of: source).count
3231 }
33
3474 private static func lines(of source: String) -> [Substring] {
3574 var lines = source.split(separator: "\n", omittingEmptySubsequences: false)
3674 if lines.last?.isEmpty == true {
3773 lines.removeLast()
3873 }
3974 return lines
4074 }
41
42 /// Where the page goes, relative to the site's root: `coverage/<relativePath>.html`.
4378 public var sitePath: String {
4478 Self.sitePath(for: relativePath)
4578 }
46
47189 static func sitePath(for relativePath: String) -> String {
48189 "coverage/\(relativePath).html"
49189 }
50
51 /// The whole page. Links to the stylesheet and the tabs are relative, so the site
52 /// works from any folder or host.
5351 public var html: String {
5451 let root = String(repeating: "../", count: sitePath.split(separator: "/").count - 1)
5551 let path = escapingHTML(relativePath)
5651 return """
5751 <!doctype html>
5851 <html lang="en">
5951 <head>
6051 <meta charset="utf-8">
6151 <meta name="viewport" content="width=device-width, initial-scale=1">
6251 <title>\(path) · \(escapingHTML(siteTitle))</title>
6351 <link rel="stylesheet" href="\(root)\(SiteStylesheet.fileName)">
6451 </head>
6551 <body class="source-page">
6651 <header class="page-header">
6751 \(SiteHeader(title: siteTitle, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: root).html)
6851 <p class="path">\(path)</p>
6951 \(totalsMarkup)
7051 </header>
7151 <main>
7251 <table class="source">
7351 <tbody>
7451 \(rowsMarkup)
7551 </tbody>
7651 </table>
7751 </main>
7851 \(minimapMarkup)
7951 <script>\(Self.missNavigationScript)</script>
8051 </body>
8151 </html>
8251
8351 """
8451 }
85
8651 private var totalsMarkup: String {
8751 let summary = LineSummary(lines: coverage)
88155 let missed = coverage.count { $0.state == .missed }
89155 let partly = coverage.count { $0.state == .partlyCovered }
9051 return """
9151 <p class="totals"><span class="percent \(summary.tier.rawValue)">\
9251 \(summary.percentText)</span> \(groupingDigits(summary.covered)) of \
9351 \(groupingDigits(summary.count)) lines · \(groupingDigits(missed)) missed · \
9451 \(groupingDigits(partly)) partly covered</p>
9551 """
9651 }
97
9851 private var rowsMarkup: String {
99159 sourceLines.indices.map { index in
100159 let line = lineCoverage(at: index)
101159 let number = index + 1
102159 return """
103159 <tr id="L\(number)" class="\(Self.rowClass(of: line.state))">\
104159 <td class="number"><a href="#L\(number)">\(number)</a></td>\
105159 \(Self.countCell(line.count))\
106159 <td class="code"><code>\(Self.codeMarkup(sourceLines[index], missedSpans: line.missedSpans))</code></td></tr>
107159 """
108159 }.joined(separator: "\n")
10951 }
110
111353 private func lineCoverage(at index: Int) -> LineCoverage {
112353 index < coverage.count ? coverage[index] : LineCoverage(state: .notCode, count: nil)
113353 }
114
115 /// A mark down the right edge for each run of missed or partly covered lines, placed
116 /// and sized by where the run sits in the file; red if any line in it never ran.
11751 private var minimapMarkup: String {
11851 let total = sourceLines.count
11951 var marks: [String] = []
12051 var index = 0
121200 while index < total {
122149 let start = index
123149 var isAnyLineMissed = false
124173 while index < total, lineCoverage(at: index).isMiss {
12524 isAnyLineMissed = isAnyLineMissed || lineCoverage(at: index).state == .missed
12624 index += 1
127149 }
128149 guard index > start else {
129135 index += 1
130135 continue
131135 }
13214 let position = String(
13314 format: "top: %.2f%%; height: %.2f%%", Double(start) * 100 / Double(total),
13414 Double(index - start) * 100 / Double(total))
13514 let state = isAnyLineMissed ? "missed" : "partly"
13614 marks.append(
13714 ##"<a class="mark \##(state)" href="#L\##(start + 1)" style="\##(position)"></a>"##)
13851 }
13951 guard !marks.isEmpty else { return "" }
14012 return #"<nav class="minimap" aria-label="Missed lines">"# + marks.joined() + "</nav>"
14151 }
142
143 /// Measures the sticky header so linked lines land below it, and makes `n` and `p`
144 /// scroll to the next and previous run of misses. Without scripts the page still
145 /// reads; linked lines may sit under a wrapped header and the keys are lost.
146 private static let missNavigationScript = """
147 (() => {
148 const header = document.querySelector(".page-header");
149 const measureHeader = () =>
150 document.documentElement.style.setProperty("--header-height", header.offsetHeight + "px");
151 measureHeader();
152 addEventListener("resize", measureHeader);
153 if (location.hash) document.querySelector(location.hash)?.scrollIntoView();
154 const isMiss = row => row && (row.classList.contains("missed") || row.classList.contains("partly"));
155 const runs = [...document.querySelectorAll("tr.missed, tr.partly")]
156 .filter(row => !isMiss(row.previousElementSibling));
157 document.addEventListener("keydown", event => {
158 if (event.metaKey || event.ctrlKey || event.altKey || (event.key !== "n" && event.key !== "p")) return;
159 // Rows land a little below the sticky header, and "next" means below that spot,
160 // so pressing n again moves on instead of finding the same row.
161 const spot = header.getBoundingClientRect().bottom + 24;
162 const target = event.key === "n"
163 ? runs.find(row => row.getBoundingClientRect().top > spot + 2)
164 : runs.findLast(row => row.getBoundingClientRect().top < spot - 2);
165 if (!target) return;
166 event.preventDefault();
167 window.scrollBy(0, target.getBoundingClientRect().top - spot);
168 history.replaceState(null, "", "#" + target.id);
169 });
170 })();
171 """
172
173159 private static func rowClass(of state: LineState) -> String {
174159 switch state {
175159 case .notCode: "plain"
176159 case .covered: "covered"
177159 case .partlyCovered: "partly"
178159 case .missed: "missed"
179159 }
180159 }
181
182 /// llvm-cov clamps a counter that wrapped around to `Int64.max` (docs/DESIGN.md,
183 /// D2); printing it would only mislead.
184159 private static func countCell(_ count: UInt64?) -> String {
185159 guard let count else { return #"<td class="count"></td>"# }
186147 guard count < UInt64(Int64.max) else {
1871 return #"<td class="count" title="The counter overflowed"></td>"#
188146 }
189146 return #"<td class="count">\#(shortened(count))</td>"#
190159 }
191
192146 private static func shortened(_ count: UInt64) -> String {
193146 guard count >= 10_000 else { return String(count) }
1946 for (scale, unit) in [(1e9, "G"), (1e6, "M"), (1e3, "k")] where Double(count) >= scale {
1956 let value = Double(count) / scale
1966 return String(format: value < 100 ? "%.1f%@" : "%.0f%@", value, unit)
1976 }
1980 return String(count)
199146 }
200
201 /// llvm-cov's columns count UTF-8 bytes, so spans are cut in bytes, not characters.
202159 private static func codeMarkup(_ line: Substring, missedSpans: [ColumnSpan]) -> String {
203159 let bytes = Array(line.utf8)
204187 func text(_ range: Range<Int>) -> String {
205187 escapingHTML(String(decoding: bytes[range], as: UTF8.self))
206187 }
207159 var markup = ""
208159 var cursor = 0
209159 for span in missedSpans {
21014 let start = min(max(span.start - 1, cursor), bytes.count)
21114 let end = min(max((span.end ?? bytes.count + 1) - 1, start), bytes.count)
21214 markup +=
21314 text(cursor..<start) + #"<span class="unrun">"# + text(start..<end) + "</span>"
21414 cursor = end
215159 }
216159 return markup + text(cursor..<bytes.count)
217159 }
218}
219
220extension LineCoverage {
221170 fileprivate var isMiss: Bool { state == .missed || state == .partlyCovered }
222}