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.
1869 public init(runs: [RunTotals]) {
1969 self.runs = runs.sorted { ($0.date, $0.commit ?? "") < ($1.date, $1.commit ?? "") }
2069 }
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.
3024 public var chart: String {
3124 svg(
3224 width: Self.chartWidth, height: Self.chartHeight,
3324 metrics: [
3441 ("lines", { $0.lines }), ("branches", { $0.branches }),
3541 ("conditions", { $0.conditions }),
3624 ])
3724 }
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.
4118 public var scaleText: String? {
4218 guard let axis else { return nil }
4314 return "\(Self.percent(axis.lowerBound))–\(Self.percent(axis.upperBound))"
4418 }
45
46 /// Fractions covered that every series plots, widened to the minimum span and kept
47 /// inside 0...1.
4863 private var axis: ClosedRange<Double>? {
4963 var fractions: [Double] = []
50101 for run in runs where run.unavailable == nil {
51303 for count in [run.lines, run.branches, run.conditions] {
52303 guard let count, count.total > 0 else { continue }
53111 fractions.append(Double(count.covered) / Double(count.total))
54111 }
55101 }
5663 guard let low = fractions.min(), let high = fractions.max() else { return nil }
5755 let extra = max(0, Self.minimumSpan - (high - low)) / 2
5855 let upper = min(1, high + extra)
5955 let lower = max(0, min(low - extra, upper - Self.minimumSpan))
6055 return lower...upper
6163 }
62
63 private func svg(
64 width: Double, height: Double, metrics: [(String, (RunTotals) -> RunTotals.Lines?)]
6572 ) -> String {
6672 guard !runs.isEmpty else { return "" }
6745 let plotWidth = width - Self.padding * 2
6845 let plotHeight = height - Self.padding * 2
6980 let x = { (index: Int) in
7080 Self.padding
7180 + (self.runs.count == 1
7280 ? plotWidth / 2 : Double(index) / Double(self.runs.count - 1) * plotWidth)
7380 }
7445 let axis = self.axis ?? 0...1
7591 let series = metrics.map { name, metric in
7691 var segments: [[String]] = []
7791 var points: [String] = []
78169 for (index, run) in runs.enumerated() {
79169 if run.unavailable == nil, let count = metric(run), count.total > 0 {
8074 let percentage = Double(count.covered) / Double(count.total)
8174 points.append(
8274 "\(Self.number(x(index))),\(Self.number(Self.padding + (axis.upperBound - percentage) / (axis.upperBound - axis.lowerBound) * plotHeight))"
8374 )
8495 } else if !points.isEmpty {
856 segments.append(points)
866 points = []
876 }
88169 }
8991 if !points.isEmpty { segments.append(points) }
9091 let bridges = zip(segments, segments.dropFirst()).compactMap { earlier, later in
915 earlier.last.flatMap { from in
925 later.first.map { to in
935 #"<polyline class="trend-\#(name) trend-gap" points="\#(from) \#(to)"/>"#
945 }
955 }
965 }
9791 return bridges.joined()
9891 + segments.map { segment in
9953 if segment.count == 1, let point = segment.first {
10039 let coordinates = point.split(separator: ",")
10139 return
10239 #"<circle class="trend-\#(name)" cx="\#(coordinates[0])" cy="\#(coordinates[1])" r="\#(Self.pointRadius)"/>"#
10339 }
10414 return
10514 #"<polyline class="trend-\#(name)" points="\#(segment.joined(separator: " "))"/>"#
10653 }.joined()
10791 }.joined()
10875 let missing = runs.enumerated().filter { $0.element.unavailable != nil }.map { index, _ in
1096 #"<circle class="trend-unavailable" cx="\#(Self.number(x(index)))" cy="\#(Self.number(height - Self.padding))" r="\#(Self.unavailableRadius)"><title>No coverage data</title></circle>"#
1106 }.joined()
11145 return
11245 #"<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>"#
11372 }
114
11528 private static func percent(_ fraction: Double) -> String {
11628 String(format: "%.1f%%", locale: Locale(identifier: "en_US_POSIX"), fraction * 100)
11728 }
118
119250 private static func number(_ value: Double) -> String {
120250 String(format: "%.1f", locale: Locale(identifier: "en_US_POSIX"), value)
121250 }
122}