Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Launcher: the engine channels and the installer (engine updates, part 2)

LNPANDYb9fb766ee799
diff --git a/frontend/Sources/NSPortBuilder/EngineUpdater.swift b/frontend/Sources/NSPortBuilder/EngineUpdater.swift
new file mode 100644
index 00000000..05e79449
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/EngineUpdater.swift
@@ -0,0 +1,124 @@
+import Foundation
+
+/// Which engine the launcher follows, and where its manifest lives.
+///
+/// - `stable` is the engine that shipped with the running app's release: the tested one, and the default.
+/// - `experimental` ("实验版") is the tree the nightly sync built from the newest pin, published as a
+/// pre-release under a fixed tag. It is opt-in, it never carries the app, and it is only checked by CI
+/// (compiled, patches applied, host tests) — not played on hardware.
+enum EngineChannel: String, CaseIterable {
+ case stable, experimental
+
+ /// The pre-release tag the nightly job replaces the experimental engine under. A fixed tag, so the
+ /// launcher's URL never changes; the assets inside are re-uploaded.
+ static let experimentalTag = "engine-experimental"
+ /// Where this repository's release assets live.
+ static let releaseBase = "https://github.com/LNPANDY/NX2Apple/releases/download/"
+
+ /// The manifest for this channel. `version` is the running app's release version, which names the
+ /// stable tag (`v0.7.2`); the experimental channel ignores it.
+ func manifestURL(version: String) -> URL? {
+ switch self {
+ case .stable: return URL(string: Self.releaseBase + "v" + version + "/latest.json")
+ case .experimental: return URL(string: Self.releaseBase + Self.experimentalTag + "/latest.json")
+ }
+ }
+
+ /// Where an asset of this channel lives when the manifest names no source. A manifest that lists
+ /// sources wins: that is how a mirror is introduced without a new launcher.
+ func assetURL(_ name: String, version: String, sources: [String]) -> URL? {
+ if let first = sources.first {
+ let base = first.hasSuffix("/") ? first : first + "/"
+ return URL(string: base + name)
+ }
+ let tag = self == .stable ? "v" + version : Self.experimentalTag
+ return URL(string: Self.releaseBase + tag + "/" + name)
+ }
+}
+
+/// Installing an engine tree: unpack it beside the others, check it is complete, switch to it, and keep
+/// the previous one until the next successful switch (a build started moments ago may still be running).
+enum EngineInstaller {
+ enum Failure: Error, Equatable {
+ case unpack // ditto failed: not a zip, or out of space
+ case incomplete(String) // the tree lacks what the launcher runs by path
+ case move // could not put it in place
+ }
+
+ /// Unpack `zip` into `<store>/<pin>/`. The archive's root is the tree itself
+ /// (`scripts/`, `dm/`, `.upstream-ref`, …), as the release workflow builds it.
+ ///
+ /// Unpacking goes to a hidden folder first and is renamed only when complete, so an interrupted
+ /// download never leaves a tree that looks usable.
+ @discardableResult
+ static func install(zip: URL, pin: String, store: EngineStore, keeping previous: String? = nil) throws -> URL {
+ let fm = FileManager.default
+ let dest = store.directory(for: pin)
+ let tmp = store.root.appendingPathComponent(".tmp-" + UUID().uuidString, isDirectory: true)
+ try? fm.createDirectory(at: store.root, withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: tmp) }
+
+ let ditto = Process()
+ ditto.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")
+ ditto.arguments = ["-x", "-k", zip.path, tmp.path] // the same unpacker the app's own update uses
+ ditto.standardOutput = FileHandle.nullDevice
+ ditto.standardError = FileHandle.nullDevice
+ do { try ditto.run() } catch { throw Failure.unpack }
+ ditto.waitUntilExit()
+ guard ditto.terminationStatus == 0 else { throw Failure.unpack }
+
+ // A release asset may wrap the tree in one folder (`engine/…`, or `<something>/engine/…`): descend
+ // while the folder has no build script and exactly one subdirectory, two levels at most.
+ let marker = "scripts/build_ipa_from_nsp.py"
+ var source = tmp
+ for _ in 0..<2 where !fm.fileExists(atPath: source.appendingPathComponent(marker).path) {
+ let kids = ((try? fm.contentsOfDirectory(at: source, includingPropertiesForKeys: [.isDirectoryKey])) ?? [])
+ .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
+ guard kids.count == 1, let only = kids.first else { break }
+ source = only
+ }
+ guard fm.fileExists(atPath: source.appendingPathComponent("scripts/build_ipa_from_nsp.py").path),
+ fm.fileExists(atPath: source.appendingPathComponent("dm/tools/romfs_image.py").path),
+ fm.fileExists(atPath: source.appendingPathComponent(".upstream-ref").path) else {
+ throw Failure.incomplete(source.lastPathComponent)
+ }
+
+ try? fm.removeItem(at: dest)
+ do { try fm.moveItem(at: source, to: dest) } catch { throw Failure.move }
+ guard store.isUsable(pin) else { throw Failure.incomplete(pin) }
+
+ var keep: Set<String> = [pin]
+ if let previous, previous != pin { keep.insert(previous) }
+ store.prune(keeping: keep)
+ return dest
+ }
+}
+
+/// Which channel and pin the launcher is on, remembered between launches.
+struct EngineSelection: Equatable {
+ var channel: EngineChannel
+ var pin: String // empty: nothing installed by the launcher yet (a developer's checkout)
+ var previousPin: String // the one kept for a build that was already running
+
+ private static let channelKey = "engineChannel"
+ private static let pinKey = "enginePin"
+ private static let previousKey = "enginePreviousPin"
+
+ static func load(_ defaults: UserDefaults = .standard) -> EngineSelection {
+ EngineSelection(channel: EngineChannel(rawValue: defaults.string(forKey: channelKey) ?? "") ?? .stable,
+ pin: defaults.string(forKey: pinKey) ?? "",
+ previousPin: defaults.string(forKey: previousKey) ?? "")
+ }
+
+ func save(_ defaults: UserDefaults = .standard) {
+ defaults.set(channel.rawValue, forKey: Self.channelKey)
+ defaults.set(pin, forKey: Self.pinKey)
+ defaults.set(previousPin, forKey: Self.previousKey)
+ }
+
+ /// Move to a newly installed pin, keeping the one we came from.
+ mutating func switched(to pin: String) {
+ if !self.pin.isEmpty, self.pin != pin { previousPin = self.pin }
+ self.pin = pin
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/EngineUpdaterTests.swift b/frontend/Tests/NSPortBuilderTests/EngineUpdaterTests.swift
new file mode 100644
index 00000000..94376121
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/EngineUpdaterTests.swift
@@ -0,0 +1,128 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// Channels, asset URLs and the installer (EngineUpdater.swift). The archive is built here with `ditto`,
+/// so the unpack path is real; nothing touches the network.
+final class EngineUpdaterTests: XCTestCase {
+ private var root: URL!
+
+ override func setUpWithError() throws {
+ root = FileManager.default.temporaryDirectory.appendingPathComponent("engine-updater-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try? FileManager.default.removeItem(at: root) }
+
+ // MARK: Channels
+
+ func testEachChannelHasItsManifestURL() {
+ XCTAssertEqual(EngineChannel.stable.manifestURL(version: "0.7.2")?.absoluteString,
+ "https://github.com/LNPANDY/NX2Apple/releases/download/v0.7.2/latest.json")
+ XCTAssertEqual(EngineChannel.experimental.manifestURL(version: "0.7.2")?.absoluteString,
+ "https://github.com/LNPANDY/NX2Apple/releases/download/engine-experimental/latest.json",
+ "the experimental tag is fixed: the nightly job replaces the assets inside it")
+ }
+
+ func testAnAssetComesFromTheManifestSourcesWhenItNamesThem() {
+ let url = EngineChannel.stable.assetURL("engine.zip", version: "0.7.2", sources: ["https://mirror.invalid/v0.7.2"])
+ XCTAssertEqual(url?.absoluteString, "https://mirror.invalid/v0.7.2/engine.zip")
+ let withSlash = EngineChannel.stable.assetURL("engine.zip", version: "0.7.2", sources: ["https://mirror.invalid/v0.7.2/"])
+ XCTAssertEqual(withSlash?.absoluteString, "https://mirror.invalid/v0.7.2/engine.zip", "no doubled slash")
+ }
+
+ func testAnAssetFallsBackToTheChannelTag() {
+ XCTAssertEqual(EngineChannel.stable.assetURL("engine.zip", version: "0.7.2", sources: [])?.absoluteString,
+ "https://github.com/LNPANDY/NX2Apple/releases/download/v0.7.2/engine.zip")
+ XCTAssertEqual(EngineChannel.experimental.assetURL("engine.zip", version: "0.7.2", sources: [])?.absoluteString,
+ "https://github.com/LNPANDY/NX2Apple/releases/download/engine-experimental/engine.zip")
+ }
+
+ // MARK: Installing
+
+ /// A tree as the release publishes it: the files the launcher runs by path, at the archive's root.
+ private func makeTree(_ name: String = "tree") throws -> URL {
+ let fm = FileManager.default
+ let dir = root.appendingPathComponent(name, isDirectory: true)
+ try fm.createDirectory(at: dir.appendingPathComponent("scripts"), withIntermediateDirectories: true)
+ try fm.createDirectory(at: dir.appendingPathComponent("dm/tools"), withIntermediateDirectories: true)
+ try Data("print()".utf8).write(to: dir.appendingPathComponent("scripts/build_ipa_from_nsp.py"))
+ try Data([0]).write(to: dir.appendingPathComponent("dm/tools/romfs_image.py"))
+ try Data("ee6648cb".utf8).write(to: dir.appendingPathComponent(".upstream-ref"))
+ return dir
+ }
+
+ private func zip(_ source: URL) throws -> URL {
+ let out = root.appendingPathComponent(UUID().uuidString + ".zip")
+ let ditto = Process()
+ ditto.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")
+ ditto.arguments = ["-c", "-k", "--keepParent", source.path, out.path]
+ try ditto.run(); ditto.waitUntilExit()
+ XCTAssertEqual(ditto.terminationStatus, 0, "test archive")
+ return out
+ }
+
+ func testInstallingATreeMakesItUsableAndKeepsTheChosenPins() throws {
+ let store = EngineStore(root: root.appendingPathComponent("engine"))
+ let archive = try zip(makeTree())
+
+ try EngineInstaller.install(zip: archive, pin: "aaaaaaa", store: store)
+ XCTAssertTrue(store.isUsable("aaaaaaa"))
+
+ try EngineInstaller.install(zip: archive, pin: "bbbbbbb", store: store, keeping: "aaaaaaa")
+ XCTAssertTrue(store.isUsable("bbbbbbb"))
+ XCTAssertTrue(store.isUsable("aaaaaaa"), "the previous pin stays for a build that is still running")
+
+ try EngineInstaller.install(zip: archive, pin: "ccccccc", store: store, keeping: "bbbbbbb")
+ XCTAssertTrue(store.isUsable("ccccccc"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: store.directory(for: "aaaaaaa").path), "older trees are pruned")
+ }
+
+ /// A release may wrap the tree in one folder; the installer takes that level.
+ func testAWrappedTreeIsFound() throws {
+ let store = EngineStore(root: root.appendingPathComponent("engine"))
+ let wrapped = root.appendingPathComponent("wrap", isDirectory: true)
+ try FileManager.default.createDirectory(at: wrapped, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: try makeTree(), to: wrapped.appendingPathComponent("engine"))
+ try EngineInstaller.install(zip: try zip(wrapped), pin: "ddddddd", store: store)
+ XCTAssertTrue(store.isUsable("ddddddd"))
+ }
+
+ func testAnIncompleteTreeIsRefusedAndNothingIsLeftBehind() throws {
+ let store = EngineStore(root: root.appendingPathComponent("engine"))
+ let broken = root.appendingPathComponent("broken", isDirectory: true)
+ try FileManager.default.createDirectory(at: broken.appendingPathComponent("scripts"), withIntermediateDirectories: true)
+ try Data([0]).write(to: broken.appendingPathComponent("scripts/build_ipa_from_nsp.py")) // no dm/tools, no .upstream-ref
+ XCTAssertThrowsError(try EngineInstaller.install(zip: try zip(broken), pin: "eeeeeee", store: store)) { error in
+ guard case EngineInstaller.Failure.incomplete = error else { return XCTFail("\(error)") }
+ }
+ XCTAssertFalse(FileManager.default.fileExists(atPath: store.directory(for: "eeeeeee").path))
+ }
+
+ func testSomethingThatIsNotAnArchiveFails() throws {
+ let store = EngineStore(root: root.appendingPathComponent("engine"))
+ let notZip = root.appendingPathComponent("nope.zip")
+ try Data("not a zip".utf8).write(to: notZip)
+ XCTAssertThrowsError(try EngineInstaller.install(zip: notZip, pin: "fffffff", store: store)) { error in
+ XCTAssertEqual(error as? EngineInstaller.Failure, .unpack)
+ }
+ }
+
+ // MARK: Remembering the choice
+
+ func testTheSelectionSurvivesAndRemembersWhereItCameFrom() {
+ let suite = UserDefaults(suiteName: "engine-selection-" + UUID().uuidString)!
+ var s = EngineSelection.load(suite)
+ XCTAssertEqual(s.channel, .stable, "stable by default")
+ XCTAssertEqual(s.pin, "")
+
+ s.channel = .experimental
+ s.switched(to: "aaaaaaa"); s.save(suite)
+ XCTAssertEqual(EngineSelection.load(suite).pin, "aaaaaaa")
+ XCTAssertEqual(EngineSelection.load(suite).channel, .experimental)
+
+ s.switched(to: "bbbbbbb"); s.save(suite)
+ let back = EngineSelection.load(suite)
+ XCTAssertEqual(back.pin, "bbbbbbb")
+ XCTAssertEqual(back.previousPin, "aaaaaaa", "the pin we came from is kept")
+ }
+}