Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

Async ConnectionManager

Kabir Oberaiedca15b605be
diff --git a/Package.resolved b/Package.resolved
index 9471da4..21d9bbd 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "f5935ae26f2a05b003fab58924d18ded1d3eb79e578be093e900459aaaae1468",
+ "originHash" : "68963a2b495f68da4ce56ba0e65958909f1eaaea18e6ac09c7c3fe2b1a3e11d5",
"pins" : [
{
"identity" : "async-http-client",
@@ -186,8 +186,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/SuperchargeApp/SwiftyMobileDevice",
"state" : {
- "revision" : "c7772fb58452c9df727568dda3ca08cf716ef608",
- "version" : "1.2.1"
+ "revision" : "954fff0438c181b64c0ab5dac5428486cc0cb6e0",
+ "version" : "1.3.0"
}
},
{
diff --git a/Package.swift b/Package.swift
index 4cdde70..7d3fafb 100644
--- a/Package.swift
+++ b/Package.swift
@@ -28,7 +28,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/SuperchargeApp/SuperchargeCore", .upToNextMinor(from: "1.2.0")),
- .package(url: "https://github.com/SuperchargeApp/SwiftyMobileDevice", .upToNextMinor(from: "1.2.1")),
+ .package(url: "https://github.com/SuperchargeApp/SwiftyMobileDevice", .upToNextMinor(from: "1.3.0")),
.package(url: "https://github.com/kabiroberai/zsign", .upToNextMinor(from: "1.3.0")),
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.23.0"),
.package(url: "https://github.com/vapor/websocket-kit.git", from: "2.15.0"),
@@ -36,7 +36,7 @@ let package = Package(
.package(url: "https://github.com/apple/swift-crypto", from: "3.9.1"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
.package(url: "https://github.com/attaswift/BigInt", from: "5.5.0"),
- .package(url: "https://github.com/pointfreeco/swift-concurrency-extras.git", from: "1.3.0"),
+ .package(url: "https://github.com/pointfreeco/swift-concurrency-extras", from: "1.3.0"),
],
targets: [
.systemLibrary(name: "CSupersette"),
diff --git a/Sources/Supersign/Installation/ConnectionManager.swift b/Sources/Supersign/Installation/ConnectionManager.swift
index 772cba0..9d3750c 100644
--- a/Sources/Supersign/Installation/ConnectionManager.swift
+++ b/Sources/Supersign/Installation/ConnectionManager.swift
@@ -9,18 +9,13 @@
import Foundation
import SwiftyMobileDevice
-public protocol ConnectionManagerDelegate: AnyObject {
- func connectionManager(_ manager: ConnectionManager, clientsDidChangeFrom oldValue: [ConnectionManager.Client])
-}
-
-public final class ConnectionManager {
-
- public enum SearchMode: CaseIterable {
+public struct ClientDevice: Sendable {
+ public enum SearchMode: CaseIterable, Sendable {
case usb
case network
case all
- func allows(_ connectionType: ConnectionType) -> Bool {
+ fileprivate func allows(_ connectionType: ConnectionType) -> Bool {
switch self {
case .usb:
return connectionType == .usb
@@ -32,6 +27,25 @@ public final class ConnectionManager {
}
}
+ private let key: ConnectionManager.ConnectionKey
+ private let value: ConnectionManager.ConnectionValue
+
+ public var udid: String { key.udid }
+ public var connectionType: ConnectionType { key.connectionType }
+ public var device: Device { value.device }
+ public var deviceName: String { value.deviceName }
+
+ fileprivate init(key: ConnectionManager.ConnectionKey, value: ConnectionManager.ConnectionValue) {
+ self.key = key
+ self.value = value
+ }
+
+ public static func search(mode: SearchMode = .all) async throws -> AsyncStream<[ClientDevice]> {
+ try await ConnectionManager(searchMode: mode).clients
+ }
+}
+
+private actor ConnectionManager {
fileprivate struct ConnectionKey: Hashable, Equatable, Comparable {
let udid: String
let connectionType: ConnectionType
@@ -50,7 +64,7 @@ public final class ConnectionManager {
}
}
- fileprivate class ConnectionValue {
+ fileprivate struct ConnectionValue: Sendable {
let device: Device
let deviceName: String
@@ -75,58 +89,40 @@ public final class ConnectionManager {
}
}
- public final class Client {
- private let key: ConnectionKey
- private let value: ConnectionValue
-
- public var udid: String { key.udid }
- public var connectionType: ConnectionType { key.connectionType }
- public var device: Device { value.device }
- public var deviceName: String { value.deviceName }
-
- fileprivate init(key: ConnectionKey, value: ConnectionValue) {
- self.key = key
- self.value = value
- }
- }
-
private var clientsDict: [ConnectionKey: ConnectionValue] {
didSet {
clientsDidChange()
}
}
- public private(set) var clients: [Client] = [] {
- didSet {
- delegate?.connectionManager(self, clientsDidChangeFrom: oldValue)
- }
- }
-
- private var token: USBMux.SubscriptionToken?
+ private var subscription: Task<Void, Never>?
+ private let continuation: AsyncStream<[ClientDevice]>.Continuation
- public let searchMode: SearchMode
- public private(set) weak var delegate: ConnectionManagerDelegate?
+ let searchMode: ClientDevice.SearchMode
+ let clients: AsyncStream<[ClientDevice]>
private func clientsDidChange() {
- clients = clientsDict.sorted { $0.0 < $1.0 }.map(Client.init)
+ continuation.yield(clientsDict.sorted { $0.0 < $1.0 }.map(ClientDevice.init))
}
- public init(searchMode: SearchMode = .all, delegate: ConnectionManagerDelegate? = nil) throws {
+ init(searchMode: ClientDevice.SearchMode = .all) async throws {
self.searchMode = searchMode
- self.delegate = delegate
self.clientsDict = Dictionary(try USBMux.allDevices().compactMap { dev -> (ConnectionKey, ConnectionValue)? in
guard searchMode.allows(dev.connectionType) else { return nil }
let key = ConnectionKey(udid: dev.udid, connectionType: dev.connectionType)
return try (key, ConnectionValue(key: key))
}) { _, b in b }
- if !clientsDict.isEmpty {
- clientsDidChange()
- }
+ let events = try USBMux.subscribe()
+
+ (clients, continuation) = AsyncStream.makeStream()
- token = try USBMux.subscribe { [weak self] event in
- guard let self = self else { return }
- self.handleEvent(event)
+ clientsDidChange()
+
+ subscription = Task { [events] in
+ for await event in events {
+ handleEvent(event)
+ }
}
}
@@ -145,6 +141,4 @@ public final class ConnectionManager {
}
}
- deinit { try? token.map(USBMux.unsubscribe(withToken:)) }
-
}
diff --git a/Sources/SupersignCLI/main.swift b/Sources/SupersignCLI/main.swift
index 8460d04..0f21e5e 100644
--- a/Sources/SupersignCLI/main.swift
+++ b/Sources/SupersignCLI/main.swift
@@ -11,12 +11,12 @@ import SupersignCLISupport
// see https://github.com/atom/node-keytar
let storage: KeyValueStorage
-#if os(macOS)
-storage = KeychainStorage(service: "com.kabiroberai.Supercharge-Keychain.credentials")
-#else
-let directory = URL.homeDirectory.appending(path: ".config/Supercharge/data")
+// #if os(macOS)
+// storage = KeychainStorage(service: "com.kabiroberai.Supercharge-Keychain.credentials")
+// #else
+let directory = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(".config/Supercharge/data")
storage = DirectoryStorage(base: directory)
-#endif
+// #endif
try await SupersignCLI.run(configuration: SupersignCLI.Configuration(
superchargeApp: nil,
diff --git a/Sources/SupersignCLISupport/ConnectionDelegate.swift b/Sources/SupersignCLISupport/ConnectionDelegate.swift
deleted file mode 100644
index 72449c4..0000000
--- a/Sources/SupersignCLISupport/ConnectionDelegate.swift
+++ /dev/null
@@ -1,52 +0,0 @@
-import Foundation
-import Supersign
-import ArgumentParser
-
-class ConnectionDelegate: ConnectionManagerDelegate {
- var onConnect: (([ConnectionManager.Client]) -> Void)?
- init(onConnect: @escaping ([ConnectionManager.Client]) -> Void) {
- self.onConnect = onConnect
- }
-
- func connectionManager(_ manager: ConnectionManager, clientsDidChangeFrom oldValue: [ConnectionManager.Client]) {
- let usableClients = manager.clients
- guard !usableClients.isEmpty else { return }
- onConnect?(usableClients)
- onConnect = nil
- }
-}
-
-extension ConnectionManager.Client: ExpressibleByArguments {
- public struct Arguments: ParsableArguments {
- @Option(name: .shortAndLong) var udid: String?
- @Flag var search: ConnectionManager.SearchMode = .all
- public init() {}
- }
-
- public static func from(_ args: Arguments) throws -> ConnectionManager.Client {
- print("Waiting for device to be connected...")
- var clients: [ConnectionManager.Client]!
- let semaphore = DispatchSemaphore(value: 0)
- let connDelegate = ConnectionDelegate { currClients in
- if let udid = args.udid {
- if let client = currClients.first(where: { $0.udid == udid }) {
- clients = [client]
- } else {
- clients = []
- }
- } else {
- clients = currClients
- }
- semaphore.signal()
- }
- try withExtendedLifetime(ConnectionManager(searchMode: args.search, delegate: connDelegate)) {
- semaphore.wait()
- }
- return try Console.choose(
- from: clients,
- onNoElement: { throw ValidationError("Device not found") },
- multiPrompt: "Choose device",
- formatter: { "\($0.deviceName) (\($0.connectionType), udid: \($0.udid))" }
- )
- }
-}
diff --git a/Sources/SupersignCLISupport/ConnectionOptions.swift b/Sources/SupersignCLISupport/ConnectionOptions.swift
new file mode 100644
index 0000000..c1b55de
--- /dev/null
+++ b/Sources/SupersignCLISupport/ConnectionOptions.swift
@@ -0,0 +1,43 @@
+import Foundation
+import Supersign
+import ArgumentParser
+
+struct ConnectionOptions: ParsableArguments {
+ @Option(name: .shortAndLong) var udid: String?
+
+ @Flag var search: ClientDevice.SearchMode = .all
+
+ init() {}
+
+ init(
+ udid: String?,
+ search: ClientDevice.SearchMode = .all
+ ) {
+ self.udid = udid
+ self.search = search
+ }
+
+ func client() async throws -> ClientDevice {
+ print("Waiting for device to be connected...")
+
+ let stream = try await ClientDevice.search(mode: search)
+ for await devices in stream {
+ guard !devices.isEmpty else { continue }
+ if let udid {
+ guard let device = devices.first(where: { $0.udid == udid }) else {
+ continue
+ }
+ return device
+ } else {
+ return try Console.choose(
+ from: devices,
+ onNoElement: { throw ValidationError("Device not found") },
+ multiPrompt: "Choose device",
+ formatter: { "\($0.deviceName) (\($0.connectionType), udid: \($0.udid))" }
+ )
+ }
+ }
+
+ throw ValidationError("Device not found")
+ }
+}
diff --git a/Sources/SupersignCLISupport/DevicesCommand.swift b/Sources/SupersignCLISupport/DevicesCommand.swift
index dbb53d4..d2035a5 100644
--- a/Sources/SupersignCLISupport/DevicesCommand.swift
+++ b/Sources/SupersignCLISupport/DevicesCommand.swift
@@ -2,31 +2,39 @@ import Foundation
import Supersign
import ArgumentParser
-extension ConnectionManager.SearchMode: EnumerableFlag {
+extension ClientDevice.SearchMode: EnumerableFlag {
// public static func name(for value: ConnectionManager.SearchMode) -> NameSpecification {
// [.short, .long]
// }
}
-struct DevicesCommand: ParsableCommand {
+struct DevicesCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "devices",
abstract: "List devices"
)
- @Flag(help: "Which devices to search for") var search: ConnectionManager.SearchMode = .all
+ @Flag(help: "Which devices to search for") var search: ClientDevice.SearchMode = .all
+ @Flag(
+ inversion: .prefixedNo,
+ help: "If no devices are found at first, wait until at least one is connected."
+ ) var wait = true
- func run() throws {
- var _clients: [ConnectionManager.Client]!
- let semaphore = DispatchSemaphore(value: 0)
- let connDelegate = ConnectionDelegate { currClients in
- _clients = currClients
- semaphore.signal()
+ func run() async throws {
+ var shouldPrint = true
+ var foundDevices: [ClientDevice] = []
+ for await devices in try await ClientDevice.search(mode: search) {
+ if !devices.isEmpty {
+ foundDevices = devices
+ break
+ }
+ guard wait else { break }
+ if shouldPrint {
+ shouldPrint = false
+ print("Waiting for devices to be connected...")
+ }
}
- try withExtendedLifetime(ConnectionManager(searchMode: search, delegate: connDelegate)) {
- semaphore.wait()
- }
- let clients = _clients!
- print(clients.map { "\($0.deviceName) [\($0.connectionType)]: \($0.udid)" }.joined(separator: "\n"))
+
+ print(foundDevices.map { "\($0.deviceName) [\($0.connectionType)]: \($0.udid)" }.joined(separator: "\n"))
}
}
diff --git a/Sources/SupersignCLISupport/ExpressibleByArguments.swift b/Sources/SupersignCLISupport/ExpressibleByArguments.swift
deleted file mode 100644
index 4cfbe41..0000000
--- a/Sources/SupersignCLISupport/ExpressibleByArguments.swift
+++ /dev/null
@@ -1,27 +0,0 @@
-import ArgumentParser
-
-public protocol ExpressibleByArguments {
- associatedtype Arguments: ParsableArguments
- static func from(_ arguments: Arguments) throws -> Self
-}
-
-@propertyWrapper
-struct FromArguments<Inner: ExpressibleByArguments>: ParsableArguments {
- @OptionGroup private var arguments: Inner.Arguments
- private var decoded: Inner?
-
- var wrappedValue: Inner {
- guard let decoded = decoded else {
- fatalError("Value has not yet been parsed")
- }
- return decoded
- }
-
- private enum CodingKeys: String, CodingKey {
- case arguments
- }
-
- mutating func validate() throws {
- decoded = try .from(arguments)
- }
-}
diff --git a/Sources/SupersignCLISupport/InstallCommand.swift b/Sources/SupersignCLISupport/InstallCommand.swift
index a234481..e4e3cc5 100644
--- a/Sources/SupersignCLISupport/InstallCommand.swift
+++ b/Sources/SupersignCLISupport/InstallCommand.swift
@@ -9,23 +9,25 @@ struct InstallCommand: AsyncParsableCommand {
abstract: "Install an ipa file to your device"
)
- @Option(name: .shortAndLong) var account: String?
@Option(
name: .shortAndLong,
help: "Preferred team ID"
) var team: String?
- @OptionGroup @FromArguments var client: ConnectionManager.Client
+
+ @OptionGroup var connectionOptions: ConnectionOptions
@Argument(
help: "The path to a custom app/ipa to install"
) var path: String
func run() async throws {
- let token = try account.flatMap(AuthToken.init(string:)) ?? AuthToken.saved()
+ let token = try AuthToken.saved()
let username = token.appleID
let credentials: IntegratedInstaller.Credentials = .token(token.dsToken)
+ let client = try await connectionOptions.client()
+
print("Installing to device: \(client.deviceName) (udid: \(client.udid))")
let installDelegate = SupersignCLIDelegate(preferredTeam: team.map(DeveloperServicesTeam.ID.init))
diff --git a/Sources/SupersignCLISupport/RunCommand.swift b/Sources/SupersignCLISupport/RunCommand.swift
index f1e03c2..6e86b60 100644
--- a/Sources/SupersignCLISupport/RunCommand.swift
+++ b/Sources/SupersignCLISupport/RunCommand.swift
@@ -3,13 +3,13 @@ import Supersign
import SwiftyMobileDevice
import ArgumentParser
-struct RunCommand: ParsableCommand {
+struct RunCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "run",
abstract: "Run an installed app"
)
-
- @OptionGroup @FromArguments var connection: ConnectionManager.Client
+
+ @OptionGroup var connectionOptions: ConnectionOptions
@Argument(
help: "The app to run"
@@ -22,8 +22,10 @@ struct RunCommand: ParsableCommand {
)
) var args: [String] = []
- func run() throws {
- let installProxy = try InstallationProxyClient(device: connection.device, label: "supersign-inst")
+ func run() async throws {
+ let client = try await connectionOptions.client()
+
+ let installProxy = try InstallationProxyClient(device: client.device, label: "supersign-inst")
let executable: URL
do {
executable = try installProxy.executable(forBundleID: bundleID)
@@ -33,7 +35,7 @@ struct RunCommand: ParsableCommand {
print("Launching \(executable.lastPathComponent)...")
- let debugserver = try DebugserverClient(device: connection.device, label: "supersign")
+ let debugserver = try DebugserverClient(device: client.device, label: "supersign")
guard try debugserver.launch(executable: executable, arguments: args) == "OK" else {
throw Console.Error("Launch failed (!OK)")
}
diff --git a/Sources/SupersignCLISupport/SuperchargeCommand.swift b/Sources/SupersignCLISupport/SuperchargeCommand.swift
index c6f66cc..80f0460 100644
--- a/Sources/SupersignCLISupport/SuperchargeCommand.swift
+++ b/Sources/SupersignCLISupport/SuperchargeCommand.swift
@@ -9,52 +9,17 @@ struct InstallSuperchargeCommand: AsyncParsableCommand {
)
@Option(name: .shortAndLong) var udid: String?
- @Option(name: .shortAndLong) var account: String?
func run() async throws {
guard let app = SupersignCLI.config.superchargeApp else {
throw Console.Error("This copy of Supersign is not configured to install Supercharge.")
}
- let username: String
- let credentials: IntegratedInstaller.Credentials
+ let auth = try AuthToken.saved()
+ let username = auth.appleID
+ let credentials: IntegratedInstaller.Credentials = .token(auth.dsToken)
- if let account = account, let auth = AuthToken(string: account) {
- username = auth.appleID
- credentials = .token(auth.dsToken)
- } else {
- guard let appleID = account ?? Console.prompt("Apple ID: "),
- let password = Console.getPassword("Password: ")
- else { return }
- username = appleID
- credentials = .password(password)
- }
-
- print("Waiting for device to be connected...")
- var clients: [ConnectionManager.Client]!
- let semaphore = DispatchSemaphore(value: 0)
- let connDelegate = ConnectionDelegate { currClients in
- if let udid = udid {
- if let client = currClients.first(where: { $0.udid == udid }) {
- clients = [client]
- } else {
- return
- }
- } else {
- clients = currClients
- }
- semaphore.signal()
- }
- try withExtendedLifetime(ConnectionManager(searchMode: .usb, delegate: connDelegate)) {
- semaphore.wait()
- }
-
- let client = Console.choose(
- from: clients,
- onNoElement: { fatalError("No devices available") },
- multiPrompt: "Choose device",
- formatter: { "\($0.deviceName) (udid: \($0.udid))" }
- )
+ let client = try await ConnectionOptions(udid: udid, search: .usb).client()
print("Installing to device: \(client.deviceName) (udid: \(client.udid))")
diff --git a/Sources/SupersignCLISupport/UninstallCommand.swift b/Sources/SupersignCLISupport/UninstallCommand.swift
index 7622139..d0af202 100644
--- a/Sources/SupersignCLISupport/UninstallCommand.swift
+++ b/Sources/SupersignCLISupport/UninstallCommand.swift
@@ -8,15 +8,16 @@ struct UninstallCommand: AsyncParsableCommand {
commandName: "uninstall",
abstract: "Uninstall an installed app"
)
-
- @OptionGroup @FromArguments var connection: ConnectionManager.Client
+
+ @OptionGroup var connectionOptions: ConnectionOptions
@Argument(
help: "The app to uninstall"
) var bundleID: String
func run() async throws {
- let installProxy = try InstallationProxyClient(device: connection.device, label: "supersign-inst")
+ let client = try await connectionOptions.client()
+ let installProxy = try InstallationProxyClient(device: client.device, label: "supersign-inst")
do {
try await installProxy.uninstall(
bundleID: bundleID,