Skip to content

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

Connecting a ZIP copy to git keeps the copy as it was on a local branch before the checkout overwrites it (#87)

v0lumehie65f5a8cbeb3
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 58420bfc..29a1542f 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -483,6 +483,13 @@ final class BuildModel: ObservableObject {
branch.trimmingCharacters(in: .whitespacesAndNewlines) == "main" && status.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
+ /// The local branch that keeps a ZIP copy as it was when it is connected to git.
+ nonisolated static func zipCopyBranch(date: Date = Date()) -> String {
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd"
+ return "zip-copy-" + f.string(from: date)
+ }
+
/// What the launch does with the configured repository when it is a copy without .git (#87: a ZIP copy never updated
/// itself, so its build tools were older than the app).
enum ZipAdoption: Equatable { case notNeeded, adopt, waitsForBuild, autoUpdateOff }
@@ -509,8 +516,12 @@ final class BuildModel: ObservableObject {
}
/// 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.
+ /// update buttons work and the folder keeps its path. The copy may hold the player's own edits (a tweaked game
+ /// profile), and the checkout resets every tracked file to origin/main, so the copy is recorded first: after the
+ /// fetch, the files of the copy that origin/main also has are committed on the local branch `zip-copy-<date>`
+ /// (fixed local author, no git identity needed). Only those paths: a build folder or any other file that origin/main
+ /// does not track is never committed (and the checkout leaves such files where they are). The build's own files live
+ /// outside the repository.
/// `automatic`: the launch-time adoption (adoptAtLaunch); `remote` is GitHub unless a test points it at a local repository.
func adoptRepoAsGit(automatic: Bool = false, remote: String = BuildModel.repoURL) {
guard !running, !repoBusy, repoOK, !repoIsGit, let git = Self.gitBinary() else { return }
@@ -518,12 +529,26 @@ final class BuildModel: ObservableObject {
let dir = repoPath
DispatchQueue.global().async {
var out = "", ok = true
- for args in [["init"], ["remote", "add", "origin", remote],
- ["fetch", "--depth", "1", "origin", "main"],
- ["checkout", "-f", "-B", "main", "origin/main"]] {
+ let branch = Self.zipCopyBranch()
+ func run(_ args: [String]) -> (ok: Bool, out: String) {
let r = Self.runQuiet([git, "-C", dir] + args, env: Self.gitEnv())
out += "$ git \(args.joined(separator: " "))\n\(r.out)\n"
- if !r.ok { ok = false; break }
+ return r
+ }
+ // Nothing in the folder changes before the fetch has worked, so an offline failure leaves the copy as it was.
+ ok = run(["init"]).ok && run(["remote", "add", "origin", remote]).ok && run(["fetch", "--depth", "1", "origin", "main"]).ok
+ if ok {
+ let tree = run(["ls-tree", "-r", "-z", "--name-only", "origin/main"])
+ let present = tree.out.split(separator: "\0").map(String.init).filter { FileManager.default.fileExists(atPath: dir + "/" + $0) }
+ let list = NSTemporaryDirectory() + "nspb-zip-paths-\(UUID().uuidString.prefix(8)).txt"
+ defer { try? FileManager.default.removeItem(atPath: list) }
+ let identity = ["-c", "user.name=NX2Apple", "-c", "user.email=nx2apple@localhost", "-c", "commit.gpgsign=false"]
+ ok = tree.ok
+ && run(["symbolic-ref", "HEAD", "refs/heads/" + branch]).ok
+ && ((try? Data(present.joined(separator: "\0").utf8).write(to: URL(fileURLWithPath: list))) != nil)
+ && run(["add", "--pathspec-from-file=" + list, "--pathspec-file-nul"]).ok
+ && run(identity + ["commit", "--allow-empty", "-m", "The ZIP copy as it was before it was connected to git"]).ok
+ && run(["checkout", "-f", "-B", "main", "origin/main"]).ok
}
if ok { _ = Self.runQuiet([git, "-C", dir, "branch", "--set-upstream-to=origin/main", "main"], env: Self.gitEnv()) } // checkout -B usually set it
// A failed adoption (offline) must not leave the .git that `git init` made: the copy would count as a
@@ -536,8 +561,8 @@ final class BuildModel: ObservableObject {
if ok && self.repoIsGit {
// the checkout is origin/main as just fetched: up to date, nothing left to pull
self.repoBehind = 0
- if automatic { self.autoAdopted = true; self.repoStatus = self.t("repo.adoptedAuto") }
- else { self.repoStatus = self.t("repo.adopted"); self.checkRepoUpdates() }
+ self.repoStatus = String(format: self.t(automatic ? "repo.adoptedAuto" : "repo.adopted"), branch)
+ if automatic { self.autoAdopted = true }
} else {
self.repoStatus = self.t(automatic ? "repo.adoptFailAuto" : "repo.adoptFail")
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index f55b225e..0e24899b 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -248,9 +248,9 @@ enum L10n {
"This is a ZIP copy (no git history); builds work fine — Make updatable connects it to git"),
"repo.adopt": ("接入 git(可更新)", "Make updatable (git)"),
"repo.adopting": ("正在接入 git…", "Connecting git…"),
- "repo.adopted": ("已接入 git,可以检查更新了", "Connected — updates work now"),
+ "repo.adopted": ("已接入 git,可以更新了;原来的文件保存在分支 %@", "Connected — updates work now. Your previous files are kept on branch %@"),
"repo.adoptFail": ("接入失败——详情见日志", "Connect failed — see the log"),
- "repo.adoptedAuto": ("打开时已接入 git 并更新到最新版本", "Connected to git and updated when the app opened"),
+ "repo.adoptedAuto": ("打开时已接入 git 并更新到最新版本;原来的文件保存在分支 %@", "Connected to git and updated when the app opened. Your previous files are kept on branch %@"),
"repo.adoptFailAuto": ("打开时未能接入 git(网络不通?详情见日志)——点「接入 git」重试",
"Could not connect to git when the app opened (offline? see the log) — try Make updatable"),
"repo.zipWaits": ("构建运行中,暂不接入 git——构建结束后重启 App 或点「接入 git」",
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index 6c484a3e..bb86d020 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -706,7 +706,7 @@ final class LibraryTests: XCTestCase {
model.autoUpdateRepo = false
try capture("settings-zip-auto-off", page: .settings)
model.autoUpdateRepo = true
- model.repoStatus = model.t("repo.adoptedAuto")
+ model.repoStatus = String(format: model.t("repo.adoptedAuto"), "zip-copy-2026-10-27")
model.autoAdopted = true
try capture("library-adopted")
model.autoAdopted = false
diff --git a/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift b/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift
index 614b4acb..2d63c873 100644
--- a/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift
@@ -110,12 +110,30 @@ final class RepoToolsTests: XCTestCase {
let m = openZip(f, auto: true)
XCTAssertTrue(m.repoIsGit)
XCTAssertTrue(m.autoAdopted)
- XCTAssertEqual(m.repoStatus, m.t("repo.adoptedAuto"))
+ XCTAssertEqual(m.repoStatus, String(format: m.t("repo.adoptedAuto"), BuildModel.zipCopyBranch()))
XCTAssertEqual(BuildModel.missingTools(in: f.zip.path), [], "the tools of origin/main are there now")
XCTAssertEqual(try git("rev-parse", "--abbrev-ref", "HEAD", in: f.zip), "main")
XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(BuildModel.buildScript), encoding: .utf8), "new")
}
+ @MainActor func testTheCopyIsKeptOnABranchBeforeTheCheckoutOverwritesIt() throws {
+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
+ let f = try fixture()
+ try "my tweak".write(to: f.zip.appendingPathComponent(BuildModel.buildScript), atomically: true, encoding: .utf8) // an edited tracked file
+ try write(["dm/mine/notes.txt"], in: f.zip, text: "mine") // a file origin does not have
+ try write(["dm/tools/build/huge.bin"], in: f.zip, text: "build output")
+ let m = openZip(f, auto: true)
+ let branch = BuildModel.zipCopyBranch()
+ XCTAssertEqual(try git("show", "main:" + BuildModel.buildScript, in: f.zip), "new", "main has origin's version")
+ XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(BuildModel.buildScript), encoding: .utf8), "new")
+ XCTAssertEqual(try git("show", branch + ":" + BuildModel.buildScript, in: f.zip), "my tweak", "the branch has the edit")
+ XCTAssertEqual(try git("ls-tree", "-r", "--name-only", branch, in: f.zip).split(separator: "\n").map(String.init).sorted(),
+ ["dm/tools/nx_extract/Program.cs", BuildModel.buildScript].sorted(), "only paths origin tracks are recorded")
+ XCTAssertEqual(try git("log", "-1", "--format=%an", branch, in: f.zip), "NX2Apple")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: f.zip.appendingPathComponent("dm/mine/notes.txt").path), "untracked files stay where they are")
+ XCTAssertTrue(m.repoStatus.contains(branch), m.repoStatus)
+ }
+
@MainActor func testWithTheAutomaticUpdateOffTheZipCopyIsLeftAlone() throws {
guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
let f = try fixture()
@@ -133,5 +151,7 @@ final class RepoToolsTests: XCTestCase {
XCTAssertEqual(m.repoStatus, m.t("repo.adoptFailAuto"))
XCTAssertFalse(m.autoAdopted)
XCTAssertTrue(BuildModel.isRepo(f.zip.path), "the files are still there")
+ XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(BuildModel.buildScript), encoding: .utf8), "old", "nothing was changed")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: f.zip.appendingPathComponent(".git").path))
}
}