1import Foundation
2
3/// How a module's or file's line coverage moved since the baseline run (DESIGN.md D6).
4enum LineChange: Equatable {
5 /// Not in the baseline.
6 case new
7 /// Percentage points gained (positive) or lost (negative).
8 case points(Double)
9
10 /// What the table shows: `new`, or points to one decimal with a sign, such as `+0.4`.
11 /// A move that rounds to nothing shows `0.0`.
1247 var text: String {
1347 switch self {
1447 case .new: "new"
1547 case .points: roundedPoints == 0 ? "0.0" : String(format: "%+.1f", roundedPoints)
1647 }
1747 }
18
19 /// The style the table gives the change: `new`, `up`, `down` or `flat`.
2037 var styleName: String {
2137 switch self {
2237 case .new: "new"
2337 case .points: roundedPoints > 0 ? "up" : roundedPoints < 0 ? "down" : "flat"
2437 }
2537 }
26
2768 private var roundedPoints: Double {
2868 guard case .points(let points) = self else { return 0 }
2968 return (points * 10).rounded() / 10
3068 }
31}
32
33/// The current run's modules and files set against an earlier run's `totals.json`.
34struct BaselineComparison {
35 private let total: RunTotals.Lines
36 private let modules: [String: RunTotals.Lines]
37 private let files: [String: RunTotals.Lines]
38
3910 init(baseline: RunTotals) {
4010 total = baseline.lines
4110 modules = Dictionary(uniqueKeysWithValues: baseline.modules.map { ($0.name, $0.lines) })
4210 files = Dictionary(
4311 uniqueKeysWithValues: baseline.modules.flatMap(\.files).map { ($0.path, $0.lines) })
4410 }
45
46 /// The whole run's line coverage, which the baseline always has, so never `.new`.
478 func changeOfTotal(now: LineSummary) -> LineChange {
488 Self.change(from: total, to: now)
498 }
50
5118 func change(ofModule name: String, now: LineSummary) -> LineChange {
5218 Self.change(from: modules[name], to: now)
5318 }
54
55 /// - Parameter path: below the sources folder, as in `FileTotals.relativePath`.
5622 func change(ofFile path: String, now: LineSummary) -> LineChange {
5722 Self.change(from: files[path], to: now)
5822 }
59
6048 private static func change(from before: RunTotals.Lines?, to now: LineSummary) -> LineChange {
6148 guard let before else { return .new }
6225 return .points(
6325 now.percent - LineSummary(count: before.total, covered: before.covered).percent)
6448 }
65}