1import Foundation
2
3/// Coverage over time, including gaps for missing metrics and runs without data.
4public struct CoverageTrend: Sendable {
5 private let runs: [RunTotals]
6 private static let padding = 4.0
7 private static let sparklineWidth = 120.0
8 private static let sparklineHeight = 32.0
9 private static let chartWidth = 640.0
10 private static let chartHeight = 160.0
11 private static let pointRadius = 2
12 private static let unavailableRadius = 3
13 /// The least share of coverage the vertical axis spans, so a 0.1-point change isn't
14 /// drawn as a cliff.
15 private static let minimumSpan = 0.035
16
17 /// Accepts runs in any order; points are ordered by date, then commit.
1866 public init(runs: [RunTotals]) {
1966 self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") }
2066 }
21
22 /// A compact line-only chart; empty when no runs were supplied.
2348 public var sparkline: String {
2448 svg(
2548 width: Self.sparklineWidth, height: Self.sparklineHeight,
2648 metrics: [("lines", { $0.lines })])
2748 }
28
29 /// Lines and any recorded branch/condition series, with no-data markers.
3022 public var chart: String {
3122 svg(
3222 width: Self.chartWidth, height: Self.chartHeight,
3322 metrics: [
3436 ("lines", { $0.lines }), ("branches", { $0.branches }),
3536 ("conditions", { $0.conditions }),
3622 ])
3722 }
38
39 /// The vertical axis as text, for example `89.8%–99.9%`; nil when nothing is plotted.
40 /// The axis fits the plotted values rather than starting at 0%, so readers need it.
4117 public var scaleText: String? {
4217 guard let axis else { return nil }
4313 return "\(Self.percent(axis.lowerBound))–\(Self.percent(axis.upperBound))"
4417 }
45
46 /// Fractions covered that every series plots, widened to the minimum span and kept
47 /// inside 0...1.
4860 private var axis: ClosedRange<Double>? {
4960 var fractions: [Double] = []
5093 for run in runs where run.unavailable == nil {
51279 for count in [run.lines, run.branches, run.conditions] {
52279 guard let count, count.total > 0 else { continue }
53103 fractions.append(Double(count.covered) / Double(count.total))
54103 }
5593 }
5660 guard let low = fractions.min(), let high = fractions.max() else { return nil }
5752 let extra = max(0, Self.minimumSpan - (high - low)) / 2
5852 let upper = min(1, high + extra)
5952 let lower = max(0, min(low - extra, upper - Self.minimumSpan))
6052 return lower...upper
6160 }
62
63 private func svg(
64 width: Double, height: Double, metrics: [(String, (RunTotals) -> RunTotals.Lines?)]
6570 ) -> String {
6670 guard !runs.isEmpty else { return "" }
6743 let plotWidth = width - Self.padding * 2
6843 let plotHeight = height - Self.padding * 2
6975 let x = { (index: Int) in
7075 Self.padding
7175 + (self.runs.count == 1
7275 ? plotWidth / 2 : Double(index) / Double(self.runs.count - 1) * plotWidth)
7375 }
7443 let axis = self.axis ?? 0...1
7585 let series = metrics.map { name, metric in
7685 var segments: [[String]] = []
7785 var points: [String] = []
78154 for (index, run) in runs.enumerated() {
79154 if run.unavailable == nil, let count = metric(run), count.total > 0 {
8069 let percentage = Double(count.covered) / Double(count.total)
8169 points.append(
8269 "\(Self.number(x(index))),\(Self.number(Self.padding + (axis.upperBound - percentage) / (axis.upperBound - axis.lowerBound) * plotHeight))"
8369 )
8485 } else if !points.isEmpty {
856 segments.append(points)
866 points = []
876 }
88154 }
8985 if !points.isEmpty { segments.append(points) }
9085 return segments.map { segment in
9151 if segment.count == 1, let point = segment.first {
9239 let coordinates = point.split(separator: ",")
9339 return
9439 #"<circle class="trend-\#(name)" cx="\#(coordinates[0])" cy="\#(coordinates[1])" r="\#(Self.pointRadius)"/>"#
9539 }
9612 return
9712 #"<polyline class="trend-\#(name)" points="\#(segment.joined(separator: " "))"/>"#
9851 }.joined()
9985 }.joined()
10070 let missing = runs.enumerated().filter { $0.element.unavailable != nil }.map { index, _ in
1016 #"<circle class="trend-unavailable" cx="\#(Self.number(x(index)))" cy="\#(Self.number(height - Self.padding))" r="\#(Self.unavailableRadius)"><title>No coverage data</title></circle>"#
1026 }.joined()
10343 return
10443 #"<svg class="coverage-trend" viewBox="0 0 \#(Self.number(width)) \#(Self.number(height))" role="img" aria-label="Coverage history"><title>Coverage history</title>\#(series)\#(missing)</svg>"#
10570 }
106
10726 private static func percent(_ fraction: Double) -> String {
10826 String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100)
10926 }
110
111236 private static func number(_ value: Double) -> String {
112236 String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value)
113236 }
114}