Modern Apps git

xtool.git

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

xtool.git / Sources / XToolSupport / DevCommand.swift

DevCommand.swift350 lines · 10.6 KiBRaw
1import XCLIUtils
2import Foundation
3import ArgumentParser
4import PackLib
5import XKit
6import Dependencies
7import XUtils
8
9struct PackOperation {
10 struct BuildOptions: ParsableArguments {
11 @Option(
12 name: .shortAndLong,
13 help: "Build with configuration"
14 ) var configuration: BuildConfiguration = .debug
15
16 init() {}
17
18 init(configuration: BuildConfiguration) {
19 self.configuration = configuration
20 }
21 }
22
23 static let defaultTriple = "arm64-apple-ios"
24
25 /// Default build triple carrying the installed SDK version (e.g.
26 /// `arm64-apple-ios27.1`), so the Mach-O `LC_BUILD_VERSION` records a
27 /// current SDK (App Store error 90725). The deployment target is pinned
28 /// separately at link time (see `Plan.Product.linkerSettings`).
29 static var sdkVersionedDefaultTriple: String {
30 if let sdk = Packer.darwinSDKInfo() {
31 return "arm64-apple-ios\(sdk.version)"
32 }
33 return defaultTriple
34 }
35
36 var triple: String?
37 var buildOptions = BuildOptions(configuration: .debug)
38 var xcode = false
39
40 @discardableResult
41 func run() async throws -> URL {
42 // TODO: support running inside a child directory
43
44 let contents = try FileManager.default.contentsOfDirectory(atPath: ".")
45 guard contents.contains("Package.swift")
46 || contents.contains(where: { $0.hasPrefix("Package@") && $0.hasSuffix(".swift") })
47 else {
48 throw Console.Error("Could not find Package.swift in this directory.")
49 }
50
51 try await EnsureSDKOperation(quiet: true).run()
52
53 d.out.print("Planning...")
54
55 let schema: PackSchema
56 let configPath = URL(fileURLWithPath: "xtool.yml")
57 if FileManager.default.fileExists(atPath: configPath.path) {
58 schema = try await PackSchema(url: configPath)
59 } else {
60 schema = .default
61 d.out.print("""
62 warning: Could not locate configuration file '\(configPath.path)'. Using default \
63 configuration with 'com.example' organization ID.
64 """)
65 }
66
67 await LSPConfig.tryEnsure(using: schema)
68
69 let buildSettings = try await BuildSettings(
70 configuration: buildOptions.configuration,
71 triple: triple ?? Self.sdkVersionedDefaultTriple,
72 options: []
73 )
74
75 let planner = Planner(
76 buildSettings: buildSettings,
77 schema: schema
78 )
79 let plan = try await planner.createPlan()
80
81 if xcode {
82 return try await XcodePacker(plan: plan).createProject()
83 }
84
85 let packer = Packer(
86 buildSettings: buildSettings,
87 plan: plan
88 )
89 let bundle = try await packer.pack()
90
91 let productsWithEntitlements = plan
92 .allProducts
93 .compactMap { p in p.entitlementsPath.map { (p, $0) } }
94 if !productsWithEntitlements.isEmpty {
95 let mapping = try await withThrowingTaskGroup(of: (URL, Data).self) { group in
96 for (product, path) in productsWithEntitlements {
97 group.addTask {
98 let entitlements = try await Data(reading: URL(fileURLWithPath: path))
99 return (product.directory(inApp: bundle), entitlements)
100 }
101 }
102 return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
103 }
104 d.out.print("Applying entitlements...")
105 try await d.signer.sign(
106 app: bundle,
107 identity: .adhoc,
108 entitlementMapping: mapping,
109 deep: true,
110 progress: { _ in }
111 )
112 }
113
114 return bundle
115 }
116}
117
118struct DevXcodeCommand: AsyncParsableCommand {
119 static let configuration = CommandConfiguration(
120 commandName: "generate-xcode-project",
121 abstract: "Generate Xcode project"
122 )
123
124 func run() async throws {
125 let result = try await PackOperation(xcode: true).run()
126 d.out.print("Wrote to \(result.path)")
127 }
128}
129
130struct DevBuildCommand: AsyncParsableCommand {
131 static let configuration = CommandConfiguration(
132 commandName: "build",
133 abstract: "Build app with SwiftPM",
134 discussion: """
135 This command builds the SwiftPM-based iOS app in the current directory
136 """
137 )
138
139 @OptionGroup var packOptions: PackOperation.BuildOptions
140
141 @Flag(
142 name: .shortAndLong,
143 help: "Codesign the built app",
144 ) var sign = false
145
146 @Flag(
147 name: .shortAndLong,
148 help: "Output a .ipa file instead of a .app"
149 ) var ipa = false
150
151 @Option(
152 help: ArgumentHelp(
153 "Custom target triple to build for",
154 discussion: "Defaults to '\(PackOperation.defaultTriple)'"
155 )
156 ) var triple: String?
157
158 @Option(
159 help: ArgumentHelp(
160 "Distribution channel for the built app",
161 discussion: """
162 'app-store' signs the app with an Apple Distribution identity \
163 (XTOOL_DIST_P12_PATH / XTOOL_DIST_P12_PASSWORD) and an \
164 IOS_APP_STORE provisioning profile fetched via the App Store \
165 Connect API. Combine with --ipa for an uploadable build.
166 """
167 )
168 ) var distribution: Distribution?
169
170 func run() async throws {
171 let signingAuthToken: AuthToken?
172 if sign {
173 guard let token = try AuthToken.savedIfPresent() else {
174 throw Console.Error("`build --sign` requires logging in with `xtool auth`")
175 }
176 signingAuthToken = token
177 } else {
178 signingAuthToken = nil
179 }
180
181 let url = try await PackOperation(
182 triple: triple,
183 buildOptions: packOptions
184 ).run()
185
186 if distribution == .appStore {
187 guard signingAuthToken == nil else {
188 throw Console.Error("--distribution app-store cannot be combined with --sign")
189 }
190 try await DistributionSigning.signAppStore(url)
191 }
192
193 if let signingAuthToken {
194 let installDelegate = XToolInstallerDelegate()
195 let installer = IntegratedInstaller(
196 auth: signingAuthToken.authData(),
197 delegate: installDelegate
198 )
199 do {
200 defer { d.out.print() }
201 try await installer.signInPlace(app: url)
202 } catch let error as CancellationError {
203 throw error
204 } catch {
205 d.out.print("Error: \(error)")
206 throw ExitCode.failure
207 }
208 }
209
210 let finalURL: URL
211 if ipa {
212 @Dependency(\.zipCompressor) var compressor
213 finalURL = url.deletingPathExtension().appendingPathExtension("ipa")
214 let tmpDir = try TemporaryDirectory(name: "Payload")
215 let payloadDir = tmpDir.url
216 try FileManager.default.moveItem(at: url, to: payloadDir.appendingPathComponent(url.lastPathComponent))
217 let ipaURL = try await compressor.compress(directory: payloadDir) { progress in
218 if let progress {
219 let percent = Int(progress * 100)
220 d.out.print("\rPackaging... \(percent)%", terminator: "")
221 } else {
222 d.out.print("\rPackaging...", terminator: "")
223 }
224 }
225 d.out.print()
226 try? FileManager.default.removeItem(at: finalURL)
227 try FileManager.default.moveItem(at: ipaURL, to: finalURL)
228 } else {
229 finalURL = url
230 }
231
232 d.out.print("Wrote to \(finalURL.path)")
233 }
234}
235
236struct DevRunCommand: AsyncParsableCommand {
237 static let configuration = CommandConfiguration(
238 commandName: "run",
239 abstract: "Build and run app with SwiftPM",
240 discussion: """
241 This command deploys the SwiftPM-based iOS app in the current directory
242 """
243 )
244
245 @OptionGroup var packOptions: PackOperation.BuildOptions
246
247 #if os(macOS)
248 @Flag(
249 name: .shortAndLong,
250 help: "Target the iOS Simulator"
251 ) var simulator = false
252
253 var triple: String? {
254 if simulator {
255 #if arch(arm64)
256 return "arm64-apple-ios-simulator"
257 #elseif arch(x86_64)
258 return "x86_64-apple-ios-simulator"
259 #else
260 #error("Unsupported architecture")
261 #endif
262 }
263 return nil
264 }
265 #else
266 var triple: String? { nil }
267 #endif
268
269 @OptionGroup var connectionOptions: ConnectionOptions
270
271 func run() async throws {
272 let output = try await PackOperation(triple: triple, buildOptions: packOptions).run()
273
274 #if os(macOS)
275 if simulator {
276 try await SimInstallOperation(path: output).run()
277 return
278 }
279 #endif
280
281 let token = try AuthToken.saved()
282
283 let client = try await connectionOptions.client()
284 d.out.print("Installing to device: \(client.deviceName) (udid: \(client.udid))")
285
286 let installDelegate = XToolInstallerDelegate()
287 let installer = IntegratedInstaller(
288 auth: token.authData(),
289 delegate: installDelegate
290 )
291
292 defer { d.out.print() }
293
294 do {
295 try await installer.install(
296 app: output,
297 udid: client.udid,
298 lookupMode: .only(client.connectionType),
299 configureDevice: false,
300 )
301 } catch let error as CancellationError {
302 throw error
303 } catch {
304 d.out.print("\nError: \(error)")
305 throw ExitCode.failure
306 }
307 }
308}
309
310struct DevCommand: AsyncParsableCommand {
311 static let configuration = CommandConfiguration(
312 commandName: "dev",
313 abstract: "Build and run an xtool SwiftPM project",
314 subcommands: [
315 DevXcodeCommand.self,
316 DevBuildCommand.self,
317 DevRunCommand.self,
318 DevBSPCommand.self,
319 ],
320 defaultSubcommand: DevRunCommand.self
321 )
322}
323
324extension BuildConfiguration: ExpressibleByArgument {}
325
326enum Distribution: String, CaseIterable, ExpressibleByArgument, Sendable {
327 case development
328 case appStore = "app-store"
329}
330
331#if os(macOS)
332import Subprocess
333
334struct SimInstallOperation {
335 var path: URL
336
337 // TODO: allow customizing this
338 var simulator = "booted"
339
340 func run() async throws {
341 try await Subprocess.run(
342 .path("/usr/bin/xcrun"),
343 arguments: ["simctl", "install", simulator, path.path],
344 output: .discarded
345 )
346 .checkSuccess()
347 d.out.print("Installed to simulator")
348 }
349}
350#endif