Modern Apps git

xtool.git

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

xtool.git / Sources / XToolSupport / DevCommand.swift

DevCommand.swift350 lines · 10.6 KiBRaw
1import Foundation
2import ArgumentParser
3import PackLib
4import XKit
5import Dependencies
6import XUtils
7
8struct PackOperation {
9 struct BuildOptions: ParsableArguments {
10 @Option(
11 name: .shortAndLong,
12 help: "Build with configuration"
13 ) var configuration: BuildConfiguration = .debug
14
15 init() {}
16
17 init(configuration: BuildConfiguration) {
18 self.configuration = configuration
19 }
20 }
21
22 static let defaultTriple = "arm64-apple-ios"
23
24 /// Default build triple carrying the installed SDK version (e.g.
25 /// `arm64-apple-ios27.1`), so the Mach-O `LC_BUILD_VERSION` records a
26 /// current SDK (App Store error 90725). The deployment target is pinned
27 /// separately at link time (see `Plan.Product.linkerSettings`).
28 static var sdkVersionedDefaultTriple: String {
29 if let sdk = Packer.darwinSDKInfo() {
30 return "arm64-apple-ios\(sdk.version)"
31 }
32 return defaultTriple
33 }
34
35 var triple: String?
36 var buildOptions = BuildOptions(configuration: .debug)
37 var xcode = false
38
39 @discardableResult
40 func run() async throws -> URL {
41 // TODO: support running inside a child directory
42
43 let contents = try FileManager.default.contentsOfDirectory(atPath: ".")
44 guard contents.contains("Package.swift")
45 || contents.contains(where: { $0.hasPrefix("Package@") && $0.hasSuffix(".swift") })
46 else {
47 throw Console.Error("Could not find Package.swift in this directory.")
48 }
49
50 try await EnsureSDKOperation(quiet: true).run()
51
52 print("Planning...")
53
54 let schema: PackSchema
55 let configPath = URL(fileURLWithPath: "xtool.yml")
56 if FileManager.default.fileExists(atPath: configPath.path) {
57 schema = try await PackSchema(url: configPath)
58 } else {
59 schema = .default
60 print("""
61 warning: Could not locate configuration file '\(configPath.path)'. Using default \
62 configuration with 'com.example' organization ID.
63 """)
64 }
65
66 await LSPConfig.tryEnsure(using: schema)
67
68 let buildSettings = try await BuildSettings(
69 configuration: buildOptions.configuration,
70 triple: triple ?? Self.sdkVersionedDefaultTriple,
71 options: []
72 )
73
74 let planner = Planner(
75 buildSettings: buildSettings,
76 schema: schema
77 )
78 let plan = try await planner.createPlan()
79
80 if xcode {
81 return try await XcodePacker(plan: plan).createProject()
82 }
83
84 let packer = Packer(
85 buildSettings: buildSettings,
86 plan: plan
87 )
88 let bundle = try await packer.pack()
89
90 let productsWithEntitlements = plan
91 .allProducts
92 .compactMap { p in p.entitlementsPath.map { (p, $0) } }
93 if !productsWithEntitlements.isEmpty {
94 let mapping = try await withThrowingTaskGroup(of: (URL, Entitlements).self) { group in
95 for (product, path) in productsWithEntitlements {
96 group.addTask {
97 let data = try await Data(reading: URL(fileURLWithPath: path))
98 let decoder = PropertyListDecoder()
99 let entitlements = try decoder.decode(Entitlements.self, from: data)
100 return (product.directory(inApp: bundle), entitlements)
101 }
102 }
103 return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
104 }
105 print("Applying entitlements...")
106 try await Signer.first().sign(
107 app: bundle,
108 identity: .adhoc,
109 entitlementMapping: mapping,
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 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 { print() }
201 try await installer.signInPlace(app: url)
202 } catch let error as CancellationError {
203 throw error
204 } catch {
205 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 print("\rPackaging... \(percent)%", terminator: "")
221 } else {
222 print("\rPackaging...", terminator: "")
223 }
224 }
225 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 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 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 { 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 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 print("Installed to simulator")
348 }
349}
350#endif