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 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import class Foundation.Bundle
import class Foundation.ProcessInfo
package import SWBCore
package import SWBProtocol
package import SWBUtil
package import Testing
package import SWBMacro
private protocol Resolver {
/// The name of the containing workspace
var workspaceName: String { get }
/// The `sourceRoot` path.
var sourceRoot: Path { get }
/// Find a file reference with the given name, or target reference corresponding to a product with the given name.
func findAuto(_ name: String) throws -> TestBuildableItem
/// Find a file reference GUID with the given name.
func findFile(_ name: String) throws -> String
/// Find a target with the given name. Returns `nil` if no target of that name can be found.
func findTarget(_ name: String) -> (any TestInternalTarget)?
/// Find the project for the given target.
func findProject(for target: any TestInternalTarget) throws -> TestProject
}
private enum TestBuildableItem {
case reference(guid: String)
case targetProduct(guid: String)
}
package protocol TestItem: AnyObject {}
private protocol TestInternalItem: TestItem {
static var guidCode: String { get }
var guidIdentifier: String { get }
var guid: String { get }
}
extension TestInternalItem {
var guid: String {
return "\(Self.guidCode)\(guidIdentifier)"
}
}
private let _nextGuidIdentifier = LockedValue(1)
private func nextGuidIdentifier() -> String {
return _nextGuidIdentifier.withLock { value in
defer { value += 1 }
return String(value)
}
}
/// A top-level object.
private protocol TestInternalObjectItem: TestInternalItem {
/// The object signature.
var signature: String { get }
/// Convert the item into its standalone PIF object.
func toObject(_ resolver: any Resolver) throws -> PropertyListItem
}
package protocol TestStructureItem { }
private protocol TestInternalStructureItem: TestInternalItem, TestStructureItem, Sendable {
func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.GroupTreeReference
}
// Support .toProtocol() on individual items, using a mock resolver.
private struct MockResolver: Resolver {
var workspaceName: String {
fatalError("unexpected request for \(#function)")
}
var sourceRoot: Path {
fatalError("unexpected request for \(#function)")
}
func findAuto(_ name: String) -> TestBuildableItem {
fatalError("unexpected request for \(#function)")
}
func findFile(_ name: String) -> String {
fatalError("unexpected request for \(#function)")
}
func findTarget(_ name: String) -> (any TestInternalTarget)? {
fatalError("unexpected request for \(#function)")
}
func findProject(for target: any TestInternalTarget) throws -> TestProject {
fatalError("unexpected request for \(#function)")
}
}
extension TestStructureItem {
package func toProtocol() throws -> SWBProtocol.Reference {
return try (self as! (any TestInternalStructureItem)).toProtocol(MockResolver())
}
}
extension TestTarget {
package func toProtocol() throws -> SWBProtocol.Target {
return try (self as! (any TestInternalTarget)).toProtocol(MockResolver())
}
}
package enum TestSourceTree: Equatable, Sendable {
case absolute
case groupRelative
case buildSetting(String) // FIXME: This should be a MacroExpressionSource.
}
extension TestSourceTree {
fileprivate func toProtocol() -> SWBProtocol.SourceTree {
switch self {
case .absolute: return .absolute
case .groupRelative: return .groupRelative
case .buildSetting(let value): return .buildSetting(value)
}
}
}
package final class TestFile: TestInternalStructureItem, CustomStringConvertible {
static let guidCode = "FR"
package let name: String
private let _guid: String?
private let path: String?
private let projectDirectory: String?
private let fileTypeId: String?
private let regionVariantName: String?
private let fileTextEncoding: FileTextEncoding?
private let sourceTree: TestSourceTree
private let expectedSignature: String?
/// We use stable GUIDs for file references, since they are referenced indirectly.
///
/// Test projects are expected to not have collisions in these.
package var guid: String {
return actualGUID
}
var actualGUID: String {
return _guid ?? (TestFile.guidCode + guidIdentifier)
}
var guidIdentifier: String {
return name + (regionVariantName ?? "")
}
package init(_ name: String, guid: String? = nil, path: String? = nil, projectDirectory: String? = nil, fileType: String? = nil, regionVariantName: String? = nil, fileTextEncoding: FileTextEncoding? = nil, sourceTree: TestSourceTree = .groupRelative, expectedSignature: String? = nil) {
self.name = name
self._guid = guid
self.path = path
self.projectDirectory = projectDirectory
self.fileTypeId = fileType
self.regionVariantName = regionVariantName
self.fileTextEncoding = fileTextEncoding
self.sourceTree = sourceTree
self.expectedSignature = expectedSignature
}
private var fileType: String {
// FIXME: This should be able to just use some method on the actual FileType specs?
guard fileTypeId == nil else { return fileTypeId! }
switch Path(path ?? name).fileSuffix {
case ".a":
return "archive.ar"
case ".app":
return "wrapper.application"
case ".appex":
return "wrapper.app-extension"
case ".applescript":
return "sourcecode.applescript"
case ".atlas":
return "folder.skatlas"
case ".bundle":
return "wrapper.cfbundle"
case ".s":
return "sourcecode.asm"
case ".c":
return "sourcecode.c.c"
case ".cl":
return "sourcecode.opencl"
case ".cpp":
return "sourcecode.cpp.cpp"
case ".d":
return "sourcecode.dtrace"
case ".dae", ".DAE":
return "text.xml.dae"
case ".dat":
return "file"
case ".defs":
return "sourcecode.mig"
case ".dylib":
return "compiled.mach-o.dylib"
case ".entitlements":
return "text.plist.entitlements"
case ".exp":
return "sourcecode.exports"
case ".hpp", ".hp", ".hh", ".hxx", ".h++", ".ipp", ".pch++":
return "sourcecode.cpp.h"
case ".iconset":
return "folder.iconset"
case ".iig":
return "sourcecode.iig"
case ".instrpkg":
return "com.apple.instruments.package-definition"
case ".intentdefinition":
return "file.intentdefinition"
case ".intents":
return "wrapper.intents"
case ".js":
return "sourcecode.javascript"
case ".jpg", ".jpeg":
return "image.jpeg"
case ".m":
return "sourcecode.c.objc"
case ".mm":
return "sourcecode.cpp.objcpp"
case ".metal":
return "sourcecode.metal"
case ".pch", ".h", ".H":
return "sourcecode.c.h"
case ".framework":
return "wrapper.framework"
case ".l":
return "sourcecode.lex"
case ".mlmodel":
return "file.mlmodel"
case ".mlpackage":
return "folder.mlpackage"
case ".map", ".modulemap":
return "sourcecode.module-map"
case ".nib":
return "file.nib"
case ".o":
return "compiled.mach-o.objfile"
case ".plist":
return "text.plist"
case ".vocabulary":
return "text.plist.vocabulary"
case ".plugindata":
return "com.apple.xcode.plugindata"
case ".png":
return "image.png"
case ".xcprivacy":
return "text.plist.app-privacy"
case ".r":
return "sourcecode.rez"
case ".referenceobject":
return "file.referenceobject"
case ".rkassets":
return "folder.rkassets"
case ".scnassets":
return "wrapper.scnassets"
case ".scncache":
return "wrapper.scncache"
case ".storyboard":
return "file.storyboard"
case ".strings":
return "text.plist.strings"
case ".stringsdict":
return "text.plist.stringsdict"
case ".xcstrings":
return "text.json.xcstrings"
case ".swift":
return "sourcecode.swift"
case ".tbd":
return "sourcecode.text-based-dylib-definition"
case ".tif", ".tiff":
return "image.tiff"
case ".txt":
return "text"
case ".uicatalog":
return "file.uicatalog"
case ".xcassets":
return "folder.assetcatalog"
case ".icon":
return "folder.iconcomposer.icon"
case ".xcdatamodeld":
return "wrapper.xcdatamodel"
case ".xcfilelist":
return "text"
case ".xcmappingmodel":
return "wrapper.xcmappingmodel"
case ".xcstickers":
return "folder.stickers"
case ".xcconfig":
return "text.xcconfig"
case ".xcdatamodel":
return "wrapper.xcdatamodel"
case ".xcappextensionpoints":
return "text.plist.xcappextensionpoints"
case ".xcframework":
return "wrapper.xcframework"
case ".xcspec":
return "text.plist.xcspec"
case ".xib":
return "file.xib"
case ".xpc":
return "wrapper.xpc-service"
case ".y":
return "sourcecode.yacc"
case ".ym":
return "sourcecode.yacc"
case ".docc":
return "folder.documentationcatalog"
case ".tightbeam":
return "sourcecode.tightbeam"
case let ext where ext.hasPrefix(".fake-"):
// If this is a fake extension, just return "file".
return "file"
case let ext:
fatalError("unknown extension: \(ext)")
}
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.GroupTreeReference {
return SWBProtocol.FileReference(guid: actualGUID, sourceTree: sourceTree.toProtocol(), path: .string(path ?? name), fileTypeIdentifier: fileType, regionVariantName: regionVariantName, fileTextEncoding: fileTextEncoding, expectedSignature: self.expectedSignature)
}
package var description: String {
return "<TestFile: \(path ?? name)>"
}
}
package final class TestGroup: TestInternalItem, TestInternalStructureItem, CustomStringConvertible, Sendable {
static let guidCode = "G"
let guidIdentifier = nextGuidIdentifier()
fileprivate let name: String
fileprivate let path: String?
private let sourceTree: TestSourceTree?
fileprivate let children: [any TestInternalStructureItem]
private let overriddenGuid: String?
package var guid: String {
return overriddenGuid ?? "\(TestGroup.guidCode)\(guidIdentifier)"
}
package init(_ name: String, guid: String? = nil, path: String? = nil, sourceTree: TestSourceTree? = nil, children: [any TestStructureItem] = []) {
self.name = name
self.overriddenGuid = guid
self.path = path
self.sourceTree = sourceTree
self.children = children.map { $0 as! (any TestInternalStructureItem) }
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.GroupTreeReference {
return try toProtocol(resolver, isRoot: false)
}
fileprivate func toProtocol(_ resolver: any Resolver, isRoot: Bool) throws -> SWBProtocol.FileGroup {
let sourceTree = self.sourceTree ?? (isRoot ? .buildSetting("PROJECT_DIR") : .groupRelative)
return try SWBProtocol.FileGroup(guid: guid, sourceTree: sourceTree.toProtocol(), path: .string(path ?? (sourceTree == .buildSetting("PROJECT_DIR") ? "" : name)), name: name, children: children.map{ try $0.toProtocol(resolver) })
}
package var description: String {
return "<TestGroup: \(path ?? name)>"
}
}
package final class TestVariantGroup: TestInternalItem, TestInternalStructureItem, CustomStringConvertible {
static let guidCode = "VG"
let guidIdentifier = nextGuidIdentifier()
fileprivate let name: String
fileprivate let children: [any TestInternalStructureItem]
package init(_ name: String, children: [any TestStructureItem] = []) {
self.name = name
self.children = children.map { $0 as! (any TestInternalStructureItem) }
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.GroupTreeReference {
return try SWBProtocol.VariantGroup(guid: guid, sourceTree: .groupRelative, path: .string(""), name: name, children: children.map{ try $0.toProtocol(resolver) })
}
package var description: String {
return "<TestVariantGroup: \(name)>"
}
}
package final class TestVersionGroup: TestInternalItem, TestInternalStructureItem, CustomStringConvertible {
static let guidCode = "VersG"
let guidIdentifier = nextGuidIdentifier()
fileprivate let name: String
fileprivate let path: String?
private let sourceTree: TestSourceTree?
fileprivate let children: [any TestInternalStructureItem]
package init(_ name: String, path: String? = nil, sourceTree: TestSourceTree? = nil, children: [any TestStructureItem] = []) {
self.name = name
self.path = path
self.sourceTree = sourceTree
self.children = children.map { $0 as! (any TestInternalStructureItem) }
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.GroupTreeReference {
let sourceTree = self.sourceTree ?? .groupRelative
return try SWBProtocol.VersionGroup(guid: guid, sourceTree: .groupRelative, path: .string(path ?? (sourceTree == .buildSetting("PROJECT_DIR") ? "" : name)), children: children.map{ try $0.toProtocol(resolver) })
}
package var description: String {
return "<TestVersionGroup: \(path ?? name)>"
}
}
package final class TestBuildFile: TestInternalItem, Sendable {
package enum BuildableItemName: Sendable {
case auto(String)
case file(String)
case target(String)
case namedReference(name: String, fileTypeIdentifier: String)
}
package enum HeaderVisibility: Sendable {
case `public`
case `private`
}
package enum MigCodegenFiles: String, Sendable {
case client
case server
case both
}
package enum ResourceRule: String, Sendable {
case process
case copy
case embedInCode
}
static let guidCode = "BF"
let guidIdentifier = nextGuidIdentifier()
/// While `BuildFile` does not have a name property, for ease of testing `TestBuildFile` does, and the guid of the file it represents will be looked up using the name.
let buildableItemName: BuildableItemName
let file: TestFile?
let resourceRule: ResourceRule
let codeSignOnCopy: Bool?
let removeHeadersOnCopy: Bool?
let headerVisibility: HeaderVisibility?
let additionalArgs: [String]?
let decompress: Bool
let migCodegenFiles: MigCodegenFiles?
let shouldLinkWeakly: Bool?
let assetTags: Set<String>
let intentsCodegenVisibility: IntentsCodegenVisibility
let platformFilters: Set<PlatformFilter>
let shouldWarnIfNoRuleToProcess: Bool
package init(_ buildableItemName: BuildableItemName, codeSignOnCopy: Bool? = nil, removeHeadersOnCopy: Bool? = nil, headerVisibility: HeaderVisibility? = nil, additionalArgs: [String]? = nil, decompress: Bool = false, migCodegenFiles: MigCodegenFiles? = nil, shouldLinkWeakly: Bool? = nil, assetTags: Set<String> = Set(), intentsCodegenVisibility: IntentsCodegenVisibility = .noCodegen, platformFilters: Set<PlatformFilter> = [], shouldWarnIfNoRuleToProcess: Bool = true, resourceRule: ResourceRule = .process) {
self.buildableItemName = buildableItemName
self.file = nil
self.codeSignOnCopy = codeSignOnCopy
self.removeHeadersOnCopy = removeHeadersOnCopy
self.headerVisibility = headerVisibility
self.additionalArgs = additionalArgs
self.decompress = decompress
self.migCodegenFiles = migCodegenFiles
self.shouldLinkWeakly = shouldLinkWeakly
self.assetTags = assetTags
self.intentsCodegenVisibility = intentsCodegenVisibility
self.platformFilters = platformFilters
self.shouldWarnIfNoRuleToProcess = shouldWarnIfNoRuleToProcess
self.resourceRule = resourceRule
}
package convenience init(_ fileName: String, codeSignOnCopy: Bool? = nil, removeHeadersOnCopy: Bool? = nil, headerVisibility: HeaderVisibility? = nil, additionalArgs: [String]? = nil, decompress: Bool = false, migCodegenFiles: MigCodegenFiles? = nil, shouldLinkWeakly: Bool? = nil, assetTags: Set<String> = Set(), intentsCodegenVisibility: IntentsCodegenVisibility = .noCodegen, platformFilters: Set<PlatformFilter> = [], shouldWarnIfNoRuleToProcess: Bool = true) {
self.init(.auto(fileName), codeSignOnCopy: codeSignOnCopy, removeHeadersOnCopy: removeHeadersOnCopy, headerVisibility: headerVisibility, additionalArgs: additionalArgs, decompress: decompress, migCodegenFiles: migCodegenFiles, shouldLinkWeakly: shouldLinkWeakly, assetTags: assetTags, intentsCodegenVisibility: intentsCodegenVisibility, platformFilters: platformFilters, shouldWarnIfNoRuleToProcess: shouldWarnIfNoRuleToProcess)
}
package init(_ file: TestFile, codeSignOnCopy: Bool? = nil, removeHeadersOnCopy: Bool? = nil, headerVisibility: HeaderVisibility? = nil, additionalArgs: [String]? = nil, decompress: Bool = false, migCodegenFiles: MigCodegenFiles? = nil, shouldLinkWeakly: Bool? = nil, assetTags: Set<String> = Set(), intentsCodegenVisibility: IntentsCodegenVisibility = .noCodegen, platformFilters: Set<PlatformFilter> = [], shouldWarnIfNoRuleToProcess: Bool = true, resourceRule: ResourceRule = .process) {
self.buildableItemName = .auto(file.name)
self.file = file
self.codeSignOnCopy = codeSignOnCopy
self.removeHeadersOnCopy = removeHeadersOnCopy
self.headerVisibility = headerVisibility
self.additionalArgs = additionalArgs
self.decompress = decompress
self.migCodegenFiles = migCodegenFiles
self.shouldLinkWeakly = shouldLinkWeakly
self.assetTags = assetTags
self.intentsCodegenVisibility = intentsCodegenVisibility
self.platformFilters = platformFilters
self.shouldWarnIfNoRuleToProcess = shouldWarnIfNoRuleToProcess
self.resourceRule = resourceRule
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildFile {
let buildableItemGUID: SWBProtocol.BuildFile.BuildableItemGUID
switch buildableItemName {
case let .auto(name):
if let guid = self.file?.guid {
buildableItemGUID = .reference(guid: guid)
} else {
switch try resolver.findAuto(name) {
case let .reference(guid):
buildableItemGUID = .reference(guid: guid)
case let .targetProduct(guid):
buildableItemGUID = .targetProduct(guid: guid)
}
}
case let .file(name):
buildableItemGUID = try .reference(guid: self.file?.guid ?? resolver.findFile(name))
case let .target(name):
// Note: falling back to "name" is wrong, as a target's name isn't going to be a valid GUID,
// but we need a non-nil value here, and it will just fail to resolve more gracefully later on.
buildableItemGUID = .targetProduct(guid: resolver.findTarget(name)?.guid ?? name)
case let .namedReference(name, fileTypeIdentifier):
buildableItemGUID = .namedReference(name: name, fileTypeIdentifier: fileTypeIdentifier)
}
return SWBProtocol.BuildFile(guid: guid, buildableItemGUID: buildableItemGUID, additionalArgs: additionalArgs.map{ .stringList($0) }, decompress: decompress, headerVisibility: headerVisibility?.toProtocol(), migCodegenFiles: migCodegenFiles?.toProtocol(), intentsCodegenVisibility: intentsCodegenVisibility, resourceRule: resourceRule.toProtocol(), codeSignOnCopy: codeSignOnCopy ?? false, removeHeadersOnCopy: removeHeadersOnCopy ?? false, shouldLinkWeakly: shouldLinkWeakly ?? false, assetTags: assetTags, platformFilters: platformFilters, shouldWarnIfNoRuleToProcess: shouldWarnIfNoRuleToProcess)
}
}
extension TestBuildFile.HeaderVisibility {
fileprivate func toProtocol() -> SWBProtocol.BuildFile.HeaderVisibility {
switch self {
case .public: return .public
case .private: return .private
}
}
}
extension TestBuildFile.MigCodegenFiles {
fileprivate func toProtocol() -> SWBProtocol.BuildFile.MigCodegenFiles {
switch self {
case .client: return .client
case .server: return .server
case .both: return .both
}
}
}
extension TestBuildFile.ResourceRule {
fileprivate func toProtocol() -> SWBProtocol.BuildFile.ResourceRule {
switch self {
case .copy: return .copy
case .embedInCode: return .embedInCode
case .process: return .process
}
}
}
extension TestBuildFile: ExpressibleByStringLiteral {
package typealias UnicodeScalarLiteralType = StringLiteralType
package typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
package convenience init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(value)
}
package convenience init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(value)
}
package convenience init(stringLiteral value: StringLiteralType) {
self.init(value)
}
}
package protocol TestBuildPhase { }
fileprivate protocol TestInternalBuildPhase: TestInternalItem, TestBuildPhase, Sendable {
func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase
}
package final class TestCopyFilesBuildPhase: TestInternalBuildPhase {
static let guidCode = "CFBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
private let destinationSubfolder: String
private let destinationSubpath: String
private let onlyForDeployment: Bool
package enum TestDestinationSubfolder: Sendable {
case absolute
case builtProductsDir
case buildSetting(String)
package static let wrapper = Self.buildSetting("$(WRAPPER_NAME)")
package static let resources = Self.buildSetting("$(UNLOCALIZED_RESOURCES_FOLDER_PATH)")
package static let frameworks = Self.buildSetting("$(FRAMEWORKS_FOLDER_PATH)")
package static let sharedFrameworks = Self.buildSetting("$(SHARED_FRAMEWORKS_FOLDER_PATH)")
package static let sharedSupport = Self.buildSetting("$(SHARED_SUPPORT_FOLDER_PATH)")
package static let plugins = Self.buildSetting("$(PLUGINS_FOLDER_PATH)")
package static let javaResources = Self.buildSetting("$(JAVA_FOLDER_PATH)")
package var pathString: String {
switch self {
case .absolute:
return "<absolute>"
case .builtProductsDir:
return "<builtProductsDir>"
case .buildSetting(let value):
return value
}
}
}
package init(_ buildFiles: [TestBuildFile] = [], destinationSubfolder: TestDestinationSubfolder, destinationSubpath: String = "", onlyForDeployment: Bool = true) {
self.buildFiles = buildFiles
self.destinationSubfolder = destinationSubfolder.pathString
self.destinationSubpath = destinationSubpath
self.onlyForDeployment = onlyForDeployment
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.CopyFilesBuildPhase(
guid: guid,
buildFiles: buildFiles.map { try $0.toProtocol(resolver) },
destinationSubfolder: .string(destinationSubfolder),
destinationSubpath: .string(destinationSubpath),
runOnlyForDeploymentPostprocessing: onlyForDeployment)
}
}
package final class TestAppleScriptBuildPhase: TestInternalBuildPhase {
static let guidCode = "ASBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
package init(_ buildFiles: [TestBuildFile] = [], onlyForDeployment: Bool = true) {
self.buildFiles = buildFiles
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.AppleScriptBuildPhase(guid: guid, buildFiles: buildFiles.map{ try $0.toProtocol(resolver) })
}
}
package final class TestFrameworksBuildPhase: TestInternalBuildPhase {
static let guidCode = "FBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
package init(_ buildFiles: [TestBuildFile] = []) {
self.buildFiles = buildFiles
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.FrameworksBuildPhase(guid: guid, buildFiles: buildFiles.map{ try $0.toProtocol(resolver) })
}
}
package final class TestHeadersBuildPhase: TestInternalBuildPhase {
static let guidCode = "HBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
package init(_ buildFiles: [TestBuildFile] = []) {
self.buildFiles = buildFiles
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.HeadersBuildPhase(guid: guid, buildFiles: buildFiles.map{ try $0.toProtocol(resolver) })
}
}
package final class TestShellScriptBuildPhase: TestInternalBuildPhase {
static let guidCode = "SSBP"
let guidIdentifier = nextGuidIdentifier()
private let overriddenGuid: String?
private let name: String
private let shellPath: String
private let originalObjectID: String
private let contents: String
private let inputs: [String]
private let inputFileLists: [String]
private let outputs: [String]
private let outputFileLists: [String]
private let onlyForDeployment: Bool
private let emitEnvironment: Bool
private let sandboxingOverride: SWBProtocol.SandboxingOverride
private let dependencyInfo: SWBProtocol.DependencyInfo?
private let alwaysOutOfDate: Bool
private let alwaysRunForInstallHdrs: Bool
var guid: String {
return overriddenGuid ?? "\(Self.guidCode)\(guidIdentifier)"
}
package init(name: String, guid: String? = nil, shellPath: String = "/bin/sh", originalObjectID: String, contents: String = "", inputs: [String] = [], inputFileLists: [String] = [], outputs: [String] = [], outputFileLists: [String] = [], onlyForDeployment: Bool = false, emitEnvironment: Bool = false, dependencyInfo: SWBProtocol.DependencyInfo? = nil, alwaysOutOfDate: Bool = false, sandboxingOverride: SWBProtocol.SandboxingOverride = .basedOnBuildSetting, alwaysRunForInstallHdrs: Bool = false) {
self.name = name
self.overriddenGuid = guid
self.shellPath = shellPath
self.originalObjectID = originalObjectID
self.contents = contents
self.inputs = inputs
self.inputFileLists = inputFileLists
self.outputs = outputs
self.outputFileLists = outputFileLists
self.onlyForDeployment = onlyForDeployment
self.emitEnvironment = emitEnvironment
self.dependencyInfo = dependencyInfo
self.alwaysOutOfDate = alwaysOutOfDate
self.sandboxingOverride = sandboxingOverride
self.alwaysRunForInstallHdrs = alwaysRunForInstallHdrs
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.BuildPhase {
let inputs = self.inputs.map{ MacroExpressionSource.string($0) }
let outputs = self.outputs.map{ MacroExpressionSource.string($0) }
let inputFileLists = self.inputFileLists.map{ MacroExpressionSource.string($0) }
let outputFileLists = self.outputFileLists.map{ MacroExpressionSource.string($0) }
return SWBProtocol.ShellScriptBuildPhase(
guid: guid,
name: name,
// FIXME: This is not a path.
shellPath: Path(shellPath),
scriptContents: contents,
originalObjectID: originalObjectID,
inputFilePaths: inputs,
inputFileListPaths: inputFileLists,
outputFilePaths: outputs,
outputFileListPaths: outputFileLists,
emitEnvironment: emitEnvironment,
runOnlyForDeploymentPostprocessing: onlyForDeployment,
dependencyInfo: dependencyInfo,
alwaysOutOfDate: alwaysOutOfDate,
sandboxingOverride: sandboxingOverride,
alwaysRunForInstallHdrs: alwaysRunForInstallHdrs
)
}
}
package final class TestResourcesBuildPhase: TestInternalBuildPhase {
static let guidCode = "RBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
package init(_ buildFiles: [TestBuildFile] = [], onlyForDeployment: Bool = true) {
self.buildFiles = buildFiles
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.ResourcesBuildPhase(guid: guid, buildFiles: buildFiles.map{ try $0.toProtocol(resolver) })
}
}
package final class TestRezBuildPhase: TestInternalBuildPhase {
static let guidCode = "ZBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
package init(_ buildFiles: [TestBuildFile] = []) {
self.buildFiles = buildFiles
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.RezBuildPhase(guid: guid, buildFiles: buildFiles.map{ try $0.toProtocol(resolver) })
}
}
package final class TestSourcesBuildPhase: TestInternalBuildPhase {
static let guidCode = "SBP"
let guidIdentifier = nextGuidIdentifier()
private let buildFiles: [TestBuildFile]
package init(_ buildFiles: [TestBuildFile] = []) {
self.buildFiles = buildFiles
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildPhase {
return try SWBProtocol.SourcesBuildPhase(guid: guid, buildFiles: buildFiles.map{ try $0.toProtocol(resolver) })
}
}
package final class TestBuildRule: TestInternalItem, Sendable {
static let guidCode = "BR"
let guidIdentifier = nextGuidIdentifier()
private let name: String
private let inputSpecifier: SWBProtocol.BuildRule.InputSpecifier
private let actionSpecifier: SWBProtocol.BuildRule.ActionSpecifier
package init(name: String = "Test Build Rule", fileTypeIdentifier: String, compilerIdentifier: String) {
self.name = name
self.inputSpecifier = .fileType(identifier: fileTypeIdentifier)
self.actionSpecifier = .compiler(identifier: compilerIdentifier)
}
package init(name: String = "Test Build Rule", filePattern: String, compilerIdentifier: String) {
self.name = name
self.inputSpecifier = .patterns(.string(filePattern))
self.actionSpecifier = .compiler(identifier: compilerIdentifier)
}
package convenience init(name: String = "Test Build Rule", fileTypeIdentifier: String, script: String, inputs: [String] = [], outputs: [String] = [], outputFilesCompilerFlags: [[String]] = [], dependencyInfo: SWBProtocol.DependencyInfo? = nil, runOncePerArchitecture: Bool? = nil) {
self.init(name: name, inputSpecifier: .fileType(identifier: fileTypeIdentifier), script: script, inputs: inputs, inputFileLists: [], outputs: outputs, outputFileLists: [], outputFilesCompilerFlags: outputFilesCompilerFlags, dependencyInfo: dependencyInfo, runOncePerArchitecture: runOncePerArchitecture)
}
package convenience init(name: String = "Test Build Rule", filePattern: String, script: String, inputs: [String] = [], outputs: [String] = [], outputFilesCompilerFlags: [[String]] = [], dependencyInfo: SWBProtocol.DependencyInfo? = nil, runOncePerArchitecture: Bool? = nil) {
self.init(name: name, inputSpecifier: .patterns(.string(filePattern)), script: script, inputs: inputs, inputFileLists: [], outputs: outputs, outputFileLists: [], outputFilesCompilerFlags: outputFilesCompilerFlags, dependencyInfo: dependencyInfo, runOncePerArchitecture: runOncePerArchitecture)
}
package convenience init(name: String = "Test Build Rule", filePattern: String, script: String, inputs: [String] = [], inputFileLists: [String] = [], outputs: [String] = [], outputFileLists: [String] = [], outputFilesCompilerFlags: [[String]] = [], dependencyInfo: SWBProtocol.DependencyInfo? = nil, runOncePerArchitecture: Bool? = nil) {
self.init(name: name, inputSpecifier: .patterns(.string(filePattern)), script: script, inputs: inputs, inputFileLists: inputFileLists, outputs: outputs, outputFileLists: outputFileLists, outputFilesCompilerFlags: outputFilesCompilerFlags, dependencyInfo: dependencyInfo, runOncePerArchitecture: runOncePerArchitecture)
}
private init(name: String, inputSpecifier: SWBProtocol.BuildRule.InputSpecifier, script: String, inputs: [String], inputFileLists: [String], outputs: [String], outputFileLists: [String], outputFilesCompilerFlags: [[String]], dependencyInfo: SWBProtocol.DependencyInfo?, runOncePerArchitecture: Bool?) {
self.name = name
self.inputSpecifier = inputSpecifier
let outputs = outputs.enumerated().map{ (entry) -> SWBProtocol.BuildRule.ShellScriptOutputInfo in
let (i, output) = entry
if i < outputFilesCompilerFlags.count {
return .init(path: .string(output), additionalCompilerFlags: .stringList(outputFilesCompilerFlags[i]))
} else {
return .init(path: .string(output), additionalCompilerFlags: nil)
}
}
self.actionSpecifier = .shellScript(contents: script, inputs: inputs.map{ .string($0) }, inputFileLists: inputFileLists.map { .string($0) }, outputs: outputs, outputFileLists: outputFileLists.map { .string($0) }, dependencyInfo: dependencyInfo, runOncePerArchitecture: runOncePerArchitecture ?? true)
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.BuildRule {
return SWBProtocol.BuildRule(guid: guid, name: name, inputSpecifier: inputSpecifier, actionSpecifier: actionSpecifier)
}
}
package final class TestCustomTask: Sendable {
package let commandLine: [String]
package let environment: [String: String]
package let workingDirectory: String
package let executionDescription: String
package let inputs: [String]
package let outputs: [String]
package let enableSandboxing: Bool
package let preparesForIndexing: Bool
package init(commandLine: [String], environment: [String : String], workingDirectory: String, executionDescription: String, inputs: [String], outputs: [String], enableSandboxing: Bool, preparesForIndexing: Bool) {
self.commandLine = commandLine
self.environment = environment
self.workingDirectory = workingDirectory
self.executionDescription = executionDescription
self.inputs = inputs
self.outputs = outputs
self.enableSandboxing = enableSandboxing
self.preparesForIndexing = preparesForIndexing
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.CustomTask {
return SWBProtocol.CustomTask(
commandLine: commandLine.map { MacroExpressionSource.string($0) },
environment: environment.map { (MacroExpressionSource.string($0), MacroExpressionSource.string($1)) },
workingDirectory: MacroExpressionSource.string(workingDirectory),
executionDescription: MacroExpressionSource.string(executionDescription),
inputFilePaths: inputs.map { MacroExpressionSource.string($0) },
outputFilePaths: outputs.map { MacroExpressionSource.string($0) },
enableSandboxing: enableSandboxing,
preparesForIndexing: preparesForIndexing
)
}
}
package typealias PlatformFilter = SWBProtocol.PlatformFilter
package final class TestTargetDependency: Sendable {
package let name: String
package let platformFilters: Set<PlatformFilter>
package init(_ name: String, platformFilters: Set<PlatformFilter> = []) {
self.name = name
self.platformFilters = platformFilters
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.TargetDependency {
return SWBProtocol.TargetDependency(guid: resolver.findTarget(name)?.guid ?? name, name: name, platformFilters: platformFilters)
}
}
extension TestTargetDependency: ExpressibleByStringLiteral {
package typealias StringLiteralType = String
package convenience init(stringLiteral value: StringLiteralType) {
self.init(value)
}
}
package protocol TestTarget: Sendable {
var guid: String { get }
var name: String { get }
}
private protocol TestInternalTarget: TestInternalObjectItem, TestTarget {
var name: String { get }
var signature: String { get }
func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.Target
}
extension TestInternalTarget {
fileprivate func toObject(_ resolver: any Resolver) throws -> PropertyListItem {
let serializer = MsgPackSerializer()
try serializer.serialize(toProtocol(resolver))
return .plDict([
"signature": .plString(signature),
"type": .plString("target"),
"contents": .plDict(["data": .plArray(serializer.byteString.bytes.map { .plInt(Int($0)) })])
])
}
}
package final class TestStandardTarget: TestInternalTarget, Sendable {
package var signature: String { return "TARGET@v11_\(guid)" }
// Redeclaring this as public, so clients can use it.
package var guid: String {
return overriddenGuid ?? "\(Swift.type(of: self).guidCode)-\(name)-\(guidIdentifier)"
}
package enum TargetType: Sendable {
case application
case commandLineTool
case hostBuildTool
case framework
case staticFramework
case staticLibrary
case objectFile
case dynamicLibrary
case bundle
case xpcService
case applicationExtension
case extensionKitExtension
case xcodeExtension
case unitTest
case uiTest
case multiDeviceUITest
case systemExtension
case driverExtension
case kernelExtension
case watchKitAppContainer
case watchKitApp
case watchKitExtension
case messagesApp
case messagesExtension
case messagesStickerPackExtension
case instrumentsPackage
case inAppPurchaseContent
case appClip
// This only still exists to test the deprecation error message
case watchKit1App
var productTypeIdentifier: String {
switch self {
case .application:
return "com.apple.product-type.application"
case .commandLineTool:
return "com.apple.product-type.tool"
case .hostBuildTool:
return "com.apple.product-type.tool.host-build"
case .framework:
return "com.apple.product-type.framework"
case .staticFramework:
return "com.apple.product-type.framework.static"
case .staticLibrary:
return "com.apple.product-type.library.static"
case .objectFile:
return "com.apple.product-type.objfile"
case .dynamicLibrary:
return "com.apple.product-type.library.dynamic"
case .bundle:
return "com.apple.product-type.bundle"
case .xpcService:
return "com.apple.product-type.xpc-service"
case .applicationExtension:
return "com.apple.product-type.app-extension"
case .extensionKitExtension:
return "com.apple.product-type.extensionkit-extension"
case .xcodeExtension:
return "com.apple.product-type.xcode-extension"
case .unitTest:
return "com.apple.product-type.bundle.unit-test"
case .uiTest:
return "com.apple.product-type.bundle.ui-testing"
case .multiDeviceUITest:
return "com.apple.product-type.bundle.multi-device-ui-testing"
case .systemExtension:
return "com.apple.product-type.system-extension"
case .driverExtension:
return "com.apple.product-type.driver-extension"
case .kernelExtension:
return "com.apple.product-type.kernel-extension"
case .watchKitAppContainer:
return "com.apple.product-type.application.watchapp2-container"
case .watchKit1App:
return "com.apple.product-type.application.watchapp"
case .watchKitApp:
return "com.apple.product-type.application.watchapp2"
case .watchKitExtension:
return "com.apple.product-type.watchkit2-extension"
case .messagesApp:
return "com.apple.product-type.application.messages"
case .messagesExtension:
return "com.apple.product-type.app-extension.messages"
case .messagesStickerPackExtension:
return "com.apple.product-type.app-extension.messages-sticker-pack"
case .instrumentsPackage:
return "com.apple.product-type.instruments-package"
case .inAppPurchaseContent:
return "com.apple.product-type.in-app-purchase-content"
case .appClip:
return "com.apple.product-type.application.on-demand-install-capable"
}
}
func computeProductReferenceName(_ name: String) -> String {
switch self {
case .application,
.watchKit1App,
.watchKitApp,
.watchKitAppContainer,
.messagesApp,
.appClip:
return "\(name).app"
case .commandLineTool,
.hostBuildTool:
return "\(name)"
case .framework,
.staticFramework:
return "\(name).framework"
case .staticLibrary:
return "lib\(name).a"
case .objectFile:
return "\(name).o"
case .dynamicLibrary:
// FIXME: This should be based on the target platform, not the host. See also: <rdar://problem/29410050> Swift Build doesn't support product references with non-constant basenames
guard let suffix = try? ProcessInfo.processInfo.hostOperatingSystem().imageFormat.dynamicLibraryExtension else {
return ""
}
return "lib\(name).\(suffix)"
case .bundle:
return "\(name).bundle"
case .xpcService:
return "\(name).xpc"
case .applicationExtension,
.extensionKitExtension,
.xcodeExtension,
.watchKitExtension,
.messagesExtension,
.messagesStickerPackExtension:
return "\(name).appex"
case .unitTest, .uiTest, .multiDeviceUITest:
return "\(name).xctest"
case .systemExtension:
return "\(name).systemextension"
case .driverExtension:
return "\(name).dext"
case .kernelExtension:
return "\(name).kext"
case .instrumentsPackage:
return "\(name).instrdst"
case .inAppPurchaseContent:
return "\(name)"
}
}
}
static let guidCode = "T"
let guidIdentifier = nextGuidIdentifier()
package let name: String
private let type: TargetType
private let buildConfigurations: [TestBuildConfiguration]
private let buildPhases: [any TestInternalBuildPhase]
private let buildRules: [TestBuildRule]
private let customTasks: [TestCustomTask]
private let dependencies: [TestTargetDependency]
private let explicitProductReferenceName: String?
private let predominantSourceCodeLanguage: SWBCore.StandardTarget.SourceCodeLanguage
private let provisioningSourceData: [ProvisioningSourceData]
private let overriddenGuid: String?
private let dynamicTargetVariantName: String?
private let approvedByUser: Bool
/// Create a test target
package init(_ name: String, guid: String? = nil, type: TargetType, buildConfigurations: [TestBuildConfiguration]? = nil, buildPhases: [any TestBuildPhase] = [], buildRules: [TestBuildRule] = [], customTasks: [TestCustomTask] = [], dependencies: [TestTargetDependency] = [], productReferenceName: String? = nil, predominantSourceCodeLanguage: SWBCore.StandardTarget.SourceCodeLanguage = .undefined, provisioningSourceData: [ProvisioningSourceData] = [], dynamicTargetVariantName: String? = nil, approvedByUser: Bool = true) {
self.name = name
self.overriddenGuid = guid
self.type = type
self.buildConfigurations = buildConfigurations ?? [TestBuildConfiguration("Debug")]
self.buildPhases = buildPhases.map { $0 as! (any TestInternalBuildPhase) }
self.buildRules = buildRules
self.customTasks = customTasks
self.dependencies = dependencies
self.explicitProductReferenceName = productReferenceName ?? {
// Try to correctly determine the product reference if not specified explicitly
let productNames = Set((buildConfigurations ?? []).compactMap { $0.buildSettings["PRODUCT_NAME"] })
if productNames.count > 1 {
preconditionFailure("productReferenceName must be explicitly set for this target because it cannot be determined automatically in this context")
}
// Just return nil; we'll end up using the target name
if productNames.first == "$(TARGET_NAME)" {
return nil
}
if productNames.first?.contains("$") == true {
preconditionFailure("productReferenceName must be explicitly set for this target because it cannot be determined automatically in this context (build setting references are not evaluated here)")
}
return productNames.first.map { type.computeProductReferenceName($0) }
}()
self.predominantSourceCodeLanguage = predominantSourceCodeLanguage
self.provisioningSourceData = provisioningSourceData
self.dynamicTargetVariantName = dynamicTargetVariantName
self.approvedByUser = approvedByUser
}
fileprivate var productReferenceGUID: String {
return "PR\(guidIdentifier)"
}
fileprivate var productReferenceName: String {
return explicitProductReferenceName ?? type.computeProductReferenceName(name)
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.Target {
let ref = SWBProtocol.ProductReference(guid: productReferenceGUID, name: productReferenceName)
let performanceTestsBaselinePath = try (type == .unitTest) ? resolver.findProject(for: self).getPath(resolver).join("xcshareddata/xcbaselines").join("\(guid).xcbaseline") : nil
return try SWBProtocol.StandardTarget(guid: guid, name: name, buildConfigurations: buildConfigurations.map{ try $0.toProtocol(resolver) }, customTasks: customTasks.map { $0.toProtocol(resolver) }, dependencies: dependencies.map{ $0.toProtocol(resolver) }, buildPhases: buildPhases.map{ try $0.toProtocol(resolver) }, buildRules: buildRules.map{ $0.toProtocol(resolver) }, productTypeIdentifier: type.productTypeIdentifier, productReference: ref, performanceTestsBaselinesPath: performanceTestsBaselinePath?.str, predominantSourceCodeLanguage: predominantSourceCodeLanguage.description, provisioningSourceData: provisioningSourceData, dynamicTargetVariantGuid: dynamicTargetVariantName?.nilIfEmpty.map(resolver.findTarget)??.guid, approvedByUser: approvedByUser)
}
}
package final class TestAggregateTarget: TestInternalTarget {
package var signature: String { return "TARGET@v11_\(guid)" }
private let overriddenGuid: String?
// Redeclaring this as public, so clients can use it.
package var guid: String {
return overriddenGuid ?? "\(type(of: self).guidCode)-\(name)-\(guidIdentifier)"
}
static let guidCode = "AT"
let guidIdentifier = nextGuidIdentifier()
package let name: String
private let buildConfigurations: [TestBuildConfiguration]
private let buildPhases: [any TestInternalBuildPhase]
private let customTasks: [TestCustomTask]
private let dependencies: [String]
package init(_ name: String, guid: String? = nil, buildConfigurations: [TestBuildConfiguration]? = nil, buildPhases: [any TestBuildPhase] = [], customTasks: [TestCustomTask] = [], dependencies: [String] = []) {
self.name = name
self.overriddenGuid = guid
self.buildConfigurations = buildConfigurations ?? [TestBuildConfiguration("Debug")]
self.buildPhases = buildPhases.map { $0 as! (any TestInternalBuildPhase) }
self.customTasks = customTasks
self.dependencies = dependencies
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.Target {
let deps = dependencies.map { SWBProtocol.TargetDependency(guid: resolver.findTarget($0)?.guid ?? $0, name: $0) }
return try SWBProtocol.AggregateTarget(guid: guid, name: name, buildConfigurations: buildConfigurations.map{ try $0.toProtocol(resolver) }, customTasks: customTasks.map { $0.toProtocol(resolver) }, dependencies: deps, buildPhases: buildPhases.map{ try $0.toProtocol(resolver) })
}
}
package final class TestExternalTarget: TestInternalTarget {
package var signature: String { return "TARGET@v11_\(guid)" }
// Redeclaring this as public, so clients can use it.
package var guid: String {
return actualGUID
}
var actualGUID: String {
return "\(type(of: self).guidCode)\(guidIdentifier)"
}
static let guidCode = "ET"
let guidIdentifier = nextGuidIdentifier()
package let name: String
private let toolPath: String
private let arguments: String
private let workingDirectory: String
private let buildConfigurations: [TestBuildConfiguration]
private let customTasks: [TestCustomTask]
private let dependencies: [String]
private let passBuildSettingsInEnvironment: Bool?
package init(_ name: String, toolPath: String = "/usr/bin/make", arguments: String = "$(ACTION)", workingDirectory: String = "$(PROJECT_DIR)", buildConfigurations: [TestBuildConfiguration]? = nil, customTasks: [TestCustomTask] = [], dependencies: [String] = [], passBuildSettingsInEnvironment: Bool? = nil) {
self.name = name
self.toolPath = toolPath
self.arguments = arguments
self.workingDirectory = workingDirectory
self.buildConfigurations = buildConfigurations ?? [TestBuildConfiguration("Debug")]
self.customTasks = customTasks
self.dependencies = dependencies
self.passBuildSettingsInEnvironment = passBuildSettingsInEnvironment
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.Target {
return try SWBProtocol.ExternalTarget(guid: actualGUID, name: name, buildConfigurations: buildConfigurations.map{ try $0.toProtocol(resolver) }, customTasks: customTasks.map { $0.toProtocol(resolver) }, dependencies: dependencies.map { TargetDependency(guid: resolver.findTarget($0)?.guid ?? $0, name: $0) }, toolPath: .string(toolPath), arguments: .string(arguments), workingDirectory: .string(workingDirectory), passBuildSettingsInEnvironment: passBuildSettingsInEnvironment ?? true)
}
}
package final class TestPackageProductTarget: TestInternalTarget {
package var signature: String { return "TARGET@v11_\(guid)" }
// Redeclaring this as public, so clients can use it.
package var guid: String {
return "\(type(of: self).guidCode)\(guidIdentifier)"
}
static let guidCode = "PPT"
let guidIdentifier = nextGuidIdentifier()
package let name: String
private let frameworksBuildPhase: TestFrameworksBuildPhase
private let customTasks: [TestCustomTask]
private let dependencies: [String]
private let buildConfigurations: [TestBuildConfiguration]
private let dynamicTargetVariantName: String?
private let approvedByUser: Bool
package init(_ name: String, frameworksBuildPhase: TestFrameworksBuildPhase, dynamicTargetVariantName: String? = nil, approvedByUser: Bool = true, buildConfigurations: [TestBuildConfiguration]? = nil, customTasks: [TestCustomTask] = [], dependencies: [String] = []) {
self.name = name
self.frameworksBuildPhase = frameworksBuildPhase
self.dynamicTargetVariantName = dynamicTargetVariantName
self.approvedByUser = approvedByUser
self.buildConfigurations = buildConfigurations ?? [TestBuildConfiguration("Debug")]
self.customTasks = customTasks
self.dependencies = dependencies
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.Target {
let deps = dependencies.map { SWBProtocol.TargetDependency(guid: resolver.findTarget($0)?.guid ?? $0, name: $0) }
return try SWBProtocol.PackageProductTarget(guid: guid, name: name, buildConfigurations: buildConfigurations.map{ try $0.toProtocol(resolver) }, customTasks: customTasks.map { $0.toProtocol(resolver) }, dependencies: deps, frameworksBuildPhase: frameworksBuildPhase.toProtocol(resolver) as! SWBProtocol.FrameworksBuildPhase, dynamicTargetVariantGuid: dynamicTargetVariantName?.nilIfEmpty.map(resolver.findTarget)??.guid, approvedByUser: approvedByUser)
}
}
package final class TestBuildConfiguration: TestInternalItem, Sendable {
static let guidCode = "BC"
let guidIdentifier = nextGuidIdentifier()
fileprivate let name: String
private let baseConfig: String?
fileprivate let buildSettings: [String: String]
private let impartedBuildProperties: TestImpartedBuildProperties
package init(_ name: String, baseConfig: String? = nil, buildSettings: [String: String] = [:], impartedBuildProperties: TestImpartedBuildProperties = TestImpartedBuildProperties()) {
self.name = name
self.baseConfig = baseConfig
self.buildSettings = buildSettings
self.impartedBuildProperties = impartedBuildProperties
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.BuildConfiguration {
let baseConfigGUID = try self.baseConfig.map{ try resolver.findFile($0) }
return SWBProtocol.BuildConfiguration(name: name, buildSettings: buildSettings.map{ .init(key: $0.0, value: .string($0.1)) }, baseConfigurationFileReferenceGUID: baseConfigGUID, impartedBuildProperties: impartedBuildProperties.toProtocol(resolver))
}
}
package final class TestImpartedBuildProperties: TestInternalItem, Sendable {
static let guidCode = "BP"
let guidIdentifier = nextGuidIdentifier()
private let buildSettings: [String: String]
package init(buildSettings: [String: String] = [:]) {
self.buildSettings = buildSettings
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.ImpartedBuildProperties {
return SWBProtocol.ImpartedBuildProperties(buildSettings: buildSettings.map{ .init(key: $0.0, value: .string($0.1)) })
}
}
package class TestProject: TestInternalObjectItem, @unchecked Sendable {
static let guidCode = "P"
let guidIdentifier = nextGuidIdentifier()
package let name: String
fileprivate var isPackage: Bool { return false }
package let sourceRoot: Path?
private let defaultConfigurationName: String
private let developmentRegion: String
private let buildConfigurations: [TestBuildConfiguration]
package let targets: [any TestTarget]
fileprivate var _targets: [any TestInternalTarget] {
return targets.map { $0 as! (any TestInternalTarget) }
}
fileprivate let groupTree: TestGroup
package var signature: String { return "PROJECT@v11_\(guid)" }
private let classPrefix: String
private let appPreferencesBuildSettings: [String: String]
private let overriddenGuid: String?
// Redeclaring this as public, so clients can use it.
package var guid: String {
return overriddenGuid ?? "\(type(of: self).guidCode)\(guidIdentifier)"
}
package init(_ name: String, guid: String? = nil, sourceRoot: Path? = nil, defaultConfigurationName: String? = nil, groupTree: TestGroup, buildConfigurations: [TestBuildConfiguration]? = nil, targets: [any TestTarget] = [], developmentRegion: String? = nil, classPrefix: String = "", appPreferencesBuildSettings: [String: String] = [:]) {
self.name = name
self.overriddenGuid = guid
self.sourceRoot = sourceRoot
self.defaultConfigurationName = defaultConfigurationName ?? buildConfigurations?.first?.name ?? "Release"
self.developmentRegion = developmentRegion ?? "English"
self.buildConfigurations = buildConfigurations ?? [TestBuildConfiguration("Debug")]
self.targets = targets
self.groupTree = groupTree
self.classPrefix = classPrefix
self.appPreferencesBuildSettings = appPreferencesBuildSettings
}
fileprivate func getPath(_ resolver: any Resolver) -> Path {
let srcroot = sourceRoot ?? resolver.sourceRoot.join(name)
return srcroot.join("\(name).xcodeproj")
}
fileprivate func toObject(_ resolver: any Resolver) throws -> PropertyListItem {
let serializer = MsgPackSerializer()
try serializer.serialize(toProtocol(resolver))
return .plDict([
"signature": .plString(signature),
"type": .plString("project"),
"contents": .plDict(["data": .plArray(serializer.byteString.bytes.map { .plInt(Int($0)) })])
])
}
fileprivate func toProtocol(_ resolver: any Resolver) throws -> SWBProtocol.Project {
let path = getPath(resolver)
return try SWBProtocol.Project(guid: guid, isPackage: isPackage, xcodeprojPath: path, sourceRoot: sourceRoot ?? path.dirname, targetSignatures: _targets.map{ $0.signature }, groupTree: groupTree.toProtocol(resolver, isRoot: true), buildConfigurations: buildConfigurations.map{ try $0.toProtocol(resolver) }, defaultConfigurationName: defaultConfigurationName, developmentRegion: developmentRegion, classPrefix: classPrefix, appPreferencesBuildSettings: appPreferencesBuildSettings.map{ .init(key: $0.0, value: .string($0.1)) })
}
}
package final class TestPackageProject: TestProject, @unchecked Sendable {
override var isPackage: Bool {
return true
}
}
package final class TestWorkspace: Resolver, TestInternalItem, Sendable {
static let guidCode = "W"
let guidIdentifier: String = nextGuidIdentifier()
package let name: String
package let sourceRoot: Path
package let projects: [TestProject]
package var signature: String { return "WORKSPACE@v11_\(guid)" }
private let overriddenGuid: String?
// Redeclaring this as public, so clients can use it.
package var guid: String {
return overriddenGuid ?? "\(type(of: self).guidCode)\(guidIdentifier)"
}
package init(_ name: String, guid: String? = nil, sourceRoot: Path? = nil, projects: [TestProject], sourceLocation: SourceLocation = #_sourceLocation) {
self.name = name
self.overriddenGuid = guid
self.sourceRoot = sourceRoot ?? Path.root.join("tmp").join(name)
self.projects = projects
}
/// Load the test workspace into a concrete object, via a PIF.
package func load(_ core: Core) throws -> SWBCore.Workspace {
// Convert the workspace to a property list.
let propertyList = try PropertyListItem(toObjects())
// Load as a PIF.
let loader = PIFLoader(data: propertyList, namespace: core.specRegistry.internalMacroNamespace)
return try loader.load(workspaceSignature: signature)
}
/// Load the test workspace into a helper which can provide various derived objects.
package func loadHelper(_ core: Core) throws-> WorkspaceTestHelper {
return WorkspaceTestHelper(try load(core), core: core)
}
package func toObjects() throws -> [PropertyListItem] {
return try [toObject(self)] + projects.map{ try $0.toObject(self) } + projects.flatMap{ try $0._targets.map{ try $0.toObject(self) } }
}
fileprivate func toObject(_ resolver: any Resolver) -> PropertyListItem {
let serializer = MsgPackSerializer()
serializer.serialize(toProtocol(resolver))
return .plDict([
"signature": .plString(signature),
"type": .plString("workspace"),
"contents": .plDict(["data": .plArray(serializer.byteString.bytes.map { .plInt(Int($0)) })])
])
}
fileprivate func toProtocol(_ resolver: any Resolver) -> SWBProtocol.Workspace {
return SWBProtocol.Workspace(guid: guid, name: name, path: sourceRoot.join("\(name).xcworkspace"), projectSignatures: projects.map{ $0.signature })
}
var workspaceName: String {
return name
}
package func findSourceFiles() -> [Path] {
var result: [Path] = []
func visit(_ path: Path, _ item: any TestInternalStructureItem) {
switch item {
case let file as TestFile:
result.append(path.join(file.name))
case let group as TestGroup:
for item in group.children {
let subpath: Path
if let groupPath = group.path {
subpath = path.join(groupPath)
} else {
subpath = path
}
visit(subpath, item)
}
case let group as TestVariantGroup:
// Variant groups don't have a path, so we don't add to the subpath here to visit their children.
for item in group.children {
visit(path, item)
}
case let group as TestVersionGroup:
// Version groups get added to the results, and their children get added to the results.
result.append(path.join(group.name))
for item in group.children {
let subpath: Path
if let groupPath = group.path {
subpath = path.join(groupPath)
} else {
subpath = path
}
visit(subpath, item)
}
default:
break
}
}
for project in projects {
visit(project.getPath(self).dirname, project.groupTree)
}
return result
}
fileprivate func findAuto(_ name: String) throws -> TestBuildableItem {
for project in projects {
// Look in the product references.
for target in project._targets {
guard let standardTarget = target as? TestStandardTarget else { continue }
// FIXME: <rdar://119010301> This should not resolve to a product reference if the target is in a different project (unless a project reference is involved, which I don't think the test model presently supports). This can result in subtle issues not being caught by the test when logic which relies on using a product reference (or not) is a factor. For example some of the mergeable libraries logic.
if standardTarget.productReferenceName == name {
return .targetProduct(guid: standardTarget.guid)
}
}
// Look in the group tree.
if let result = visit(name, project.groupTree) {
return .reference(guid: result)
}
}
throw StubError.error("unable to find file (or target) in workspace named: '\(name)'")
}
fileprivate func findFile(_ name: String) throws -> String {
for project in projects {
// Look in the group tree.
if let result = visit(name, project.groupTree) {
return result
}
}
throw StubError.error("unable to find file in workspace named: '\(name)'")
}
private func visit(_ name: String, _ item: any TestInternalStructureItem) -> String? {
switch item {
case let file as TestFile:
return file.guid == name || Path(file.name).ends(with: name) ? file.guid : nil
case let group as TestGroup:
for item in group.children {
if let result = visit(name, item) {
return result
}
}
return nil
case let variantGroup as TestVariantGroup:
return variantGroup.name == name ? variantGroup.guid : nil
case let versionGroup as TestVersionGroup:
return versionGroup.name == name ? versionGroup.guid : nil
default:
fatalError("unrecognized group item: \(item)")
}
}
package func findTarget(name: String, project: String?) throws -> any TestTarget {
let targets = projects.filter { $0.name == project || project == nil }.map { $0.targets }.reduce([], +).filter { $0.name == name }
if let onlyTarget = targets.only {
return onlyTarget
}
if !targets.isEmpty {
if let project = project {
throw StubError.error("Multiple targets named '\(name)' in project '\(project)'")
}
throw StubError.error("Multiple targets named '\(name)'; specify project name to disambiguate")
}
if let project {
throw StubError.error("No target named '\(name)' in project '\(project)'")
}
throw StubError.error("No target named '\(name)'")
}
fileprivate func findTarget(_ name: String) -> (any TestInternalTarget)? {
for project in projects {
for target in project._targets {
if target.name == name {
return target
}
}
}
return nil
}
fileprivate func findProject(for target: any TestInternalTarget) throws -> TestProject {
for project in projects {
for aTarget in project._targets {
if aTarget === target {
return project
}
}
}
throw StubError.error("could not find project for target \(target)")
}
}
/// A helper object for fetching test data from a workspace.
package final class WorkspaceTestHelper: Sendable {
/// The core in use.
package let core: Core
/// The wrapped workspace.
package let workspace: SWBCore.Workspace
/// A temporary workspace context.
package let workspaceContext: WorkspaceContext
init(_ workspace: SWBCore.Workspace, core: Core) {
self.core = core
self.workspace = workspace
self.workspaceContext = WorkspaceContext(core: core, workspace: workspace, processExecutionCache: .sharedForTesting)
self.workspaceContext.updateUserInfo(UserInfo(user: "exampleUser", group: "exampleGroup", uid: 1234, gid:12345, home: Path("/Users/exampleUser"), environment: [:]))
self.workspaceContext.updateSystemInfo(SystemInfo(operatingSystemVersion: Version(99, 98, 97), productBuildVersion: "99A98", nativeArchitecture: "x86_64"))
}
/// The project in the workspace, if there is only one.
package var project: SWBCore.Project {
precondition(workspace.projects.count == 1)
return workspace.projects[0]
}
/// Fetch mock settings for the workspace.
///
/// These settings are for the build action and an empty environment.
///
/// - Parameters:
/// - project: The project to get settings for.
/// - target: The target to get settings for.
package func settings(buildRequestContext: BuildRequestContext, project: SWBCore.Project, target: SWBCore.Target? = nil, configuration: String? = "Debug") -> Settings {
let parameters = BuildParameters(action: .build, configuration: configuration)
return Settings(workspaceContext: workspaceContext, buildRequestContext: buildRequestContext, parameters: parameters, project: project, target: target, includeExports: false)
}
/// Create a global scope using the default mock settings.
package func globalScope(buildRequestContext: BuildRequestContext, project: SWBCore.Project, target: SWBCore.Target? = nil, configuration: String? = "Debug") -> MacroEvaluationScope {
return settings(buildRequestContext: buildRequestContext, project: project, target: target, configuration: configuration).globalScope
}
}
extension UserPreferences {
package static let defaultForTesting = UserPreferences(
enableDebugActivityLogs: false,
enableBuildDebugging: false,
enableBuildSystemCaching: true,
activityTextShorteningLevel: .default,
usePerConfigurationBuildLocations: nil,
allowsExternalToolExecution: false)
package func with(
enableDebugActivityLogs: Bool? = nil,
enableBuildDebugging: Bool? = nil,
enableBuildSystemCaching: Bool? = nil,
activityTextShorteningLevel: ActivityTextShorteningLevel? = nil,
usePerConfigurationBuildLocations: Bool?? = .none,
allowsExternalToolExecution: Bool? = nil
) -> UserPreferences {
let usePerConfigurationBuildLocationsValue: Bool?
switch usePerConfigurationBuildLocations {
case let .some(.some(value)):
usePerConfigurationBuildLocationsValue = value
case .some(.none):
usePerConfigurationBuildLocationsValue = nil
case .none:
usePerConfigurationBuildLocationsValue = self.usePerConfigurationBuildLocations
}
return UserPreferences(
enableDebugActivityLogs: enableDebugActivityLogs ?? self.enableDebugActivityLogs,
enableBuildDebugging: enableBuildDebugging ?? self.enableBuildDebugging,
enableBuildSystemCaching: enableBuildSystemCaching ?? self.enableBuildSystemCaching,
activityTextShorteningLevel: activityTextShorteningLevel ?? self.activityTextShorteningLevel,
usePerConfigurationBuildLocations: usePerConfigurationBuildLocationsValue,
allowsExternalToolExecution: allowsExternalToolExecution ?? self.allowsExternalToolExecution
)
}
}
|