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
54272 static func sitePath(for relativePath: String) -> String {
55272 "coverage/\(relativePath).html"
56272 }
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"
1107 + " · \(groupingDigits(regions.total - regions.covered)) missed"
11167 }
112
11367 private var rowsMarkup: String {
114174 sourceLines.indices.map { index in
115174 let line = lineCoverage(at: index)
116174 let number = index + 1
117174 return """
118174 <tr id="L\(number)" class="\(Self.rowClass(of: line.state))">\
119174 <td class="number"><a href="#L\(number)">\(number)</a></td>\
120174 \(Self.countCell(line.count))\
121174 <td class="code"><code>\(Self.codeMarkup(sourceLines[index], missedSpans: line.missedSpans))</code></td></tr>
122174 """
123174 }.joined(separator: "\n")
12467 }
125
126383 private func lineCoverage(at index: Int) -> LineCoverage {
127383 index < coverage.count ? coverage[index] : LineCoverage(state: .notCode, count: nil)
128383 }
129
130 /// A mark down the right edge for each run of missed or partly covered lines, placed
131 /// and sized by where the run sits in the file; red if any line in it never ran.
13267 private var minimapMarkup: String {
13367 let total = sourceLines.count
13467 var marks: [String] = []
13567 var index = 0
136231 while index < total {
137164 let start = index
138164 var isAnyLineMissed = false
139188 while index < total, lineCoverage(at: index).isMiss {
14024 isAnyLineMissed = isAnyLineMissed || lineCoverage(at: index).state == .missed
14124 index += 1
142164 }
143164 guard index > start else {
144150 index += 1
145150 continue
146150 }
14714 let position = String(
14814 format: "top: %.2f%%; height: %.2f%%", Double(start) * 100 / Double(total),
14914 Double(index - start) * 100 / Double(total))
15014 let state = isAnyLineMissed ? "missed" : "partly"
15114 marks.append(
15214 ##"<a class="mark \##(state)" href="#L\##(start + 1)" style="\##(position)"></a>"##)
15367 }
15467 guard !marks.isEmpty else { return "" }
15512 return #"<nav class="minimap" aria-label="Missed lines">"# + marks.joined() + "</nav>"
15667 }
157
158 /// Measures the sticky header so linked lines land below it, and makes `n` and `p`
159 /// scroll to the next and previous run of misses. Without scripts the page still
160 /// reads; linked lines may sit under a wrapped header and the keys are lost.
161 private static let missNavigationScript = """
162 (() => {
163 const header = document.querySelector(".page-header");
164 const measureHeader = () =>
165 document.documentElement.style.setProperty("--header-height", header.offsetHeight + "px");
166 measureHeader();
167 addEventListener("resize", measureHeader);
168 if (location.hash) document.querySelector(location.hash)?.scrollIntoView();
169 const isMiss = row => row && (row.classList.contains("missed") || row.classList.contains("partly"));
170 const runs = [...document.querySelectorAll("tr.missed, tr.partly")]
171 .filter(row => !isMiss(row.previousElementSibling));
172 document.addEventListener("keydown", event => {
173 if (event.metaKey || event.ctrlKey || event.altKey || (event.key !== "n" && event.key !== "p")) return;
174 // Rows land a little below the sticky header, and "next" means below that spot,
175 // so pressing n again moves on instead of finding the same row.
176 const spot = header.getBoundingClientRect().bottom + 24;
177 const target = event.key === "n"
178 ? runs.find(row => row.getBoundingClientRect().top > spot + 2)
179 : runs.findLast(row => row.getBoundingClientRect().top < spot - 2);
180 if (!target) return;
181 event.preventDefault();
182 window.scrollBy(0, target.getBoundingClientRect().top - spot);
183 history.replaceState(null, "", "#" + target.id);
184 });
185 })();
186 """
187
188174 private static func rowClass(of state: LineState) -> String {
189174 switch state {
190174 case .notCode: "plain"
191174 case .covered: "covered"
192174 case .partlyCovered: "partly"
193174 case .missed: "missed"
194174 }
195174 }
196
197 /// llvm-cov clamps a counter that wrapped around to `Int64.max` (docs/DESIGN.md,
198 /// D2); printing it would only mislead.
199174 private static func countCell(_ count: UInt64?) -> String {
200174 guard let count else { return #"<td class="count"></td>"# }
201162 guard count < UInt64(Int64.max) else {
2021 return #"<td class="count" title="The counter overflowed"></td>"#
203161 }
204161 return #"<td class="count">\#(shortened(count))</td>"#
205174 }
206
207161 private static func shortened(_ count: UInt64) -> String {
208161 guard count >= 10_000 else { return String(count) }
2096 for (scale, unit) in [(1e9, "G"), (1e6, "M"), (1e3, "k")] where Double(count) >= scale {
2106 let value = Double(count) / scale
2116 return String(format: value < 100 ? "%.1f%@" : "%.0f%@", value, unit)
2126 }
2130 return String(count)
214161 }
215
216 /// llvm-cov's columns count UTF-8 bytes, so spans are cut in bytes, not characters.
217174 private static func codeMarkup(_ line: Substring, missedSpans: [ColumnSpan]) -> String {
218174 let bytes = Array(line.utf8)
219202 func text(_ range: Range<Int>) -> String {
220202 escapingHTML(String(decoding: bytes[range], as: UTF8.self))
221202 }
222174 var markup = ""
223174 var cursor = 0
224174 for span in missedSpans {
22514 let start = min(max(span.start - 1, cursor), bytes.count)
22614 let end = min(max((span.end ?? bytes.count + 1) - 1, start), bytes.count)
22714 markup +=
22814 text(cursor..<start) + #"<span class="unrun">"# + text(start..<end) + "</span>"
22914 cursor = end
230174 }
231174 return markup + text(cursor..<bytes.count)
232174 }
233}
234
235extension LineCoverage {
236185 fileprivate var isMiss: Bool { state == .missed || state == .partlyCovered }
237}