-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathApp.swift
More file actions
655 lines (518 loc) · 26.6 KB
/
Copy pathApp.swift
File metadata and controls
655 lines (518 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import Foundation
@preconcurrency import ArgumentParser
import Version
import XcodesCLIKit
import XcodesKit
import LegibleError
import Path
@preconcurrency import Rainbow
func configureRainbow(enabled: Bool) {
Rainbow.enabled = Rainbow.enabled && enabled
}
func getDirectory(possibleDirectory: String?, default: Path = Path.root.join("Applications")) -> Path {
let directory = possibleDirectory.flatMap(Path.init) ??
ProcessInfo.processInfo.environment["XCODES_DIRECTORY"].flatMap(Path.init) ??
`default`
guard directory.isDirectory else {
Current.logging.log("Directory argument must be a directory, but was provided \(directory.string).".red)
exit(1)
}
return directory
}
struct GlobalDirectoryOption: ParsableArguments {
@Option(help: "The directory where your Xcodes are installed. Defaults to /Applications.",
completion: .directory)
var directory: String?
}
struct GlobalDataSourceOption: ParsableArguments {
@Option(
help: ArgumentParser.ArgumentHelp(
"The data source for available Xcode versions.",
discussion: """
The Apple data source ("apple") scrapes the Apple Developer website. It will always show the latest releases that are available, but is more fragile.
Xcode Releases ("xcodeReleases") is an unofficial list of Xcode releases. It's provided as well-formed data, contains extra information that is not readily available from Apple, and is less likely to break if Apple redesigns their developer website.
"""
)
)
var dataSource: DataSource = .xcodeReleases
}
struct GlobalColorOption: ParsableArguments {
@Flag(
inversion: .prefixedNo,
help: ArgumentHelp(
"Determines whether output should be colored.",
discussion: """
xcodes will also disable colored output if its not running in an interactive terminal, if the NO_COLOR environment variable is set, or if the TERM environment variable is set to "dumb".
"""
)
)
var color: Bool = true
}
extension ArchitectureFilter: @retroactive ExpressibleByArgument {
public init?(argument: String) {
self.init(argument)
}
}
@main
struct Xcodes: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Manage the Xcodes installed on your Mac",
shouldDisplay: true,
subcommands: [Download.self, Install.self, Installed.self, List.self, Runtimes.self, Select.self, Uninstall.self, Update.self, Version.self, Signout.self]
)
private struct Services {
let sessionService: AppleSessionService
let xcodeList: XcodeList
let runtimeInstaller: RuntimeInstaller
let xcodeInstaller: XcodeInstaller
let fastlaneSessionManager: FastlaneSessionManager
}
private static func makeServices() -> Services {
var xcodesConfiguration = Configuration()
try? xcodesConfiguration.load()
let sessionService = AppleSessionService(configuration: xcodesConfiguration)
let xcodeList = XcodeList()
let runtimeList = RuntimeList()
return Services(
sessionService: sessionService,
xcodeList: xcodeList,
runtimeInstaller: RuntimeInstaller(runtimeList: runtimeList, sessionService: sessionService),
xcodeInstaller: XcodeInstaller(xcodeList: xcodeList, sessionService: sessionService),
fastlaneSessionManager: FastlaneSessionManager()
)
}
private static func availableXcodeCompletions() -> [String] {
XcodeList().availableXcodes
.sorted { $0.version < $1.version }
.map { $0.version.appleDescription }
}
static func main() async {
migrateApplicationSupportFiles()
do {
var command = try parseAsRoot()
if var asyncCommand = command as? AsyncParsableCommand {
try await asyncCommand.run()
} else {
try command.run()
}
} catch {
exit(withError: error)
}
}
struct Download: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Download a specific version of Xcode",
discussion: """
By default, xcodes will use a URLSession to download the specified version. If aria2 (https://aria2.github.io, available in Homebrew) is installed, either somewhere in PATH or at the path specified by the --aria2 flag, then it will be used instead. aria2 will use up to 16 connections to download Xcode 3-5x faster. If you have aria2 installed and would prefer to not use it, you can use the --no-aria2 flag.
EXAMPLES:
xcodes download 10.2.1
xcodes download 11 Beta 7
xcodes download 11.2 GM seed
xcodes download 9.0 --directory ~/Archive
xcodes download --latest-prerelease
"""
)
@Argument(help: "The version to download",
completion: .custom { _ in Xcodes.availableXcodeCompletions() })
var version: [String] = []
@Flag(help: "Update and then download the latest release version available.")
var latest: Bool = false
@Flag(help: "Update and then download the latest prerelease version available, including GM seeds and GMs.")
var latestPrerelease = false
@Option(help: "The path to an aria2 executable. Searches $PATH by default.",
completion: .file())
var aria2: String?
@Flag(help: "Don't use aria2 to download Xcode, even if its available.")
var noAria2: Bool = false
@Option(help: "The directory to download Xcode to. Defaults to ~/Downloads.",
completion: .directory)
var directory: String?
@Flag(help: "Use fastlane spaceship session.")
var useFastlaneAuth: Bool = false
@Option(help: "The fastlane spaceship user",
completion: .shellCommand("ls \(FastlaneSessionManager.Constants.fastlaneSpaceshipDir)"))
var fastlaneUser: String = FastlaneSessionManager.Constants.fastlaneSessionEnvVarName
@OptionGroup
var globalDataSource: GlobalDataSourceOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let services = Xcodes.makeServices()
let versionString = version.joined(separator: " ")
let installation: XcodeInstaller.InstallationType
// Deliberately not using InstallationType.path here as it doesn't make sense to download an Xcode from a .xip that's already on disk
if latest {
installation = .latest
} else if latestPrerelease {
installation = .latestPrerelease
} else {
installation = .version(versionString)
}
let downloader = noAria2 ? Downloader.urlSession : Downloader(aria2Path: aria2)
let destination = getDirectory(possibleDirectory: directory, default: .environmentDownloads)
if useFastlaneAuth {
services.fastlaneSessionManager.setupFastlaneAuth(fastlaneUser: fastlaneUser)
}
do {
try await services.xcodeInstaller.download(installation, dataSource: globalDataSource.dataSource, downloader: downloader, destinationDirectory: destination)
} catch {
Install.processDownloadOrInstall(error: error)
}
}
}
struct Install: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Download and install a specific version of Xcode",
discussion: """
By default, xcodes will use a URLSession to download the specified version. If aria2 (https://aria2.github.io, available in Homebrew) is installed, either somewhere in PATH or at the path specified by the --aria2 flag, then it will be used instead. aria2 will use up to 16 connections to download Xcode 3-5x faster. If you have aria2 installed and would prefer to not use it, you can use the --no-aria2 flag.
EXAMPLES:
xcodes install 10.2.1
xcodes install 11 Beta 7
xcodes install 11.2 GM seed
xcodes install 9.0 --path ~/Archive/Xcode_9.xip
xcodes install --latest-prerelease
xcodes install --latest --directory "/Volumes/Bag Of Holding/"
"""
)
@Argument(help: "The version to install",
completion: .custom { _ in Xcodes.availableXcodeCompletions() })
var version: [String] = []
@Option(name: .customLong("path"),
help: "Local path to Xcode .xip",
completion: .file(extensions: ["xip"]))
var pathString: String?
@Flag(help: "Update and then install the latest release version available.")
var latest: Bool = false
@Flag(help: "Update and then install the latest prerelease version available, including GM seeds and GMs.")
var latestPrerelease = false
@Option(help: "The path to an aria2 executable. Searches $PATH by default.",
completion: .file())
var aria2: String?
@Flag(help: "Don't use aria2 to download Xcode, even if its available.")
var noAria2: Bool = false
@Flag(help: "Select the installed xcode version after installation.")
var select: Bool = false
@Flag(help: "Whether to update the list before installing")
var update: Bool = false
@ArgumentParser.Flag(name: [.customShort("p"), .customLong("print-path")], help: "Print the path of the selected Xcode")
var print: Bool = false
@Flag(help: "Use the experimental unxip functionality. May speed up unarchiving by up to 2-3x.")
var experimentalUnxip: Bool = false
@Flag(help: "Don't ask for superuser (root) permission. Some optional steps of the installation will be skipped.")
var noSuperuser: Bool = false
@Flag(help: "Completely delete Xcode .xip after installation, instead of keeping it on the user's Trash.")
var emptyTrash: Bool = false
@Option(help: "The directory to install Xcode into. Defaults to /Applications.",
completion: .directory)
var directory: String?
@Flag(help: "Expands (decompress) Xcode .xip on the same directory it's downloaded, instead of using a temporal directory.")
var expandXipInplace: Bool = false
@Flag(help: "Use fastlane spaceship session.")
var useFastlaneAuth: Bool = false
@Option(help: "The fastlane spaceship user.",
completion: .shellCommand("ls \(FastlaneSessionManager.Constants.fastlaneSpaceshipDir)"))
var fastlaneUser: String = FastlaneSessionManager.Constants.fastlaneSessionEnvVarName
@OptionGroup
var globalDataSource: GlobalDataSourceOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let services = Xcodes.makeServices()
let versionString = version.joined(separator: " ")
let installation: XcodeInstaller.InstallationType
if latest {
installation = .latest
} else if latestPrerelease {
installation = .latestPrerelease
} else if let pathString = pathString, let path = Path(pathString) {
installation = .path(versionString, path)
} else {
installation = .version(versionString)
}
let downloader = noAria2 ? Downloader.urlSession : Downloader(aria2Path: aria2)
let destination = getDirectory(possibleDirectory: directory)
if select, case .version(let version) = installation {
do {
try await selectXcodeAsync(shouldPrint: print, pathOrVersion: version, directory: destination, fallbackToInteractive: false)
} catch {
try await install(installation, using: downloader, to: destination, services: services)
}
} else {
try await install(installation, using: downloader, to: destination, services: services)
}
}
private func install(_ installation: XcodeInstaller.InstallationType,
using downloader: Downloader,
to destination: Path,
services: Xcodes.Services) async throws {
do {
if useFastlaneAuth { services.fastlaneSessionManager.setupFastlaneAuth(fastlaneUser: fastlaneUser) }
// update the list before installing only for version type because the other types already update internally
if update, case .version = installation {
Current.logging.log("Updating...")
_ = try await services.xcodeList.updateAvailableXcodes(dataSource: globalDataSource.dataSource)
}
let xcode = try await services.xcodeInstaller.install(installation, dataSource: globalDataSource.dataSource, downloader: downloader, destination: destination, experimentalUnxip: experimentalUnxip, shouldExpandXipInplace: expandXipInplace, emptyTrash: emptyTrash, noSuperuser: noSuperuser)
if select {
try await selectXcodeAsync(shouldPrint: print, pathOrVersion: xcode.path.string, directory: destination, fallbackToInteractive: false)
}
Install.exit()
} catch {
if select, case let XcodeInstaller.Error.versionAlreadyInstalled(installedXcode) = error {
Current.logging.log(error.legibleLocalizedDescription.green)
if select {
try await selectXcodeAsync(shouldPrint: print, pathOrVersion: installedXcode.path.string, directory: destination, fallbackToInteractive: false)
}
Install.exit()
} else {
Install.processDownloadOrInstall(error: error)
}
}
}
}
struct Installed: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "List the versions of Xcode that are installed"
)
@Argument(help: "The version installed to which to print the path for",
completion: .custom { _ in Current.files.installedXcodes(getDirectory(possibleDirectory: nil)).sorted { $0.version < $1.version }.map { $0.version.appleDescription } })
var version: [String] = []
@OptionGroup
var globalDirectory: GlobalDirectoryOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let directory = getDirectory(possibleDirectory: globalDirectory.directory)
let services = Xcodes.makeServices()
do {
try await services.xcodeInstaller.printXcodePath(ofVersion: version.joined(separator: " "), searchingIn: directory)
Installed.exit()
} catch XcodeInstaller.Error.invalidVersion {
try await services.xcodeInstaller.printInstalledXcodes(directory: directory)
Installed.exit()
} catch {
Installed.exit(withLegibleError: error)
}
}
}
struct List: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "List all versions of Xcode that are available to install"
)
@Option(help: "Only list Xcodes matching the specified architecture: arm64, x86_64, appleSilicon, or universal. Can be used multiple times.")
var architecture: [ArchitectureFilter] = []
@OptionGroup
var globalDirectory: GlobalDirectoryOption
@OptionGroup
var globalDataSource: GlobalDataSourceOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let directory = getDirectory(possibleDirectory: globalDirectory.directory)
let services = Xcodes.makeServices()
do {
if services.xcodeList.shouldUpdateBeforeListingVersions {
try await services.xcodeInstaller.updateAndPrint(dataSource: globalDataSource.dataSource, directory: directory, architectures: architecture)
}
else {
try await services.xcodeInstaller.printAvailableXcodes(services.xcodeList.availableXcodes, installed: Current.files.installedXcodes(directory), architectures: architecture)
}
List.exit()
} catch {
List.exit(withLegibleError: error)
}
}
}
struct Runtimes: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "List all simulator runtimes that are available to install",
subcommands: [Download.self, Install.self]
)
@Flag(help: "Include beta runtimes available to install")
var includeBetas: Bool = false
@Option(help: "Only list runtimes matching the specified architecture: arm64, x86_64, appleSilicon, or universal. Can be used multiple times.")
var architecture: [ArchitectureFilter] = []
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let services = Xcodes.makeServices()
try await services.runtimeInstaller.printAvailableRuntimes(includeBetas: includeBetas, architectures: architecture)
}
struct Install: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Download and install a specific simulator runtime"
)
@Argument(help: "The runtime to install")
var version: String
@Option(help: "The path to an aria2 executable. Searches $PATH by default.",
completion: .file())
var aria2: String?
@Flag(help: "Don't use aria2 to download the runtime, even if its available.")
var noAria2: Bool = false
@Option(help: "The directory to download the runtime archive to. Defaults to ~/Downloads.",
completion: .directory)
var directory: String?
@Option(help: "Install the runtime matching the specified architecture: arm64, x86_64, appleSilicon, or universal. Can be used multiple times.")
var architecture: [ArchitectureFilter] = []
@Flag(help: "Do not delete the runtime archive after the installation is finished.")
var keepArchive = false
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let downloader = noAria2 ? Downloader.urlSession : Downloader(aria2Path: aria2)
let destination = getDirectory(possibleDirectory: directory, default: .environmentDownloads)
let services = Xcodes.makeServices()
try await services.runtimeInstaller.downloadAndInstallRuntime(identifier: version, to: destination, with: downloader, shouldDelete: !keepArchive, architectures: architecture)
Current.logging.log("Finished")
}
}
struct Download: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Download a specific simulator runtime"
)
@Argument(help: "The runtime to download")
var version: String
@Option(help: "The path to an aria2 executable. Searches $PATH by default.",
completion: .file())
var aria2: String?
@Flag(help: "Don't use aria2 to download the runtime, even if its available.")
var noAria2: Bool = false
@Option(help: "The directory to download the runtime archive to. Defaults to ~/Downloads.",
completion: .directory)
var directory: String?
@Option(help: "Download the runtime matching the specified architecture: arm64, x86_64, appleSilicon, or universal. Can be used multiple times.")
var architecture: [ArchitectureFilter] = []
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let downloader = noAria2 ? Downloader.urlSession : Downloader(aria2Path: aria2)
let destination = getDirectory(possibleDirectory: directory, default: .environmentDownloads)
let services = Xcodes.makeServices()
try await services.runtimeInstaller.downloadRuntime(identifier: version, to: destination, with: downloader, architectures: architecture)
Current.logging.log("Finished")
}
}
}
struct Select: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Change the selected Xcode",
discussion: """
Select a version of Xcode by specifying a version number or an absolute path. Run without arguments to select the version specified in your .xcode-version file. If no version file is found, you will be prompted to interactively select from a list.
EXAMPLES:
xcodes select
xcodes select 11.4.0
xcodes select /Applications/Xcode-11.4.0.app
xcodes select -p
"""
)
@ArgumentParser.Flag(name: [.customShort("p"), .customLong("print-path")], help: "Print the path of the selected Xcode")
var print: Bool = false
@Argument(help: "Version or path",
completion: .custom { _ in Current.files.installedXcodes(getDirectory(possibleDirectory: nil)).sorted { $0.version < $1.version }.map { $0.version.appleDescription } })
var versionOrPath: [String] = []
@OptionGroup
var globalDirectory: GlobalDirectoryOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let directory = getDirectory(possibleDirectory: globalDirectory.directory)
do {
try await selectXcodeAsync(shouldPrint: print, pathOrVersion: versionOrPath.joined(separator: " "), directory: directory)
Select.exit()
} catch {
Select.exit(withLegibleError: error)
}
}
}
struct Uninstall: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Uninstall a version of Xcode",
discussion: """
Run without any arguments to interactively select from a list.
EXAMPLES:
xcodes uninstall
xcodes uninstall 11.4.0
"""
)
@Argument(help: "The version to uninstall",
completion: .custom { _ in Current.files.installedXcodes(getDirectory(possibleDirectory: nil)).sorted { $0.version < $1.version }.map { $0.version.appleDescription } })
var version: [String] = []
@Flag(help: "Completely delete Xcode, instead of keeping it on the user's Trash.")
var emptyTrash: Bool = false
@OptionGroup
var globalDirectory: GlobalDirectoryOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let directory = getDirectory(possibleDirectory: globalDirectory.directory)
let services = Xcodes.makeServices()
do {
try await services.xcodeInstaller.uninstallXcode(version.joined(separator: " "), directory: directory, emptyTrash: emptyTrash)
Uninstall.exit()
} catch {
Uninstall.exit(withLegibleError: error)
}
}
}
struct Update: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Update the list of available versions of Xcode"
)
@OptionGroup
var globalDirectory: GlobalDirectoryOption
@OptionGroup
var globalDataSource: GlobalDataSourceOption
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let directory = getDirectory(possibleDirectory: globalDirectory.directory)
let services = Xcodes.makeServices()
do {
try await services.xcodeInstaller.updateAndPrint(dataSource: globalDataSource.dataSource, directory: directory)
Update.exit()
} catch {
Update.exit(withLegibleError: error)
}
}
}
struct Version: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the version number of xcodes itself"
)
@OptionGroup
var globalColor: GlobalColorOption
func run() {
configureRainbow(enabled: globalColor.color)
Current.logging.log(XcodesCLIKit.version.description)
}
}
struct Signout: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Clears the stored username and password"
)
@OptionGroup
var globalColor: GlobalColorOption
func run() async throws {
configureRainbow(enabled: globalColor.color)
let services = Xcodes.makeServices()
do {
try await services.sessionService.logout()
Current.logging.log("Successfully signed out".green)
Signout.exit()
} catch {
Current.logging.log(error.legibleLocalizedDescription)
Signout.exit()
}
}
}
}