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()
2669 ) {
2769 self.run = run
2869 self.regions = regions
2969 self.relativePath = relativePath
3069 self.siteTitle = siteTitle
3169 self.hasTestsPage = hasTestsPage
3269 self.sourceLines = Self.lines(of: source)
3369 self.coverage = coverage
3469 }
35
36 /// The number of lines in `source`; a final line break doesn't start another line.
3755 public static func lineCount(of source: String) -> Int {
3855 lines(of: source).count
3955 }
40
41124 private static func lines(of source: String) -> [Substring] {
42124 var lines = source.split(separator: "\n", omittingEmptySubsequences: false)
43124 if lines.last?.isEmpty == true {
44123 lines.removeLast()
45123 }
46124 return lines
47124 }
48
49 /// Where the page goes, relative to the site's root: `coverage/<relativePath>.html`.
50128 public var sitePath: String {
51128 Self.sitePath(for: relativePath)
52128 }
53
54302 static func sitePath(for relativePath: String) -> String {
55302 "coverage/\(relativePath).html"
56302 }
57
58 /// The whole page. Links to the stylesheet and the tabs are relative, so the site
59 /// works from any folder or host.
6077 public var html: String {
6177 let root = String(repeating: "../", count: sitePath.split(separator: "/").count - 1)
6277 let path = escapingHTML(relativePath)
6377 return """
6477 <!doctype html>
6577 <html lang="en">
6677 <head>
6777 <meta charset="utf-8">
6877 <meta name="viewport" content="width=device-width, initial-scale=1">
6977 <title>\(path) · \(escapingHTML(siteTitle))</title>
7077 <link rel="stylesheet" href="\(root)\(SiteStylesheet.fileName)">
7177 </head>
7277 <body class="source-page">
7377 <header class="page-header">
7477 \(SiteHeader(title: siteTitle, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: root, run: run).html)
7577 <p class="path">\(path)</p>
7677 \(totalsMarkup)
7777 </header>
7877 <main>
7977 <table class="source">
8077 <tbody>
8177 \(rowsMarkup)
8277 </tbody>
8377 </table>
8477 </main>
8577 \(minimapMarkup)
8677 <script>\(Self.missNavigationScript)</script>
8777 </body>
8877 </html>
8977
9077 """
9177 }
92
9377 private var totalsMarkup: String {
9477 let summary = LineSummary(lines: coverage)
95195 let missed = coverage.count { $0.state == .missed }
96195 let partly = coverage.count { $0.state == .partlyCovered }
9777 return """
9877 <p class="totals"><span class="percent \(summary.tier.rawValue)">\
9977 \(summary.percentText)</span> \(groupingDigits(summary.covered)) of \
10077 \(groupingDigits(summary.count)) lines · \(groupingDigits(missed)) missed · \
10177 \(groupingDigits(partly)) partly covered\(regionsMarkup)</p>
10277 """
10377 }
104
10577 private var regionsMarkup: String {
10677 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"
11177 }
112
11377 private var rowsMarkup: String {
114199 sourceLines.indices.map { index in
115199 let line = lineCoverage(at: index)
116199 let number = index + 1
117199 return """
118199 <tr id="L\(number)" class="\(Self.rowClass(of: line.state))">\
119199 <td class="number"><a href="#L\(number)">\(number)</a></td>\
120199 \(Self.countCell(line.count))\
121199 <td class="code"><code>\(Self.codeMarkup(sourceLines[index], missedSpans: line.missedSpans))</code></td></tr>
122199 """
123199 }.joined(separator: "\n")
12477 }
125
126433 private func lineCoverage(at index: Int) -> LineCoverage {
127433 index < coverage.count ? coverage[index] : LineCoverage(state: .notCode, count: nil)
128433 }
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.
13277 private var minimapMarkup: String {
13377 let total = sourceLines.count
13477 var marks: [String] = []
13577 var index = 0
136266 while index < total {
137189 let start = index
138189 var isAnyLineMissed = false
139213 while index < total, lineCoverage(at: index).isMiss {
14024 isAnyLineMissed = isAnyLineMissed || lineCoverage(at: index).state == .missed
14124 index += 1
142189 }
143189 guard index > start else {
144175 index += 1
145175 continue
146175 }
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>"##)
15377 }
15477 guard !marks.isEmpty else { return "" }
15512 return #"<nav class="minimap" aria-label="Missed lines">"# + marks.joined() + "</nav>"
15677 }
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
188199 private static func rowClass(of state: LineState) -> String {
189199 switch state {
190199 case .notCode: "plain"
191199 case .covered: "covered"
192199 case .partlyCovered: "partly"
193199 case .missed: "missed"
194199 }
195199 }
196
197 /// llvm-cov clamps a counter that wrapped around to `Int64.max` (docs/DESIGN.md,
198 /// D2); printing it would only mislead.
199199 private static func countCell(_ count: UInt64?) -> String {
200199 guard let count else { return #"<td class="count"></td>"# }
201187 guard count < UInt64(Int64.max) else {
2021 return #"<td class="count" title="The counter overflowed"></td>"#
203186 }
204186 return #"<td class="count">\#(shortened(count))</td>"#
205199 }
206
207186 private static func shortened(_ count: UInt64) -> String {
208186 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)
214186 }
215
216 /// llvm-cov's columns count UTF-8 bytes, so spans are cut in bytes, not characters.
217199 private static func codeMarkup(_ line: Substring, missedSpans: [ColumnSpan]) -> String {
218199 let bytes = Array(line.utf8)
219227 func text(_ range: Range<Int>) -> String {
220227 escapingHTML(String(decoding: bytes[range], as: UTF8.self))
221227 }
222199 var markup = ""
223199 var cursor = 0
224199 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
230199 }
231199 return markup + text(cursor..<bytes.count)
232199 }
233}
234
235extension LineCoverage {
236210 fileprivate var isMiss: Bool { state == .missed || state == .partlyCovered }
237}