Skip to content

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

A ZIP copy of the repository is connected to git when the app opens, and a build with tools older than the app refuses to start (#87)

v0lumehi1fb5035f3833
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 5ec6e955..58420bfc 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -256,12 +256,25 @@ final class BuildModel: ObservableObject {
FileManager.default.fileExists(atPath: dir + "/dm/tools/nx_extract/Program.cs")
}
+ /// Every file of the repository the launcher itself runs by path: one list, next to the calls that use it
+ /// (the build script in startBuild, the RomFS archive in the archive step). A copy older than this app lacks some of
+ /// them (#87: romfs_image.py exists since v0.4.8, so a build ran 70 minutes and failed at its last step). A new
+ /// tool the launcher calls goes into this list and is then checked before every build.
+ nonisolated static let buildScript = "scripts/build_ipa_from_nsp.py"
+ nonisolated static let romfsImageTool = "dm/tools/romfs_image.py"
+ nonisolated static let requiredTools = [buildScript, romfsImageTool]
+
+ /// The tools of `requiredTools` that `dir` does not have (empty: the build tools are as new as this app needs).
+ nonisolated static func missingTools(in dir: String) -> [String] {
+ requiredTools.filter { !FileManager.default.fileExists(atPath: dir + "/" + $0) }
+ }
+
/// Whether the checkout's build script has this fork's `--work-dir` (issue #5): an upstream
/// nxnative checkout, or a ZIP of an older release, stops with "unrecognized arguments" when the
/// app passes it. Read from the script's own argparse rather than assumed — the option is the
/// fork's, not upstream's.
nonisolated static func repoSupportsWorkDir(_ dir: String) -> Bool {
- let script = dir + "/scripts/build_ipa_from_nsp.py"
+ let script = dir + "/" + buildScript
guard let text = try? String(contentsOfFile: script, encoding: .utf8) else { return false }
return text.contains("'--work-dir'") || text.contains("\"--work-dir\"")
}
@@ -321,6 +334,8 @@ final class BuildModel: ObservableObject {
}
/// The commits the automatic update brought when the app opened; the library's activity line names them. nil: none.
@Published var autoPulled: Int?
+ /// A copy without .git was connected to git and brought to the current version when the app opened (adoptAtLaunch).
+ @Published var autoAdopted = false
nonisolated static func gitBinary() -> String? {
for c in ["/usr/bin/git", "/opt/homebrew/bin/git", "/usr/local/bin/git"]
@@ -468,16 +483,42 @@ final class BuildModel: ObservableObject {
branch.trimmingCharacters(in: .whitespacesAndNewlines) == "main" && status.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
+ /// 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 }
+
+ /// Pure: adopt a valid checkout without .git into git, but never while a build runs (or another repository task),
+ /// and not when the player turned the automatic update off.
+ nonisolated static func zipAdoption(isRepo: Bool, isGit: Bool, buildRunning: Bool, repoBusy: Bool, autoUpdate: Bool) -> ZipAdoption {
+ guard isRepo, !isGit else { return .notNeeded }
+ if buildRunning || repoBusy { return .waitsForBuild }
+ return autoUpdate ? .adopt : .autoUpdateOff
+ }
+
+ /// The launch-time step for a ZIP copy; a git checkout is left to checkRepoUpdates. Settings and the library's
+ /// activity line say what happened.
+ func adoptAtLaunch(remote: String = BuildModel.repoURL) {
+ switch Self.zipAdoption(isRepo: repoOK, isGit: repoIsGit, buildRunning: running, repoBusy: repoBusy, autoUpdate: autoUpdateRepo) {
+ case .notNeeded: break
+ case .waitsForBuild: repoStatus = t("repo.zipWaits")
+ case .autoUpdateOff: break // Settings says so next to the repository (repo.zipNoAuto): the player chose this
+ case .adopt:
+ if Self.gitBinary() == nil { repoStatus = t("repo.gitMissing") }
+ else { adoptRepoAsGit(automatic: true, remote: remote) }
+ }
+ }
+
/// 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.
- func adoptRepoAsGit() {
+ /// `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 }
repoBusy = true; repoStatus = t("repo.adopting")
let dir = repoPath
DispatchQueue.global().async {
var out = "", ok = true
- for args in [["init"], ["remote", "add", "origin", Self.repoURL],
+ for args in [["init"], ["remote", "add", "origin", remote],
["fetch", "--depth", "1", "origin", "main"],
["checkout", "-f", "-B", "main", "origin/main"]] {
let r = Self.runQuiet([git, "-C", dir] + args, env: Self.gitEnv())
@@ -485,14 +526,20 @@ final class BuildModel: ObservableObject {
if !r.ok { ok = false; break }
}
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
+ // checkout from then on, and neither the launch nor the button would try again. The guard above
+ // means there was no .git before, so this removes only what this call created.
+ if !ok { try? FileManager.default.removeItem(atPath: dir + "/.git") }
DispatchQueue.main.async {
self.repoBusy = false
self.append(out + "\n")
- if self.repoIsGit {
- self.repoStatus = self.t("repo.adopted")
- self.checkRepoUpdates()
+ 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() }
} else {
- self.repoStatus = self.t("repo.adoptFail")
+ self.repoStatus = self.t(automatic ? "repo.adoptFailAuto" : "repo.adoptFail")
}
}
}
@@ -910,6 +957,12 @@ final class BuildModel: ObservableObject {
// empty, and the old fallback was Apple's /usr/bin/python3 (3.9), which the script then
// rejected with "require Python 3.12 or newer" whatever the machine actually had (#53).
let py = pythonPath.isEmpty ? Self.findPython().path : pythonPath
+ // The tools this app runs, before a build that takes an hour finds one missing at its last step (#87)
+ let missing = Self.missingTools(in: repoPath)
+ if !missing.isEmpty {
+ fail(String(format: t("msg.toolsOld"), missing.joined(separator: ", ")))
+ return
+ }
// One folder when everything lives together; otherwise a staging folder of symlinks. A folder
// that holds other games too (a ROMs folder with one file per game) is staged as well: the
@@ -985,7 +1038,7 @@ final class BuildModel: ObservableObject {
return
}
}
- var args = [repoPath + "/scripts/build_ipa_from_nsp.py", inputDir, "-k", keysPath,
+ var args = [repoPath + "/" + Self.buildScript, inputDir, "-k", keysPath,
"--progress", "json"]
// A compatibility switch the player turned on: written to a small env file the pipeline
// copies into the app bundle (main.m sets one variable per line at boot). Only for an IPA;
@@ -1470,7 +1523,7 @@ final class BuildModel: ObservableObject {
let p = Process()
p.executableURL = URL(fileURLWithPath: pythonPath.isEmpty ? "/usr/bin/python3" : pythonPath)
// dest/romfs.img: one file, which main.m's per-game lookup takes before any folder.
- p.arguments = [repoPath + "/dm/tools/romfs_image.py", "--reuse", romfs, dest + "/romfs.img"]
+ p.arguments = [repoPath + "/" + Self.romfsImageTool, "--reuse", romfs, dest + "/romfs.img"]
p.environment = ["PATH": "/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", "PYTHONPATH": repoPath + "/dm/tools"]
Self.inOwnGroup(p, python: p.executableURL!.path)
let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe
@@ -2635,10 +2688,15 @@ struct BuilderView: View {
.font(.manrope(12)).padding(.horizontal, 18).padding(.bottom, 12)
}
if m.repoOK, !m.repoIsGit {
- Text(m.t("repo.noGit")).font(.manrope(12)).foregroundStyle(.secondary)
+ Text(m.t(m.autoUpdateRepo ? "repo.noGit" : "repo.zipNoAuto")).font(.manrope(12)).foregroundStyle(.secondary)
+ .padding(.horizontal, 18).padding(.bottom, 12)
+ }
+ if m.repoOK, !BuildModel.missingTools(in: m.repoPath).isEmpty {
+ Text(String(format: m.t("repo.toolsOld"), BuildModel.missingTools(in: m.repoPath).joined(separator: ", ")))
+ .font(.manrope(12)).foregroundStyle(LauncherPalette.building)
.padding(.horizontal, 18).padding(.bottom, 12)
}
- if m.repoOK, m.repoIsGit {
+ if m.repoOK { // a ZIP copy too: its adoption at launch follows this switch
divider
row(m.t("repo.auto"), detail: m.t("repo.autoNote")) {
Toggle("", isOn: $m.autoUpdateRepo).labelsHidden().toggleStyle(LauncherSwitchStyle())
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 20286b83..278fd4ed 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -90,7 +90,7 @@ struct ContentView: View {
if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }
if performStartupChecks {
m.checkDeps()
- if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) }
+ if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) } else { m.adoptAtLaunch() }
m.checkAppUpdate(silent: true)
BuildNotifier.shared.watch(m, library: library) // BuildNotifications.swift
}
@@ -519,6 +519,11 @@ struct ContentView: View {
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)
}
+ if m.autoAdopted {
+ // A ZIP copy connected to git and updated when the app opened (BuildModel.adoptAtLaunch)
+ Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6).padding(.leading, 10)
+ Text(m.t("library.toolsAdopted")).font(.manrope(13)).foregroundStyle(.secondary)
+ }
Spacer()
if let staged = m.appStaged {
// A downloaded, verified update (BuildModel.stageAppUpdate): it goes in when the app quits, or now.
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 0764d70c..f55b225e 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -250,6 +250,18 @@ enum L10n {
"repo.adopting": ("正在接入 git…", "Connecting git…"),
"repo.adopted": ("已接入 git,可以检查更新了", "Connected — updates work now"),
"repo.adoptFail": ("接入失败——详情见日志", "Connect failed — see the log"),
+ "repo.adoptedAuto": ("打开时已接入 git 并更新到最新版本", "Connected to git and updated when the app opened"),
+ "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」",
+ "A build is running, so the copy is not connected to git yet — restart the app after it, or use Make updatable"),
+ "repo.zipNoAuto": ("这是 ZIP 副本,无法自行更新,构建工具可能比 App 旧:点「接入 git」,或打开「打开时自动更新」",
+ "This ZIP copy cannot update itself, so its build tools may be older than the app: use Make updatable, or turn on “Update automatically when the app opens”"),
+ "repo.toolsOld": ("构建工具比本 App 旧(缺少 %@)——请更新(点「接入 git」或「拉取更新」)",
+ "The build tools are older than this app (missing %@) — update them (Make updatable or Pull updates)"),
+ "library.toolsAdopted": ("构建工具已接入 git 并更新", "Build tools connected to git and updated"),
+ "msg.toolsOld": ("构建工具比本 App 旧(缺少 %@),构建未开始——先在设置 → 构建工具中更新",
+ "Build not started: the build tools are older than this app (missing %@). Update them in Settings → Build tools first"),
// ---- app self-update ----
"app.checking": ("正在检查 App 更新…", "Checking for a new app version…"),
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index aa256301..6c484a3e 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -239,6 +239,11 @@ final class LibraryTests: XCTestCase {
let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")
try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data().write(to: marker)
+ try BuildModel.requiredTools.filter { $0 != BuildModel.buildScript }.forEach { tool in // the other files the build checks for (#87)
+ let url = temporary.appendingPathComponent(tool)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: url)
+ }
let script = temporary.appendingPathComponent("scripts/build_ipa_from_nsp.py")
try FileManager.default.createDirectory(at: script.deletingLastPathComponent(), withIntermediateDirectories: true)
try """
@@ -311,6 +316,11 @@ final class LibraryTests: XCTestCase {
try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data().write(to: marker)
let calls = temporary.appendingPathComponent("calls.txt")
+ try BuildModel.requiredTools.filter { $0 != BuildModel.buildScript }.forEach { tool in // the other files the build checks for (#87)
+ let url = temporary.appendingPathComponent(tool)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: url)
+ }
let script = temporary.appendingPathComponent("scripts/build_ipa_from_nsp.py")
try FileManager.default.createDirectory(at: script.deletingLastPathComponent(), withIntermediateDirectories: true)
try """
@@ -460,6 +470,11 @@ final class LibraryTests: XCTestCase {
let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")
try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
try Data().write(to: marker)
+ try BuildModel.requiredTools.filter { $0 != BuildModel.buildScript }.forEach { tool in // the other files the build checks for (#87)
+ let url = temporary.appendingPathComponent(tool)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: url)
+ }
let script = temporary.appendingPathComponent("scripts/build_ipa_from_nsp.py")
try FileManager.default.createDirectory(at: script.deletingLastPathComponent(), withIntermediateDirectories: true)
// This is a process contract fixture, not a game build or game data.
@@ -678,6 +693,28 @@ final class LibraryTests: XCTestCase {
try capture("build", page: .builds)
try capture("build-small", width: 900, height: 680, page: .builds)
try capture("settings", page: .settings)
+ do { // #87: a ZIP copy older than the app (no romfs_image.py), without git: auto-update off, then connected at launch, then a build refused
+ let zip = temporary.appendingPathComponent("NX2Apple-0.4.5")
+ for f in ["dm/tools/nx_extract/Program.cs", BuildModel.buildScript] {
+ let url = zip.appendingPathComponent(f)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data([0]).write(to: url)
+ }
+ let previous = (model.repoPath, model.autoUpdateRepo, model.repoStatus, model.autoAdopted, model.doneNote)
+ defer { (model.repoPath, model.autoUpdateRepo, model.repoStatus, model.autoAdopted, model.doneNote) = previous }
+ model.repoPath = zip.path
+ model.autoUpdateRepo = false
+ try capture("settings-zip-auto-off", page: .settings)
+ model.autoUpdateRepo = true
+ model.repoStatus = model.t("repo.adoptedAuto")
+ model.autoAdopted = true
+ try capture("library-adopted")
+ model.autoAdopted = false
+ model.repoStatus = ""
+ try capture("settings-zip-old-tools", page: .settings)
+ model.startBuild() // refuses: the copy lacks romfs_image.py
+ try capture("build-tools-old", height: 1500, page: .builds)
+ }
do { // a released copy with an update downloaded and verified: Restart now in Settings and in the activity line
let previous = (model.appInstallability, model.appUpdate, model.appStaged, model.appStatus)
defer { (model.appInstallability, model.appUpdate, model.appStaged, model.appStatus) = previous }
diff --git a/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift b/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift
new file mode 100644
index 00000000..614b4acb
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/RepoToolsTests.swift
@@ -0,0 +1,137 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// #87: a ZIP copy of the repository is connected to git when the app opens, and a build does not start with build tools
+/// older than the app. Temporary folders and a local repository stand in for the user's copy and for GitHub.
+final class RepoToolsTests: XCTestCase {
+ private var temporary: URL!
+ private var saved: [(String, Any?)] = []
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-tools87-" + 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)
+ }
+
+ private func write(_ files: [String], in dir: URL, text: String = "x") throws {
+ for f in files {
+ let url = dir.appendingPathComponent(f)
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try text.write(to: url, atomically: true, encoding: .utf8)
+ }
+ }
+
+ @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)
+ }
+
+ // MARK: the decision
+
+ func testAdoptionDecision() {
+ func decide(isRepo: Bool = true, isGit: Bool = false, running: Bool = false, busy: Bool = false, auto: Bool = true) -> BuildModel.ZipAdoption {
+ BuildModel.zipAdoption(isRepo: isRepo, isGit: isGit, buildRunning: running, repoBusy: busy, autoUpdate: auto)
+ }
+ XCTAssertEqual(decide(), .adopt, "a ZIP copy is connected")
+ XCTAssertEqual(decide(isGit: true), .notNeeded, "a git checkout is the normal update's business")
+ XCTAssertEqual(decide(isRepo: false), .notNeeded, "no valid repository, nothing to adopt")
+ XCTAssertEqual(decide(running: true), .waitsForBuild, "never while a build runs")
+ XCTAssertEqual(decide(busy: true), .waitsForBuild)
+ XCTAssertEqual(decide(auto: false), .autoUpdateOff, "the player turned the automatic update off")
+ XCTAssertEqual(decide(running: true, auto: false), .waitsForBuild)
+ }
+
+ // MARK: the missing-tool check
+
+ func testMissingToolsAreListed() throws {
+ let repo = temporary.appendingPathComponent("NX2Apple-0.4.5")
+ try write(["dm/tools/nx_extract/Program.cs", BuildModel.buildScript], in: repo) // the v0.4.5 copy of the report
+ XCTAssertEqual(BuildModel.missingTools(in: repo.path), [BuildModel.romfsImageTool])
+ try write([BuildModel.romfsImageTool], in: repo)
+ XCTAssertEqual(BuildModel.missingTools(in: repo.path), [])
+ XCTAssertEqual(BuildModel.missingTools(in: temporary.appendingPathComponent("nothing").path), BuildModel.requiredTools)
+ }
+
+ func testEveryToolTheLauncherCallsExistsInThisCheckout() throws {
+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ guard BuildModel.isRepo(root.path) else { throw XCTSkip("not run inside a checkout") }
+ XCTAssertEqual(BuildModel.missingTools(in: root.path), [])
+ }
+
+ @MainActor func testABuildWithOldToolsRefusesToStart() throws {
+ let repo = temporary.appendingPathComponent("old")
+ try write(["dm/tools/nx_extract/Program.cs", BuildModel.buildScript], in: repo)
+ let m = BuildModel()
+ m.repoPath = repo.path
+ m.startBuild()
+ XCTAssertFalse(m.running, "no build was started")
+ XCTAssertTrue(m.doneNote.contains(BuildModel.romfsImageTool), m.doneNote)
+ XCTAssertEqual(m.doneNote, String(format: m.t("msg.toolsOld"), BuildModel.romfsImageTool))
+ }
+
+ // MARK: the adoption itself (local repository as origin)
+
+ /// origin (bare) with the two tools on main, and a ZIP-like copy of an older state: no .git, the romfs tool missing
+ private func fixture() throws -> (origin: URL, zip: URL) {
+ let origin = temporary.appendingPathComponent("origin.git"), work = temporary.appendingPathComponent("work")
+ let zip = temporary.appendingPathComponent("NX2Apple-0.4.5")
+ 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)
+ try write(["dm/tools/nx_extract/Program.cs", BuildModel.buildScript, BuildModel.romfsImageTool], in: work, text: "new")
+ try git("add", ".", in: work)
+ try git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-m", "main", in: work)
+ try git("push", "origin", "HEAD:main", in: work)
+ try write(["dm/tools/nx_extract/Program.cs", BuildModel.buildScript], in: zip, text: "old")
+ return (origin, zip)
+ }
+
+ @MainActor private func openZip(_ f: (origin: URL, zip: URL), auto: Bool, remote: String? = nil) -> BuildModel {
+ let m = BuildModel()
+ m.repoPath = f.zip.path
+ m.autoUpdateRepo = auto
+ m.adoptAtLaunch(remote: remote ?? "file://" + f.origin.path)
+ guard auto else { return m } // nothing runs, nothing to wait for
+ let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repoBusy && !m.repoStatus.isEmpty && m.repoStatus != m.t("repo.adopting") }, object: nil)
+ wait(for: [settled], timeout: 20)
+ return m
+ }
+
+ @MainActor func testAZipCopyIsConnectedAndUpdatedAtLaunch() throws {
+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
+ let f = try fixture()
+ XCTAssertEqual(BuildModel.missingTools(in: f.zip.path), [BuildModel.romfsImageTool])
+ let m = openZip(f, auto: true)
+ XCTAssertTrue(m.repoIsGit)
+ XCTAssertTrue(m.autoAdopted)
+ XCTAssertEqual(m.repoStatus, m.t("repo.adoptedAuto"))
+ 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 testWithTheAutomaticUpdateOffTheZipCopyIsLeftAlone() throws {
+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
+ let f = try fixture()
+ let m = openZip(f, auto: false)
+ XCTAssertFalse(m.repoIsGit)
+ XCTAssertFalse(m.autoAdopted)
+ XCTAssertTrue(m.repoStatus.isEmpty, "Settings says it next to the repository (repo.zipNoAuto), not as a status")
+ XCTAssertEqual(BuildModel.missingTools(in: f.zip.path), [BuildModel.romfsImageTool])
+ }
+
+ @MainActor func testAnUnreachableOriginSaysWhyAndLeavesTheCopyUsable() throws {
+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { throw XCTSkip("git is required for the fixture") }
+ let f = try fixture()
+ let m = openZip(f, auto: true, remote: "file://" + temporary.appendingPathComponent("does-not-exist.git").path)
+ XCTAssertEqual(m.repoStatus, m.t("repo.adoptFailAuto"))
+ XCTAssertFalse(m.autoAdopted)
+ XCTAssertTrue(BuildModel.isRepo(f.zip.path), "the files are still there")
+ }
+}