From 637fb075158f780134d516f9fd8763cd717416f4 Mon Sep 17 00:00:00 2001 From: Florian Friedrich Date: Mon, 3 May 2021 23:18:56 +0200 Subject: [PATCH] Fix resource bundle lookup (#3463) * Fix resource bundle lookup * Add test check that `Bundle.main` is executed in the compiled binary * Ensure trailing slash for bundle path * Rely on Foundation.URL for path separators --- Sources/Build/BuildPlan.swift | 17 ++++++----------- Tests/BuildTests/BuildPlanTests.swift | 3 +++ 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/Sources/Build/BuildPlan.swift b/Sources/Build/BuildPlan.swift index e2a8ee9bffb..5ca25d4f354 100644 --- a/Sources/Build/BuildPlan.swift +++ b/Sources/Build/BuildPlan.swift @@ -17,11 +17,10 @@ import PackageLoading import Foundation import SPMBuildCore -extension AbsolutePath { - fileprivate var asSwiftStringLiteralConstant: String { - return self.pathString.unicodeScalars - .reduce("", { $0 + $1.escaped(asASCII: false) }) - } +extension String { + fileprivate var asSwiftStringLiteralConstant: String { + return unicodeScalars.reduce("", { $0 + $1.escaped(asASCII: false) }) + } } extension BuildParameters { @@ -662,17 +661,13 @@ public final class SwiftTargetBuildDescription { guard let bundlePath = self.bundlePath else { return } let stream = BufferedOutputByteStream() - - let mainPath: AbsolutePath = - AbsolutePath(Bundle.main.bundlePath).appending(component: bundlePath.basename) - stream <<< """ import class Foundation.Bundle extension Foundation.Bundle { static var module: Bundle = { - let mainPath = "\(mainPath.asSwiftStringLiteralConstant)" - let buildPath = "\(bundlePath.asSwiftStringLiteralConstant)" + let mainPath = Bundle.main.bundleURL.appendingPathComponent("\(bundlePath.basename.asSwiftStringLiteralConstant)").path + let buildPath = "\(bundlePath.pathString.asSwiftStringLiteralConstant)" let preferredBundle = Bundle(path: mainPath) diff --git a/Tests/BuildTests/BuildPlanTests.swift b/Tests/BuildTests/BuildPlanTests.swift index 3510c46d12d..b4f375f76fe 100644 --- a/Tests/BuildTests/BuildPlanTests.swift +++ b/Tests/BuildTests/BuildPlanTests.swift @@ -2464,6 +2464,9 @@ final class BuildPlanTests: XCTestCase { let resourceAccessor = fooTarget.sources.first{ $0.basename == "resource_bundle_accessor.swift" }! let contents = try fs.readFileContents(resourceAccessor).cString XCTAssertTrue(contents.contains("extension Foundation.Bundle"), contents) + // Assert that `Bundle.main` is executed in the compiled binary (and not during compilation) + // See https://bugs.swift.org/browse/SR-14555 and https://github.com/apple/swift-package-manager/pull/2972/files#r623861646 + XCTAssertTrue(contents.contains("let mainPath = Bundle.main."), contents) let barTarget = try result.target(for: "Bar").swiftTarget() XCTAssertEqual(barTarget.objects.map{ $0.pathString }, [