Skip to content

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

Launcher: update the build tools when the app opens

v0lumehi66a261074f8c
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 1ba479ca..f7d082b3 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -295,6 +295,13 @@ final class BuildModel: ObservableObject {
@Published var repoStatus = ""
/// nil = not checked yet, 0 = up to date, n = n commits behind origin/main.
@Published var repoBehind: Int?
+ /// Pull origin/main by itself when the app opens (Settings; on by default), so the build tools are the current ones:
+ /// a checkout days behind built with tools main had already fixed (spirv-cross without its x bit, #41).
+ @Published var autoUpdateRepo = UserDefaults.standard.object(forKey: "autoUpdateRepo") as? Bool ?? true {
+ didSet { UserDefaults.standard.set(autoUpdateRepo, forKey: "autoUpdateRepo") }
+ }
+ /// The commits the automatic update brought when the app opened; the library's activity line names them. nil: none.
+ @Published var autoPulled: Int?
nonisolated static func gitBinary() -> String? {
for c in ["/usr/bin/git", "/opt/homebrew/bin/git", "/usr/local/bin/git"]
@@ -373,6 +380,7 @@ final class BuildModel: ObservableObject {
if behind >= 0 {
self.repoBehind = behind
if !silent { self.repoStatus = behind == 0 ? self.t("repo.upToDate") : String(format: self.t("repo.behind"), behind) }
+ else if behind > 0 && self.autoUpdateRepo { self.autoPull(behind) } // the check when the app opens
} else if !silent {
self.repoStatus = self.t("repo.netFail")
}
@@ -401,6 +409,38 @@ final class BuildModel: ObservableObject {
}
}
+ /// The automatic update when the app opens: a fast-forward to origin/main, only for a checkout on main with no changes
+ /// to its tracked files and no build running, so a checkout someone works in is never touched. Settings says what
+ /// happened (or why not), and the library's activity line names the new commits.
+ func autoPull(_ behind: Int) {
+ guard !running, !repoBusy, repoOK, repoIsGit, let git = Self.gitBinary() else { return }
+ repoBusy = true
+ let dir = repoPath
+ DispatchQueue.global().async {
+ let branch = Self.runQuiet([git, "-C", dir, "rev-parse", "--abbrev-ref", "HEAD"], env: Self.gitEnv())
+ let status = Self.runQuiet([git, "-C", dir, "status", "--porcelain", "--untracked-files=no"], env: Self.gitEnv())
+ let allowed = branch.ok && status.ok && Self.autoPullAllowed(branch: branch.out, status: status.out)
+ let pulled = allowed ? Self.runQuiet([git, "-C", dir, "pull", "--ff-only", "origin", "main"], env: Self.gitEnv()) : nil
+ DispatchQueue.main.async {
+ self.repoBusy = false
+ guard let pulled else { self.repoStatus = self.t("repo.autoSkipped"); return }
+ if pulled.ok {
+ self.repoBehind = 0; self.autoPulled = behind
+ self.repoStatus = String(format: self.t("repo.autoPulled"), behind)
+ } else {
+ self.repoStatus = self.t("repo.pullFail")
+ self.append(pulled.out + "\n")
+ }
+ }
+ }
+ }
+
+ /// A checkout the automatic update may move: on main, with no changes to tracked files (untracked files stay; a pull
+ /// that would overwrite one fails as a fast-forward and says so).
+ nonisolated static func autoPullAllowed(branch: String, status: String) -> Bool {
+ branch.trimmingCharacters(in: .whitespacesAndNewlines) == "main" && status.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
/// A ZIP copy has no .git: adopt it into git in place (init, remote, fetch, checkout) so the
/// update buttons work and the folder keeps its path. A ZIP copy carries no local changes, and
/// the checkout resets it to origin/main — the build's own files live outside the repository.
@@ -2208,6 +2248,12 @@ struct BuilderView: View {
Text(m.t("repo.noGit")).font(.manrope(12)).foregroundStyle(.secondary)
.padding(.horizontal, 18).padding(.bottom, 12)
}
+ if m.repoOK, m.repoIsGit {
+ divider
+ row(m.t("repo.auto"), detail: m.t("repo.autoNote")) {
+ Toggle("", isOn: $m.autoUpdateRepo).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ }
+ }
divider
Button(action: { withAnimation(.easeInOut(duration: 0.18)) { m.toggleDeps() } }) {
row(m.t("dep.title"),
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 0da50194..25d204e1 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -455,6 +455,11 @@ struct ContentView: View {
} else {
Image(systemName: "desktopcomputer").foregroundStyle(.secondary)
Text(m.t("library.localNote")).font(.manrope(13)).foregroundStyle(.secondary)
+ if let n = m.autoPulled, n > 0 {
+ // The automatic update when the app opened (BuildModel.autoPull): the build tools are the current ones
+ Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6).padding(.leading, 10)
+ Text(String(format: m.t("library.toolsUpdated"), n)).font(.manrope(13)).foregroundStyle(.secondary)
+ }
Spacer()
if gamepad.connected {
// The buttons a controller has here, named as the game names them (A on the right)
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index cb3b82cb..fa311e35 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -206,6 +206,11 @@ enum L10n {
"repo.pull": ("拉取更新", "Pull updates"),
"repo.pulling": ("正在更新…(构建不受影响,之前的构建文件不在仓库里)",
"Updating… (your builds are safe — their files live outside the repository)"),
+ "repo.auto": ("打开时自动更新", "Update automatically when the app opens"),
+ "repo.autoNote": ("仅限 main 分支且没有本地改动的仓库", "Only a checkout on main with no local changes"),
+ "repo.autoPulled": ("打开时已自动更新:%ld 个新提交", "Updated automatically when the app opened: %ld new commits"),
+ "repo.autoSkipped": ("未自动更新:仓库有本地改动或不在 main 分支", "Not updated automatically: the checkout has local changes or is not on main"),
+ "library.toolsUpdated": ("构建工具已更新:%ld 个新提交", "Build tools updated: %ld new commits"),
"repo.pulled": ("已更新到最新", "Updated to the latest"),
"repo.pullFail": ("更新失败——详情见日志(本地文件被改过?)",
"Update failed — see the log (local changes?)"),
diff --git a/frontend/Tests/NSPortBuilderTests/RepoAutoUpdateTests.swift b/frontend/Tests/NSPortBuilderTests/RepoAutoUpdateTests.swift
new file mode 100644
index 00000000..ca47dce8
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/RepoAutoUpdateTests.swift
@@ -0,0 +1,80 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// The automatic update when the app opens (BuildModel.autoPull): a clean checkout on main fast-forwards to origin/main,
+/// one with local changes is left as it is. A local bare repository stands in for GitHub.
+final class RepoAutoUpdateTests: XCTestCase {
+ private var temporary: URL!
+ private var saved: [(String, Any?)] = []
+
+ override func setUpWithError() throws {
+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-repo-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ saved = ["repoPath", "autoUpdateRepo"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ }
+
+ override func tearDownWithError() throws {
+ for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) }
+ try? FileManager.default.removeItem(at: temporary)
+ }
+
+ @discardableResult private func git(_ args: String..., in dir: URL) throws -> String {
+ let r = BuildModel.runQuiet(["/usr/bin/git", "-C", dir.path] + args, env: BuildModel.gitEnv())
+ guard r.ok else { throw NSError(domain: "git", code: 1, userInfo: [NSLocalizedDescriptionKey: "git \(args.joined(separator: " ")): \(r.out)"]) }
+ return r.out.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ /// origin (bare) with two commits on main, and a checkout of the first: one commit behind
+ private func fixture() throws -> URL {
+ let origin = temporary.appendingPathComponent("origin.git"), work = temporary.appendingPathComponent("work")
+ let checkout = temporary.appendingPathComponent("checkout")
+ try FileManager.default.createDirectory(at: origin, withIntermediateDirectories: true)
+ try git("init", "--bare", "-b", "main", in: origin)
+ try git("clone", origin.path, work.path, in: temporary)
+ let marker = work.appendingPathComponent("dm/tools/nx_extract/Program.cs") // what makes it a repository to the launcher
+ try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try "one".write(to: marker, atomically: true, encoding: .utf8)
+ try git("add", ".", in: work); try git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-m", "one", in: work)
+ try git("push", "origin", "HEAD:main", in: work)
+ try git("clone", "-b", "main", origin.path, checkout.path, in: temporary)
+ try "two".write(to: marker, atomically: true, encoding: .utf8)
+ try git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-am", "two", in: work)
+ try git("push", "origin", "HEAD:main", in: work)
+ return checkout
+ }
+
+ @MainActor private func open(_ checkout: URL) -> BuildModel {
+ let m = BuildModel()
+ m.repoPath = checkout.path
+ m.autoUpdateRepo = true
+ m.checkRepoUpdates(silent: true) // what the library does when the app opens
+ let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repoBusy && m.repoBehind != nil && (m.autoPulled != nil || !m.repoStatus.isEmpty) }, object: nil)
+ wait(for: [settled], timeout: 20)
+ return m
+ }
+
+ @MainActor func testACleanCheckoutOnMainIsUpdatedWhenTheAppOpens() throws {
+ let checkout = try fixture()
+ let m = open(checkout)
+ XCTAssertEqual(m.autoPulled, 1)
+ XCTAssertEqual(m.repoBehind, 0)
+ XCTAssertEqual(try git("log", "-1", "--format=%s", in: checkout), "two")
+ }
+
+ @MainActor func testACheckoutWithLocalChangesIsLeftAsItIs() throws {
+ let checkout = try fixture()
+ try "mine".write(to: checkout.appendingPathComponent("dm/tools/nx_extract/Program.cs"), atomically: true, encoding: .utf8)
+ let m = open(checkout)
+ XCTAssertNil(m.autoPulled)
+ XCTAssertEqual(m.repoStatus, m.t("repo.autoSkipped"))
+ XCTAssertEqual(try git("log", "-1", "--format=%s", in: checkout), "one")
+ }
+
+ func testOnlyMainWithoutTrackedChangesMayBeMoved() {
+ XCTAssertTrue(BuildModel.autoPullAllowed(branch: "main\n", status: ""))
+ XCTAssertFalse(BuildModel.autoPullAllowed(branch: "device-install", status: ""))
+ XCTAssertFalse(BuildModel.autoPullAllowed(branch: "main", status: " M scripts/build_ipa_from_nsp.py\n"))
+ XCTAssertFalse(BuildModel.autoPullAllowed(branch: "HEAD", status: ""), "a detached HEAD is not main")
+ }
+}