-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathSwiftBuildSystemMessageHandler.swift
More file actions
892 lines (783 loc) · 38.4 KB
/
SwiftBuildSystemMessageHandler.swift
File metadata and controls
892 lines (783 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_spi(SwiftPMInternal)
import Basics
import Foundation
@_spi(SwiftPMInternal)
import SPMBuildCore
import enum TSCUtility.Diagnostics
import SWBBuildService
import SwiftBuild
import protocol TSCBasic.OutputByteStream
/// Handler for SwiftBuildMessage events sent by the SWBBuildOperation.
public final class SwiftBuildSystemMessageHandler {
private let observabilityScope: ObservabilityScope
private let outputStream: OutputByteStream
private let logLevel: Basics.Diagnostic.Severity
private var buildState: BuildState = .init()
private let enableBacktraces: Bool
private let buildDelegate: SPMBuildCore.BuildSystemDelegate?
private var traceEventsWriter: TraceEventsWriter?
public typealias BuildSystemCallback = (SwiftBuildSystem) -> Void
let progressAnimation: ProgressAnimationProtocol
var serializedDiagnosticPathsByTargetID: [Int: [Basics.AbsolutePath]] = [:]
// FIXME: This eventually gets passed into the BuildResult, which expects a
// dictionary of [String: [AbsolutePath]]. Eventually, we should refactor it
// to accept a dictionary keyed by a unique identifier (possibly `ResolvedModule.ID`),
// and instead use the above dictionary keyed by target ID.
var serializedDiagnosticPathsByTargetName: [String: [Basics.AbsolutePath]] {
serializedDiagnosticPathsByTargetID.reduce(into: [:]) { result, entry in
if let name = buildState.targetsByID[entry.key]?.targetName {
result[name, default: []].append(contentsOf: entry.value)
}
}
}
/// Tracks the task IDs for failed tasks.
private var failedTasks: [Int] = []
/// Tracks the tasks by their signature for which we have already emitted output.
private var tasksEmitted: EmittedTasks = .init()
public init(
observabilityScope: ObservabilityScope,
outputStream: OutputByteStream,
logLevel: Basics.Diagnostic.Severity,
enableBacktraces: Bool = false,
buildDelegate: SPMBuildCore.BuildSystemDelegate? = nil,
traceEventsFilePath: Basics.AbsolutePath? = nil
)
{
self.observabilityScope = observabilityScope
self.outputStream = outputStream
self.logLevel = logLevel
self.progressAnimation = ProgressAnimation.ninja(
stream: outputStream,
verbose: self.logLevel.isVerbose,
normalizeStep: false
)
self.enableBacktraces = enableBacktraces
self.buildDelegate = buildDelegate
if let traceEventsFilePath {
do {
self.traceEventsWriter = try TraceEventsWriter(path: traceEventsFilePath)
} catch {
observabilityScope.emit(warning: "Failed to open trace events file: \(error)")
self.traceEventsWriter = nil
}
} else {
self.traceEventsWriter = nil
}
}
private func emitInfoAsDiagnostic(info: SwiftBuildMessage.DiagnosticInfo) {
let fixItsDescription = if info.fixIts.hasContent {
": " + info.fixIts.map { String(describing: $0) }.joined(separator: ", ")
} else {
""
}
let message = if let locationDescription = info.location.userDescription {
"\(locationDescription) \(info.message)\(fixItsDescription)"
} else {
"\(info.message)\(fixItsDescription)"
}
let severity: Diagnostic.Severity = switch info.kind {
case .error: .error
case .warning: .warning
case .note: .info
case .remark: .debug
}
self.observabilityScope.emit(severity: severity, message: "\(message)\n")
for childDiagnostic in info.childDiagnostics {
emitInfoAsDiagnostic(info: childDiagnostic)
}
}
private func emitDiagnosticCompilerOutput(_ info: SwiftBuildMessage.TaskStartedInfo, condition: OutputCondition) {
// Don't redundantly emit task output.
guard !self.tasksEmitted.contains(info.taskSignature) else {
return
}
// Assure we have a data buffer to decode.
guard let buffer = buildState.dataBuffer(for: info), !buffer.isEmpty else {
return
}
// Decode the buffer to a string
let decodedOutput = String(decoding: buffer, as: UTF8.self)
// Emit message.
observabilityScope.print(decodedOutput, condition: condition)
// Record that we've emitted the output for a given task.
self.tasksEmitted.insert(info)
}
private func renderTaskBacktrace(
for startedInfo: SwiftBuildMessage.TaskStartedInfo
) -> String? {
guard
let id = SWBBuildOperationBacktraceFrame.Identifier(taskSignatureData: Data(startedInfo.taskSignature.utf8)),
let backtrace = SWBTaskBacktrace(from: id, collectedFrames: buildState.collectedBacktraceFrames)
else {
return nil
}
let rendered = backtrace.renderTextualRepresentation()
return rendered.isEmpty ? nil : rendered
}
private func handleTaskOutput(
_ info: SwiftBuildMessage.TaskCompleteInfo,
_ startedInfo: SwiftBuildMessage.TaskStartedInfo,
_ renderedBacktrace: String?
) throws {
// Begin by emitting the text received by the task started event.
if let started = self.buildState.startedInfo(for: startedInfo) {
// Emit depending on verbosity level.
if logLevel.isVerbose {
self.outputStream.send(started)
}
self.observabilityScope.print(started, condition: .onlyWhenVerbose)
}
guard info.result == .success else {
// Don't emit error output for tasks that were cancelled (e.g. collateral damage
// when another task failed and the build was aborted). These are not real errors.
if info.result != .cancelled {
emitFailedTaskOutput(info, startedInfo)
}
return
}
// Handle diagnostics, if applicable.
// This handles diagnostics for successful tasks, which could be notes or warnings.
let diagnostics = self.buildState.diagnostics(for: info)
if !diagnostics.isEmpty {
// Emit diagnostics using the `DiagnosticInfo` model.
diagnostics.forEach({ emitInfoAsDiagnostic(info: $0) })
} else {
// Emit diagnostics through textual compiler output.
let isDiagnosticOutput = self.buildState.diagnosticDataBufferExists(for: info)
emitDiagnosticCompilerOutput(startedInfo, condition: isDiagnosticOutput ? .always : .onlyWhenVerbose)
}
// Handle task backtraces, if applicable.
if let renderedBacktrace, !renderedBacktrace.isEmpty {
self.observabilityScope.emit(info: "Task backtrace:\n\(renderedBacktrace)")
}
}
private func emitFailedTaskOutput(
_ info: SwiftBuildMessage.TaskCompleteInfo,
_ startedInfo: SwiftBuildMessage.TaskStartedInfo
) {
// Assure that the task has failed.
guard info.result != .success else {
return
}
// Don't redundantly emit task output.
guard !tasksEmitted.contains(startedInfo.taskSignature) else {
return
}
// Track failed tasks.
self.failedTasks.append(info.taskID)
// Check for existing diagnostics with matching taskID/taskSignature.
// If we've captured the compiler output with formatted diagnostics keyed by
// this task's signature, emit them.
// Note that this is a workaround instead of emitting directly from a `DiagnosticInfo`
// message, as here we receive the formatted code snippet directly from the compiler.
let diagnosticsBuffer = buildState.diagnostics(for: info)
if !diagnosticsBuffer.isEmpty {
diagnosticsBuffer.forEach({ emitInfoAsDiagnostic(info: $0) })
} else {
emitDiagnosticCompilerOutput(startedInfo, condition: .always)
}
let message = "\(startedInfo.ruleInfo) failed with a nonzero exit code."
// If we have the command line display string available, then we
// should continue to emit this as an error. Otherwise, this doesn't
// give enough information to the user for it to be useful so we can
// demote it to an info-level log.
if let cmdLineDisplayStr = startedInfo.commandLineDisplayString {
self.observabilityScope.emit(severity: .error, message: "\(message) Command line: \(cmdLineDisplayStr)")
} else {
self.observabilityScope.emit(severity: .info, message: message)
}
// Track that we have emitted output for this task.
tasksEmitted.insert(startedInfo)
}
public func emitEvent(_ message: SwiftBuild.SwiftBuildMessage) throws -> BuildSystemCallback? {
var callback: BuildSystemCallback? = nil
guard !self.logLevel.isQuiet else { return callback }
switch message {
case .buildCompleted(let info):
self.traceEventsWriter?.close()
progressAnimation.complete(success: info.result == .ok)
if info.result == .cancelled {
callback = { [weak self] buildSystem in
self?.buildDelegate?.buildSystemDidCancel(buildSystem)
}
} else {
callback = { [weak self] buildSystem in
self?.buildDelegate?.buildSystem(buildSystem, didFinishWithResult: info.result == .ok)
}
}
case .didUpdateProgress(let progressInfo):
let message = if let targetName = progressInfo.targetName {
"[\(progressInfo.message)] \(targetName)"
} else {
"[\(progressInfo.message)]"
}
// Skip if message doesn't contain anything useful to display.
if !message.isEmpty {
progressAnimation.update(step: -1, total: 100, text: message)
}
callback = { [weak self] buildSystem in
self?.buildDelegate?.buildSystem(buildSystem, didUpdateTaskProgress: message)
}
case .diagnostic(let info):
// If this is representative of a global/target diagnostic
// then we can emit immediately.
// Otherwise, defer emission of diagnostic to matching taskCompleted event.
if info.locationContext.isGlobal || info.locationContext.isTarget {
emitInfoAsDiagnostic(info: info)
} else if info.appendToOutputStream {
buildState.appendDiagnostic(info)
} else {
// Track task IDs for diagnostics to later emit them via compiler output.
buildState.appendDiagnosticID(info)
}
case .output(let info):
// Append to buffer-per-task storage
buildState.appendToBuffer(info)
case .taskStarted(let info):
try buildState.started(task: info, self.logLevel)
self.traceEventsWriter?.taskStarted(info)
let targetInfo = try buildState.target(for: info)
callback = { [weak self] buildSystem in
self?.buildDelegate?.buildSystem(buildSystem, willStartCommand: BuildSystemCommand(info, targetInfo: targetInfo))
self?.buildDelegate?.buildSystem(buildSystem, didStartCommand: BuildSystemCommand(info, targetInfo: targetInfo))
}
case .taskComplete(let info):
let startedInfo = try buildState.completed(task: info)
let renderedBacktrace = self.enableBacktraces
? self.renderTaskBacktrace(for: startedInfo)
: nil
traceEventsWriter?.taskCompleted(
info,
startedInfo: startedInfo,
backtrace: renderedBacktrace
)
// Handler for task output, handling failures if applicable.
try self.handleTaskOutput(info, startedInfo, renderedBacktrace)
let targetInfo = try buildState.target(for: startedInfo)
callback = { [weak self] buildSystem in
self?.buildDelegate?.buildSystem(buildSystem, didFinishCommand: BuildSystemCommand(startedInfo, targetInfo: targetInfo))
}
if let targetID = targetInfo?.targetID {
try serializedDiagnosticPathsByTargetID[targetID, default: []].append(contentsOf: startedInfo.serializedDiagnosticsPaths.compactMap {
try Basics.AbsolutePath(validating: $0.pathString)
})
}
case .targetStarted(let info):
try buildState.started(target: info)
case .backtraceFrame(let info):
if self.enableBacktraces {
buildState.collectedBacktraceFrames.add(frame: info)
}
case .targetComplete(let info):
_ = try buildState.completed(target: info)
case .planningOperationStarted(_):
// Emitting under higher-level verbosity so as not to overwhelm output.
// This is the same behaviour as the native system.
if self.logLevel.isVerbose {
self.outputStream.send("Planning build" + "\n")
}
case .planningOperationCompleted(_):
// Emitting under higher-level verbosity so as not to overwhelm output.
if self.logLevel.isVerbose {
self.outputStream.send("Planning complete" + "\n")
}
case .targetUpToDate(let info):
// Received when a target is entirely up to date and did not need to be built.
if self.logLevel.isVerbose {
self.outputStream.send("Target \(info.guid) up to date." + "\n")
}
case .reportBuildDescription, .reportPathMap, .preparedForIndex, .buildStarted, .preparationComplete, .taskUpToDate:
break
case .buildDiagnostic, .targetDiagnostic, .taskDiagnostic:
break // deprecated
case .buildOutput, .targetOutput, .taskOutput:
break // deprecated
@unknown default:
break
}
return callback
}
}
// MARK: SwiftBuildSystemMessageHandler.BuildState
extension SwiftBuildSystemMessageHandler {
/// Manages the state of an active build operation, tracking targets, tasks, buffers, and backtrace frames.
/// This struct maintains the complete state model for build operations, coordinating data between
/// different phases of the build lifecycle.
struct BuildState {
// Targets
internal var targetsByID: [Int: SwiftBuild.SwiftBuildMessage.TargetStartedInfo] = [:]
private var completedTargets: [Int: SwiftBuild.SwiftBuildMessage.TargetCompleteInfo] = [:]
// Tasks
private var activeTasks: [Int: SwiftBuild.SwiftBuildMessage.TaskStartedInfo] = [:]
private var completedTasks: [Int: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo] = [:]
private var taskIDToSignature: [Int: String] = [:]
// Per-task buffers
private var taskDataBuffer: TaskDataBuffer = .init()
private var diagnosticsBuffer: TaskDiagnosticBuffer = .init()
private var diagnosticTaskIDs: Set<Int> = []
// Backtrace frames
internal var collectedBacktraceFrames = SWBBuildOperationCollectedBacktraceFrames()
/// Registers the start of a build task, validating that the task hasn't already been started.
/// - Parameter task: The task start information containing task ID and signature
/// - Throws: Fatal error if the task is already active
mutating func started(task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo, _ logLevel: Basics.Diagnostic.Severity) throws {
if activeTasks[task.taskID] != nil {
throw Diagnostics.fatalError
}
activeTasks[task.taskID] = task
taskIDToSignature[task.taskID] = task.taskSignature
// Track relevant task info to emit to user.
let output = if let cmdLineDisplayStr = task.commandLineDisplayString, logLevel.isVerbose {
"\(task.executionDescription)\n\(cmdLineDisplayStr)"
} else {
task.executionDescription
}
taskDataBuffer.setTaskStartedInfo(task, output)
}
/// Marks a task as completed and removes it from active tracking.
/// - Parameter task: The task completion information
/// - Returns: The original task start information for the completed task
/// - Throws: Fatal error if the task was not started or already completed
mutating func completed(task: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo) throws -> SwiftBuild.SwiftBuildMessage.TaskStartedInfo {
guard let startedTaskInfo = activeTasks[task.taskID] else {
throw Diagnostics.fatalError
}
if completedTasks[task.taskID] != nil {
throw Diagnostics.fatalError
}
// Track completed task, remove from active tasks.
self.completedTasks[task.taskID] = task
self.activeTasks[task.taskID] = nil
return startedTaskInfo
}
/// Registers the start of a build target, validating that the target hasn't already been started.
/// - Parameter target: The target start information containing target ID and name
/// - Throws: Fatal error if the target is already active
mutating func started(target: SwiftBuild.SwiftBuildMessage.TargetStartedInfo) throws {
if targetsByID[target.targetID] != nil {
throw Diagnostics.fatalError
}
targetsByID[target.targetID] = target
}
/// Marks a target as completed and removes it from active tracking.
/// - Parameter target: The target completion information
/// - Returns: The original target start information for the completed target
/// - Throws: Fatal error if the target was not started
mutating func completed(target: SwiftBuild.SwiftBuildMessage.TargetCompleteInfo) throws -> SwiftBuild.SwiftBuildMessage.TargetStartedInfo {
guard let targetStartedInfo = targetsByID[target.targetID] else {
throw Diagnostics.fatalError
}
completedTargets[target.targetID] = target
return targetStartedInfo
}
/// Retrieves the target information associated with a given task.
/// - Parameter task: The task start information to look up the target for
/// - Returns: The target start information if the task has an associated target, nil otherwise
/// - Throws: Fatal error if the target ID exists but no matching target is found
func target(for task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo) throws -> SwiftBuild.SwiftBuildMessage.TargetStartedInfo? {
guard let id = task.targetID else {
return nil
}
guard let target = targetsByID[id] else {
throw Diagnostics.fatalError
}
return target
}
/// Retrieves the task signature for a given task ID.
/// - Parameter id: The task ID to look up
/// - Returns: The task signature string if found, nil otherwise
func taskSignature(for id: Int) -> String? {
if let signature = taskIDToSignature[id] {
return signature
}
return nil
}
}
}
// MARK: - SwiftBuildSystemMessageHandler.BuildState.TaskDataBuffer
extension SwiftBuildSystemMessageHandler.BuildState {
/// Manages data buffers for build tasks, supporting multiple indexing strategies.
/// This buffer system stores output data from tasks using both task signatures and task IDs,
/// providing flexible access patterns for different build message types and legacy support.
struct TaskDataBuffer {
// Emit using observabilityScope.print(_:verbose:)
private var taskSignatureBuffer: [String: Data] = [:]
private var taskIDBuffer: [Int: Data] = [:]
// Emit using observabilityScope.emit(info:)
private var taskStartedNotifications: [Int: String] = [:]
/// Retrieves data for a task signature key.
/// - Parameter key: The task signature string
/// - Returns: The associated data buffer, or nil if not found
subscript(key: String) -> Data? {
self.taskSignatureBuffer[key]
}
/// Retrieves or sets data for a task signature key with a default value.
/// - Parameters:
/// - key: The task signature string
/// - defaultValue: The default data to return/store if no value exists
/// - Returns: The stored data buffer or the default value
subscript(key: String, default defaultValue: Data) -> Data {
get { self.taskSignatureBuffer[key] ?? defaultValue }
set { self.taskSignatureBuffer[key] = newValue }
}
/// Retrieves or sets data using a LocationContext for task identification.
/// - Parameters:
/// - key: The location context containing task or target ID information
/// - defaultValue: The default data to return/store if no value exists
/// - Returns: The stored data buffer or the default value
subscript(key: SwiftBuildMessage.LocationContext, default defaultValue: Data) -> Data {
get {
// Check each ID kind and try to fetch the associated buffer.
// If unable to get a non-nil result, then follow through to the
// next check.
if let taskID = key.taskID,
let result = self.taskIDBuffer[taskID] {
return result
} else {
return defaultValue
}
}
set {
if let taskID = key.taskID {
self.taskIDBuffer[taskID] = newValue
}
}
}
/// Retrieves or sets data using a LocationContext2 for task identification.
/// - Parameter key: The location context containing task signature information
/// - Returns: The associated data buffer, or nil if not found
subscript(key: SwiftBuildMessage.LocationContext2) -> Data? {
get {
if let taskSignature = key.taskSignature {
return self.taskSignatureBuffer[taskSignature]
}
return nil
}
set {
if let taskSignature = key.taskSignature {
self.taskSignatureBuffer[taskSignature] = newValue
}
}
}
/// Retrieves data for a specific task using TaskStartedInfo.
/// - Parameter task: The task start information containing signature and ID
/// - Returns: The associated data buffer, or nil if not found
subscript(task: SwiftBuildMessage.TaskStartedInfo) -> Data? {
get {
guard let result = self.taskSignatureBuffer[task.taskSignature] else {
// Default to checking targetID and taskID.
if let result = self.taskIDBuffer[task.taskID] {
return result
}
return nil
}
return result
}
}
func taskStartedInfo(_ task: SwiftBuildMessage.TaskStartedInfo) -> String? {
guard let result = taskStartedNotifications[task.taskID] else {
return nil
}
return result
}
mutating func setTaskStartedInfo(_ task: SwiftBuildMessage.TaskStartedInfo, _ text: String) {
self.taskStartedNotifications[task.taskID] = text
}
}
/// Appends output data to the appropriate task buffer based on location context information.
/// - Parameter info: The output info containing data and location context for storage
mutating func appendToBuffer(_ info: SwiftBuildMessage.OutputInfo) {
// Attempt to key by taskSignature; at times this may not be possible,
// in which case we'd need to fall back to using LocationContext.
guard let taskSignature = info.locationContext2.taskSignature else {
// If we cannot find the task signature from the locationContext2,
// use deprecated locationContext instead to find task signature.
// If this fails to find an associated task signature, track
// relevant IDs from the location context in the task buffer.
if let taskID = info.locationContext.taskID,
let taskSignature = self.taskSignature(for: taskID) {
self.taskDataBuffer[taskSignature, default: .init()].append(info.data)
}
self.taskDataBuffer[info.locationContext, default: .init()].append(info.data)
return
}
self.taskDataBuffer[taskSignature, default: .init()].append(info.data)
}
/// Retrieves the accumulated data buffer for a specific task.
/// - Parameter task: The task start information to look up data for
/// - Returns: The accumulated data buffer for the task, or nil if no data exists
func dataBuffer(for task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo) -> Data? {
guard let data = taskDataBuffer[task.taskSignature] else {
// Fallback to checking taskID and targetID.
return taskDataBuffer[task]
}
return data
}
func startedInfo(for task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo) -> String? {
return self.taskDataBuffer.taskStartedInfo(task)
}
}
// MARK: - SwiftBuildSystemMessageHandler.BuildState.TaskDiagnosticBuffer
extension SwiftBuildSystemMessageHandler.BuildState {
/// Manages diagnostic information buffers for build tasks, organized by task signatures and IDs.
/// This buffer system collects diagnostic messages during task execution for later retrieval
/// and structured reporting of build errors, warnings, and other diagnostic information.
struct TaskDiagnosticBuffer {
private var diagnosticSignatureBuffer: [String: [SwiftBuildMessage.DiagnosticInfo]] = [:]
private var diagnosticIDBuffer: [Int: [SwiftBuildMessage.DiagnosticInfo]] = [:]
/// Retrieves diagnostic information using LocationContext2 for task identification.
/// - Parameter key: The location context containing task signature information
/// - Returns: Array of diagnostic info for the task, or nil if not found
subscript(key: SwiftBuildMessage.LocationContext2) -> [SwiftBuildMessage.DiagnosticInfo]? {
guard let taskSignature = key.taskSignature else {
return nil
}
return self.diagnosticSignatureBuffer[taskSignature]
}
/// Retrieves or sets diagnostic information using LocationContext2 with a default value.
/// - Parameters:
/// - key: The location context containing task signature information
/// - defaultValue: The default diagnostic array to return if no value exists
/// - Returns: Array of diagnostic info for the task, or the default value
subscript(key: SwiftBuildMessage.LocationContext2, default defaultValue: [SwiftBuildMessage.DiagnosticInfo]) -> [SwiftBuildMessage.DiagnosticInfo] {
get { self[key] ?? defaultValue }
set {
self[key, default: defaultValue]
}
}
/// Retrieves diagnostic information using LocationContext for task identification.
/// - Parameter key: The location context containing task ID information
/// - Returns: Array of diagnostic info for the task, or nil if not found
subscript(key: SwiftBuildMessage.LocationContext) -> [SwiftBuildMessage.DiagnosticInfo]? {
guard let taskID = key.taskID else {
return nil
}
return self.diagnosticIDBuffer[taskID]
}
/// Retrieves diagnostic information using LocationContext with a default value.
/// - Parameters:
/// - key: The location context containing task ID information
/// - defaultValue: The default diagnostic array to return if no value exists
/// - Returns: Array of diagnostic info for the task, or the default value
subscript(key: SwiftBuildMessage.LocationContext, default defaultValue: [SwiftBuildMessage.DiagnosticInfo]) -> [SwiftBuildMessage.DiagnosticInfo] {
get { self[key] ?? defaultValue }
}
/// Retrieves or sets diagnostic information using a task signature string.
/// - Parameter key: The task signature string
/// - Returns: Array of diagnostic info for the task signature
subscript(key: String) -> [SwiftBuildMessage.DiagnosticInfo] {
get { self.diagnosticSignatureBuffer[key] ?? [] }
set { self.diagnosticSignatureBuffer[key] = newValue }
}
/// Retrieves or sets diagnostic information using a task ID.
/// - Parameter key: The task ID
/// - Returns: Array of diagnostic info for the task ID
subscript(key: Int) -> [SwiftBuildMessage.DiagnosticInfo] {
get { self.diagnosticIDBuffer[key] ?? [] }
set { self.diagnosticIDBuffer[key] = newValue }
}
}
/// Appends a diagnostic message to the appropriate diagnostic buffer.
/// - Parameter info: The diagnostic information to store, containing location context for identification
mutating func appendDiagnostic(_ info: SwiftBuildMessage.DiagnosticInfo) {
guard let taskID = info.locationContext.taskID else {
return
}
diagnosticsBuffer[taskID].append(info)
}
/// Appends a diagnostic task ID to the appropriate diagnostic buffer.
/// - Parameter info: The diagnostic information to store, containing location context for identification
mutating func appendDiagnosticID(_ info: SwiftBuildMessage.DiagnosticInfo) {
guard let taskID = info.locationContext.taskID else {
return
}
self.diagnosticTaskIDs.insert(taskID)
// Swift compiler subtasks may also contribute diagnostics, mark their parents
// as containing diagnostics so that they get printed.
if let task = activeTasks[taskID], let parentID = task.parentTaskID {
self.diagnosticTaskIDs.insert(parentID)
}
}
/// Retrieves all diagnostic information for a completed task.
/// - Parameter task: The task completion information containing the task ID
/// - Returns: Array of diagnostic info associated with the task
func diagnostics(for task: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo) -> [SwiftBuildMessage.DiagnosticInfo] {
return self.diagnosticsBuffer[task.taskID]
}
/// Determines whether there is a data buffer for the given diagnostic task ID.
/// - Parameter task: The task completion information containing the task ID
/// - Returns: A Bool that indicates whether a data buffer entry exists for the given task ID.
func diagnosticDataBufferExists(for task: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo) -> Bool {
return self.diagnosticTaskIDs.contains(task.taskID)
}
}
// MARK: - SwiftBuildSystemMessageHandler.EmittedTasks
extension SwiftBuildSystemMessageHandler {
/// A collection that tracks tasks for which output has already been emitted to prevent duplicate output.
/// This struct ensures that task output is only displayed once during the build process, improving
/// the readability and accuracy of build logs by avoiding redundant messaging.
struct EmittedTasks: Collection {
public typealias Index = Set<TaskInfo>.Index
public typealias Element = Set<TaskInfo>.Element
var startIndex: Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index {
self.storage.startIndex
}
var endIndex: Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index {
self.storage.endIndex
}
private var storage: Set<TaskInfo> = []
public init() { }
/// Inserts a task info into the emitted tasks collection.
/// - Parameter task: The task information to mark as emitted
mutating func insert(_ task: TaskInfo) {
storage.insert(task)
}
subscript(position: Index) -> Element {
return storage[position]
}
func index(after i: Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index) -> Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index {
return storage.index(after: i)
}
/// Checks if a specific task info has been marked as emitted.
/// - Parameter task: The task information to check
/// - Returns: True if the task has already been emitted, false otherwise
func contains(_ task: TaskInfo) -> Bool {
return storage.contains(task)
}
/// Checks if a task with the given ID has been marked as emitted.
/// - Parameter taskID: The task ID to check
/// - Returns: True if a task with this ID has already been emitted, false otherwise
public func contains(_ taskID: Int) -> Bool {
return storage.contains(where: { $0.taskID == taskID })
}
/// Checks if a task with the given signature has been marked as emitted.
/// - Parameter taskSignature: The task signature to check
/// - Returns: True if a task with this signature has already been emitted, false otherwise
public func contains(_ taskSignature: String) -> Bool {
return storage.contains(where: { $0.taskSignature == taskSignature })
}
/// Convenience method to insert a task using TaskStartedInfo.
/// - Parameter startedTaskInfo: The task start information to mark as emitted
public mutating func insert(_ startedTaskInfo: SwiftBuildMessage.TaskStartedInfo) {
self.storage.insert(.init(startedTaskInfo))
}
}
/// Represents essential identifying information for a build task.
/// This struct encapsulates both the numeric task ID and string task signature,
/// providing efficient lookup and comparison capabilities for task tracking.
struct TaskInfo: Hashable {
let taskID: Int
let taskSignature: String
/// Initializes TaskInfo from TaskStartedInfo.
/// - Parameter startedTaskInfo: The task start information containing ID and signature
public init(_ startedTaskInfo: SwiftBuildMessage.TaskStartedInfo) {
self.taskID = startedTaskInfo.taskID
self.taskSignature = startedTaskInfo.taskSignature
}
/// Compares TaskInfo with a task signature string.
/// - Parameters:
/// - lhs: The TaskInfo instance
/// - rhs: The task signature string to compare
/// - Returns: True if the TaskInfo's signature matches the string
public static func ==(lhs: Self, rhs: String) -> Bool {
return lhs.taskSignature == rhs
}
/// Compares TaskInfo with a task ID integer.
/// - Parameters:
/// - lhs: The TaskInfo instance
/// - rhs: The task ID integer to compare
/// - Returns: True if the TaskInfo's ID matches the integer
public static func ==(lhs: Self, rhs: Int) -> Bool {
return lhs.taskID == rhs
}
}
}
/// Convenience extensions to extract taskID and targetID from the LocationContext.
extension SwiftBuildMessage.LocationContext {
/// Extracts the task ID from the location context.
/// - Returns: The task ID if the context represents a task or global task, nil otherwise
var taskID: Int? {
switch self {
case .task(let id, _), .globalTask(let id):
return id
case .target, .global:
return nil
}
}
/// Extracts the target ID from the location context.
/// - Returns: The target ID if the context represents a task or target, nil otherwise
var targetID: Int? {
switch self {
case .task(_, let id), .target(let id):
return id
case .global, .globalTask:
return nil
}
}
/// Determines if the location context represents a global scope.
/// - Returns: True if the context is global, false otherwise
var isGlobal: Bool {
switch self {
case .global:
return true
case .task, .target, .globalTask:
return false
}
}
/// Determines if the location context represents a target scope.
/// - Returns: True if the context is target-specific, false otherwise
var isTarget: Bool {
switch self {
case .target:
return true
case .global, .globalTask, .task:
return false
}
}
}
fileprivate extension SwiftBuild.SwiftBuildMessage.DiagnosticInfo.Location {
var userDescription: String? {
switch self {
case .path(let path, let fileLocation):
switch fileLocation {
case .textual(let line, let column):
var description = "\(path):\(line)"
if let column { description += ":\(column)" }
return description
case .object(let identifier):
return "\(path):\(identifier)"
case .none:
return path
}
case .buildSettings(let names):
return names.joined(separator: ", ")
case .buildFiles(let buildFiles, let targetGUID):
return "\(targetGUID): " + buildFiles.map { String(describing: $0) }.joined(separator: ", ")
case .unknown:
return nil
}
}
}
fileprivate extension BuildSystemCommand {
init(_ taskStartedInfo: SwiftBuildMessage.TaskStartedInfo, targetInfo: SwiftBuildMessage.TargetStartedInfo?) {
self = .init(
name: taskStartedInfo.executionDescription,
targetName: targetInfo?.targetName,
description: taskStartedInfo.commandLineDisplayString ?? "",
serializedDiagnosticPaths: taskStartedInfo.serializedDiagnosticsPaths.compactMap {
try? Basics.AbsolutePath(validating: $0.pathString)
}
)
}
}