| 1 | | import Foundation |
| 2 | | |
| 3 | | /// The coverage page of one source file: its code, line by line, marked with what ran. |
| 4 | | public 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] |
| 21 | 43 | ) { |
| 22 | 43 | self.relativePath = relativePath |
| 23 | 43 | self.siteTitle = siteTitle |
| 24 | 43 | self.hasTestsPage = hasTestsPage |
| 25 | 43 | self.sourceLines = Self.lines(of: source) |
| 26 | 43 | self.coverage = coverage |
| 27 | 43 | } |
| 28 | | |
| 29 | | /// The number of lines in `source`; a final line break doesn't start another line. |
| 30 | 31 | public static func lineCount(of source: String) -> Int { |
| 31 | 31 | lines(of: source).count |
| 32 | 31 | } |
| 33 | | |
| 34 | 74 | private static func lines(of source: String) -> [Substring] { |
| 35 | 74 | var lines = source.split(separator: "\n", omittingEmptySubsequences: false) |
| 36 | 74 | if lines.last?.isEmpty == true { |
| 37 | 73 | lines.removeLast() |
| 38 | 73 | } |
| 39 | 74 | return lines |
| 40 | 74 | } |
| 41 | | |
| 42 | | /// Where the page goes, relative to the site's root: `coverage/<relativePath>.html`. |
| 43 | 78 | public var sitePath: String { |
| 44 | 78 | Self.sitePath(for: relativePath) |
| 45 | 78 | } |
| 46 | | |
| 47 | 189 | static func sitePath(for relativePath: String) -> String { |
| 48 | 189 | "coverage/\(relativePath).html" |
| 49 | 189 | } |
| 50 | | |
| 51 | | /// The whole page. Links to the stylesheet and the tabs are relative, so the site |
| 52 | | /// works from any folder or host. |
| 53 | 51 | public var html: String { |
| 54 | 51 | let root = String(repeating: "../", count: sitePath.split(separator: "/").count - 1) |
| 55 | 51 | let path = escapingHTML(relativePath) |
| 56 | 51 | return """ |
| 57 | 51 | <!doctype html> |
| 58 | 51 | <html lang="en"> |
| 59 | 51 | <head> |
| 60 | 51 | <meta charset="utf-8"> |
| 61 | 51 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 62 | 51 | <title>\(path) · \(escapingHTML(siteTitle))</title> |
| 63 | 51 | <link rel="stylesheet" href="\(root)\(SiteStylesheet.fileName)"> |
| 64 | 51 | </head> |
| 65 | 51 | <body class="source-page"> |
| 66 | 51 | <header class="page-header"> |
| 67 | 51 | \(SiteHeader(title: siteTitle, currentTab: .coverage, hasTestsPage: hasTestsPage, rootPath: root).html) |
| 68 | 51 | <p class="path">\(path)</p> |
| 69 | 51 | \(totalsMarkup) |
| 70 | 51 | </header> |
| 71 | 51 | <main> |
| 72 | 51 | <table class="source"> |
| 73 | 51 | <tbody> |
| 74 | 51 | \(rowsMarkup) |
| 75 | 51 | </tbody> |
| 76 | 51 | </table> |
| 77 | 51 | </main> |
| 78 | 51 | \(minimapMarkup) |
| 79 | 51 | <script>\(Self.missNavigationScript)</script> |
| 80 | 51 | </body> |
| 81 | 51 | </html> |
| 82 | 51 | |
| 83 | 51 | """ |
| 84 | 51 | } |
| 85 | | |
| 86 | 51 | private var totalsMarkup: String { |
| 87 | 51 | let summary = LineSummary(lines: coverage) |
| 88 | 155 | let missed = coverage.count { $0.state == .missed } |
| 89 | 155 | let partly = coverage.count { $0.state == .partlyCovered } |
| 90 | 51 | return """ |
| 91 | 51 | <p class="totals"><span class="percent \(summary.tier.rawValue)">\ |
| 92 | 51 | \(summary.percentText)</span> \(groupingDigits(summary.covered)) of \ |
| 93 | 51 | \(groupingDigits(summary.count)) lines · \(groupingDigits(missed)) missed · \ |
| 94 | 51 | \(groupingDigits(partly)) partly covered</p> |
| 95 | 51 | """ |
| 96 | 51 | } |
| 97 | | |
| 98 | 51 | private var rowsMarkup: String { |
| 99 | 159 | sourceLines.indices.map { index in |
| 100 | 159 | let line = lineCoverage(at: index) |
| 101 | 159 | let number = index + 1 |
| 102 | 159 | return """ |
| 103 | 159 | <tr id="L\(number)" class="\(Self.rowClass(of: line.state))">\ |
| 104 | 159 | <td class="number"><a href="#L\(number)">\(number)</a></td>\ |
| 105 | 159 | \(Self.countCell(line.count))\ |
| 106 | 159 | <td class="code"><code>\(Self.codeMarkup(sourceLines[index], missedSpans: line.missedSpans))</code></td></tr> |
| 107 | 159 | """ |
| 108 | 159 | }.joined(separator: "\n") |
| 109 | 51 | } |
| 110 | | |
| 111 | 353 | private func lineCoverage(at index: Int) -> LineCoverage { |
| 112 | 353 | index < coverage.count ? coverage[index] : LineCoverage(state: .notCode, count: nil) |
| 113 | 353 | } |
| 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. |
| 117 | 51 | private var minimapMarkup: String { |
| 118 | 51 | let total = sourceLines.count |
| 119 | 51 | var marks: [String] = [] |
| 120 | 51 | var index = 0 |
| 121 | 200 | while index < total { |
| 122 | 149 | let start = index |
| 123 | 149 | var isAnyLineMissed = false |
| 124 | 173 | while index < total, lineCoverage(at: index).isMiss { |
| 125 | 24 | isAnyLineMissed = isAnyLineMissed || lineCoverage(at: index).state == .missed |
| 126 | 24 | index += 1 |
| 127 | 149 | } |
| 128 | 149 | guard index > start else { |
| 129 | 135 | index += 1 |
| 130 | 135 | continue |
| 131 | 135 | } |
| 132 | 14 | let position = String( |
| 133 | 14 | format: "top: %.2f%%; height: %.2f%%", Double(start) * 100 / Double(total), |
| 134 | 14 | Double(index - start) * 100 / Double(total)) |
| 135 | 14 | let state = isAnyLineMissed ? "missed" : "partly" |
| 136 | 14 | marks.append( |
| 137 | 14 | ##"<a class="mark \##(state)" href="#L\##(start + 1)" style="\##(position)"></a>"##) |
| 138 | 51 | } |
| 139 | 51 | guard !marks.isEmpty else { return "" } |
| 140 | 12 | return #"<nav class="minimap" aria-label="Missed lines">"# + marks.joined() + "</nav>" |
| 141 | 51 | } |
| 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 | | |
| 173 | 159 | private static func rowClass(of state: LineState) -> String { |
| 174 | 159 | switch state { |
| 175 | 159 | case .notCode: "plain" |
| 176 | 159 | case .covered: "covered" |
| 177 | 159 | case .partlyCovered: "partly" |
| 178 | 159 | case .missed: "missed" |
| 179 | 159 | } |
| 180 | 159 | } |
| 181 | | |
| 182 | | /// llvm-cov clamps a counter that wrapped around to `Int64.max` (docs/DESIGN.md, |
| 183 | | /// D2); printing it would only mislead. |
| 184 | 159 | private static func countCell(_ count: UInt64?) -> String { |
| 185 | 159 | guard let count else { return #"<td class="count"></td>"# } |
| 186 | 147 | guard count < UInt64(Int64.max) else { |
| 187 | 1 | return #"<td class="count" title="The counter overflowed"></td>"# |
| 188 | 146 | } |
| 189 | 146 | return #"<td class="count">\#(shortened(count))</td>"# |
| 190 | 159 | } |
| 191 | | |
| 192 | 146 | private static func shortened(_ count: UInt64) -> String { |
| 193 | 146 | guard count >= 10_000 else { return String(count) } |
| 194 | 6 | for (scale, unit) in [(1e9, "G"), (1e6, "M"), (1e3, "k")] where Double(count) >= scale { |
| 195 | 6 | let value = Double(count) / scale |
| 196 | 6 | return String(format: value < 100 ? "%.1f%@" : "%.0f%@", value, unit) |
| 197 | 6 | } |
| 198 | 0 | return String(count) |
| 199 | 146 | } |
| 200 | | |
| 201 | | /// llvm-cov's columns count UTF-8 bytes, so spans are cut in bytes, not characters. |
| 202 | 159 | private static func codeMarkup(_ line: Substring, missedSpans: [ColumnSpan]) -> String { |
| 203 | 159 | let bytes = Array(line.utf8) |
| 204 | 187 | func text(_ range: Range<Int>) -> String { |
| 205 | 187 | escapingHTML(String(decoding: bytes[range], as: UTF8.self)) |
| 206 | 187 | } |
| 207 | 159 | var markup = "" |
| 208 | 159 | var cursor = 0 |
| 209 | 159 | for span in missedSpans { |
| 210 | 14 | let start = min(max(span.start - 1, cursor), bytes.count) |
| 211 | 14 | let end = min(max((span.end ?? bytes.count + 1) - 1, start), bytes.count) |
| 212 | 14 | markup += |
| 213 | 14 | text(cursor..<start) + #"<span class="unrun">"# + text(start..<end) + "</span>" |
| 214 | 14 | cursor = end |
| 215 | 159 | } |
| 216 | 159 | return markup + text(cursor..<bytes.count) |
| 217 | 159 | } |
| 218 | | } |
| 219 | | |
| 220 | | extension LineCoverage { |
| 221 | 170 | fileprivate var isMiss: Bool { state == .missed || state == .partlyCovered } |
| 222 | | } |