Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / PackLib / BuildSettings.swift

BuildSettings.swift198 lines · 6.7 KiBRaw
1import Foundation
2import Subprocess
3import XUtils
4import Superutils
5
6public struct BuildSettings: Sendable {
7 private static let customBinDir =
8 // this is the same option used by SwiftPM itself for dev builds
9 ProcessInfo.processInfo.environment["SWIFTPM_CUSTOM_BIN_DIR"].map { FilePath($0) }
10
11 public var packagePath: String
12 public let configuration: BuildConfiguration
13 public let triple: String
14 public let buildSystem: BuildSystem
15 public let customOptions: [String]
16
17 public var sdkOptions: [String]
18 public var sdkEnvironment: [Environment.Key: String?]
19
20 private var configOptions: [String] {
21 return [
22 "--configuration", configuration.rawValue,
23 "--build-system", buildSystem.pmName,
24 "--package-path", packagePath,
25 ]
26 }
27
28 private var resolvedBaseOptions: [String] {
29 configOptions + sdkOptions + customOptions
30 }
31
32 public init(
33 configuration: BuildConfiguration,
34 triple: String,
35 buildSystem: BuildSystem? = nil,
36 packagePath: String = ".",
37 options: [String] = []
38 ) async throws {
39 self.packagePath = packagePath
40 self.configuration = configuration
41 self.customOptions = options
42 self.triple = triple
43 self.buildSystem = if let buildSystem { buildSystem } else { try await .default() }
44
45 self.sdkEnvironment = [
46 // xcrun passes an SDKROOT that messes with our sdk configuration
47 "SDKROOT": nil,
48 ]
49
50 switch self.buildSystem {
51 case .swiftPM:
52 // on macOS we don't explicitly install a Swift SDK but
53 // SwiftPM vends "implicit" Darwin SDKs as of Swift 6.1,
54 // i.e. we can pass `--swift-sdk arm64-apple-ios` and it
55 // just works. See:
56 // https://github.com/swiftlang/swift-package-manager/pull/6828
57 self.sdkOptions = ["--swift-sdk", triple]
58 case .swiftBuild:
59 self.sdkOptions = ["--triple", triple]
60 #if !os(macOS)
61 let darwinSDK = try DarwinSDK.current()
62 .orThrow(StringError("No Darwin SDK configured. Please run `xtool setup`."))
63 self.sdkOptions += [
64 "--toolset", "\(darwinSDK.bundle.path)/toolset-swb.json",
65 ]
66 self.sdkEnvironment.merge([
67 "XCODE_EXTRA_PLATFORM_FOLDERS": "\(darwinSDK.bundle.path)/Developer/Platforms",
68 // SWB looks for dsymutil in the PATH. Other stuff (lld, libtool) is handled by toolset-swb.json.
69 "PATH": "\(darwinSDK.bundle.path)/toolset/bin:\(ProcessInfo.processInfo.environment["PATH"] ?? "")",
70 ]) { $1 }
71 #endif
72 }
73 }
74
75 #if os(macOS)
76 private static func xcrun(_ arguments: [String]) async throws -> String {
77 let result = try await Subprocess.run(
78 .path("/usr/bin/xcrun"),
79 arguments: .init(arguments),
80 output: .string(limit: .max)
81 ).checkSuccess()
82 return result.standardOutput.trimmingCharacters(in: .whitespacesAndNewlines)
83 }
84
85 private static let _swiftURL = Task {
86 try await FilePath(xcrun(["-f", "swift"]))
87 }
88
89 public static func swiftURL() async throws -> FilePath {
90 try await _swiftURL.value
91 }
92
93 private static let _swiftcURL = Task {
94 try await FilePath(xcrun(["-f", "swiftc"]))
95 }
96
97 public static func swiftcURL() async throws -> FilePath {
98 try await _swiftcURL.value
99 }
100 #else
101 public static func swiftURL() async throws -> FilePath {
102 try await FilePath(ToolRegistry.locate("swift")).orThrow(StringError("Got bad path for swift executable"))
103 }
104
105 public static func swiftcURL() async throws -> FilePath {
106 try await FilePath(ToolRegistry.locate("swiftc")).orThrow(StringError("Got bad path for swiftc executable"))
107 }
108 #endif
109
110 public func withPackagePath(_ path: String) -> Self {
111 var copy = self
112 copy.packagePath = path
113 return copy
114 }
115
116 public func swiftPMInvocation(
117 forTool tool: String,
118 arguments: [String],
119 ) async throws -> Subprocess.Configuration {
120 let executable: Executable
121 let baseArguments: [String]
122 if let customBinDir = Self.customBinDir {
123 executable = .path(customBinDir.appending("swift-\(tool)"))
124 baseArguments = []
125 } else {
126 #if os(macOS)
127 // xcrun/libxcrun (via the /usr/bin/swift trampoline) is very trigger-happy
128 // to add SDKROOT=.../MacOSX.sdk to our invocations. We avoid this by
129 // 1) invoking the real swift executable (located with `xcrun -f`) and
130 // 2) explicitly removing SDKROOT from the env, as it may be inherited
131 // through a parent process (e.g. `swift run xtool`).
132 executable = .path(try await Self.swiftURL())
133 #else
134 executable = .name("swift")
135 #endif
136 baseArguments = [tool]
137 }
138
139 return Configuration(
140 executable: executable,
141 arguments: .init(baseArguments + resolvedBaseOptions + arguments),
142 environment: .inherit.updating(sdkEnvironment),
143 platformOptions: .withGracefulShutDown,
144 )
145 }
146
147 // loosely based on
148 // https://github.com/swiftlang/sourcekit-lsp/blob/c55899a/Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift#L92
149 private var baseBuildServerArguments: [String] {
150 return [
151 "experimental-build-server",
152 "--disable-automatic-resolution",
153 "--scratch-path", ".build/index-build",
154 // this requires Swift 6.4 but we need 6.4 on Linux anyway, for the platform toolset fixes
155 "--experimental-skip-acquiring-lock",
156 ]
157 }
158
159 public var buildServerArguments: [String] {
160 ["package"] + baseBuildServerArguments + resolvedBaseOptions
161 }
162
163 public func buildServerInvocation() async throws -> Subprocess.Configuration {
164 try await swiftPMInvocation(forTool: "package", arguments: baseBuildServerArguments)
165 }
166}
167
168public enum BuildConfiguration: String, CaseIterable, Sendable {
169 case debug
170 case release
171
172 var swiftBuildValue: String {
173 switch self {
174 case .debug: "Debug"
175 case .release: "Release"
176 }
177 }
178}
179
180public enum BuildSystem: Sendable {
181 case swiftPM
182 case swiftBuild
183
184 public static func `default`() async throws -> Self {
185 if try await SwiftVersion.current.supportsSwiftBuild {
186 return .swiftBuild
187 } else {
188 return .swiftPM
189 }
190 }
191
192 var pmName: String {
193 switch self {
194 case .swiftPM: "native"
195 case .swiftBuild: "swiftbuild"
196 }
197 }
198}