File: TaskPlanningTestSupport.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (509 lines) | stat: -rw-r--r-- 19,783 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

package import SWBCore
public import enum SWBProtocol.ExternalToolResult
public import struct SWBProtocol.BuildOperationTaskEnded
public import SWBTaskConstruction
import SWBTaskExecution
public import SWBUtil
import Testing
package import SWBMacro
import Foundation
import Synchronization

extension PlannedTask {
    package var dependencyData: DependencyDataStyle? {
        execTask.dependencyData
    }

    package var commandLine: [ByteString] {
        execTask.commandLine.map(\.asByteString)
    }

    package var commandLineAsStrings: AnySequence<String> {
        execTask.commandLineAsStrings
    }

    package var environment: EnvironmentBindings {
        execTask.environment
    }

    package var workingDirectory: Path {
        execTask.workingDirectory
    }

    package var preparesForIndexing: Bool {
        execTask.preparesForIndexing
    }

    package var execDescription: String? {
        execTask.execDescription
    }

    package func generateIndexingInfo(input: TaskGenerateIndexingInfoInput) -> [TaskGenerateIndexingInfoOutput] {
        execTask.generateIndexingInfo(input: input)
    }

    /// Convenience method to report on a task when emitting a test failure.
    package var testIssueDescription: String {
        var result = ""
        if let targetName = forTarget?.target.name {
            result = result + "\(targetName):"
        }
        result = result + ruleInfo.quotedDescription
        return result
    }
}

/// Conditions which can describe possible task matches in test results.
package enum TaskCondition: CustomStringConvertible, Sendable {
    /// Match against the specific target.
    case matchTarget(ConfiguredTarget)
    /// Match against any target with the given name.
    case matchTargetName(String)
    /// Match against any task with the given rule info.
    case matchRule([String])
    /// Match against any task matching the given rule info.
    case matchRulePattern([StringPattern])
    /// Match against any task with the given rule type.
    case matchRuleType(String)
    /// Match against any task with the given string in the rule info.
    case matchRuleItem(String)
    /// Match against any task whose rule info contains an item with the given basename.
    case matchRuleItemBasename(String)
    /// Match against any task whose rule info contains an item with the given pattern.
    case matchRuleItemPattern(StringPattern)
    /// Match against any task whose command line contains the given argument.
    case matchCommandLineArgument(String)
    /// Match against any task whose command line contains an argument with the given pattern.
    case matchCommandLineArgumentPattern(StringPattern)

    package var description: String {
        switch self {
        case .matchTarget(let target):
            return "Target == \(target)"

        case .matchTargetName(let name):
            return "Target == \(name)"

        case .matchRule(let rule):
            return "Rule == \(rule)"

        case .matchRulePattern(let rulePattern):
            return "Rule matches \(rulePattern)"

        case .matchRuleType(let name):
            return "RuleType == \(name)"

        case .matchRuleItem(let name):
            return "RuleItems contains \(name)"

        case .matchRuleItemBasename(let name):
            return "RuleItem.basename == \(name)"

        case .matchRuleItemPattern(let pattern):
            return "RuleItem matches \(pattern)"

        case .matchCommandLineArgument(let argument):
            return "CommandLineArguments contains \(argument)"

        case .matchCommandLineArgumentPattern(let pattern):
            return "CommandLineArguments match \(pattern)"
        }
    }

    package func match(_ task: any PlannedTask) -> Bool {
        return match(task.execTask)
    }

    package func match(_ task: any ExecutableTask) -> Bool {
        return match(target: task.forTarget, ruleInfo: task.ruleInfo, commandLine: task.commandLine.map(\.asByteString))
    }

    package func match(target forTarget: ConfiguredTarget?, ruleInfo: [String], commandLine: [ByteString]) -> Bool {
        switch self {
        case .matchTarget(let target):
            return forTarget == target

        case .matchTargetName(let name):
            return forTarget?.target.name == name

        case .matchRule(let rule):
            return ruleInfo == rule

        case .matchRulePattern(let rulePattern):
            return rulePattern ~= ruleInfo

        case .matchRuleType(let name):
            return ruleInfo.first == name

        case .matchRuleItem(let name):
            return ruleInfo.firstIndex(where: { $0 == name }) != nil

        case .matchRuleItemBasename(let name):
            return ruleInfo.firstIndex(where: { Path($0).basename == name }) != nil

        case .matchRuleItemPattern(let pattern):
            return ruleInfo.firstIndex(where: { pattern ~= $0 }) != nil

        case .matchCommandLineArgument(let argument):
            return commandLine.firstIndex(where: { $0 == argument }) != nil

        case .matchCommandLineArgumentPattern(let pattern):
            return commandLine.firstIndex(where: { item in
                guard let itemStr = item.stringValue else {
                    return false
                }

                return pattern ~= itemStr
            }) != nil
        }
    }
}

package extension Array where Element == TaskCondition {
    static func gateTask(_ targetName: String, suffix: String) -> [TaskCondition] {
        return [.matchTargetName(targetName), .matchRuleType("Gate"), .matchRuleItemPattern(.suffix("-\(suffix)"))]
    }

    static func compileC(_ targetName: String, fileName: String) -> [TaskCondition] {
        return [.matchTargetName(targetName), .matchRuleType("CompileC"), .matchRuleItemPattern(.suffix(fileName))]
    }

    static func compileSwift(_ targetName: String) -> [TaskCondition] {
        return [.matchTargetName(targetName), .matchRuleType("SwiftDriver Compilation")]
    }

    static func emitSwiftCompilationRequirements(_ targetName: String) -> [TaskCondition] {
        return [.matchTargetName(targetName), .matchRuleType("SwiftDriver Compilation Requirements")]
    }
}

open class MockTestTaskPlanningClientDelegate: TaskPlanningClientDelegate, @unchecked Sendable {
    package init() {}

    open func executeExternalTool(commandLine: [String], workingDirectory: Path?, environment: [String: String]) async throws -> ExternalToolResult {
        let args = commandLine.dropFirst()
        switch commandLine.first.map(Path.init)?.basenameWithoutSuffix {
        case "actool" where args == ["--version", "--output-format", "xml1"]:
            return .deferred
        case "cat": // docc
            return .deferred
        case "clang" where args.first == "-v":
            return .deferred
        case "distill" where args == ["--version"]:
            return .deferred
        case "distill" where args == ["--version", "--output-format", "xml1"]:
            return .deferred
        case "ibtool" where args == ["--version", "--output-format", "xml1"]:
            return .deferred
        case "iig" where args == ["--version"]:
            return .deferred
        case "ld" where args == ["-version_details"]:
            return .deferred
        case "libtool" where args == ["-V"] || args == ["--version"]:
            return .deferred
        case "mig" where args == ["-version"]:
            return .deferred
        case "swiftc" where args == ["--version"]:
            return .deferred
        case "tapi" where args == ["--version"]:
            return .deferred
        case "what":
            return .deferred
        default:
            break
        }
        throw StubError.error("Unit test should implement its own instance of TaskPlanningClientDelegate.")
    }
}

package class TestTaskPlanningDelegate: TaskPlanningDelegate, @unchecked Sendable {
    private let _diagnosticsEngines = LockedValue<[ConfiguredTarget?: DiagnosticsEngine]>(.init())

    private let queue = SWBQueue(label: "SWBTestSupport.TestTaskPlanningDelegate.queue", qos: UserDefaults.defaultRequestQoS)

    let allPlannedBuildDirectoryNodes = SWBMutex<[Path: PlannedPathNode]>([:])
    let fs: any FSProxy
    let tmpDir: NamedTemporaryDirectory?

    package init(clientDelegate: any TaskPlanningClientDelegate, workspace: Workspace? = nil, fs: any FSProxy) {
        self.clientDelegate = clientDelegate
        self.diagnosticContext = DiagnosticContextData(target: nil)
        self.fs = fs
        self.tmpDir = try? NamedTemporaryDirectory(fs: fs)
    }

    package let diagnosticContext: DiagnosticContextData

    package func diagnosticsEngine(for target: ConfiguredTarget?) -> DiagnosticProducingDelegateProtocolPrivate<DiagnosticsEngine> {
        .init(_diagnosticsEngines.withLock { diagnosticsEngines in
            diagnosticsEngines.getOrInsert(target, { DiagnosticsEngine() })
        })
    }

    var diagnostics: [ConfiguredTarget?: [Diagnostic]] {
        _diagnosticsEngines.withLock { $0.mapValues { $0.diagnostics } }
    }

    package func beginActivity(ruleInfo: String, executionDescription: String, signature: ByteString, target: ConfiguredTarget?, parentActivity: ActivityID?) -> ActivityID {
        .init(rawValue: -1)
    }

    package func endActivity(id: ActivityID, signature: ByteString, status: BuildOperationTaskEnded.Status) {

    }

    package func emit(data: [UInt8], for activity: ActivityID, signature: ByteString) {

    }

    package func emit(diagnostic: Diagnostic, for activity: ActivityID, signature: ByteString) {

    }

    package var hadErrors: Bool {
        false
    }

    package var cancelled: Bool { return false }
    package func updateProgress(statusMessage: String, showInLog: Bool) { }

    package func createVirtualNode(_ name: String) -> PlannedVirtualNode {
        return MakePlannedVirtualNode(name)
    }

    package func createNode(absolutePath path: Path) -> PlannedPathNode {
        assert(path.isAbsolute)
        return MakePlannedPathNode(path)
    }

    package func createDirectoryTreeNode(absolutePath path: Path, excluding: [String]) -> PlannedDirectoryTreeNode {
        return MakePlannedDirectoryTreeNode(path, excluding: excluding)
    }

    package func createBuildDirectoryNode(absolutePath path: Path) -> PlannedPathNode {
        assert(path.isAbsolute)
        return allPlannedBuildDirectoryNodes.withLock { allPlannedBuildDirectoryNodes in
            if let node = allPlannedBuildDirectoryNodes[path] {
                return node
            } else {
                let node = createNode(absolutePath: path)
                allPlannedBuildDirectoryNodes[path] = node
                return node
            }
        }
    }

    package func createTask(_ builder: inout PlannedTaskBuilder) -> any PlannedTask {
        return ConstructedTask(&builder, execTask: Task(&builder))
    }

    package func createGateTask(_ inputs: [any PlannedNode], output: any PlannedNode, name: String, mustPrecede: [any PlannedTask], taskConfiguration: (inout PlannedTaskBuilder) -> Void) -> any PlannedTask {
        var builder = PlannedTaskBuilder(type: GateTask.type, ruleInfo: ["Gate", name], commandLine: [], environment: EnvironmentBindings(), inputs: inputs, outputs: [output], mustPrecede: mustPrecede, repairViaOwnershipAnalysis: false)
        builder.preparesForIndexing = true
        builder.makeGate()
        taskConfiguration(&builder)
        return GateTask(&builder, execTask: Task(&builder))
    }

    package func recordAttachment(contents: SWBUtil.ByteString) -> SWBUtil.Path {
        let digester = InsecureHashContext()
        digester.add(bytes: contents)
        if let path = tmpDir?.path.join(digester.signature.asString) {
            do {
                try fs.write(path, contents: contents)
            } catch {
                Issue.record("Failed to write attachment at \(path): \(error.localizedDescription)")
                return Path("")
            }
            return path
        } else {
            Issue.record("Failed to create temporary directory")
            return Path("")
        }
    }

    package var taskActionCreationDelegate: any TaskActionCreationDelegate { return self }

    package let clientDelegate: any TaskPlanningClientDelegate
}

extension TestTaskPlanningDelegate: TaskActionCreationDelegate {
    package func createAuxiliaryFileTaskAction(_ context: AuxiliaryFileTaskActionContext) -> any PlannedTaskAction {
        return AuxiliaryFileTaskAction(context)
    }

    package func createCodeSignTaskAction() -> any PlannedTaskAction {
        return CodeSignTaskAction()
    }

    package func createConcatenateTaskAction() -> any PlannedTaskAction {
        return ConcatenateTaskAction()
    }

    package func createCopyPlistTaskAction() -> any PlannedTaskAction {
        return CopyPlistTaskAction()
    }

    package func createCopyStringsFileTaskAction() -> any PlannedTaskAction {
        return CopyStringsFileTaskAction()
    }

    package func createCopyTiffTaskAction() -> any PlannedTaskAction {
        return CopyTiffTaskAction()
    }

    package func createDeferredExecutionTaskAction() -> any PlannedTaskAction {
        return DeferredExecutionTaskAction()
    }

    package func createBuildDirectoryTaskAction() -> any PlannedTaskAction {
        return CreateBuildDirectoryTaskAction()
    }

    package func createSwiftHeaderToolTaskAction() -> any PlannedTaskAction {
        return SwiftHeaderToolTaskAction()
    }

    package func createEmbedSwiftStdLibTaskAction() -> any PlannedTaskAction {
        return EmbedSwiftStdLibTaskAction()
    }

    package func createFileCopyTaskAction(_ context: FileCopyTaskActionContext) -> any PlannedTaskAction {
        return FileCopyTaskAction(context)
    }

    package func createGenericCachingTaskAction(enableCacheDebuggingRemarks: Bool, enableTaskSandboxEnforcement: Bool, sandboxDirectory: Path, extraSandboxSubdirectories: [Path], developerDirectory: Path, casOptions: CASOptions) -> any PlannedTaskAction {
        return GenericCachingTaskAction(enableCacheDebuggingRemarks: enableCacheDebuggingRemarks, enableTaskSandboxEnforcement: enableTaskSandboxEnforcement, sandboxDirectory: sandboxDirectory, extraSandboxSubdirectories: extraSandboxSubdirectories, developerDirectory: developerDirectory, casOptions: casOptions)
    }

    package func createInfoPlistProcessorTaskAction(_ contextPath: Path) -> any PlannedTaskAction {
        return InfoPlistProcessorTaskAction(contextPath)
    }

    package func createMergeInfoPlistTaskAction() -> any PlannedTaskAction {
        return MergeInfoPlistTaskAction()
    }

    package func createLinkAssetCatalogTaskAction() -> any PlannedTaskAction {
        return LinkAssetCatalogTaskAction()
    }

    package func createLSRegisterURLTaskAction() -> any PlannedTaskAction {
        return LSRegisterURLTaskAction()
    }

    package func createProcessProductEntitlementsTaskAction(scope: MacroEvaluationScope, mergedEntitlements: PropertyListItem, entitlementsVariant: EntitlementsVariant, destinationPlatformName: String, entitlementsFilePath: Path?, fs: any FSProxy) -> any PlannedTaskAction {
        return ProcessProductEntitlementsTaskAction(scope: scope, fs: fs, entitlements: mergedEntitlements, entitlementsVariant: entitlementsVariant, destinationPlatformName: destinationPlatformName, entitlementsFilePath: entitlementsFilePath)
    }

    package func createProcessProductProvisioningProfileTaskAction() -> any PlannedTaskAction {
        return ProcessProductProvisioningProfileTaskAction()
    }

    package func createRegisterExecutionPolicyExceptionTaskAction() -> any PlannedTaskAction {
        return RegisterExecutionPolicyExceptionTaskAction()
    }

    package func createValidateProductTaskAction() -> any PlannedTaskAction {
        return ValidateProductTaskAction()
    }

    package func createConstructStubExecutorInputFileListTaskAction() -> any PlannedTaskAction {
        return ConstructStubExecutorInputFileListTaskAction()
    }

    package func createODRAssetPackManifestTaskAction() -> any PlannedTaskAction {
        return ODRAssetPackManifestTaskAction()
    }

    package func createClangCompileTaskAction() -> any PlannedTaskAction {
        return ClangCompileTaskAction()
    }

    package func createClangScanTaskAction() -> any PlannedTaskAction {
        return ClangScanTaskAction()
    }

    package func createSwiftDriverTaskAction() -> any PlannedTaskAction {
        return SwiftDriverTaskAction()
    }

    package func createSwiftCompilationRequirementTaskAction() -> any PlannedTaskAction {
        return SwiftDriverCompilationRequirementTaskAction()
    }

    package func createSwiftCompilationTaskAction() -> any PlannedTaskAction {
        return SwiftCompilationTaskAction()
    }

    package func createProcessXCFrameworkTask() -> any PlannedTaskAction {
        return ProcessXCFrameworkTaskAction()
    }

    package func createValidateDevelopmentAssetsTaskAction() -> any PlannedTaskAction {
        return ValidateDevelopmentAssetsTaskAction()
    }

    package func createSignatureCollectionTaskAction() -> any PlannedTaskAction {
        return SignatureCollectionTaskAction()
    }

    package func createClangModuleVerifierInputGeneratorTaskAction() -> any PlannedTaskAction {
        return ClangModuleVerifierInputGeneratorTaskAction()
    }

    package func createProcessSDKImportsTaskAction() -> any PlannedTaskAction {
        return ProcessSDKImportsTaskAction()
    }
}

package final class CancellingTaskPlanningDelegate: TestTaskPlanningDelegate, @unchecked Sendable {
    let afterNodes: Int
    let afterTasks: Int
    var numNodesSeen: Int = 0
    var numTasksSeen: Int = 0

    private let queue = SWBQueue(label: "SWBTestSupport.CancellingTaskPlanningDelegate.queue", qos: UserDefaults.defaultRequestQoS)

    package init(afterNodes: Int = Int.max, afterTasks: Int = Int.max, clientDelegate: any TaskPlanningClientDelegate, workspace: Workspace, fs: any FSProxy) {
        self.afterNodes = afterNodes
        self.afterTasks = afterTasks
        super.init(clientDelegate: clientDelegate, workspace: workspace, fs: fs)
    }

    package override var cancelled: Bool {
        return (queue.blocking_sync{ numNodesSeen }) > afterNodes || (queue.blocking_sync{ numTasksSeen }) > afterTasks
    }

    package override func createVirtualNode(_ name: String) -> PlannedVirtualNode {
        queue.blocking_sync{ numNodesSeen += 1 }
        return super.createVirtualNode(name)
    }

    package override func createDirectoryTreeNode(absolutePath path: Path, excluding: [String]) -> PlannedDirectoryTreeNode {
        queue.blocking_sync{ numNodesSeen += 1 }
        return super.createDirectoryTreeNode(absolutePath: path, excluding: excluding)
    }

    package override func createNode(absolutePath path: Path) -> PlannedPathNode {
        queue.blocking_sync{ numNodesSeen += 1 }
        return super.createNode(absolutePath: path)
    }

    package override func createTask(_ builder: inout PlannedTaskBuilder) -> any PlannedTask {
        queue.blocking_sync{ numTasksSeen += 1 }
        return super.createTask(&builder)
    }
}