Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XToolSupport / SDKCommand.swift

SDKCommand.swift287 lines · 9.0 KiBRaw
1import XCLIUtils
2import Foundation
3import XKit
4import ArgumentParser
5import Dependencies
6import PackLib
7import XUtils
8import Subprocess
9
10struct SDKCommand: AsyncParsableCommand {
11 static let configuration = CommandConfiguration(
12 commandName: "sdk",
13 abstract: "Manage the Darwin Swift SDK",
14 subcommands: [
15 DevSDKInstallCommand.self,
16 DevSDKUpdateCommand.self,
17 DevSDKRemoveCommand.self,
18 DevSDKBuildCommand.self,
19 DevSDKStatusCommand.self,
20 ],
21 defaultSubcommand: DevSDKInstallCommand.self
22 )
23}
24
25struct DevSDKBuildCommand: AsyncParsableCommand {
26 static let configuration = CommandConfiguration(
27 commandName: "build",
28 abstract: "Build the Darwin SDK from Xcode.xip"
29 )
30
31 @Argument(
32 help: "Path to Xcode.xip or Xcode.app",
33 completion: .file(extensions: ["xip", "app"])
34 )
35 var path: String
36
37 @Argument(
38 help: "Output directory"
39 )
40 var outputDir: String
41
42 @Option(
43 help: ArgumentHelp(
44 "The architecture of the Linux host the SDK is being built for.",
45 discussion: "Defaults to 'auto', which attempts to match the current host architecture."
46 )
47 ) var arch: ArchSelection = .auto
48
49 func run() async throws {
50 let builderArch = try arch.sdkBuilderArch
51 let input = try SDKBuilder.Input(path: path)
52 let output = URL(fileURLWithPath: outputDir, isDirectory: true).appending(path: "darwin.xtoolsdk")
53 let builder = SDKBuilder(input: input, output: output, arch: builderArch, mode: .buildSlim)
54 try await builder.buildSDK()
55 d.out.print("Built SDK at \(output.path). You can install it with `xtool sdk install`.")
56 }
57}
58
59enum ArchSelection: String, ExpressibleByArgument {
60 case auto
61 case x86_64
62 case arm64
63
64 var sdkBuilderArch: SDKBuilder.Arch {
65 get throws {
66 switch self {
67 case .auto:
68 #if arch(arm64)
69 .aarch64
70 #elseif arch(x86_64)
71 .x86_64
72 #else
73 throw Console.Error("Could not auto-detect target architecture. Please specify one with '--arch'.")
74 #endif
75 case .arm64: .aarch64
76 case .x86_64: .x86_64
77 }
78 }
79 }
80}
81
82struct DevSDKInstallCommand: AsyncParsableCommand {
83 static let configuration = CommandConfiguration(
84 commandName: "install",
85 abstract: "Install the Darwin Swift SDK"
86 )
87
88 @Argument(
89 help: "Path to Xcode.xip, Xcode.app, or darwin.xtoolsdk",
90 completion: .file(extensions: ["xip", "app", "xtoolsdk"])
91 )
92 var path: String
93
94 @Flag(
95 help: "Install a slim SDK (uses less disk space). Slim SDKs cannot be updated in place."
96 )
97 var slim = false
98
99 func run() async throws {
100 try await InstallSDKOperation(path: path, slim: slim).run()
101 }
102}
103
104struct DevSDKUpdateCommand: AsyncParsableCommand {
105 static let configuration = CommandConfiguration(
106 commandName: "update",
107 abstract: "Update the installed Darwin Swift SDK"
108 )
109
110 func run() async throws {
111 try await UpdateSDKOperation().run()
112 }
113}
114
115struct DevSDKRemoveCommand: AsyncParsableCommand {
116 static let configuration = CommandConfiguration(
117 commandName: "remove",
118 abstract: "Remove the Darwin Swift SDK"
119 )
120
121 func run() async throws {
122 guard let sdk = try DarwinSDK.current() else {
123 throw Console.Error("Cannot remove SDK: no Darwin SDK installed")
124 }
125 try sdk.remove()
126 d.out.print("Uninstalled SDK")
127 }
128}
129
130struct DevSDKStatusCommand: AsyncParsableCommand {
131 static let configuration = CommandConfiguration(
132 commandName: "status",
133 abstract: "Get the status of the Darwin Swift SDK"
134 )
135
136 func run() async throws {
137 if let sdk = try DarwinSDK.current() {
138 d.out.print("Darwin SDK is installed")
139 d.out.print(" Path: \(sdk.bundle.path)")
140 d.out.print(" Flavor: \(sdk.flavor)")
141 d.out.print(" Version: \(sdk.version)")
142 } else {
143 d.out.print("Not installed")
144 }
145 }
146}
147
148extension DarwinSDK {
149 func isUpToDate() -> Bool {
150 version == SDKBuilder.currentSDKVersion
151 }
152}
153
154struct EnsureSDKOperation {
155 let quiet: Bool
156
157 func run() async throws {
158 #if os(macOS)
159 if !quiet {
160 d.out.print("Skipping Darwin SDK setup since we're on macOS.")
161 }
162 #else
163 let sdk = try DarwinSDK.current()
164 switch sdk.map({ ($0.isUpToDate(), $0.flavor) }) {
165 case (true, _)?: // swiftlint:disable:this optional_enum_case_matching
166 if !quiet {
167 d.out.print("Darwin SDK is up to date.")
168 }
169 case (false, .slim)?: // swiftlint:disable:this optional_enum_case_matching
170 throw Console.Error("""
171 Darwin SDK is out of date, and was installed in 'slim' mode.
172
173 Slim SDKs take less disk space, but can't be auto-updated.
174 Please install a new SDK with
175 xtool sdk install [--slim]
176 """)
177 case (false, .normal)?: // swiftlint:disable:this optional_enum_case_matching
178 d.out.print("Darwin SDK is out of date. Rebuilding...")
179 try await UpdateSDKOperation().run()
180 case (false, .legacy)?: // swiftlint:disable:this optional_enum_case_matching
181 d.out.print("""
182 Darwin SDK is incompatible: built with an older version of xtool.
183
184 Requesting re-install. This is a one-time rebuild; after this,
185 xtool will be able to resolve incompatibilities automatically.
186
187 """)
188 try await generateSDK()
189 case nil:
190 d.out.print("Now generating the Darwin SDK.\n")
191 try await generateSDK()
192 }
193
194 func generateSDK() async throws {
195 let path = try await Console.prompt("""
196 Please download Xcode from http://developer.apple.com/download/all/?q=Xcode
197 and enter the path to the downloaded Xcode.xip.
198
199 Path to Xcode.xip: \("" /* pacify swiftlint trailing_whitespace */)
200 """)
201
202 let expanded = (path as NSString).expandingTildeInPath
203
204 try await InstallSDKOperation(path: expanded).run()
205 }
206 #endif
207 }
208}
209
210struct InstallSDKOperation {
211 let path: String
212 let slim: Bool
213
214 init(path: String, slim: Bool = false) {
215 self.path = path
216 self.slim = slim
217 }
218
219 func run() async throws {
220 #if os(macOS)
221 d.out.print("Skipping SDK install; the iOS SDK ships with Xcode on macOS")
222 #else
223
224 let temporaryBundle = try DarwinSDK.prepareTemporaryBundle()
225
226 if path.hasSuffix(".xtoolsdk") {
227 d.out.print("Installing prebuilt SDK...")
228 try await FileManager.default.copyItem(at: URL(filePath: path), to: temporaryBundle.url, preserveOwner: false)
229 } else {
230 // validate input before removing existing SDK
231 let input = try SDKBuilder.Input(path: path)
232 let arch = try ArchSelection.auto.sdkBuilderArch
233
234 let mode: SDKBuilder.Mode = slim ? .buildSlim : .buildNormal
235 let builder = SDKBuilder(input: input, output: temporaryBundle.url, arch: arch, mode: mode)
236 try await builder.buildSDK()
237 }
238
239 if let sdk = try DarwinSDK.current() {
240 d.out.print("Removing existing SDK...")
241 try sdk.remove()
242 }
243
244 try await temporaryBundle.install()
245 #endif
246 }
247}
248
249struct UpdateSDKOperation {
250 func run() async throws {
251 #if os(macOS)
252 d.out.print("Skipping SDK install; the iOS SDK ships with Xcode on macOS")
253 #else
254 guard let existing = try DarwinSDK.current() else {
255 throw Console.Error("Could not locate existing SDK; cannot perform update.")
256 }
257 let xcode = existing.bundle.appendingPathComponent("Xcode.app")
258 guard xcode.dirExists else {
259 // This includes prebuilt .xtoolsdk installs and installs created with --slim.
260 throw Console.Error("""
261 The installed SDK was built in 'slim' mode and cannot be updated in place. \
262 Please install a new copy with `xtool sdk install`.
263 """)
264 }
265
266 let input = try SDKBuilder.Input(path: xcode.path)
267 let arch = try ArchSelection.auto.sdkBuilderArch
268
269 let temporaryBundle = try DarwinSDK.prepareTemporaryBundle()
270 let builder = SDKBuilder(input: input, output: temporaryBundle.url, arch: arch, mode: .update)
271 try await builder.buildSDK()
272
273 guard DarwinSDK(bundle: temporaryBundle.url) != nil else {
274 throw Console.Error("Invalid Darwin SDK at '\(temporaryBundle.url.path)'")
275 }
276
277 try FileManager.default.moveItem(
278 at: xcode,
279 to: temporaryBundle.url.appendingPathComponent("Xcode.app")
280 )
281 try existing.remove()
282 try await temporaryBundle.install()
283
284 d.out.print("Updated SDK")
285 #endif
286 }
287}