Unable to find Bundle in package target tests when package depends on another package containing resources accessed via Bundle.module

Thanks for that, it does work for me but with some changes to maintain existing behaviour whilst adding the local fallbacks. See below:

private class CurrentBundleFinder {}

extension Foundation.Bundle {

	static var myModule: Bundle = {

		let bundleName = "UILibrary_UILibrary"
		let localBundleName = "LocalPackages_UILibrary"

		let candidates = [
			/* Bundle should be present here when the package is linked into an App. */
			Bundle.main.resourceURL,

			/* Bundle should be present here when the package is linked into a framework. */
			Bundle(for: CurrentBundleFinder.self).resourceURL,

			/* For command-line tools. */
			Bundle.main.bundleURL,

			/* Bundle should be present here when running previews from a different package (this is the path to "…/Debug-iphonesimulator/"). */
			Bundle(for: CurrentBundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent(),
			Bundle(for: CurrentBundleFinder.self).resourceURL?.deletingLastPathComponent().deletingLastPathComponent(),
		]

		for candidate in candidates {
			let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
			if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
				return bundle
			}

			let localBundlePath = candidate?.appendingPathComponent(localBundleName + ".bundle")
			if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
				return bundle
			}
		}

		fatalError("unable to find bundle")

	}()

}

The problem is public packages are using Bundle.module (in my case SwiftGen) so it's going to be difficult to merge in a workaround like this into something I don't have much control over. I can obviously raise a PR, but I doubt it would be approved as the problem is with Bundle.module behaviour rather than the library itself.

I really appreciate you sharing this solution though – it's given me some food for thought! :slight_smile:

Edit: For the SwiftGen issue above I'm going to look at using a custom template which generates this workaround automatically, which should in theory avoid the need of having to raise a PR to modify SwiftGen itself.

1 Like