Skip to content

Commit d3fe1f9

Browse files
authored
Merge pull request #71 from a7ex/codex/cobertura-2.2.1
Speed up Cobertura coverage generation for 2.2.1
2 parents 95ca65d + b65afb2 commit d3fe1f9

12 files changed

Lines changed: 315 additions & 49 deletions

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7+
## Version 2.2.1 - 2026-11-18
8+
### CHANGES:
9+
- Speed up `cobertura` output on large result bundles: each package's line rate is now computed in one pass instead of rescanning every file per package.
10+
- For `cobertura` output, the command line tool now runs the `xccov` and `xcresulttool` calls concurrently. If the coverage report fails to load or a requested coverage target doesn't exist, the calls still running are stopped.
11+
- The command line tool now uses an async `@main` entry point, so `CommandlineTool/main.swift` is now `CommandlineTool/XcresultparserCommand.swift`.
12+
713
## Version 2.2.0 - 2026-07-18
814
### FIXES:
915
- Fix issue #69: use canonical Xcode test identifiers instead of Swift Testing suite display names when resolving SonarQube test file paths.

CommandlineTool/main.swift renamed to CommandlineTool/XcresultparserCommand.swift

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//
2-
// main.swift
2+
// XcresultparserCommand.swift
33
// xcresultparser
44
//
55
// Created by Alex da Franca on 11.06.21.
@@ -9,9 +9,10 @@ import ArgumentParser
99
import Foundation
1010
import XcresultparserLib
1111

12-
private let marketingVersion = "2.2.0"
12+
private let marketingVersion = "2.2.1"
1313

14-
struct xcresultparser: ParsableCommand {
14+
@main
15+
struct xcresultparser: AsyncParsableCommand {
1516
static let configuration = CommandConfiguration(
1617
abstract: "xcresultparser \(marketingVersion)\nInterpret binary .xcresult files and print summary in different formats: txt, xml, html or colored cli output."
1718
)
@@ -58,7 +59,7 @@ struct xcresultparser: ParsableCommand {
5859
@Argument(help: "The path to the .xcresult file.")
5960
var xcresultFile: String?
6061

61-
mutating func run() throws {
62+
mutating func run() async throws {
6263
guard version != 1 else {
6364
print(marketingVersion)
6465
return
@@ -82,7 +83,7 @@ struct xcresultparser: ParsableCommand {
8283
try outputJUnitXML(for: xcresult, with: .junit)
8384
case .cobertura:
8485
coverage = 1
85-
try outputCoberturaXML(for: xcresult)
86+
try await outputCoberturaXML(for: xcresult)
8687
case .cli, .md, .txt, .html, .github:
8788
try outputDescription(for: xcresult)
8889
case .warnings, .errors, .warningsAndErrors:
@@ -102,9 +103,9 @@ struct xcresultparser: ParsableCommand {
102103
writeToStdOut(rslt)
103104
}
104105

105-
private func outputCoberturaXML(for xcresult: String) throws {
106-
let converter = try CoberturaCoverageConverter(
107-
with: URL(fileURLWithPath: xcresult),
106+
private func outputCoberturaXML(for xcresult: String) async throws {
107+
let converter = try await CoberturaCoverageConverter(
108+
loadingConcurrently: URL(fileURLWithPath: xcresult),
108109
projectRoot: projectRoot ?? "",
109110
coverageTargets: coverageTargets,
110111
excludedPaths: excludedPaths,
@@ -193,5 +194,3 @@ struct xcresultparser: ParsableCommand {
193194
enum ParseError: Error {
194195
case argumentError
195196
}
196-
197-
xcresultparser.main()

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ You should see the tool respond like this:
9999
```
100100
Error: Missing expected argument '<xcresult-file>'
101101
102-
OVERVIEW: xcresultparser 2.2.0
102+
OVERVIEW: xcresultparser 2.2.1
103103
Interpret binary .xcresult files and print summary in different formats: txt,
104104
xml, html or colored cli output.
105105

‎Scripts/testAndRunSonar.sh‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,11 @@ if [ ! -d "$path_to_xcresults" ]; then
6060
/usr/bin/xcrun xcodebuild clean test -workspace .swiftpm/xcode/package.xcworkspace -scheme xcresultparser -destination "platform=macOS" -resultBundlePath "$path_to_xcresults"
6161
fi
6262

63-
app_project_version=$(grep 'marketingVersion =' CommandlineTool/main.swift | cut -d "=" -f2 | xargs)
63+
app_project_version=$(grep 'marketingVersion =' CommandlineTool/XcresultparserCommand.swift | cut -d "=" -f2 | xargs)
6464

6565
if [ -d "$path_to_xcresults" ]
6666
then
67-
sh runSonar.sh \
67+
sh "$(dirname "$0")/runSonar.sh" \
6868
-s $sonarqube_host_url \
6969
-p $sonarqube_login_token \
7070
-k $sonarqube_project_key \

‎Sources/xcresultparser/CoberturaCoverageConverter.swift‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ public class CoberturaCoverageConverter: CoverageConverter, XmlSerializable {
9696
}
9797
// Sort files to avoid duplicated packages
9898
fileInfo.sort { $0.path > $1.path }
99+
let packageLineCoverage = calculatePackageLineCoverage(in: fileInfo)
99100

100101
var currentPackage = ""
101102
var currentPackageElement: XMLElement!
@@ -117,9 +118,9 @@ public class CoberturaCoverageConverter: CoverageConverter, XmlSerializable {
117118

118119
currentPackage = packageName
119120
if isNewPackage {
120-
let packageLineCoverage = calculatePackageLineCoverage(for: packageName, in: fileInfo)
121+
let lineCoverage = packageLineCoverage[packageName] ?? 0.0
121122
currentPackageElement.addAttribute(XMLNode.nodeAttribute(withName: "name", stringValue: packageName))
122-
currentPackageElement.addAttribute(XMLNode.nodeAttribute(withName: "line-rate", stringValue: "\(packageLineCoverage)"))
123+
currentPackageElement.addAttribute(XMLNode.nodeAttribute(withName: "line-rate", stringValue: "\(lineCoverage)"))
123124
currentPackageElement.addAttribute(XMLNode.nodeAttribute(withName: "branch-rate", stringValue: "1.0"))
124125
currentPackageElement.addAttribute(XMLNode.nodeAttribute(withName: "complexity", stringValue: "0.0"))
125126
currentClassesElement = XMLElement(name: "classes")
@@ -199,21 +200,18 @@ public class CoberturaCoverageConverter: CoverageConverter, XmlSerializable {
199200
return "\(packageName).\(baseName)"
200201
}
201202

202-
private func calculatePackageLineCoverage(for packageName: String, in fileInfoArray: [FileInfo]) -> Float {
203-
let packageFiles = fileInfoArray.filter { file in
203+
private func calculatePackageLineCoverage(in fileInfoArray: [FileInfo]) -> [String: Float] {
204+
var packageCounts = [String: (total: Int, covered: Int)]()
205+
for file in fileInfoArray {
204206
let pathComponents = file.path.split(separator: "/")
205-
let filePackageName = createValidPackageName(from: pathComponents)
206-
return filePackageName == packageName
207+
let packageName = createValidPackageName(from: pathComponents)
208+
packageCounts[packageName, default: (0, 0)].total += file.lines.count
209+
packageCounts[packageName, default: (0, 0)].covered += file.lines.count(where: { $0.coverage > 0 })
207210
}
208211

209-
guard !packageFiles.isEmpty else { return 0.0 }
210-
211-
let totalLines = packageFiles.reduce(0) { $0 + $1.lines.count }
212-
let coveredLines = packageFiles.reduce(0) { total, file in
213-
total + file.lines.count(where: { $0.coverage > 0 })
212+
return packageCounts.mapValues { counts in
213+
counts.total > 0 ? Float(counts.covered) / Float(counts.total) : 0.0
214214
}
215-
216-
return totalLines > 0 ? Float(coveredLines) / Float(totalLines) : 0.0
217215
}
218216

219217
private var dtd04 = """

‎Sources/xcresultparser/CoverageConverter.swift‎

Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@
77

88
import Foundation
99

10+
struct PrefetchedCoverageInputs {
11+
let report: CoverageReport
12+
let startTime: Double?
13+
let data: FileCoverage
14+
}
15+
1016
public enum CoverageConverterError: LocalizedError, Equatable {
1117
case couldNotLoadCoverageReport
1218
case unknownCoverageTargets(requested: [String], available: [String])
@@ -50,6 +56,7 @@ public class CoverageConverter {
5056
let excludedPaths: Set<String>
5157
let strictPathnames: Bool
5258
let startTime: Double?
59+
private let prefetchedCoverage: FileCoverage?
5360

5461
// MARK: - Dependencies
5562

@@ -74,20 +81,61 @@ public class CoverageConverter {
7481
)
7582
}
7683

84+
/// Runs xccov and xcresulttool concurrently.
85+
/// If the coverage report fails to load or a requested target doesn't exist,
86+
/// the runs still in progress are terminated.
87+
package convenience init(
88+
loadingConcurrently url: URL,
89+
projectRoot: String = "",
90+
coverageTargets: [String] = [],
91+
excludedPaths: [String] = [],
92+
strictPathnames: Bool
93+
) async throws {
94+
async let fetchedReport = try await XCCovClient().coverageReport(path: url)
95+
async let fetchedStartTime = try? await XCResultToolClient().testSummary(path: url).startTime
96+
async let fetchedData = try await XCCovClient().coverageData(path: url)
97+
98+
let report: CoverageReport
99+
do {
100+
report = try await fetchedReport
101+
} catch {
102+
throw CoverageConverterError.couldNotLoadCoverageReport
103+
}
104+
// Report unknown targets before waiting for the other runs, as the synchronous initialiser does.
105+
_ = try CoverageConverter.selectCoverageTargets(coverageTargets, in: report)
106+
let startTime = await fetchedStartTime
107+
let data = try await fetchedData
108+
try self.init(
109+
with: url,
110+
projectRoot: projectRoot,
111+
coverageTargets: coverageTargets,
112+
excludedPaths: excludedPaths,
113+
strictPathnames: strictPathnames,
114+
xcResultToolClient: XCResultToolClient(),
115+
xcCovClient: XCCovClient(),
116+
prefetchedInputs: PrefetchedCoverageInputs(report: report, startTime: startTime, data: data)
117+
)
118+
}
119+
77120
init(
78121
with url: URL,
79122
projectRoot: String = "",
80123
coverageTargets: [String] = [],
81124
excludedPaths: [String] = [],
82125
strictPathnames: Bool,
83126
xcResultToolClient: XCResultToolProviding,
84-
xcCovClient: XCCovProviding
127+
xcCovClient: XCCovProviding,
128+
prefetchedInputs: PrefetchedCoverageInputs? = nil
85129
) throws {
86130
let report: CoverageReport
87-
do {
88-
report = try xcCovClient.getCoverageReport(path: url)
89-
} catch {
90-
throw CoverageConverterError.couldNotLoadCoverageReport
131+
if let prefetchedInputs {
132+
report = prefetchedInputs.report
133+
} else {
134+
do {
135+
report = try xcCovClient.getCoverageReport(path: url)
136+
} catch {
137+
throw CoverageConverterError.couldNotLoadCoverageReport
138+
}
91139
}
92140

93141
self.xcresultToolClient = xcResultToolClient
@@ -96,18 +144,8 @@ public class CoverageConverter {
96144
coverageReport = report
97145
self.projectRoot = projectRoot
98146
self.strictPathnames = projectRoot.isEmpty ? false : strictPathnames
99-
let targetSelection = CoverageTargetSelection(
100-
with: coverageTargets,
101-
from: report.targets.map(\.name)
102-
)
103-
let selectedCoverageTargets = targetSelection.selectedTargets
147+
let selectedCoverageTargets = try CoverageConverter.selectCoverageTargets(coverageTargets, in: report)
104148
self.coverageTargets = selectedCoverageTargets
105-
if !targetSelection.unmatchedRequested.isEmpty {
106-
throw CoverageConverterError.unknownCoverageTargets(
107-
requested: targetSelection.unmatchedRequested.sorted(),
108-
available: targetSelection.availableTargets.sorted()
109-
)
110-
}
111149
let includedTargetFiles = report.targets
112150
.filter { selectedCoverageTargets.contains($0.name) }
113151
.flatMap { $0.files.map(\.path) }
@@ -116,13 +154,26 @@ public class CoverageConverter {
116154
projectRoot: projectRoot
117155
)
118156
self.excludedPaths = Set(excludedPaths)
119-
startTime = if let summary = try? xcResultToolClient.getTestSummary(path: url) {
120-
summary.startTime
157+
if let prefetchedInputs {
158+
startTime = prefetchedInputs.startTime
159+
prefetchedCoverage = prefetchedInputs.data
121160
} else {
122-
nil
161+
startTime = try? xcResultToolClient.getTestSummary(path: url).startTime
162+
prefetchedCoverage = nil
123163
}
124164
}
125165

166+
static func selectCoverageTargets(_ targets: [String], in report: CoverageReport) throws -> Set<String> {
167+
let selection = CoverageTargetSelection(with: targets, from: report.targets.map(\.name))
168+
if !selection.unmatchedRequested.isEmpty {
169+
throw CoverageConverterError.unknownCoverageTargets(
170+
requested: selection.unmatchedRequested.sorted(),
171+
available: selection.availableTargets.sorted()
172+
)
173+
}
174+
return selection.selectedTargets
175+
}
176+
126177
public func xmlString(quiet: Bool) throws -> String {
127178
throw CoverageConverterError.notImplemented
128179
}
@@ -159,7 +210,10 @@ public class CoverageConverter {
159210

160211
// Use the xccov commandline tool to get results as JSON.
161212
func getCoverageDataAsJSON() throws -> FileCoverage {
162-
try xccovClient.getCoverageData(path: resultFileURL)
213+
if let prefetchedCoverage {
214+
return prefetchedCoverage
215+
}
216+
return try xccovClient.getCoverageData(path: resultFileURL)
163217
}
164218

165219
func isTargetIncluded(forFile file: String) -> Bool {

‎Sources/xcresultparser/SharedTypes/Services/Shell.swift‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,20 @@ import Foundation
99

1010
protocol Commandline {
1111
func execute(program: String, with arguments: [String], at executionPath: URL?) throws -> Data
12+
13+
/// Like `execute(program:with:at:)`, but terminates the program if the calling task is cancelled.
14+
func executeCancellable(program: String, with arguments: [String], at executionPath: URL?) async throws -> Data
1215
}
1316

1417
extension Commandline {
1518
func execute(program: String, with arguments: [String]) throws -> Data {
1619
return try execute(program: program, with: arguments, at: nil)
1720
}
21+
22+
/// Test doubles have no process to terminate.
23+
func executeCancellable(program: String, with arguments: [String], at executionPath: URL?) async throws -> Data {
24+
try execute(program: program, with: arguments, at: executionPath)
25+
}
1826
}
1927

2028
struct Shell: Commandline {
@@ -54,6 +62,46 @@ struct Shell: Commandline {
5462
}
5563
}
5664

65+
func executeCancellable(
66+
program: String,
67+
with arguments: [String],
68+
at executionPath: URL? = nil
69+
) async throws -> Data {
70+
try Task.checkCancellation()
71+
let process = Process()
72+
if let directoryUrl = executionPath {
73+
process.currentDirectoryURL = directoryUrl
74+
}
75+
process.executableURL = URL(fileURLWithPath: program)
76+
process.arguments = arguments
77+
let errorPipe = Pipe()
78+
process.standardError = errorPipe
79+
let outPipe = Pipe()
80+
process.standardOutput = outPipe
81+
defer {
82+
try? outPipe.fileHandleForReading.close()
83+
try? errorPipe.fileHandleForReading.close()
84+
}
85+
try process.run()
86+
// Terminating the program closes its end of the pipe, which ends the blocking read.
87+
let data = await withTaskCancellationHandler {
88+
autoreleasepool {
89+
outPipe.fileHandleForReading.readDataToEndOfFile()
90+
}
91+
} onCancel: {
92+
process.terminate()
93+
}
94+
process.waitUntilExit()
95+
try Task.checkCancellation()
96+
let status = process.terminationStatus
97+
if status != 0 {
98+
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
99+
let errorMessage = String(decoding: errorData, as: UTF8.self)
100+
throw CLIError.executionError(code: Int(status), message: errorMessage)
101+
}
102+
return data
103+
}
104+
57105
enum CLIError: Error {
58106
case executionError(code: Int, message: String)
59107
}

0 commit comments

Comments
 (0)