Run a virtual iPhone on an Apple Silicon Mac.
Swift
Take per-patch overrides in vphone-launchpad-cli vm create
Jacky77efe891f2bf
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.mdindex f61e65c5..e55708fb 100644--- a/Documents/Guides/launchpad-cli.md+++ b/Documents/Guides/launchpad-cli.md@@ -113,7 +113,7 @@ version while a machine is bound to it; rebind or delete those machines first.| `vm list` | Machines in every library with run state, Core Bundle and log path || `vm start <name> [--headless] [--wait]` / `vm stop <name>` | Launch with the machine's bundle, or stop; `--wait` waits for vphoned. Stop asks the guest to shut down (vphoned `system.shutdown`) and waits up to 30 s; when the guest cannot be asked or does not stop, it ends the virtual machine as before || `vm wait <name>` / `vm log <name> [--kind create\|dfu\|patch]` | Wait for vphoned; read a console log |-| `vm create <name> [--bundle <version>] [...] [--device <product-type>] [--no-template \| --slim on\|off --trim … --keep-languages … --service-profile … --remove-apps … --keep-apps … --accounts-off] [--from <step>]` | The New Machine pipeline, bound to `--bundle` or the default: cloned from a template, built first when missing (2.9), or restored on its own with `--no-template`; the slimming switches are `vphone-cli vm create`'s. `--device` makes an iPad guest, `--from` retries from a step (`findTemplate` … `firstBoot`); the result names the template and whether this creation built it |+| `vm create <name> [--bundle <version>] [...] [--device <product-type>] [--preset <preset>] [--block <patch>]... [--allow <patch>]... [--no-template \| --slim on\|off --trim … --keep-languages … --service-profile … --remove-apps … --keep-apps … --accounts-off] [--from <step>]` | The New Machine pipeline, bound to `--bundle` or the default: cloned from a template, built first when missing (2.9), or restored on its own with `--no-template`; the slimming switches are `vphone-cli vm create`'s. `--block`/`--allow` (repeatable) turn one patch of the preset off or on, as New Machine's patch list and `vphone-cli fw set-patches` do (see below). `--device` makes an iPad guest, `--from` retries from a step (`findTemplate` … `firstBoot`) with the options the creation started with; the result names the template, whether this creation built it, and the patches it used || `vm set-bundle <name> <version> [--update-environment]` | Bind a machine to another installed version. `--update-environment` also redeploys that version's guest environment and needs a stopped machine || `vm leases [--release]` | DHCP leases on the shared NAT network and the machine that owns each. `--release` frees the ones no machine in any library uses, through the helper (see [Networking](networking.md#addresses-held-by-old-macs)) || `cfw install <name>` | Install CFW into a stopped machine with its own bundle, through the helper. The helper puts temporary work files on the VM library's external volume when applicable. |@@ -124,6 +124,33 @@ version while a machine is bound to it; rebind or delete those machines first.| `guest unlock <name> [--passcode <code>] [--timeout <seconds>]` | Turn the screen on and unlock the guest, whatever state it was in (vphoned `screen.unlock`). `--passcode` is needed only when the guest has one || `exec [--bundle <version>] <vphone-cli arguments>` | Run the default bundle's `vphone-cli`, or that version's, streaming its output. `--bundle` must come first |+### Patch overrides in `vm create`++`--block <patch>` and `--allow <patch>` take the identifiers `vphone-cli fw+patches` lists (`vphone-launchpad-cli exec fw patches --preset <preset>`),+once per patch. Launchpad reads that catalog from the creation's bundle,+refuses an identifier no patch set declares or one both blocked and allowed,+and keeps only what differs from the preset, as `fw set-patches` does. It+then splits them the way New Machine does:++- Boot-chain patches (AVPBooter, iBSS, iBEC, LLB, TXM, kernelcache,+ DeviceTree …) are part of the template's key: Find Template looks for a+ template built with them, and a template build records them with `fw+ set-patches` before `fw patch`.+- Guest patches stay out of the template. The clone records them with `fw+ set-patches`, and the Apply Guest Patches step writes them with `cfw+ update-environment` through the helper before the first boot. A guest+ override alone therefore reuses the plain template.++```sh+vphone-launchpad-cli vm create rt-e --block system-debugserver-cfw-install+```++The result's `patches` object holds the preset, the `blocked` and `allowed`+overrides and the `guest` ones applied to the clone. With `--no-template`+every override goes into the machine's own restore. `--from` refuses+`--block` and `--allow`: a retry keeps the creation's patches.+Machine commands take `--root <library>` when two libraries hold a machinewith the same name. `guest` commands and `--wait` go through the machine's`vphone.sock`, which every launch serves; bundles up to 2.0.9 serve it onlydiff --git a/VPhoneLaunchpad/Tests/ControlTests.sh b/VPhoneLaunchpad/Tests/ControlTests.shnew file mode 100755index 00000000..ff258dcc--- /dev/null+++ b/VPhoneLaunchpad/Tests/ControlTests.sh@@ -0,0 +1,13 @@+#!/bin/zsh+set -euo pipefail++launchpad="${0:a:h:h}"+temporary="$(/usr/bin/mktemp -d)"+trap '/bin/rm -rf "$temporary"' EXIT++/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \+ -parse-as-library \+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift" \+ "$launchpad/Tests/ControlTests.swift" \+ -o "$temporary/control-tests"+"$temporary/control-tests" "$@"diff --git a/VPhoneLaunchpad/Tests/ControlTests.swift b/VPhoneLaunchpad/Tests/ControlTests.swiftnew file mode 100644index 00000000..32528a16--- /dev/null+++ b/VPhoneLaunchpad/Tests/ControlTests.swift@@ -0,0 +1,84 @@+import Foundation++/// `vphone-launchpad-cli`'s command line, parsed into the request the+/// control socket carries.+@main+struct ControlTests {+ static func main() throws {+ try parsing()+ try repeatedOptions()+ try requestCoding()+ print("Control tests passed")+ }++ static func parse(_ words: [String]) throws -> (VPhoneLaunchpadControlRequest, foreground: Bool) {+ var foreground = false+ let request = try VPhoneLaunchpadControlRequest.parse(words, foreground: &foreground)+ return (request, foreground)+ }++ static func failure(_ words: [String]) -> VPhoneLaunchpadControlUsageError? {+ do {+ _ = try parse(words)+ return nil+ } catch {+ return error as? VPhoneLaunchpadControlUsageError+ }+ }++ // MARK: - Commands and options++ static func parsing() throws {+ let (start, foreground) = try parse(["vm", "start", "lab-01", "--headless", "--timeout=30", "--foreground"])+ precondition(start.command == "vm.start" && start.arguments == ["lab-01"], "Grouped command: \(start)")+ precondition(start.flag("headless") && start.option("timeout") == "30" && foreground, "Options: \(start)")+ precondition(start.repeated == nil, "No repeated options")++ let (exec, _) = try parse(["exec", "--bundle", "2.9.0", "vm", "list", "--json"])+ precondition(exec.option("bundle") == "2.9.0" && exec.arguments == ["vm", "list", "--json"], "exec: \(exec)")++ let (root, _) = try parse(["vm", "stop", "lab-01", "--root", "/tmp/a/../b"])+ precondition(root.option("root") == "/tmp/b", "Root standardized: \(String(describing: root.option("root")))")++ precondition(failure(["vm"])?.message == "vm needs a command.", "A group alone")+ precondition(failure(["vm", "start"])?.message == "wrong number of arguments.", "Missing name")+ precondition(failure(["vm", "start", "a", "--nope"])?.message == "unknown option --nope.", "Unknown option")+ precondition(failure(["vm", "log", "a", "--lines"])?.message == "--lines needs a value.", "Missing value")+ // Only vm create repeats --block.+ precondition(failure(["vm", "start", "a", "--block", "x"])?.message == "unknown option --block.", "Not repeatable elsewhere")+ }++ static func repeatedOptions() throws {+ let (create, _) = try parse([+ "vm", "create", "rt-e", "--preset", "standard",+ "--block", "system-debugserver-cfw-install", "--allow=kernel-exp-x", "--block", "ibss-cfw-serial_label",+ ])+ precondition(create.command == "vm.create" && create.arguments == ["rt-e"], "Create: \(create)")+ precondition(create.option("preset") == "standard", "Preset")+ precondition(create.values("block") == ["system-debugserver-cfw-install", "ibss-cfw-serial_label"], "Blocks in order: \(create.values("block"))")+ precondition(create.values("allow") == ["kernel-exp-x"], "Allows: \(create.values("allow"))")+ precondition(create.option("block") == nil, "A repeated option is not a single one")+ precondition(failure(["vm", "create", "a", "--block"])?.message == "--block needs a value.", "Block needs a value")++ let usage = try require(VPhoneLaunchpadControlCommand.named("vm.create")).usage+ precondition(usage.contains("[--block <value>]...") && usage.contains("[--allow <value>]..."), usage)+ }++ /// A request from a CLI without repeated options still decodes, and+ /// the values survive the socket.+ static func requestCoding() throws {+ let old = try JSONDecoder().decode(VPhoneLaunchpadControlRequest.self, from: Data(#"{"command":"vm.create","arguments":["a"],"options":{"preset":"standard"}}"#.utf8))+ precondition(old.values("block").isEmpty && old.option("preset") == "standard", "Old request")++ let (create, _) = try parse(["vm", "create", "a", "--block", "x", "--block", "y"])+ let decoded = try JSONDecoder().decode(VPhoneLaunchpadControlRequest.self, from: JSONEncoder().encode(create))+ precondition(decoded.values("block") == ["x", "y"], "Round trip: \(decoded.values("block"))")+ }++ static func require<T>(_ value: T?) throws -> T {+ guard let value else {+ preconditionFailure("missing value")+ }+ return value+ }+}diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swiftindex 426246a5..c39b6ca8 100644--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift@@ -170,6 +170,40 @@ struct TemplatesTests {precondition(!VPhoneLaunchpadTemplateCommands.find(request).contains("--block"), "Guest-only overrides find the plain template")let none = VPhoneLaunchpadPatchOverrides(preset: "experimental", guestPatches: ["dyld-cfw-camera"])precondition(!none.hasGuestOverrides && !none.hasBootChainOverrides, "A guest patch not overridden is no override")++ // vphone-launchpad-cli vm create --block/--allow, reduced as fw+ // set-patches reduces them and split as New Machine splits them.+ let declared: Set = ["ibss-cfw-serial_label", "system-debugserver-cfw-install", "dyld-cfw-camera", "kernel-exp-x", "kernel-boot-y"]+ let inPreset: Set = ["ibss-cfw-serial_label", "system-debugserver-cfw-install", "kernel-boot-y"]+ let guest: Set = ["system-debugserver-cfw-install", "dyld-cfw-camera"]+ func requested(_ block: [String], _ allow: [String]) throws(VPhoneLaunchpadPatchOverrides.RequestError) -> VPhoneLaunchpadPatchOverrides {+ try VPhoneLaunchpadPatchOverrides.requested(preset: "standard", block: block, allow: allow, declared: declared, inPreset: inPreset, guest: guest)+ }+ let cli = try? requested(["system-debugserver-cfw-install", "ibss-cfw-serial_label", "dyld-cfw-camera"], ["kernel-exp-x", "kernel-boot-y"])+ // Blocking one the preset leaves off, or allowing one it turns on,+ // changes nothing and is not kept.+ precondition(cli?.blocked == ["system-debugserver-cfw-install", "ibss-cfw-serial_label"], "Blocked: \(String(describing: cli?.blocked))")+ precondition(cli?.allowed == ["kernel-exp-x"], "Allowed: \(String(describing: cli?.allowed))")+ precondition(cli?.guestPatches == ["system-debugserver-cfw-install"], "Guest: \(String(describing: cli?.guestPatches))")+ precondition(cli?.bootChainBlocked == ["ibss-cfw-serial_label"] && cli?.bootChainAllowed == ["kernel-exp-x"], "Boot chain")+ // The retest's case: one guest patch blocked finds the plain template+ // and is applied to the clone.+ let debugserver = try? requested(["system-debugserver-cfw-install"], [])+ precondition(debugserver.map { !$0.hasBootChainOverrides && $0.hasGuestOverrides } == true, "Guest only from the CLI")+ precondition(debugserver.map { $0.setPatchesArguments(includingGuest: true) }+ == ["--preset", "standard", "--block", "system-debugserver-cfw-install"], "Clone's set-patches")+ do {+ _ = try requested(["no-such-patch"], [])+ preconditionFailure("An unknown patch is refused")+ } catch {+ precondition(error == .unknown(["no-such-patch"]) && error.message.contains("No patch declares no-such-patch"), error.message)+ }+ do {+ _ = try requested(["kernel-boot-y"], ["kernel-boot-y"])+ preconditionFailure("Blocked and allowed is refused")+ } catch {+ precondition(error == .contradictory(["kernel-boot-y"]), error.message)+ }print("Patch override tests passed")}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swiftindex fd2589a4..34d8683d 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift@@ -475,6 +475,10 @@ struct VPhoneLaunchpadControlCommands {let pipeline: VPhoneLaunchpadCreationPipelineif let from = request.option("from") {+ // A retry runs with the options the creation started with.+ guard request.values("block").isEmpty, request.values("allow").isEmpty else {+ throw VPhoneLaunchpadError("--from retries with the patches the creation started with; --block and --allow cannot change them.")+ }guard let step = VPhoneLaunchpadCreationPipeline.Step.allCases.first(where: { from == "\($0)" }) else {let steps = VPhoneLaunchpadCreationPipeline.Step.allCases.map { "\($0)" }.joined(separator: ", ")throw VPhoneLaunchpadError("--from takes one of: \(steps).")@@ -562,10 +566,7 @@ struct VPhoneLaunchpadControlCommands {}return value}- var patches = VPhoneLaunchpadPatchSelection()- if let preset = request.option("preset") {- patches.preset = preset- }+ let (patches, guestPatches) = try await Self.patches(request, commandLine: commandLine, emit: emit)let usesTemplate = !request.flag("no-template")let slimming = try Self.slimming(request, usesTemplate: usesTemplate)let options = try VPhoneLaunchpadCreationPipeline.Options(@@ -580,6 +581,7 @@ struct VPhoneLaunchpadControlCommands {diskSizeGB: number("disk-size", 64),network: request.option("network") ?? "nat",patches: patches,+ guestPatches: guestPatches,keepArtifacts: request.flag("keep-artifacts"),usesTemplate: usesTemplate,slimming: slimming,@@ -587,6 +589,56 @@ struct VPhoneLaunchpadControlCommands {return library.create(options)}+ /// The preset and the per-patch overrides of `--block` and `--allow`,+ /// split as New Machine splits them: the bundle's catalog for the preset+ /// says which patches it turns on and which lie outside the boot chain.+ /// The boot-chain overrides go into the template's key and build; the+ /// guest ones are applied to the clone in Apply Guest Patches.+ private static func patches(+ _ request: VPhoneLaunchpadControlRequest,+ commandLine: VPhoneLaunchpadCommandLine,+ emit: Emit,+ ) async throws -> (VPhoneLaunchpadPatchSelection, guest: Set<String>) {+ var selection = VPhoneLaunchpadPatchSelection()+ if let preset = request.option("preset") {+ selection.preset = preset+ }+ let block = request.values("block")+ let allow = request.values("allow")+ guard !block.isEmpty || !allow.isEmpty else {+ return (selection, [])+ }+ let catalog = try await VPhoneLaunchpadPatchCatalog.read(using: commandLine, machine: nil, preset: selection.preset)+ let overrides: VPhoneLaunchpadPatchOverrides+ do {+ overrides = try VPhoneLaunchpadPatchOverrides.requested(+ preset: selection.preset,+ block: block,+ allow: allow,+ declared: Set(catalog.patches.map(\.identifier)),+ inPreset: Set(catalog.patches.filter(\.inPreset).map(\.identifier)),+ guest: Set(catalog.patches.filter { !$0.isBootChain }.map(\.identifier)),+ )+ } catch {+ throw VPhoneLaunchpadError(error.message)+ }+ selection.blocked = overrides.blocked+ selection.allowed = overrides.allowed+ let unchanged = Set(block + allow).subtracting(overrides.blocked).subtracting(overrides.allowed)+ if !unchanged.isEmpty {+ emit("note: preset \(selection.preset) already has \(unchanged.sorted().joined(separator: ", ")) that way")+ }+ let essentialOff = selection.bootEssentialOff(in: catalog).map(\.identifier)+ if !essentialOff.isEmpty {+ emit("warning: \(essentialOff.count) boot-essential patch(es) are off — the machine may not boot: \(essentialOff.joined(separator: ", "))")+ }+ let bootChain = overrides.bootChainBlocked.map { "-\($0)" } + overrides.bootChainAllowed.map { "+\($0)" }+ let guest = overrides.blocked.intersection(overrides.guestPatches).map { "-\($0)" }+ + overrides.allowed.intersection(overrides.guestPatches).map { "+\($0)" }+ emit("patches: preset \(selection.preset); boot chain \(bootChain.isEmpty ? "as the preset" : bootChain.sorted().joined(separator: " ")); guest \(guest.isEmpty ? "as the preset" : guest.sorted().joined(separator: " "))")+ return (selection, overrides.guestPatches)+ }+/// The template switches, refused where `vphone-cli vm create` refuses/// them: with `--no-template`, after `--slim off`, `--accounts-off`/// without the trimmed profile, an app outside the removable list.@@ -680,6 +732,13 @@ struct VPhoneLaunchpadControlCommands {// Only once Find Template has decided to build: a creation that// clones a template it found never makes this machine."buildMachine": pipeline.plan.buildingName ?? NSNull(),+ "patches": [+ "preset": pipeline.options.patches.preset,+ "blocked": pipeline.options.patches.blocked.sorted(),+ "allowed": pipeline.options.patches.allowed.sorted(),+ // Applied to the clone; the others went into the template.+ "guest": pipeline.options.guestPatches.sorted(),+ ],"steps": pipeline.steps.map { step -> [String: Any] invar item: [String: Any] = ["step": "\(step)", "status": pipeline.status(step).rawValue]if let duration = pipeline.durations[step] {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swiftindex 6dab3877..0fab38a9 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift@@ -286,6 +286,47 @@ nonisolated struct VPhoneLaunchpadPatchOverrides: Hashable, Sendable {!blocked.isDisjoint(with: guestPatches) || !allowed.isDisjoint(with: guestPatches)}+ /// Overrides asked for by name (`vphone-launchpad-cli vm create --block+ /// … --allow …`), checked and reduced as `vphone-cli fw set-patches`+ /// does: a patch no set declares, or one both blocked and allowed, is+ /// refused, and only differences from the preset are kept. `declared`,+ /// `inPreset` and `guest` (the patches outside the boot chain) come from+ /// the bundle's catalog for `preset`.+ static func requested(+ preset: String,+ block: [String],+ allow: [String],+ declared: Set<String>,+ inPreset: Set<String>,+ guest: Set<String>,+ ) throws(RequestError) -> Self {+ let unknown = Set(block + allow).subtracting(declared)+ guard unknown.isEmpty else {+ throw .unknown(unknown.sorted())+ }+ let contradictory = Set(block).intersection(allow)+ guard contradictory.isEmpty else {+ throw .contradictory(contradictory.sorted())+ }+ let blocked = Set(block).intersection(inPreset)+ let allowed = Set(allow).subtracting(inPreset)+ return Self(preset: preset, blocked: blocked, allowed: allowed, guestPatches: blocked.union(allowed).intersection(guest))+ }++ nonisolated enum RequestError: Error, Equatable {+ case unknown([String])+ case contradictory([String])++ var message: String {+ switch self {+ case let .unknown(patches):+ "No patch declares \(patches.joined(separator: ", ")). Run exec fw patches for the identifiers."+ case let .contradictory(patches):+ "\(patches.joined(separator: ", ")) cannot be both blocked and allowed."+ }+ }+ }+/// `fw set-patches` arguments without the machine. Each run writes the/// whole record, so the clone's run repeats the boot-chain overrides it/// already has from its template.diff --git a/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift b/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swiftindex 68b2c011..8a3f09d0 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift@@ -39,96 +39,6 @@ func fail(_ message: String, detail: String? = nil) -> Never {exit(1)}-func parse(_ words: [String], foreground: inout Bool) -> VPhoneLaunchpadControlRequest {- // Two words name a grouped command ("vm start"), one word the others.- var rest = words- var command: VPhoneLaunchpadControlCommand?- if rest.count >= 2, let grouped = VPhoneLaunchpadControlCommand.named("\(rest[0]).\(rest[1])") {- command = grouped- rest.removeFirst(2)- } else if let single = VPhoneLaunchpadControlCommand.named(rest[0]) {- command = single- rest.removeFirst()- }- guard let command else {- let group = VPhoneLaunchpadControlCommand.all.filter { $0.name.hasPrefix("\(words[0]).") }- if !group.isEmpty {- fail("\(words[0]) needs a command.", detail: group.map { " \($0.usage)" }.joined(separator: "\n"))- }- fail("unknown command \(words.prefix(2).joined(separator: " ")). Run vphone-launchpad-cli help.")- }- var request = VPhoneLaunchpadControlRequest(command: command.name)- // exec hands everything after it to vphone-cli untouched, except a- // leading --bundle that picks whose vphone-cli runs.- if command.name == "exec" {- if let first = rest.first, first == "--bundle" || first.hasPrefix("--bundle=") {- rest.removeFirst()- if first == "--bundle" {- guard !rest.isEmpty else {- fail("--bundle needs a value.")- }- request.options["bundle"] = rest.removeFirst()- } else {- request.options["bundle"] = String(first.dropFirst("--bundle=".count))- }- }- request.arguments = rest- return request- }-- var positional: [String] = []- var index = 0- while index < rest.count {- let word = rest[index]- index += 1- if word == "--" {- positional += rest[index...]- break- }- guard word.hasPrefix("--"), word.count > 2 else {- positional.append(word)- continue- }- var name = String(word.dropFirst(2))- var value: String?- if let equals = name.firstIndex(of: "=") {- value = String(name[name.index(after: equals)...])- name = String(name[..<equals])- }- if name == "foreground", value == nil {- foreground = true- } else if command.flags.contains(name), value == nil {- request.options[name] = "true"- } else if command.options.contains(name) {- if value == nil, index < rest.count {- value = rest[index]- index += 1- }- guard let value else {- fail("--\(name) needs a value.")- }- request.options[name] = value- } else {- fail("unknown option --\(name).", detail: "usage: vphone-launchpad-cli \(command.usage)")- }- }-- // A trailing `...` argument may be empty.- let named = command.takesRest ? command.arguments.count - 1 : command.arguments.count- guard positional.count >= named, command.takesRest || positional.count == named else {- fail("wrong number of arguments.", detail: "usage: vphone-launchpad-cli \(command.usage)")- }- // The app runs elsewhere; a relative path means nothing to it.- if command.name == "bundle.install-local" {- positional[0] = URL(fileURLWithPath: positional[0]).standardizedFileURL.path- }- if let root = request.options["root"] {- request.options["root"] = URL(fileURLWithPath: root).standardizedFileURL.path- }- request.arguments = positional- return request-}-// MARK: - Connectionfunc connectControl() -> Int32? {@@ -196,7 +106,12 @@ if words.isEmpty || ["help", "-h", "--help"].contains(words[0]) {exit(words.isEmpty ? 1 : 0)}-let request = parse(words, foreground: &foreground)+let request: VPhoneLaunchpadControlRequest+do {+ request = try VPhoneLaunchpadControlRequest.parse(words, foreground: &foreground)+} catch {+ fail(error.message, detail: error.detail)+}let fd = connectControl() ?? launchAndConnect(foreground: foreground)guard var line = try? JSONEncoder().encode(request) else {diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swiftindex f9418753..9eb7d82c 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift@@ -69,6 +69,9 @@ nonisolated struct VPhoneLaunchpadControlRequest: Codable, Sendable {var arguments: [String] = []/// Valued options by name; a flag that is set has the value "true".var options: [String: String] = [:]+ /// Repeatable options (`--block a --block b`) by name, in the order+ /// given. Optional, so a request without them still decodes.+ var repeated: [String: [String]]?func option(_ name: String) -> String? {options[name]@@ -77,6 +80,11 @@ nonisolated struct VPhoneLaunchpadControlRequest: Codable, Sendable {func flag(_ name: String) -> Bool {options[name] == "true"}++ /// Every value of a repeatable option; empty when it was not given.+ func values(_ name: String) -> [String] {+ repeated?[name] ?? []+ }}/// One line from the app. `output` lines stream while a command runs; the@@ -121,11 +129,13 @@ nonisolated struct VPhoneLaunchpadControlCommand: Sendable {let options: [String]/// Options without a value.let flags: [String]+ /// Options that take a value and may be given more than once.+ var repeated: [String] = []let summary: Stringvar usage: String {let positional = arguments.map { "<\($0)>" }- let named = options.map { "[--\($0) <value>]" } + flags.map { "[--\($0)]" }+ let named = options.map { "[--\($0) <value>]" } + repeated.map { "[--\($0) <value>]..." } + flags.map { "[--\($0)]" }// exec reads its options only before the arguments it passes on.let parts = name == "exec" ? named + positional : positional + namedreturn ([name.replacingOccurrences(of: ".", with: " ")] + parts).joined(separator: " ")@@ -169,8 +179,8 @@ nonisolated struct VPhoneLaunchpadControlCommand: Sendable {Self(name: "vm.create", arguments: ["name"], options: ["root", "bundle", "iphone-source", "cloudos-source", "device", "cpu", "memory", "disk-size", "network", "preset", "from","slim", "trim", "keep-languages", "service-profile", "remove-apps", "keep-apps",- ], flags: ["keep-artifacts", "no-wait", "no-template", "accounts-off"],- summary: "Create a machine through every step, as New Machine does, bound to --bundle (default: the default bundle): cloned from a template, built first when missing, or restored on its own with --no-template. --slim, --trim, --keep-languages, --service-profile, --remove-apps, --keep-apps and --accounts-off shape the template, as in vphone-cli vm create. --from <step> retries a failed creation from that step."),+ ], flags: ["keep-artifacts", "no-wait", "no-template", "accounts-off"], repeated: ["block", "allow"],+ summary: "Create a machine through every step, as New Machine does, bound to --bundle (default: the default bundle): cloned from a template, built first when missing, or restored on its own with --no-template. --block and --allow turn one patch of --preset off or on, as New Machine's patch list and vphone-cli fw set-patches do: boot-chain ones go into the template, guest ones are applied to the clone. --slim, --trim, --keep-languages, --service-profile, --remove-apps, --keep-apps and --accounts-off shape the template, as in vphone-cli vm create. --from <step> retries a failed creation from that step, with the options it started with."),Self(name: "vm.set-bundle", arguments: ["name", "version"], options: ["root"], flags: ["update-environment"],summary: "Bind a machine to another installed version; its host programs change at the next start. --update-environment also redeploys that version's guest environment into the stopped machine. The boot chain stays as created."),Self(name: "vm.leases", arguments: [], options: [], flags: ["release"],@@ -199,3 +209,118 @@ nonisolated struct VPhoneLaunchpadControlCommand: Sendable {all.first { $0.name == name }}}++// MARK: - Parsing++/// Why `vphone-launchpad-cli` cannot send a command line: printed as+/// `error: <message>`, then the detail.+nonisolated struct VPhoneLaunchpadControlUsageError: Error, Equatable {+ var message: String+ var detail: String?+}++extension VPhoneLaunchpadControlRequest {+ /// The request for the words after `vphone-launchpad-cli`. `foreground`+ /// is set when `--foreground` is among a command's options.+ static func parse(_ words: [String], foreground: inout Bool) throws(VPhoneLaunchpadControlUsageError) -> Self {+ typealias Failure = VPhoneLaunchpadControlUsageError+ guard let first = words.first else {+ throw Failure(message: "no command. Run vphone-launchpad-cli help.")+ }+ // Two words name a grouped command ("vm start"), one word the others.+ var rest = words+ var command: VPhoneLaunchpadControlCommand?+ if rest.count >= 2, let grouped = VPhoneLaunchpadControlCommand.named("\(rest[0]).\(rest[1])") {+ command = grouped+ rest.removeFirst(2)+ } else if let single = VPhoneLaunchpadControlCommand.named(first) {+ command = single+ rest.removeFirst()+ }+ guard let command else {+ let group = VPhoneLaunchpadControlCommand.all.filter { $0.name.hasPrefix("\(first).") }+ if !group.isEmpty {+ throw Failure(message: "\(first) needs a command.", detail: group.map { " \($0.usage)" }.joined(separator: "\n"))+ }+ throw Failure(message: "unknown command \(words.prefix(2).joined(separator: " ")). Run vphone-launchpad-cli help.")+ }+ var request = Self(command: command.name)+ // exec hands everything after it to vphone-cli untouched, except a+ // leading --bundle that picks whose vphone-cli runs.+ if command.name == "exec" {+ if let first = rest.first, first == "--bundle" || first.hasPrefix("--bundle=") {+ rest.removeFirst()+ if first == "--bundle" {+ guard !rest.isEmpty else {+ throw Failure(message: "--bundle needs a value.")+ }+ request.options["bundle"] = rest.removeFirst()+ } else {+ request.options["bundle"] = String(first.dropFirst("--bundle=".count))+ }+ }+ request.arguments = rest+ return request+ }++ var positional: [String] = []+ var repeated: [String: [String]] = [:]+ var index = 0+ while index < rest.count {+ let word = rest[index]+ index += 1+ if word == "--" {+ positional += rest[index...]+ break+ }+ guard word.hasPrefix("--"), word.count > 2 else {+ positional.append(word)+ continue+ }+ var name = String(word.dropFirst(2))+ var value: String?+ if let equals = name.firstIndex(of: "=") {+ value = String(name[name.index(after: equals)...])+ name = String(name[..<equals])+ }+ if name == "foreground", value == nil {+ foreground = true+ } else if command.flags.contains(name), value == nil {+ request.options[name] = "true"+ } else if command.options.contains(name) || command.repeated.contains(name) {+ if value == nil, index < rest.count {+ value = rest[index]+ index += 1+ }+ guard let value else {+ throw Failure(message: "--\(name) needs a value.")+ }+ if command.repeated.contains(name) {+ repeated[name, default: []].append(value)+ } else {+ request.options[name] = value+ }+ } else {+ throw Failure(message: "unknown option --\(name).", detail: "usage: vphone-launchpad-cli \(command.usage)")+ }+ }++ // A trailing `...` argument may be empty.+ let named = command.takesRest ? command.arguments.count - 1 : command.arguments.count+ guard positional.count >= named, command.takesRest || positional.count == named else {+ throw Failure(message: "wrong number of arguments.", detail: "usage: vphone-launchpad-cli \(command.usage)")+ }+ // The app runs elsewhere; a relative path means nothing to it.+ if command.name == "bundle.install-local" {+ positional[0] = URL(fileURLWithPath: positional[0]).standardizedFileURL.path+ }+ if let root = request.options["root"] {+ request.options["root"] = URL(fileURLWithPath: root).standardizedFileURL.path+ }+ request.arguments = positional+ if !repeated.isEmpty {+ request.repeated = repeated+ }+ return request+ }+}