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