xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XToolSupport / XTool.swift
XTool.swift87 lines · 2.6 KiBRaw
| 1 | import Foundation |
| 2 | import XKit |
| 3 | import ArgumentParser |
| 4 | import XUtils |
| 5 | |
| 6 | public enum XTool { |
| 7 | public static func run(arguments: [String]? = nil) async throws { |
| 8 | TemporaryDirectory.prepare() |
| 9 | await XToolCommand.cancellableMain(arguments) |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | private struct XToolCommand: AsyncParsableCommand { |
| 14 | static let configuration = CommandConfiguration( |
| 15 | commandName: "xtool", |
| 16 | abstract: "Cross-platform Xcode replacement", |
| 17 | version: "xtool \(XTool.version)", |
| 18 | groupedSubcommands: [ |
| 19 | CommandGroup( |
| 20 | name: "Configuration", |
| 21 | subcommands: [ |
| 22 | SetupCommand.self, |
| 23 | AuthCommand.self, |
| 24 | SDKCommand.self, |
| 25 | ] |
| 26 | ), |
| 27 | CommandGroup( |
| 28 | name: "Development", |
| 29 | subcommands: [ |
| 30 | NewCommand.self, |
| 31 | DevCommand.self, |
| 32 | DSCommand.self, |
| 33 | DistCommand.self, |
| 34 | ] |
| 35 | ), |
| 36 | CommandGroup( |
| 37 | name: "Device", |
| 38 | subcommands: [ |
| 39 | DevicesCommand.self, |
| 40 | InstallCommand.self, |
| 41 | UninstallCommand.self, |
| 42 | LaunchCommand.self, |
| 43 | ] |
| 44 | ) |
| 45 | ] |
| 46 | ) |
| 47 | } |
| 48 | |
| 49 | #if compiler(<6.2) |
| 50 | private typealias SendableMetatype = Any |
| 51 | #endif |
| 52 | |
| 53 | extension ParsableCommand where Self: SendableMetatype { |
| 54 | fileprivate static func cancellableMain(_ arguments: [String]? = nil) async { |
| 55 | let (canStart, cont) = AsyncStream.makeStream(of: Never.self) |
| 56 | let task = Task { |
| 57 | for await _ in canStart {} |
| 58 | guard !Task.isCancelled else { return } |
| 59 | do { |
| 60 | var command = try self.parseAsRoot(arguments) |
| 61 | if var asyncCommand = command as? AsyncParsableCommand { |
| 62 | try await asyncCommand.run() |
| 63 | } else { |
| 64 | try command.run() |
| 65 | } |
| 66 | } catch where error is CancellationError || Task.isCancelled { |
| 67 | print("Cancelled.") |
| 68 | self.exit() |
| 69 | } catch { |
| 70 | if ProcessInfo.processInfo.environment["XTL_DEBUG_ERRORS"] != nil { |
| 71 | print("ERROR DETAILS:") |
| 72 | print(String(reflecting: error)) |
| 73 | } |
| 74 | self.exit(withError: error) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | signal(SIGINT, SIG_IGN) |
| 79 | let source = DispatchSource.makeSignalSource(signal: SIGINT) |
| 80 | source.setEventHandler { task.cancel() } |
| 81 | source.resume() |
| 82 | |
| 83 | cont.finish() |
| 84 | |
| 85 | await task.value |
| 86 | } |
| 87 | } |