Skip to content

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

Move the repository out of BuildModel into a RepoStore (#387)

v0lumehie5c4f6f0a2ee
diff --git a/frontend/ARCHITECTURE.md b/frontend/ARCHITECTURE.md
index 1c7be831..891bfa50 100644
--- a/frontend/ARCHITECTURE.md
+++ b/frontend/ARCHITECTURE.md
@@ -13,7 +13,7 @@ The plan and the steps are in [LNPANDY/NX2Apple#387](https://github.com/LNPANDY/
## Where it stands
-Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. The rest still lives in the app target and moves with the later steps.
+Step 1 of #387 made the targets and moved the files that already fit. Step 2 moved the language out of `BuildModel` into the `Localizer` store. Step 3 moved the build log into the `BuildLog` store. Step 4 moved the pure logic into `NXCore`. Step 5 added the first services. Step 6 added the first store, `AppUpdateStore`, the reference for the others. Step 7 moves the rest one store per PR, the repository first. The rest still lives in the app target and moves with the later steps.
- `BuildModel` is the model of the whole launcher and reaches into every layer, so the files that use it cannot leave the app target yet. It no longer owns the language: it holds the `Localizer` it was given and forwards `lang` and `t()` to it, for the text it writes itself (alerts, status, failures).
- `NXCore` holds the value types and static functions that need only Foundation: app and engine update parsing, `Localization.swift`, the release notes, the device and signing tools, the cloud folder and saves migration, the bundled tools, input staging, the build target and the pipe reader. Step 4 added four types: `TitleID` (parse a title ID from a file name, its owner, the update version, the build key), `GameInputs` (classify files into the four rows, row mismatch, allowed file types), `BuildProgress` (stage lines, progress details, durations, the steps of Xcode and the install, failure info) and `Toolchain` (probing Python, the venv, dotnet and Xcode, and the dependency rows `Dep`). `Stage` and `StepState` moved with `BuildProgress`. Step 5 added the first services (step 6 added `ReleaseSource`, see below): `ProcessRunner` (a protocol, with `SystemProcessRunner` as the real one), `ProcessGroups` (the process groups that Stop and quitting end) and `GitCheckout` (a protocol, with `SystemGitCheckout`, plus `GitRules` for the decisions that need no git). `ProcessRunner` is where a build process starts: `capture` runs to the end and keeps the output, `stream` hands out lines, `start` returns at once and can lead a process group. `BuildModel` holds a runner and a checkout, takes them in `init`, and uses them for the clone, fetch, pull, adoption of a ZIP copy, the build run, the tools of a stage, the archive step and `openOnDevice`. `Toolchain`, `Diagnostics`, `OlderTools`, `Uninstall`, `EngineLayout.runSync` and the update staging take a runner or a checkout as a parameter with the real one as default. Tests pass in a fake. These still start a `Process` themselves and move with the step that owns them: `AppSignature` (codesign) with the device store, `DeviceTools.run` (devicectl with a timeout and input) and `SaveTransfer` with the device store, `ShellInstaller.run` (a blocking read with start and end callbacks) with the build store, `EngineUpdater` (ditto) with the engine store, the administrator prompt in `LiveOnboardingDriver` and the game start in `LiveConsoleDriver`. The tests that stand in for `xcodebuild` and `devicectl` through `BuildModel.xcrunPath` stay too: `ShellInstaller` and `DeviceTools` run those tools themselves, so they move with the device store. What reads `MetalPin`, `EngineLayout` or `OnboardingDefaults` (`detectDepsSync`, `metalDep`, `needsIOSPlatform`) and the handling of the build's JSON events stay in `BuildModel` until the later store steps.
@@ -21,6 +21,8 @@ Step 1 of #387 made the targets and moved the files that already fit. Step 2 mov
- `NXCoreTests` tests `NXCore` alone. It links no other target, so these tests run without SwiftUI. New tests of pure logic go there.
- `NXModel` holds `Localizer`: `lang` and `t()`. The app creates one with each `BuildModel`, and `ContentView` hands it to every view as an environment object. A view that shows text declares `@EnvironmentObject var loc: Localizer` and calls `loc.t(...)`. A language change redraws these views and nothing else.
- `NXModel` holds `AppUpdateStore`: the release check, the staged update, the update sheet, the uninstall plan and `appVersion`. `BuildModel` creates it with its localizer, runner and release source, and the views that show the update (the launcher's top bar and activity line, the Settings section, the update sheet) observe it and not `BuildModel`. `NXModelTests` tests it with a fake runner and a fake release source, without SwiftUI.
+- `NXModel` holds `RepoStore` (step 7, repository): the repository path, the status line under it, how far it is behind origin/main, the clone, the update check, the pull, the automatic update when the app opens and the adoption of a ZIP copy. `BuildModel` creates it with its `Localizer` and `GitCheckout` and wires four closures: whether a build runs, whether this is a release app (which never clones or pulls), the build log, and `didMove`, which starts the engine sync after a clone, a pull or an adoption. The views that show the repository (Settings "Tools", the library's activity line, the setup hint) observe the store. `RepoLocation` is the narrow protocol (`path`, `isRepo`, `isGit`) for a store that needs only where the repository is. `NXCore` got the rules the store needs: `RepoLayout` (is it a repository, the tools a build needs, which checkout to use at start) and the file-system part of `EngineLayout` (`marker`, `root`, `isCheckout`, `hasEngineTool`). The stale check and the sync of `EngineLayout` stay in the app target with the engine.
+- Still in `BuildModel`, going to their store: `repoPath`, `repoOK` and `repoIsGit` are forwarders to `RepoStore`, because the build code (start, archive, install, diagnostics, the engine switch) reads the path and is not a store yet. `BuildModel` also forwards the store's `objectWillChange` to its own, because `canBuild` and the build views read the repository through it. Both go with the build store (step 7, build). `syncEngine` and its state read the path and `pythonPath` and go to the engine sync store. The engine switch of the release app (`EngineUpdateModel`) sets the path to the installed tree and goes there too. `BuildModel` is not `@MainActor` yet, so it reaches the store through `MainActor.assumeIsolated`.
- `NXModel` also holds `BuildLog`: the log text, its tail trimming and the line buffer. `BuildModel` holds it in a `let` and does not publish it, and only `BuildLogView` (in `NXLauncher`) observes it. A log line redraws the log and no game card. `LauncherPerformanceTests` writes 1000 lines during a build and allows 0 cards. `BuildModel` is not `@MainActor` yet, so it reaches the log through `BuildLog.onMain`.
- `NXLauncher` holds the views and styles that do not need `BuildModel`: `LauncherPalette`, `Typography`, `LauncherStyles`, `LauncherDropdown`, `PadFocus` and `EmbeddedFonts`.
- `NX2Apple` holds everything else, including `BuildModel`.
diff --git a/frontend/Console.md b/frontend/Console.md
index 488a903f..982b6b84 100644
--- a/frontend/Console.md
+++ b/frontend/Console.md
@@ -54,7 +54,7 @@ The visual target is the existing launcher code: `LauncherPalette`, embedded Man
The reusable `ConsoleArtwork` and `ConsoleGameTile` accept presentation values. At compact widths the cards become a touch-friendly horizontal collection, hints form two columns, and the side sheet fills the width. Vertically short windows scroll the library and sheet contents, and the primary option action stays visible. Focus/background transitions last 0.18–0.22 seconds, without springs. Reduced Motion removes focus scaling and scroll animation, retaining only fades. No UI sounds are included. Controller kinds use neutral SF Symbols, including a split rectangle for paired controllers, with no Nintendo artwork. Chips have fixed strip height, horizontal overflow, player numbers, battery percentage when reported and charging status. Connect/disconnect toasts overlay the screen without moving it. All controller copy is localized and contains no semicolons.
-Nothing is bundled. The demo takes covers from the repository's `docs/images` through `GameLibrary.artwork(for:repo:)`, the lookup the desktop launcher uses, with the repository found by `BuildModel.findRepo()`. A title without an image gets a generated placeholder (a gradient in the launcher's palette and the name). All interface copy and mock controller labels live in the shared English/Chinese localization table.
+Nothing is bundled. The demo takes covers from the repository's `docs/images` through `GameLibrary.artwork(for:repo:)`, the lookup the desktop launcher uses, with the repository found by `RepoLayout.find()`. A title without an image gets a generated placeholder (a gradient in the launcher's palette and the name). All interface copy and mock controller labels live in the shared English/Chinese localization table.
Starting takes a `ConsoleStarting` snapshot: preparing, compiling shaders (completed/total), or opening. Shader progress uses the existing cream launcher progress bar, animating for 0.3 seconds per update, and Reduced Motion removes interpolation. A preview label explicitly identifies simulated shader progress. The live driver must publish actual shader stages and counts, then end Starting when the game window appears.
diff --git a/frontend/Sources/NX2Apple/ConsoleEntryView.swift b/frontend/Sources/NX2Apple/ConsoleEntryView.swift
index 201e883b..3b6000cd 100644
--- a/frontend/Sources/NX2Apple/ConsoleEntryView.swift
+++ b/frontend/Sources/NX2Apple/ConsoleEntryView.swift
@@ -96,9 +96,9 @@ struct ConsoleConnectionPrompt: View {
}
}
-/// The demo reads covers from the repository's docs/images (BuildModel.findRepo, as the launcher does) and is otherwise isolated from ContentView: no BuildModel, library discovery, controller adapter or process is made.
+/// The demo reads covers from the repository's docs/images (RepoLayout.find, as the launcher does) and is otherwise isolated from ContentView: no BuildModel, library discovery, controller adapter or process is made.
@MainActor struct ConsoleDemoView: View {
@StateObject private var driver: MockConsoleDriver
- init(scenario: MockConsoleDriver.Scenario) { _driver = StateObject(wrappedValue: MockConsoleDriver(scenario: scenario, artworkRepo: Optional(BuildModel.findRepo()).flatMap { $0.isEmpty ? nil : $0 })) }
+ init(scenario: MockConsoleDriver.Scenario) { _driver = StateObject(wrappedValue: MockConsoleDriver(scenario: scenario, artworkRepo: Optional(RepoLayout.find()).flatMap { $0.isEmpty ? nil : $0 })) }
var body: some View { ConsoleView(driver: driver).frame(minWidth: 360, minHeight: 600) }
}
diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swift
index accb7a8e..25c983fd 100644
--- a/frontend/Sources/NX2Apple/ContentView.swift
+++ b/frontend/Sources/NX2Apple/ContentView.swift
@@ -1,3 +1,4 @@
+import Combine
import SwiftUI
import NXCore
import NXLauncher
@@ -199,100 +200,32 @@ final class BuildModel: ObservableObject {
NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { _ in ProcessGroups.endAll() }
}()
- /// The checkout of this repository the app drives. A released .app ships on its own,
- /// so the path is not known at build time: look next to the app bundle, walk up from
- /// it, then fall back to a saved choice. A repository is identified by
- /// dm/tools/nx_extract/Program.cs, which only exists in a real checkout.
- @Published var repoPath: String = BuildModel.findRepo() {
- didSet { UserDefaults.standard.set(repoPath, forKey: "repoPath") }
- }
-
- nonisolated static func isRepo(_ dir: String) -> Bool {
- EngineLayout.isCheckout(dir) // a checkout with tools/engine.py, a synced engine/, or an engine tree (#214)
- }
-
- /// 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] {
- let root = EngineLayout.root(dir) // the checkout's engine/, or an engine tree itself (Engine.swift)
- return requiredTools.filter { !FileManager.default.fileExists(atPath: root + "/" + $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 = EngineLayout.root(dir) + "/" + buildScript
- if !FileManager.default.fileExists(atPath: script), EngineLayout.hasEngineTool(dir) { return true } // engine/ not made yet: the fork's engine has it
- guard let text = try? String(contentsOfFile: script, encoding: .utf8) else { return false }
- return text.contains("'--work-dir'") || text.contains("\"--work-dir\"")
- }
-
- nonisolated static func findRepo() -> String {
- // A candidate that is merely a repository (an upstream nxnative clone) must lose to one
- // carrying this fork's `--work-dir`: building from an upstream checkout fails with
- // "unrecognized arguments" after the app has already picked it — and a saved path from an
- // earlier session pointed at exactly such a clone, so every build said 仓库不是最新版本
- // (the report's build log). The fork check is the script's own argparse, not a name match,
- // so a checkout under any folder name ranks correctly.
- let saved = UserDefaults.standard.string(forKey: "repoPath").flatMap { isRepo($0) ? $0 : nil }
- var seeds: [String] = []
- // the app bundle: …/frontend/NX2Apple.app/Contents/MacOS — the checkout it ships from wins
- let bundle = Bundle.main.bundleURL.standardizedFileURL
- seeds.append(bundle.deletingLastPathComponent().path)
- seeds.append(bundle.deletingLastPathComponent().deletingLastPathComponent()
- .deletingLastPathComponent().deletingLastPathComponent().path)
- seeds.append(FileManager.default.currentDirectoryPath)
- for base in ["/ZCodeProject/", "/", "/Documents/", "/Desktop/"] {
- seeds.append(NSHomeDirectory() + base + "nxnative-romfs-archive") // clones made before the rename still resolve
- seeds.append(NSHomeDirectory() + base + "NX2Apple")
- seeds.append(NSHomeDirectory() + base + "nxnative") // an upstream clone: last resort
- }
- var seen = Set<String>()
- var repos: [String] = []
- for s in seeds where !s.isEmpty && seen.insert(s).inserted {
- var d = s
- for _ in 0..<5 { // walk up a few levels from each seed
- if isRepo(d) { repos.append(d); break }
- let up = (d as NSString).deletingLastPathComponent
- if up == d || up == "/" { break }
- d = up
- }
- }
- let forks = repos.filter { repoSupportsWorkDir($0) }
- if let saved, repoSupportsWorkDir(saved) { return saved } // the player's own fork checkout
- if let f = forks.first, f != saved {
- if let saved { fputs("launcher: using the fork checkout \(f); the saved repository \(saved) is an upstream clone without --work-dir\n", stderr) }
- return f
- }
- return saved ?? repos.first ?? ""
- }
-
- // ---- Repository download and updates (a clone is the scripts' home; not everyone has git habits) ----
-
- static let repoURL = "https://github.com/LNPANDY/NX2Apple.git"
- /// Clone/pull/check in flight; the buttons disable and the status line says what is happening.
- @Published var repoBusy = false
- @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?
- /// A copy without .git was connected to git and brought to the current version when the app opened (adoptAtLaunch).
- @Published var autoAdopted = false
+ // ---- The repository (`RepoStore`, NXModel) ----
+ // It owns the path, the status line, the update check, the pull and the automatic update. The model creates it with its services
+ // and wires what reaches back here: whether a build runs, the log, and the engine sync that follows a clone, a pull or an adoption.
+
+ /// Created on first use, on the main thread, because its closures reach back to this model.
+ private(set) lazy var repo: RepoStore = MainActor.assumeIsolated {
+ let store = RepoStore(
+ localizer: localizer, git: gitCheckout,
+ buildRunning: { [unowned self] in running },
+ isReleaseApp: { [unowned self] in usesEngineStore },
+ log: { [unowned self] in append($0) },
+ didMove: { [unowned self] in syncEngine() }) // the pull may have moved the pin or the patches
+ // The build state that reads the repository (`canBuild`, the setup rows) is still here: a change of the repository
+ // redraws what observes this model, as it did when the repository's state was published by it. Goes with the build store.
+ repoChanges = store.objectWillChange.sink { [unowned self] _ in objectWillChange.send() }
+ return store
+ }
+ private var repoChanges: AnyCancellable?
+
+ /// The checkout the build reads, for the build code in this model. The views take it from `repo`.
+ var repoPath: String {
+ get { MainActor.assumeIsolated { repo.path } }
+ set { MainActor.assumeIsolated { repo.path = newValue } }
+ }
+ var repoOK: Bool { MainActor.assumeIsolated { repo.isRepo } }
+ var repoIsGit: Bool { MainActor.assumeIsolated { repo.isGit } }
// ---- The release app's engine (EngineUpdater.swift, EngineUpdateModel.swift) ----
@@ -318,162 +251,6 @@ final class BuildModel: ObservableObject {
BundledTools.path(base, python: python)
}
- /// First-time flow: clone the project to ~/nxnative (the discovery seeds cover it) and select it.
- func cloneRepo() {
- guard !running, !repoBusy, !usesEngineStore else { return }
- guard gitCheckout.binary != nil else { repoStatus = t("repo.gitMissing"); return }
- let dest = NSHomeDirectory() + "/NX2Apple"
- if FileManager.default.fileExists(atPath: dest) {
- if Self.isRepo(dest) { repoPath = dest; repoStatus = ""; checkRepoUpdates() }
- else { repoStatus = String(format: t("repo.destBusy"), shortPath(dest)) }
- return
- }
- repoBusy = true; repoStatus = t("repo.downloading")
- append("git clone --depth 1 \(Self.repoURL) \(dest)\n")
- let checkout = gitCheckout
- DispatchQueue.global().async {
- let ok = checkout.clone(url: Self.repoURL, into: dest) {
- line in DispatchQueue.main.async { self.append(line + "\n") }
- }
- DispatchQueue.main.async {
- self.repoBusy = false
- if ok && Self.isRepo(dest) {
- self.repoPath = dest
- self.repoStatus = String(format: self.t("repo.downloadDone"), self.shortPath(dest))
- self.syncEngine()
- } else {
- self.repoStatus = self.t("repo.downloadFail")
- try? FileManager.default.removeItem(atPath: dest) // a failed clone leaves an empty folder
- }
- }
- }
- }
-
- /// Compare the checkout with origin/main. `silent` is the launch-time check: no status text, no
- /// error noise when offline — it only fills repoBehind when it can.
- func checkRepoUpdates(silent: Bool = false) {
- guard repoOK, repoIsGit, !usesEngineStore else { return } // a release app updates its engine by version instead
- guard !running, !repoBusy, gitCheckout.binary != nil else {
- if !silent, gitCheckout.binary == nil { repoStatus = t("repo.gitMissing") }
- return
- }
- repoBusy = true
- if !silent { repoStatus = t("repo.checking") }
- let dir = repoPath, checkout = gitCheckout
- DispatchQueue.global().async {
- let behind = checkout.behind(dir) ?? -1
- DispatchQueue.main.async {
- self.repoBusy = false
- 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")
- }
- }
- }
- }
-
- /// Fast-forward the checkout to origin/main. The build keeps everything it needs under
- /// <id>_build/ outside the repository, so a pull never disturbs a previous build's files.
- /// The status line for a failed pull. A diverged checkout ("Not possible to fast-forward") has its
- /// own commit history — a clone someone worked in, or an old upstream checkout — and no amount of
- /// pulling fixes that; the actionable answer is the repository picker, which is always offered now.
- func pullFailureMessage(_ gitOutput: String) -> String {
- let diverged = gitOutput.contains("fast-forward") || gitOutput.contains("Diverging")
- return t(diverged ? "repo.pullDiverged" : "repo.pullFail")
- }
-
- func pullRepo() {
- guard !running, !repoBusy, !usesEngineStore, repoOK, repoIsGit, gitCheckout.binary != nil else { return }
- repoBusy = true; repoStatus = t("repo.pulling")
- let dir = repoPath, checkout = gitCheckout
- DispatchQueue.global().async {
- let r = checkout.pull(dir)
- DispatchQueue.main.async {
- self.repoBusy = false
- if r.ok {
- self.repoBehind = 0; self.repoStatus = self.t("repo.pulled")
- if !r.out.isEmpty { self.append(r.out + "\n") }
- self.syncEngine() // the pull may have moved the pin or the patches
- } else {
- self.repoStatus = self.pullFailureMessage(r.out)
- self.append(r.out + "\n")
- }
- }
- }
- }
-
- /// 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, !usesEngineStore, repoOK, repoIsGit, gitCheckout.binary != nil else { return }
- repoBusy = true
- let dir = repoPath, checkout = gitCheckout
- DispatchQueue.global().async {
- let pulled = checkout.autoPull(dir)
- 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)
- self.syncEngine()
- } else {
- self.repoStatus = self.pullFailureMessage(pulled.out)
- self.append(pulled.out + "\n")
- }
- }
- }
- }
-
- /// 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) {
- guard !usesEngineStore else { return }
- switch GitRules.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 gitCheckout.binary == 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. 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, !usesEngineStore, repoOK, !repoIsGit, gitCheckout.binary != nil else { return }
- repoBusy = true; repoStatus = t("repo.adopting")
- let dir = repoPath, checkout = gitCheckout
- DispatchQueue.global().async {
- let branch = GitRules.zipCopyBranch()
- let (ok, out) = checkout.adopt(dir, remote: remote, branch: branch)
- DispatchQueue.main.async {
- self.repoBusy = false
- self.append(out + "\n")
- if ok && self.repoIsGit {
- // the checkout is origin/main as just fetched: up to date, nothing left to pull
- self.repoBehind = 0
- self.repoStatus = String(format: self.t(automatic ? "repo.adoptedAuto" : "repo.adopted"), branch)
- if automatic { self.autoAdopted = true }
- self.syncEngine()
- } else {
- self.repoStatus = self.t(automatic ? "repo.adoptFailAuto" : "repo.adoptFail")
- }
- }
- }
- }
-
/// What waits for the running `tools/engine.py sync` (nil: none runs), and whether another one is due when it ends.
private var engineSyncWaiting: [(Bool) -> Void]?
private var engineSyncAgain = false
@@ -623,10 +400,6 @@ final class BuildModel: ObservableObject {
func clear(_ id: String) { updateSlot(id) { $0.paths = []; $0.problem = "" } }
- var repoOK: Bool { Self.isRepo(repoPath) }
- /// A clone has .git; a GitHub "Download ZIP" copy does not (everything builds, but there is
- /// nothing to fetch or pull — the update buttons hide and the note says to re-download instead).
- var repoIsGit: Bool { FileManager.default.fileExists(atPath: repoPath + "/.git") }
var canBuild: Bool { repoOK && slot("base").ok && slot("keys").ok && allDepsPresent && !running }
// MARK: Build
@@ -665,7 +438,7 @@ final class BuildModel: ObservableObject {
return
}
// 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)
+ let missing = RepoLayout.missingTools(in: repoPath)
if !missing.isEmpty {
fail(String(format: t("msg.toolsOld"), missing.joined(separator: ", ")))
return
@@ -724,7 +497,7 @@ final class BuildModel: ObservableObject {
// option and would stop with "unrecognized arguments" (issue #5), so ask the script; without
// it the script's own default (<input>/<title ID>_build) is used and the archive step follows
// whatever folder the build reports.
- let hasWorkDir = Self.repoSupportsWorkDir(repoPath)
+ let hasWorkDir = RepoLayout.supportsWorkDir(repoPath)
if !hasWorkDir {
say(t("msg.noWorkDir"))
}
@@ -748,7 +521,7 @@ final class BuildModel: ObservableObject {
}
}
let engine = EngineLayout.root(repoPath) // the checkout's engine/ (#214)
- var args = [engine + "/" + Self.buildScript, inputDir, "-k", keysPath,
+ var args = [engine + "/" + RepoLayout.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 iPhone or iPad build;
@@ -1282,7 +1055,7 @@ final class BuildModel: ObservableObject {
// dest/romfs.img: one file, which main.m's per-game lookup takes before any folder.
let engine = EngineLayout.root(repoPath)
let romfsPy = pythonPath.isEmpty ? "/usr/bin/python3" : pythonPath
- let launch = ProcessLaunch(executable: romfsPy, arguments: [engine + "/" + Self.romfsImageTool, "--reuse", romfs, dest + "/romfs.img"],
+ let launch = ProcessLaunch(executable: romfsPy, arguments: [engine + "/" + RepoLayout.romfsImageTool, "--reuse", romfs, dest + "/romfs.img"],
environment: ["PATH": Self.toolPath("/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", python: romfsPy), "PYTHONPATH": engine + "/dm/tools"]
.merging(BundledTools.environment(for: romfsPy)) { $1 },
groupPython: romfsPy)
@@ -1778,10 +1551,7 @@ final class BuildModel: ObservableObject {
/// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of
/// screenshots).
- func shortPath(_ path: String) -> String {
- let home = NSHomeDirectory()
- return path.hasPrefix(home) ? "~" + path.dropFirst(home.count) : path
- }
+ func shortPath(_ path: String) -> String { RepoLayout.shortPath(path) }
/// A dependency row's second column: a path when there is one, else the translated hint.
/// `detail` carries either a real path, an L10n key, or "key:argument[:argument…]".
@@ -1804,6 +1574,7 @@ final class BuildModel: ObservableObject {
struct BuilderView: View {
@ObservedObject var m: BuildModel
@ObservedObject var updates: AppUpdateStore // the app's self-update (Settings, "NX2Apple" section)
+ @ObservedObject var repo: RepoStore // the repository (Settings, "Tools" section, and the setup hint)
@EnvironmentObject var loc: Localizer
@ObservedObject var library: GameLibrary
var settings = false
@@ -1922,7 +1693,7 @@ struct BuilderView: View {
@ViewBuilder private var buildPage: some View {
pageHeading(loc.t("build.heading"), note: loc.t("build.intro"))
- if !m.repoOK || !m.allDepsPresent {
+ if !repo.isRepo || !m.allDepsPresent {
group(loc.t("section.setup")) {
row(loc.t("library.setupHint"), dot: LauncherPalette.building) {
Button(loc.t("build.setup"), action: onOpenSettings)
@@ -2186,7 +1957,7 @@ struct BuilderView: View {
Text(loc.t("status.checkingDeps")).font(.manrope(13)).foregroundStyle(.secondary)
} else if !m.allDepsPresent {
Text(loc.t("status.installFirst")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)
- } else if !m.repoOK {
+ } else if !repo.isRepo {
Text(loc.t("status.chooseRepo")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)
} else if !m.slot("base").ok || !m.slot("keys").ok {
Text(loc.t("status.needInputs")).font(.manrope(13)).foregroundStyle(.secondary)
@@ -2322,64 +2093,64 @@ struct BuilderView: View {
private func uninstallPlan() -> Uninstall.Plan {
Uninstall.plan(home: NSHomeDirectory(), gamesFolder: library.folder, outputFolder: m.outDir,
- checkouts: [m.repoPath], defaultsDomain: Bundle.main.bundleIdentifier)
+ checkouts: [repo.path], defaultsDomain: Bundle.main.bundleIdentifier)
}
private var tools: some View {
group(loc.t("section.tools"), footnote: m.usesEngineStore ? m.engineStatus
- : (m.repoStatus.isEmpty ? (m.repoOK ? "" : loc.t("repo.firstHint")) : m.repoStatus)) {
+ : (repo.status.isEmpty ? (repo.isRepo ? "" : loc.t("repo.firstHint")) : repo.status)) {
if m.usesEngineStore {
engineRows
} else {
row(loc.t("repo.title"),
- detail: m.repoOK ? m.shortPath(m.repoPath)
- : (m.repoPath.isEmpty ? loc.t("repo.notFound") : String(format: loc.t("repo.notRepo"), m.shortPath(m.repoPath))),
- dot: m.repoOK ? LauncherPalette.ready : LauncherPalette.building, help: m.repoPath) {
- if m.repoBusy { ProgressView().controlSize(.small) }
- if m.repoOK {
- if m.repoIsGit {
- if let n = m.repoBehind, n > 0 {
- Button(loc.t("repo.pull")) { m.pullRepo() }.disabled(m.repoBusy || m.running)
- .padTarget("set.repoPull", scope: "main") { if !(m.repoBusy || m.running) { m.pullRepo() } }
+ detail: repo.isRepo ? m.shortPath(repo.path)
+ : (repo.path.isEmpty ? loc.t("repo.notFound") : String(format: loc.t("repo.notRepo"), m.shortPath(repo.path))),
+ dot: repo.isRepo ? LauncherPalette.ready : LauncherPalette.building, help: repo.path) {
+ if repo.busy { ProgressView().controlSize(.small) }
+ if repo.isRepo {
+ if repo.isGit {
+ if let n = repo.behind, n > 0 {
+ Button(loc.t("repo.pull")) { repo.pull() }.disabled(repo.busy || m.running)
+ .padTarget("set.repoPull", scope: "main") { if !(repo.busy || m.running) { repo.pull() } }
}
- Button(loc.t("repo.check")) { m.checkRepoUpdates() }.disabled(m.repoBusy || m.running)
- .padTarget("set.repoCheck", scope: "main") { if !(m.repoBusy || m.running) { m.checkRepoUpdates() } }
+ Button(loc.t("repo.check")) { repo.checkForUpdates() }.disabled(repo.busy || m.running)
+ .padTarget("set.repoCheck", scope: "main") { if !(repo.busy || m.running) { repo.checkForUpdates() } }
} else {
- Button(loc.t("repo.adopt")) { m.adoptRepoAsGit() }.disabled(m.repoBusy || m.running)
- .padTarget("set.repoAdopt", scope: "main") { if !(m.repoBusy || m.running) { m.adoptRepoAsGit() } }
+ Button(loc.t("repo.adopt")) { repo.adoptAsGit() }.disabled(repo.busy || m.running)
+ .padTarget("set.repoAdopt", scope: "main") { if !(repo.busy || m.running) { repo.adoptAsGit() } }
}
}
// Always offered, including when a repository is already configured: a saved path from
// an earlier session (an upstream clone, a moved folder) is exactly the state a user
// cannot fix without this button — the report had no way to leave the wrong repository.
Button(loc.t("repo.choose")) { pickRepo() }
- if !m.repoOK {
- Button(loc.t("repo.download")) { m.cloneRepo() }.disabled(m.repoBusy || m.running)
+ if !repo.isRepo {
+ Button(loc.t("repo.download")) { repo.clone() }.disabled(repo.busy || m.running)
}
}
- if !m.repoOK {
+ if !repo.isRepo {
// GitHub does not load everywhere: the manual route (Code → Download ZIP → unzip →
// Choose repository) needs no git at all, and the note says which folder to pick.
HStack(spacing: 4) {
Text(loc.t("repo.manualHint")).foregroundStyle(.secondary)
- Link("github.com/LNPANDY/NX2Apple", destination: URL(string: BuildModel.repoURL.replacingOccurrences(of: ".git", with: ""))!)
+ Link("github.com/LNPANDY/NX2Apple", destination: URL(string: RepoStore.url.replacingOccurrences(of: ".git", with: ""))!)
Text(loc.t("repo.manualHint2")).foregroundStyle(.secondary)
}
.font(.manrope(12)).padding(.horizontal, 18).padding(.bottom, 12)
}
- if m.repoOK, !m.repoIsGit {
- Text(loc.t(m.autoUpdateRepo ? "repo.noGit" : "repo.zipNoAuto")).font(.manrope(12)).foregroundStyle(.secondary)
+ if repo.isRepo, !repo.isGit {
+ Text(loc.t(repo.autoUpdate ? "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: loc.t("repo.toolsOld"), BuildModel.missingTools(in: m.repoPath).joined(separator: ", ")))
+ if repo.isRepo, !RepoLayout.missingTools(in: repo.path).isEmpty {
+ Text(String(format: loc.t("repo.toolsOld"), RepoLayout.missingTools(in: repo.path).joined(separator: ", ")))
.font(.manrope(12)).foregroundStyle(LauncherPalette.building)
.padding(.horizontal, 18).padding(.bottom, 12)
}
- if m.repoOK { // a ZIP copy too: its adoption at launch follows this switch
+ if repo.isRepo { // a ZIP copy too: its adoption at launch follows this switch
divider
row(loc.t("repo.auto"), detail: loc.t("repo.autoNote")) {
- Toggle("", isOn: $m.autoUpdateRepo).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ Toggle("", isOn: $repo.autoUpdate).labelsHidden().toggleStyle(LauncherSwitchStyle())
}
}
}
@@ -2436,7 +2207,7 @@ struct BuilderView: View {
@ViewBuilder private var engineRows: some View {
let idle = !(m.engineBusy || m.running)
row(loc.t("engine.title"), detail: m.engineDetail,
- dot: m.engineSelection.engineID.isEmpty ? LauncherPalette.building : LauncherPalette.ready, help: m.repoPath) {
+ dot: m.engineSelection.engineID.isEmpty ? LauncherPalette.building : LauncherPalette.ready, help: repo.path) {
if m.engineBusy { ProgressView().controlSize(.small) }
if let next = m.engineAvailable {
Button(String(format: loc.t("engine.install"), next.version)) { m.installAvailableEngine() }.disabled(!idle)
@@ -2473,7 +2244,7 @@ struct BuilderView: View {
}
divider
row(loc.t("repo.auto"), detail: loc.t("engine.autoNote")) {
- Toggle("", isOn: $m.autoUpdateRepo).labelsHidden().toggleStyle(LauncherSwitchStyle())
+ Toggle("", isOn: $repo.autoUpdate).labelsHidden().toggleStyle(LauncherSwitchStyle())
}
}
@@ -2481,7 +2252,7 @@ struct BuilderView: View {
let d = NSOpenPanel()
d.canChooseDirectories = true; d.canChooseFiles = false
d.message = loc.t("repo.pickMessage")
- if d.runModal() == .OK, let u = d.url { m.repoPath = u.path }
+ if d.runModal() == .OK, let u = d.url { repo.path = u.path }
}
}
diff --git a/frontend/Sources/NX2Apple/Engine.swift b/frontend/Sources/NX2Apple/Engine.swift
index 35b06844..9057972b 100644
--- a/frontend/Sources/NX2Apple/Engine.swift
+++ b/frontend/Sources/NX2Apple/Engine.swift
@@ -19,14 +19,8 @@ import NXLauncher
/// or one a launcher cloned): it downloads the pinned engine from GitHub (about 80 MB) and shows a failure row when that does not work.
/// A release app carries the engine tree instead (`Contents/Resources/engine`, built by `tools/engine.py tree`, #227) and takes updates
/// from the release's `latest.json`: no git, no sync.
-enum EngineLayout {
- /// The file that tells an engine tree (BuildModel.isRepo always looked for it).
- static let marker = "dm/tools/nx_extract/Program.cs"
-
- static func hasEngineTool(_ repo: String) -> Bool {
- let fm = FileManager.default
- return !repo.isEmpty && fm.fileExists(atPath: repo + "/tools/engine.py") && fm.fileExists(atPath: repo + "/.upstream-ref")
- }
+extension EngineLayout {
+ // `marker`, `hasEngineTool`, `root` and `isCheckout` are in NXCore (EngineLayout.swift): the repository store needs them.
static func series(_ repo: String) -> [String]? {
guard let text = try? String(contentsOfFile: repo + "/patches/series", encoding: .utf8) else { return nil }
@@ -76,21 +70,6 @@ enum EngineLayout {
return stamp["key"] != stampKey(repo) || stamp["head"] != head(eng)
}
- /// The folder holding dm/ and scripts/ for this checkout (see the rule above).
- static func root(_ repo: String) -> String {
- guard !repo.isEmpty else { return repo }
- let fm = FileManager.default
- if hasEngineTool(repo) { return repo + "/engine" }
- if fm.fileExists(atPath: repo + "/" + marker) { return repo }
- return fm.fileExists(atPath: repo + "/engine/" + marker) ? repo + "/engine" : repo
- }
-
- /// A folder the launcher can build from: a checkout with tools/engine.py to make engine/, a synced engine/, or an engine tree.
- static func isCheckout(_ dir: String) -> Bool {
- let fm = FileManager.default
- return !dir.isEmpty && (fm.fileExists(atPath: dir + "/" + marker) || fm.fileExists(atPath: dir + "/engine/" + marker) || hasEngineTool(dir))
- }
-
/// engine/ is the only engine and it is stale or missing: the build syncs it first.
static func needsSyncBeforeBuild(_ repo: String) -> Bool {
hasEngineTool(repo) && isStale(repo)
diff --git a/frontend/Sources/NX2Apple/EngineUpdateModel.swift b/frontend/Sources/NX2Apple/EngineUpdateModel.swift
index 0a8faca1..96e94841 100644
--- a/frontend/Sources/NX2Apple/EngineUpdateModel.swift
+++ b/frontend/Sources/NX2Apple/EngineUpdateModel.swift
@@ -47,7 +47,7 @@ extension BuildModel {
/// Ask the selected channel for its engine. `automatic` is the launch check: it installs only with automatic
/// updates on, and it says nothing when the engine is current or the network is down.
func checkEngineUpdate(automatic: Bool = false) {
- runEngineUpdate(channel: engineSelection.channel, install: automatic ? autoUpdateRepo : true, quiet: automatic)
+ runEngineUpdate(channel: engineSelection.channel, install: automatic ? MainActor.assumeIsolated { repo.autoUpdate } : true, quiet: automatic)
}
/// Install the engine the launch check found (automatic updates off).
diff --git a/frontend/Sources/NX2Apple/LauncherView.swift b/frontend/Sources/NX2Apple/LauncherView.swift
index 38d6dd59..db3b4fe8 100644
--- a/frontend/Sources/NX2Apple/LauncherView.swift
+++ b/frontend/Sources/NX2Apple/LauncherView.swift
@@ -44,6 +44,7 @@ struct ContentView: View {
@StateObject private var m: BuildModel
@ObservedObject private var loc: Localizer // the strings: handed on to every view below through the environment
@ObservedObject private var updates: AppUpdateStore // the app's self-update: the update icon, the sheet, the uninstall dialog
+ @ObservedObject private var repo: RepoStore // the repository: the activity line, and the checks that follow a change of it
@StateObject private var library: GameLibrary
@State private var page: LauncherPage = .library
@State private var search = ""
@@ -98,6 +99,7 @@ struct ContentView: View {
_m = StateObject(wrappedValue: model)
_loc = ObservedObject(wrappedValue: model.localizer)
_updates = ObservedObject(wrappedValue: model.appUpdates)
+ _repo = ObservedObject(wrappedValue: model.repo)
_library = StateObject(wrappedValue: library ?? GameLibrary())
_page = State(initialValue: initialPage)
_activeBuildID = State(initialValue: activeBuildID)
@@ -174,7 +176,7 @@ struct ContentView: View {
if page == .library {
libraryPage
} else {
- BuilderView(m: m, updates: updates, library: library, settings: page == .settings, onViewGame: { page = .library },
+ BuilderView(m: m, updates: updates, repo: repo, library: library, settings: page == .settings, onViewGame: { page = .library },
onOpenSettings: { page = .settings }, onChooseLibraryFolder: chooseLibraryFolder,
onOpenControls: { controlsOpen = true }, onOpenControllers: { controllerSheet = true }, onRunSetup: onRunSetup, controlChanges: controls.changeCount,
padMerge: Binding(get: { controls.padMerge }, set: { setPadMerge($0) }))
@@ -215,7 +217,7 @@ struct ContentView: View {
m.checkDeps()
if m.usesEngineStore { m.prepareEngine() } // the release app: its engine store, never git (EngineUpdateModel.swift)
else { m.syncEngine() } // a checkout whose engine/ is missing or older than its pin (#214)
- if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) } else { m.adoptAtLaunch() }
+ if repo.isRepo && repo.isGit { repo.checkForUpdates(silent: true) } else { repo.adoptAtLaunch() }
updates.checkForUpdate(silent: true)
BuildNotifier.shared.watch(m, library: library) // BuildNotifications.swift
}
@@ -231,9 +233,9 @@ struct ContentView: View {
readSignatures()
if performStartupChecks { fetchArtwork() }
}
- .onChange(of: m.repoPath) { _ in refreshArtwork(); if performStartupChecks { checkTools() } }
+ .onChange(of: repo.path) { _ in refreshArtwork(); if performStartupChecks { checkTools() } }
// A clone, pull or update check has finished (the automatic pull at launch among them): the checkout may have moved
- .onReceive(m.$repoBusy.removeDuplicates().dropFirst()) { busy in if !busy && performStartupChecks { checkTools() } }
+ .onReceive(repo.$busy.removeDuplicates().dropFirst()) { busy in if !busy && performStartupChecks { checkTools() } }
// The engine was made or moved by a sync (its HEAD is what ToolsAge compares)
.onReceive(m.$engineSyncing.removeDuplicates().dropFirst()) { syncing in if !syncing && performStartupChecks { checkTools() } }
.onChange(of: library.selectedID) { _ in resignNote = nil } // the last re-sign's note belongs to its game
@@ -241,11 +243,11 @@ struct ContentView: View {
.onReceive(m.$running.removeDuplicates()) { running in
if !running { DockProgress.update(nil) }
if running && activeBuildID == nil { activeBuildID = library.rememberInputs(m) }
- if running && activeBuildID != nil { // the tools this build runs: a pull waits for the build (pullRepo, autoPull)
+ if running && activeBuildID != nil { // the tools this build runs: a pull waits for the build (RepoStore.pull, autoPull)
buildCommit = ""
- let repo = m.repoPath
+ let dir = repo.path
DispatchQueue.global(qos: .utility).async {
- let commit = ToolsAge.head(repo: repo) ?? ""
+ let commit = ToolsAge.head(repo: dir) ?? ""
DispatchQueue.main.async { buildCommit = commit }
}
}
@@ -704,13 +706,11 @@ struct ContentView: View {
} else {
Image(systemName: "desktopcomputer").foregroundStyle(.secondary)
Text(loc.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
+ if let n = repo.autoPulled, n > 0 { // the automatic update when the app opened (RepoStore.autoPull): the tools are current
Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6).padding(.leading, 10)
Text(String(format: loc.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)
+ if repo.autoAdopted { // a ZIP copy connected and updated when the app opened (RepoStore.adoptAtLaunch)
Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6).padding(.leading, 10)
Text(loc.t("library.toolsAdopted")).font(.manrope(13)).foregroundStyle(.secondary)
}
diff --git a/frontend/Sources/NX2Apple/Library.swift b/frontend/Sources/NX2Apple/Library.swift
index e408a55c..0c341990 100644
--- a/frontend/Sources/NX2Apple/Library.swift
+++ b/frontend/Sources/NX2Apple/Library.swift
@@ -444,7 +444,7 @@ final class GameLibrary: ObservableObject {
return result.values.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
}
- func discover(repo: String = BuildModel.findRepo()) {
+ func discover(repo: String = RepoLayout.find()) {
guard !folder.isEmpty, !scanning else { return }
scanning = true
let root = URL(fileURLWithPath: folder), installed = applicationFolders
diff --git a/frontend/Sources/NXCore/EngineLayout.swift b/frontend/Sources/NXCore/EngineLayout.swift
new file mode 100644
index 00000000..edb3961a
--- /dev/null
+++ b/frontend/Sources/NXCore/EngineLayout.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+/// Where the engine of a checkout is: the part of `EngineLayout` that needs only the file system (the rest, the stale check and the
+/// sync, is in the app target, `Engine.swift`, which explains the rule). `RepoLayout` and `RepoStore` need these.
+package enum EngineLayout {
+ /// The file that tells an engine tree.
+ package static let marker = "dm/tools/nx_extract/Program.cs"
+
+ package static func hasEngineTool(_ repo: String) -> Bool {
+ let fm = FileManager.default
+ return !repo.isEmpty && fm.fileExists(atPath: repo + "/tools/engine.py") && fm.fileExists(atPath: repo + "/.upstream-ref")
+ }
+
+ /// The folder holding dm/ and scripts/ for this checkout: its `engine/` when it can make one, else the folder when it is an
+ /// engine tree itself, else `engine/` as it is.
+ package static func root(_ repo: String) -> String {
+ guard !repo.isEmpty else { return repo }
+ let fm = FileManager.default
+ if hasEngineTool(repo) { return repo + "/engine" }
+ if fm.fileExists(atPath: repo + "/" + marker) { return repo }
+ return fm.fileExists(atPath: repo + "/engine/" + marker) ? repo + "/engine" : repo
+ }
+
+ /// A folder the launcher can build from: a checkout with tools/engine.py to make engine/, a synced engine/, or an engine tree.
+ package static func isCheckout(_ dir: String) -> Bool {
+ let fm = FileManager.default
+ return !dir.isEmpty && (fm.fileExists(atPath: dir + "/" + marker) || fm.fileExists(atPath: dir + "/engine/" + marker) || hasEngineTool(dir))
+ }
+}
diff --git a/frontend/Sources/NXCore/RepoLayout.swift b/frontend/Sources/NXCore/RepoLayout.swift
new file mode 100644
index 00000000..a7bf3c03
--- /dev/null
+++ b/frontend/Sources/NXCore/RepoLayout.swift
@@ -0,0 +1,85 @@
+import Foundation
+
+/// What the launcher knows about a repository folder without running anything: whether it is one, which build tools it has, and
+/// which checkout to use when the player has not chosen one. `RepoStore` calls these.
+package enum RepoLayout {
+ /// 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.
+ package static let buildScript = "scripts/build_ipa_from_nsp.py"
+ package static let romfsImageTool = "dm/tools/romfs_image.py"
+ package static let requiredTools = [buildScript, romfsImageTool]
+
+ /// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of screenshots).
+ package static func shortPath(_ path: String, home: String = NSHomeDirectory()) -> String {
+ path.hasPrefix(home) ? "~" + path.dropFirst(home.count) : path
+ }
+
+ /// A checkout with tools/engine.py, a synced engine/, or an engine tree (#214).
+ package static func isRepo(_ dir: String) -> Bool {
+ EngineLayout.isCheckout(dir)
+ }
+
+ /// The tools of `requiredTools` that `dir` does not have (empty: the build tools are as new as this app needs).
+ package static func missingTools(in dir: String) -> [String] {
+ let root = EngineLayout.root(dir) // the checkout's engine/, or an engine tree itself
+ return requiredTools.filter { !FileManager.default.fileExists(atPath: root + "/" + $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.
+ package static func supportsWorkDir(_ dir: String) -> Bool {
+ let script = EngineLayout.root(dir) + "/" + buildScript
+ if !FileManager.default.fileExists(atPath: script), EngineLayout.hasEngineTool(dir) { return true } // engine/ not made yet: the fork's engine has it
+ guard let text = try? String(contentsOfFile: script, encoding: .utf8) else { return false }
+ return text.contains("'--work-dir'") || text.contains("\"--work-dir\"")
+ }
+
+ /// The checkout of this repository the app drives. A released .app ships on its own,
+ /// so the path is not known at build time: look next to the app bundle, walk up from
+ /// it, then fall back to a saved choice. A repository is identified by
+ /// dm/tools/nx_extract/Program.cs, which only exists in a real checkout.
+ package static func find(defaults: UserDefaults = .standard, bundleURL: URL = Bundle.main.bundleURL,
+ currentDirectory: String = FileManager.default.currentDirectoryPath, home: String = NSHomeDirectory()) -> String {
+ // A candidate that is merely a repository (an upstream nxnative clone) must lose to one
+ // carrying this fork's `--work-dir`: building from an upstream checkout fails with
+ // "unrecognized arguments" after the app has already picked it — and a saved path from an
+ // earlier session pointed at exactly such a clone, so every build said 仓库不是最新版本
+ // (the report's build log). The fork check is the script's own argparse, not a name match,
+ // so a checkout under any folder name ranks correctly.
+ let saved = defaults.string(forKey: "repoPath").flatMap { isRepo($0) ? $0 : nil }
+ var seeds: [String] = []
+ // the app bundle: …/frontend/NX2Apple.app/Contents/MacOS — the checkout it ships from wins
+ let bundle = bundleURL.standardizedFileURL
+ seeds.append(bundle.deletingLastPathComponent().path)
+ seeds.append(bundle.deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent().path)
+ seeds.append(currentDirectory)
+ for base in ["/ZCodeProject/", "/", "/Documents/", "/Desktop/"] {
+ seeds.append(home + base + "nxnative-romfs-archive") // clones made before the rename still resolve
+ seeds.append(home + base + "NX2Apple")
+ seeds.append(home + base + "nxnative") // an upstream clone: last resort
+ }
+ var seen = Set<String>()
+ var repos: [String] = []
+ for s in seeds where !s.isEmpty && seen.insert(s).inserted {
+ var d = s
+ for _ in 0..<5 { // walk up a few levels from each seed
+ if isRepo(d) { repos.append(d); break }
+ let up = (d as NSString).deletingLastPathComponent
+ if up == d || up == "/" { break }
+ d = up
+ }
+ }
+ let forks = repos.filter { supportsWorkDir($0) }
+ if let saved, supportsWorkDir(saved) { return saved } // the player's own fork checkout
+ if let f = forks.first, f != saved {
+ if let saved { fputs("launcher: using the fork checkout \(f); the saved repository \(saved) is an upstream clone without --work-dir\n", stderr) }
+ return f
+ }
+ return saved ?? repos.first ?? ""
+ }
+}
diff --git a/frontend/Sources/NXCore/Uninstall.swift b/frontend/Sources/NXCore/Uninstall.swift
index 3dae3cd9..79808455 100644
--- a/frontend/Sources/NXCore/Uninstall.swift
+++ b/frontend/Sources/NXCore/Uninstall.swift
@@ -28,7 +28,7 @@ package enum Uninstall {
/// The paths this install would remove, computed before anything is offered: the launcher's state
/// folders that exist, and a checkout that is the launcher's own download (the clone destination
- /// `cloneRepo` uses) rather than one the player picked from anywhere on disk.
+ /// `RepoStore.clone` uses) rather than one the player picked from anywhere on disk.
/// `home` is passed in (NSHomeDirectory() at the call site): a computed home is not testable.
nonisolated package static func plan(home: String, gamesFolder: String, outputFolder: String = "", checkouts: [String],
defaultsDomain: String? = nil) -> Plan {
diff --git a/frontend/Sources/NXModel/RepoStore.swift b/frontend/Sources/NXModel/RepoStore.swift
new file mode 100644
index 00000000..d07c362e
--- /dev/null
+++ b/frontend/Sources/NXModel/RepoStore.swift
@@ -0,0 +1,253 @@
+import Foundation
+import Combine
+import NXCore
+
+/// Where the repository is, for the stores and services that only need to read it. `RepoStore` is the one that implements it.
+@MainActor package protocol RepoLocation: AnyObject {
+ /// The folder the launcher drives. Empty: none found yet.
+ var path: String { get }
+ /// `path` is a checkout the launcher can build from.
+ var isRepo: Bool { get }
+ /// `path` has a .git (a ZIP copy has none).
+ var isGit: Bool { get }
+}
+
+/// The repository (LNPANDY/NX2Apple#387, step 7): the checkout the launcher drives, its status line and the updates of it. It
+/// clones it, checks how far it is behind origin/main, pulls (by hand and by itself when the app opens) and connects a ZIP copy
+/// to git. It follows `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").
+///
+/// - What it works with comes through `init`: the `GitCheckout` service, the `Localizer`, the defaults it saves the path and the
+/// automatic-update switch in. Whether a build runs, whether this is a release app (which has no checkout to update), where
+/// the log goes and what happens after the checkout moved are closures the app wires.
+/// - The actions check their own conditions: none runs while a build runs or another repository task does.
+/// - The git work blocks, so it runs off the main actor. The method that starts it sets `busy` first and returns the `Task`.
+/// - The engine sync that follows a clone, a pull and an adoption is not here: it is `didMove`, and the engine has its own store.
+@MainActor package final class RepoStore: ObservableObject, RepoLocation {
+ nonisolated package static let url = "https://github.com/LNPANDY/NX2Apple.git"
+ nonisolated package static let pathKey = "repoPath"
+ nonisolated package static let autoUpdateKey = "autoUpdateRepo"
+
+ /// The checkout of this repository the app drives (`RepoLayout.find` picks it at start). Saved when it changes.
+ @Published package var path: String {
+ didSet { defaults.set(path, forKey: Self.pathKey) }
+ }
+ /// Clone, pull, adoption or update check in flight: the buttons disable and the status line says what is happening.
+ @Published package private(set) var busy = false
+ /// The line under the repository row of Settings.
+ @Published package var status = ""
+ /// nil = not checked yet, 0 = up to date, n = n commits behind origin/main.
+ @Published package var behind: 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 package var autoUpdate: Bool {
+ didSet { defaults.set(autoUpdate, forKey: Self.autoUpdateKey) }
+ }
+ /// The commits the automatic update brought when the app opened; the library's activity line names them. nil: none.
+ @Published package var autoPulled: Int?
+ /// A copy without .git was connected to git and brought to the current version when the app opened (`adoptAtLaunch`).
+ @Published package var autoAdopted = false
+
+ private let localizer: Localizer
+ private let git: GitCheckout
+ private let defaults: UserDefaults
+ private let home: String
+ private let buildRunning: () -> Bool
+ private let isReleaseApp: () -> Bool
+ private let log: (String) -> Void
+ private let didMove: () -> Void
+
+ /// - Parameters:
+ /// - path: the checkout to start with. nil: `RepoLayout.find`, the saved choice or one next to the app.
+ /// - buildRunning: whether a build runs (the model's flag).
+ /// - isReleaseApp: this app carries its own engine and never clones or pulls.
+ /// - log: a line for the build log (the clone's progress, git's output).
+ /// - didMove: the checkout changed (cloned, pulled, adopted): the engine may be stale now.
+ package init(localizer: Localizer, git: GitCheckout, defaults: UserDefaults = .standard, path: String? = nil,
+ home: String = NSHomeDirectory(),
+ buildRunning: @escaping () -> Bool = { false }, isReleaseApp: @escaping () -> Bool = { false },
+ log: @escaping (String) -> Void = { _ in }, didMove: @escaping () -> Void = {}) {
+ self.localizer = localizer
+ self.git = git
+ self.defaults = defaults
+ self.home = home
+ self.buildRunning = buildRunning
+ self.isReleaseApp = isReleaseApp
+ self.log = log
+ self.didMove = didMove
+ self.path = path ?? RepoLayout.find(defaults: defaults, home: home)
+ autoUpdate = defaults.object(forKey: Self.autoUpdateKey) as? Bool ?? true
+ }
+
+ private func t(_ key: String) -> String { localizer.t(key) }
+
+ package var isRepo: Bool { RepoLayout.isRepo(path) }
+ /// A clone has .git; a GitHub "Download ZIP" copy does not (everything builds, but there is
+ /// nothing to fetch or pull — the update buttons hide and the note says to re-download instead).
+ package var isGit: Bool { FileManager.default.fileExists(atPath: path + "/.git") }
+
+ /// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of screenshots).
+ package func shortPath(_ p: String) -> String { RepoLayout.shortPath(p, home: home) }
+
+ /// A task that can run now: no build, no other repository task, a checkout-based app, and git on this Mac.
+ private var mayStart: Bool { !buildRunning() && !busy && !isReleaseApp() }
+
+ // ---- Clone ----
+
+ /// First-time flow: clone the project to ~/NX2Apple (the discovery seeds cover it) and select it.
+ @discardableResult
+ package func clone() -> Task<Void, Never> {
+ guard mayStart else { return Task {} }
+ guard git.binary != nil else { status = t("repo.gitMissing"); return Task {} }
+ let dest = home + "/NX2Apple"
+ if FileManager.default.fileExists(atPath: dest) {
+ if RepoLayout.isRepo(dest) { path = dest; status = ""; return checkForUpdates() }
+ else { status = String(format: t("repo.destBusy"), shortPath(dest)) }
+ return Task {}
+ }
+ busy = true; status = t("repo.downloading")
+ let url = Self.url, log = self.log, git = self.git
+ log("git clone --depth 1 \(url) \(dest)\n")
+ return Task {
+ let ok = await Task.detached {
+ git.clone(url: url, into: dest) { line in DispatchQueue.main.async { log(line + "\n") } }
+ }.value
+ busy = false
+ if ok && RepoLayout.isRepo(dest) {
+ path = dest
+ status = String(format: t("repo.downloadDone"), shortPath(dest))
+ didMove()
+ } else {
+ status = t("repo.downloadFail")
+ try? FileManager.default.removeItem(atPath: dest) // a failed clone leaves an empty folder
+ }
+ }
+ }
+
+ // ---- Check, pull ----
+
+ /// Compare the checkout with origin/main. `silent` is the launch-time check: no status text, no
+ /// error noise when offline — it only fills `behind` when it can. With the automatic update on, a checkout that is behind is
+ /// pulled by it.
+ @discardableResult
+ package func checkForUpdates(silent: Bool = false) -> Task<Void, Never> {
+ guard isRepo, isGit, !isReleaseApp() else { return Task {} } // a release app updates its engine by version instead
+ guard !buildRunning(), !busy, git.binary != nil else {
+ if !silent, git.binary == nil { status = t("repo.gitMissing") }
+ return Task {}
+ }
+ busy = true
+ if !silent { status = t("repo.checking") }
+ let dir = path, git = self.git
+ return Task {
+ let count = await Task.detached { git.behind(dir) ?? -1 }.value
+ busy = false
+ if count >= 0 {
+ behind = count
+ if !silent { status = count == 0 ? t("repo.upToDate") : String(format: t("repo.behind"), count) }
+ else if count > 0 && autoUpdate { await autoPull(count).value } // the check when the app opens
+ } else if !silent {
+ status = t("repo.netFail")
+ }
+ }
+ }
+
+ /// The status line for a failed pull. A diverged checkout ("Not possible to fast-forward") has its
+ /// own commit history — a clone someone worked in, or an old upstream checkout — and no amount of
+ /// pulling fixes that; the actionable answer is the repository picker, which is always offered now.
+ package func pullFailureMessage(_ gitOutput: String) -> String {
+ let diverged = gitOutput.contains("fast-forward") || gitOutput.contains("Diverging")
+ return t(diverged ? "repo.pullDiverged" : "repo.pullFail")
+ }
+
+ /// Fast-forward the checkout to origin/main. The build keeps everything it needs under
+ /// <id>_build/ outside the repository, so a pull never disturbs a previous build's files.
+ @discardableResult
+ package func pull() -> Task<Void, Never> {
+ guard mayStart, isRepo, isGit, git.binary != nil else { return Task {} }
+ busy = true; status = t("repo.pulling")
+ let dir = path, git = self.git
+ return Task {
+ let r = await Task.detached { git.pull(dir) }.value
+ busy = false
+ if r.ok {
+ behind = 0; status = t("repo.pulled")
+ if !r.out.isEmpty { log(r.out + "\n") }
+ didMove() // the pull may have moved the pin or the patches
+ } else {
+ status = pullFailureMessage(r.out)
+ log(r.out + "\n")
+ }
+ }
+ }
+
+ /// 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.
+ @discardableResult
+ package func autoPull(_ behind: Int) -> Task<Void, Never> {
+ guard mayStart, isRepo, isGit, git.binary != nil else { return Task {} }
+ busy = true
+ let dir = path, git = self.git
+ return Task {
+ let pulled = await Task.detached { git.autoPull(dir) }.value
+ busy = false
+ guard let pulled else { status = t("repo.autoSkipped"); return }
+ if pulled.ok {
+ self.behind = 0; autoPulled = behind
+ status = String(format: t("repo.autoPulled"), behind)
+ didMove()
+ } else {
+ status = pullFailureMessage(pulled.out)
+ log(pulled.out + "\n")
+ }
+ }
+ }
+
+ // ---- A ZIP copy ----
+
+ /// The launch-time step for a ZIP copy; a git checkout is left to `checkForUpdates`. Settings and the library's
+ /// activity line say what happened.
+ @discardableResult
+ package func adoptAtLaunch(remote: String = RepoStore.url) -> Task<Void, Never> {
+ guard !isReleaseApp() else { return Task {} }
+ switch GitRules.zipAdoption(isRepo: isRepo, isGit: isGit, buildRunning: buildRunning(), repoBusy: busy, autoUpdate: autoUpdate) {
+ case .notNeeded: break
+ case .waitsForBuild: status = t("repo.zipWaits")
+ case .autoUpdateOff: break // Settings says so next to the repository (repo.zipNoAuto): the player chose this
+ case .adopt:
+ if git.binary == nil { status = t("repo.gitMissing") }
+ else { return adoptAsGit(automatic: true, remote: remote) }
+ }
+ return Task {}
+ }
+
+ /// 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. 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.
+ @discardableResult
+ package func adoptAsGit(automatic: Bool = false, remote: String = RepoStore.url) -> Task<Void, Never> {
+ guard mayStart, isRepo, !isGit, git.binary != nil else { return Task {} }
+ busy = true; status = t("repo.adopting")
+ let dir = path, git = self.git
+ return Task {
+ let branch = GitRules.zipCopyBranch()
+ let (ok, out) = await Task.detached { git.adopt(dir, remote: remote, branch: branch) }.value
+ busy = false
+ log(out + "\n")
+ if ok && isGit {
+ // the checkout is origin/main as just fetched: up to date, nothing left to pull
+ behind = 0
+ status = String(format: t(automatic ? "repo.adoptedAuto" : "repo.adopted"), branch)
+ if automatic { autoAdopted = true }
+ didMove()
+ } else {
+ status = t(automatic ? "repo.adoptFailAuto" : "repo.adoptFail")
+ }
+ }
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/CloudFolderTests.swift b/frontend/Tests/NX2AppleTests/CloudFolderTests.swift
index c6c5d4c5..1822d9c8 100644
--- a/frontend/Tests/NX2AppleTests/CloudFolderTests.swift
+++ b/frontend/Tests/NX2AppleTests/CloudFolderTests.swift
@@ -108,7 +108,7 @@ final class CloudFolderTests: XCTestCase {
@MainActor func testABuildInACloudFolderStopsBeforeItStarts() throws {
let repo = home.appendingPathComponent("repo")
- for f in BuildModel.requiredTools + ["dm/tools/nx_extract/Program.cs"] {
+ for f in RepoLayout.requiredTools + ["dm/tools/nx_extract/Program.cs"] {
let url = repo.appendingPathComponent(f)
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try "x".write(to: url, atomically: true, encoding: .utf8)
diff --git a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
index 520e48c1..0611ca32 100644
--- a/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
+++ b/frontend/Tests/NX2AppleTests/ConsolePadTests.swift
@@ -94,7 +94,7 @@ final class ConsolePadTests: XCTestCase {
let output = URL(fileURLWithPath: directory)
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
NSApplication.shared.setActivationPolicy(.accessory)
- let repo = BuildModel.findRepo()
+ let repo = RepoLayout.find()
for (sizeName, width, height) in [("1920", CGFloat(1920), CGFloat(1080)), ("compact", 390, 844)] {
for (name, scenario, family) in [("home", MockConsoleDriver.Scenario.full, ConsoleGlyphs.Family.xbox), ("home-dualsense", .full, .playStation), ("home-keyboard", .full, .keyboard),
("controllers", .controllersMixed, .xbox), ("home-4pads", .controllersMixed, .xbox), ("controllers-wired", .controllers, .xbox), ("options", .full, .xbox), ("empty", .empty, .xbox), ("starting", .starting, .xbox)] {
diff --git a/frontend/Tests/NX2AppleTests/DropFilesTests.swift b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
index ffcbf71f..101cd34f 100644
--- a/frontend/Tests/NX2AppleTests/DropFilesTests.swift
+++ b/frontend/Tests/NX2AppleTests/DropFilesTests.swift
@@ -138,7 +138,7 @@ final class DropFilesTests: XCTestCase {
model.deps = [Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]
let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))
// the page as a drag shows it: the highlight drawn over the Builds page
- let page = BuilderView(m: model, updates: model.appUpdates, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)
+ let page = BuilderView(m: model, updates: model.appUpdates, repo: model.repo, library: library).environmentObject(PadFocus()).environmentObject(model.localizer)
.modifier(GameFilesDrop(enabled: true, label: model.t("drop.hint"), targeted: true) { _ in })
.frame(width: 1100, height: 760).background(LauncherPalette.background).environment(\.colorScheme, .dark)
let host = NSHostingView(rootView: page)
diff --git a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift
index 64f1e9bf..f1686389 100644
--- a/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift
+++ b/frontend/Tests/NX2AppleTests/EngineLayoutTests.swift
@@ -42,7 +42,7 @@ final class EngineLayoutTests: XCTestCase {
func testAnEngineTreeIsItsOwnRoot() throws {
try touch(EngineLayout.marker)
- XCTAssertTrue(BuildModel.isRepo(repo))
+ XCTAssertTrue(RepoLayout.isRepo(repo))
XCTAssertEqual(EngineLayout.root(repo), repo)
XCTAssertFalse(EngineLayout.isStale(repo))
XCTAssertFalse(EngineLayout.needsSyncBeforeBuild(repo))
@@ -53,11 +53,11 @@ final class EngineLayoutTests: XCTestCase {
try syncedEngine()
XCTAssertFalse(EngineLayout.isStale(repo))
XCTAssertEqual(EngineLayout.root(repo), repo + "/engine")
- XCTAssertEqual(BuildModel.missingTools(in: repo), BuildModel.requiredTools) // looked for under engine/, which lacks them here
+ XCTAssertEqual(RepoLayout.missingTools(in: repo), RepoLayout.requiredTools) // looked for under engine/, which lacks them here
try touch("engine/scripts/build_ipa_from_nsp.py", "p.add_argument('--work-dir')\n")
try touch("engine/dm/tools/romfs_image.py")
- XCTAssertEqual(BuildModel.missingTools(in: repo), [])
- XCTAssertTrue(BuildModel.repoSupportsWorkDir(repo))
+ XCTAssertEqual(RepoLayout.missingTools(in: repo), [])
+ XCTAssertTrue(RepoLayout.supportsWorkDir(repo))
}
func testAStaleEngineIsStillTheCheckoutsEngineAndTheBuildSyncsItFirst() throws {
@@ -78,9 +78,9 @@ final class EngineLayoutTests: XCTestCase {
func testACheckoutWithoutAnEngineIsSyncedBeforeABuild() throws {
try newLayout()
- XCTAssertTrue(BuildModel.isRepo(repo))
+ XCTAssertTrue(RepoLayout.isRepo(repo))
XCTAssertTrue(EngineLayout.needsSyncBeforeBuild(repo))
- XCTAssertTrue(BuildModel.repoSupportsWorkDir(repo)) // the fork's engine always has --work-dir
+ XCTAssertTrue(RepoLayout.supportsWorkDir(repo)) // the fork's engine always has --work-dir
XCTAssertEqual(EngineLayout.root(repo), repo + "/engine")
try syncedEngine()
XCTAssertFalse(EngineLayout.needsSyncBeforeBuild(repo))
diff --git a/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift b/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift
index ddc12efb..4bff5102 100644
--- a/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift
+++ b/frontend/Tests/NX2AppleTests/EngineUpdateModelTests.swift
@@ -11,16 +11,16 @@ final class EngineUpdateModelTests: XCTestCase {
private func id(_ c: Character) -> String { String(repeating: c, count: 40) + "-0123456789ab" }
/// A launcher built from the repository keeps git, the release app never touches it.
- func testTheReleaseAppNeverRunsGit() {
+ @MainActor func testTheReleaseAppNeverRunsGit() {
let m = BuildModel()
m.engineBundle = root
- m.cloneRepo()
- m.pullRepo()
- m.autoPull(3)
- m.adoptRepoAsGit()
- m.checkRepoUpdates()
- XCTAssertFalse(m.repoBusy)
- XCTAssertEqual(m.repoStatus, "")
+ m.repo.clone()
+ m.repo.pull()
+ m.repo.autoPull(3)
+ m.repo.adoptAsGit()
+ m.repo.checkForUpdates()
+ XCTAssertFalse(m.repo.busy)
+ XCTAssertEqual(m.repo.status, "")
}
func testAnEngineInstalledDuringABuildWaits() {
diff --git a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
index 6f5d92bc..71aa39ae 100644
--- a/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NX2AppleTests/LauncherControlWidthTests.swift
@@ -90,7 +90,7 @@ final class LauncherControlWidthTests: XCTestCase {
},
Scenario(name: "settings with a clone that is behind and an app update", page: .settings, atLeast: 6) { m, _, directory in
m.repoPath = try self.makeRepo(directory, git: true)
- m.repoBehind = 2
+ MainActor.assumeIsolated { m.repo.behind = 2 }
MainActor.assumeIsolated { m.appUpdates.installability = .ok }
MainActor.assumeIsolated { m.appUpdates.update = release }
},
diff --git a/frontend/Tests/NX2AppleTests/LibraryTests.swift b/frontend/Tests/NX2AppleTests/LibraryTests.swift
index 0daff4da..437d217d 100644
--- a/frontend/Tests/NX2AppleTests/LibraryTests.swift
+++ b/frontend/Tests/NX2AppleTests/LibraryTests.swift
@@ -299,7 +299,7 @@ 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)
+ try RepoLayout.requiredTools.filter { $0 != RepoLayout.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)
@@ -554,7 +554,7 @@ 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)
+ try RepoLayout.requiredTools.filter { $0 != RepoLayout.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)
@@ -788,22 +788,22 @@ final class LibraryTests: XCTestCase {
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] {
+ for f in ["dm/tools/nx_extract/Program.cs", RepoLayout.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 }
+ let previous = (model.repoPath, model.repo.autoUpdate, model.repo.status, model.repo.autoAdopted, model.doneNote)
+ defer { (model.repoPath, model.repo.autoUpdate, model.repo.status, model.repo.autoAdopted, model.doneNote) = previous }
model.repoPath = zip.path
- model.autoUpdateRepo = false
+ model.repo.autoUpdate = false
try capture("settings-zip-auto-off", page: .settings)
- model.autoUpdateRepo = true
- model.repoStatus = String(format: model.t("repo.adoptedAuto"), "zip-copy-2026-10-27")
- model.autoAdopted = true
+ model.repo.autoUpdate = true
+ model.repo.status = String(format: model.t("repo.adoptedAuto"), "zip-copy-2026-10-27")
+ model.repo.autoAdopted = true
try capture("library-adopted")
- model.autoAdopted = false
- model.repoStatus = ""
+ model.repo.autoAdopted = false
+ model.repo.status = ""
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)
diff --git a/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift b/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift
index f9adb6d3..d7efc614 100644
--- a/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift
+++ b/frontend/Tests/NX2AppleTests/RepoAutoUpdateTests.swift
@@ -49,9 +49,9 @@ final class RepoAutoUpdateTests: XCTestCase {
@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)
+ m.repo.autoUpdate = true
+ m.repo.checkForUpdates(silent: true) // what the library does when the app opens
+ let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repo.busy && m.repo.behind != nil && (m.repo.autoPulled != nil || !m.repo.status.isEmpty) }, object: nil)
wait(for: [settled], timeout: 20)
return m
}
@@ -59,8 +59,8 @@ final class RepoAutoUpdateTests: XCTestCase {
@MainActor func testACleanCheckoutOnMainIsUpdatedWhenTheAppOpens() throws {
let checkout = try fixture()
let m = open(checkout)
- XCTAssertEqual(m.autoPulled, 1)
- XCTAssertEqual(m.repoBehind, 0)
+ XCTAssertEqual(m.repo.autoPulled, 1)
+ XCTAssertEqual(m.repo.behind, 0)
XCTAssertEqual(try git("log", "-1", "--format=%s", in: checkout), "two")
}
@@ -68,8 +68,8 @@ final class RepoAutoUpdateTests: XCTestCase {
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"))
+ XCTAssertNil(m.repo.autoPulled)
+ XCTAssertEqual(m.repo.status, m.t("repo.autoSkipped"))
XCTAssertEqual(try git("log", "-1", "--format=%s", in: checkout), "one")
}
}
diff --git a/frontend/Tests/NX2AppleTests/RepoFlowFakeTests.swift b/frontend/Tests/NX2AppleTests/RepoFlowFakeTests.swift
deleted file mode 100644
index eade666a..00000000
--- a/frontend/Tests/NX2AppleTests/RepoFlowFakeTests.swift
+++ /dev/null
@@ -1,110 +0,0 @@
-import XCTest
-@testable import NX2Apple
-@testable import NXCore
-
-/// The repository flows of BuildModel with a fake `GitCheckout`: the model's states and texts for each answer git can give,
-/// with no git and no network. (RepoAutoUpdateTests and RepoToolsTests run the real git against local repositories.)
-final class RepoFlowFakeTests: XCTestCase {
- private var temporary: URL!
- private var saved: [(String, Any?)] = []
-
- override func setUpWithError() throws {
- temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-fake-" + UUID().uuidString)
- // what makes it a checkout to the launcher: the extractor's project and a .git
- let marker = temporary.appendingPathComponent("dm/tools/nx_extract/Program.cs")
- try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
- try "x".write(to: marker, atomically: true, encoding: .utf8)
- try FileManager.default.createDirectory(at: temporary.appendingPathComponent(".git"), 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)
- }
-
- @MainActor private func model(_ git: GitCheckout) -> BuildModel {
- let m = BuildModel(gitCheckout: git)
- m.repoPath = temporary.path
- m.autoUpdateRepo = false
- return m
- }
-
- @MainActor private func settle(_ m: BuildModel) {
- let done = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repoBusy }, object: nil)
- wait(for: [done], timeout: 10)
- }
-
- @MainActor func testTheCheckShowsHowFarBehindTheCheckoutIs() {
- let git = FakeGitCheckout(); git.behindCount = 3
- let m = model(git)
- m.checkRepoUpdates()
- settle(m)
- XCTAssertEqual(m.repoBehind, 3)
- XCTAssertEqual(m.repoStatus, String(format: m.t("repo.behind"), 3))
- XCTAssertEqual(git.calls, ["behind " + temporary.path])
- }
-
- @MainActor func testAnOfflineCheckSaysSoAndLeavesTheCountUnknown() {
- let git = FakeGitCheckout(); git.behindCount = nil
- let m = model(git)
- m.checkRepoUpdates()
- settle(m)
- XCTAssertNil(m.repoBehind)
- XCTAssertEqual(m.repoStatus, m.t("repo.netFail"))
- }
-
- @MainActor func testASilentOfflineCheckSaysNothing() {
- let git = FakeGitCheckout(); git.behindCount = nil
- let m = model(git)
- m.checkRepoUpdates(silent: true)
- settle(m)
- XCTAssertEqual(m.repoStatus, "")
- }
-
- @MainActor func testADivergedCheckoutGetsTheRepositoryPickerAdvice() {
- let git = FakeGitCheckout()
- git.pullResult = ProcessResult(status: 128, out: "fatal: Not possible to fast-forward, aborting.")
- let m = model(git)
- m.pullRepo()
- settle(m)
- XCTAssertEqual(m.repoStatus, m.t("repo.pullDiverged"))
- XCTAssertEqual(git.calls, ["pull " + temporary.path])
- }
-
- @MainActor func testAMacWithoutGitIsToldSoAndNothingRuns() {
- let git = FakeGitCheckout(); git.binary = nil
- let m = model(git)
- m.checkRepoUpdates()
- XCTAssertEqual(m.repoStatus, m.t("repo.gitMissing"))
- XCTAssertFalse(m.repoBusy)
- XCTAssertTrue(git.calls.isEmpty)
- }
-
- @MainActor func testTheAutomaticUpdateOfACheckoutOnABranchIsSkipped() {
- let git = FakeGitCheckout(); git.autoPullResult = nil
- let m = model(git)
- m.autoPull(2)
- settle(m)
- XCTAssertEqual(m.repoStatus, m.t("repo.autoSkipped"))
- XCTAssertNil(m.autoPulled)
- }
-}
-
-/// A `GitCheckout` that runs nothing: each call is recorded and answered from the fields.
-final class FakeGitCheckout: GitCheckout, @unchecked Sendable {
- var binary: String? = "/fake/git"
- var behindCount: Int? = 0
- var pullResult = ProcessResult()
- var autoPullResult: ProcessResult?
- var adoptResult: (ok: Bool, log: String) = (true, "")
- var cloneOK = true
- var calls: [String] = []
-
- func run(_ dir: String, _ args: [String]) -> ProcessResult { calls.append("run \(dir) \(args.joined(separator: " "))"); return ProcessResult() }
- func clone(url: String, into dest: String, line: @escaping (String) -> Void) -> Bool { calls.append("clone \(url) \(dest)"); line("Cloning"); return cloneOK }
- func behind(_ dir: String) -> Int? { calls.append("behind \(dir)"); return behindCount }
- func pull(_ dir: String) -> ProcessResult { calls.append("pull \(dir)"); return pullResult }
- func autoPull(_ dir: String) -> ProcessResult? { calls.append("autoPull \(dir)"); return autoPullResult }
- func adopt(_ dir: String, remote: String, branch: String) -> (ok: Bool, log: String) { calls.append("adopt \(dir) \(remote) \(branch)"); return adoptResult }
-}
diff --git a/frontend/Tests/NX2AppleTests/RepoToolsTests.swift b/frontend/Tests/NX2AppleTests/RepoToolsTests.swift
index 0f4065c1..eecd3d52 100644
--- a/frontend/Tests/NX2AppleTests/RepoToolsTests.swift
+++ b/frontend/Tests/NX2AppleTests/RepoToolsTests.swift
@@ -40,29 +40,29 @@ final class RepoToolsTests: XCTestCase {
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)
+ try write(["dm/tools/nx_extract/Program.cs", RepoLayout.buildScript], in: repo) // the v0.4.5 copy of the report
+ XCTAssertEqual(RepoLayout.missingTools(in: repo.path), [RepoLayout.romfsImageTool])
+ try write([RepoLayout.romfsImageTool], in: repo)
+ XCTAssertEqual(RepoLayout.missingTools(in: repo.path), [])
+ XCTAssertEqual(RepoLayout.missingTools(in: temporary.appendingPathComponent("nothing").path), RepoLayout.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), [])
+ guard RepoLayout.isRepo(root.path) else { throw XCTSkip("not run inside a checkout") }
+ XCTAssertEqual(RepoLayout.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)
+ try write(["dm/tools/nx_extract/Program.cs", RepoLayout.buildScript], in: repo)
let m = BuildModel()
m.repoPath = repo.path
m.target = BuildTarget.mac
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))
+ XCTAssertTrue(m.doneNote.contains(RepoLayout.romfsImageTool), m.doneNote)
+ XCTAssertEqual(m.doneNote, String(format: m.t("msg.toolsOld"), RepoLayout.romfsImageTool))
}
// MARK: the adoption itself (local repository as origin)
@@ -74,21 +74,21 @@ final class RepoToolsTests: XCTestCase {
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 write(["dm/tools/nx_extract/Program.cs", RepoLayout.buildScript, RepoLayout.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")
+ try write(["dm/tools/nx_extract/Program.cs", RepoLayout.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)
+ m.repo.autoUpdate = auto
+ m.repo.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)
+ let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in !m.repo.busy && !m.repo.status.isEmpty && m.repo.status != m.t("repo.adopting") }, object: nil)
wait(for: [settled], timeout: 20)
return m
}
@@ -96,32 +96,32 @@ final class RepoToolsTests: XCTestCase {
@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])
+ XCTAssertEqual(RepoLayout.missingTools(in: f.zip.path), [RepoLayout.romfsImageTool])
let m = openZip(f, auto: true)
XCTAssertTrue(m.repoIsGit)
- XCTAssertTrue(m.autoAdopted)
- XCTAssertEqual(m.repoStatus, String(format: m.t("repo.adoptedAuto"), GitRules.zipCopyBranch()))
- XCTAssertEqual(BuildModel.missingTools(in: f.zip.path), [], "the tools of origin/main are there now")
+ XCTAssertTrue(m.repo.autoAdopted)
+ XCTAssertEqual(m.repo.status, String(format: m.t("repo.adoptedAuto"), GitRules.zipCopyBranch()))
+ XCTAssertEqual(RepoLayout.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")
+ XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(RepoLayout.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 "my tweak".write(to: f.zip.appendingPathComponent(RepoLayout.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 = GitRules.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("show", "main:" + RepoLayout.buildScript, in: f.zip), "new", "main has origin's version")
+ XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(RepoLayout.buildScript), encoding: .utf8), "new")
+ XCTAssertEqual(try git("show", branch + ":" + RepoLayout.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")
+ ["dm/tools/nx_extract/Program.cs", RepoLayout.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)
+ XCTAssertTrue(m.repo.status.contains(branch), m.repo.status)
}
@MainActor func testWithTheAutomaticUpdateOffTheZipCopyIsLeftAlone() throws {
@@ -129,19 +129,19 @@ final class RepoToolsTests: XCTestCase {
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])
+ XCTAssertFalse(m.repo.autoAdopted)
+ XCTAssertTrue(m.repo.status.isEmpty, "Settings says it next to the repository (repo.zipNoAuto), not as a status")
+ XCTAssertEqual(RepoLayout.missingTools(in: f.zip.path), [RepoLayout.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")
- XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(BuildModel.buildScript), encoding: .utf8), "old", "nothing was changed")
+ XCTAssertEqual(m.repo.status, m.t("repo.adoptFailAuto"))
+ XCTAssertFalse(m.repo.autoAdopted)
+ XCTAssertTrue(RepoLayout.isRepo(f.zip.path), "the files are still there")
+ XCTAssertEqual(try String(contentsOf: f.zip.appendingPathComponent(RepoLayout.buildScript), encoding: .utf8), "old", "nothing was changed")
XCTAssertFalse(FileManager.default.fileExists(atPath: f.zip.appendingPathComponent(".git").path))
}
}
diff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
index f7cc9d28..88e8b1c0 100644
--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
@@ -743,7 +743,7 @@ final class ShellInstallTests: XCTestCase {
model.signingTeam = team
model.xcrunPath = f.xcrun
try write(f.repo + "/dm/tools/nx_extract/Program.cs", "")
- for tool in BuildModel.requiredTools.filter({ $0 != BuildModel.buildScript }) { try write(f.repo + "/" + tool, "") }
+ for tool in RepoLayout.requiredTools.filter({ $0 != RepoLayout.buildScript }) { try write(f.repo + "/" + tool, "") }
// the packer stand-in writes the image from the extracted RomFS
try write(f.repo + "/dm/tools/romfs_image.py", "import sys\nopen(sys.argv[3], 'wb').write(b'image')\n")
try write(f.repo + "/scripts/build_ipa_from_nsp.py", """
@@ -807,7 +807,7 @@ final class ShellInstallTests: XCTestCase {
model.signingTeam = team
model.xcrunPath = f.xcrun
try write(f.repo + "/dm/tools/nx_extract/Program.cs", "")
- for tool in BuildModel.requiredTools.filter({ $0 != BuildModel.buildScript }) { try write(f.repo + "/" + tool, "") }
+ for tool in RepoLayout.requiredTools.filter({ $0 != RepoLayout.buildScript }) { try write(f.repo + "/" + tool, "") }
try write(f.repo + "/scripts/build_ipa_from_nsp.py", "open('\(state)/script.txt', 'w').write('ran')\n")
let base = temporary.appendingPathComponent("Test [\(titleID)].nsp"), keys = temporary.appendingPathComponent("prod.keys")
try Data([0]).write(to: base); try Data().write(to: keys)
diff --git a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
index 116324d9..f3a34c38 100644
--- a/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
+++ b/frontend/Tests/NX2AppleTests/SourceSizeTests.swift
@@ -7,7 +7,7 @@ final class SourceSizeTests: XCTestCase {
/// Path under frontend/Sources → its line count when the limit came in. Lower the number when the file shrinks.
private static let aboveTheLimit: [String: Int] = [
- "NX2Apple/ContentView.swift": 2494,
+ "NX2Apple/ContentView.swift": 2265,
"NX2Apple/LauncherView.swift": 967,
"NXCore/Localization.swift": 4237,
]
diff --git a/frontend/Tests/NXModelTests/FakeGitCheckout.swift b/frontend/Tests/NXModelTests/FakeGitCheckout.swift
new file mode 100644
index 00000000..e7c4466e
--- /dev/null
+++ b/frontend/Tests/NXModelTests/FakeGitCheckout.swift
@@ -0,0 +1,32 @@
+import Foundation
+import NXCore
+
+/// A `GitCheckout` that runs nothing: each call is recorded and answered from the fields.
+final class FakeGitCheckout: GitCheckout, @unchecked Sendable {
+ private let lock = NSLock()
+ private var recorded: [String] = []
+ var binary: String? = "/fake/git"
+ var behindCount: Int? = 0
+ var pullResult = ProcessResult()
+ var autoPullResult: ProcessResult?
+ var adoptResult: (ok: Bool, log: String) = (true, "")
+ var cloneOK = true
+ /// What a clone makes in its destination (a test makes it look like a checkout). nil: nothing.
+ var cloneMakes: ((String) -> Void)?
+
+ var calls: [String] { lock.withLock { recorded } }
+ private func record(_ call: String) { lock.withLock { recorded.append(call) } }
+
+ func run(_ dir: String, _ args: [String]) -> ProcessResult { record("run \(dir) \(args.joined(separator: " "))"); return ProcessResult() }
+ func clone(url: String, into dest: String, line: @escaping (String) -> Void) -> Bool {
+ record("clone \(url) \(dest)"); line("Cloning"); cloneMakes?(dest); return cloneOK
+ }
+ func behind(_ dir: String) -> Int? { record("behind \(dir)"); return behindCount }
+ func pull(_ dir: String) -> ProcessResult { record("pull \(dir)"); return pullResult }
+ func autoPull(_ dir: String) -> ProcessResult? { record("autoPull \(dir)"); return autoPullResult }
+ func adopt(_ dir: String, remote: String, branch: String) -> (ok: Bool, log: String) {
+ record("adopt \(dir) \(remote) \(branch)")
+ if adoptResult.ok { try? FileManager.default.createDirectory(atPath: dir + "/.git", withIntermediateDirectories: true) }
+ return adoptResult
+ }
+}
diff --git a/frontend/Tests/NXModelTests/RepoStoreTests.swift b/frontend/Tests/NXModelTests/RepoStoreTests.swift
new file mode 100644
index 00000000..c2d6de36
--- /dev/null
+++ b/frontend/Tests/NXModelTests/RepoStoreTests.swift
@@ -0,0 +1,348 @@
+import XCTest
+@testable import NXModel
+@testable import NXCore
+
+/// `RepoStore` without SwiftUI: a fake `GitCheckout` answers for git, the checkouts are folders in a temporary directory and the
+/// defaults are a suite of their own. The model's wiring is tested in NX2AppleTests (RepoAutoUpdateTests, RepoToolsTests run the
+/// real git against local repositories).
+@MainActor final class RepoStoreTests: XCTestCase {
+ private var temporary: URL!
+ private var suite: String!
+ private var defaults: UserDefaults!
+ private let git = FakeGitCheckout()
+ private let localizer = Localizer(.en)
+ private var log: [String] = []
+ private var moved = 0
+ private var building = false
+ private var releaseApp = false
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxmodel-repo-tests-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ suite = "nxmodel-repo-tests-" + UUID().uuidString
+ defaults = UserDefaults(suiteName: suite)
+ }
+
+ override func tearDownWithError() throws {
+ try FileManager.default.removeItem(at: temporary)
+ defaults.removePersistentDomain(forName: suite)
+ }
+
+ /// A folder the launcher takes for a checkout: the extractor's project, and a .git when `isGit`.
+ @discardableResult
+ private func makeCheckout(_ name: String = "clone", isGit: Bool = true) throws -> String {
+ let dir = temporary.appendingPathComponent(name)
+ let marker = dir.appendingPathComponent(EngineLayout.marker)
+ try FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try "x".write(to: marker, atomically: true, encoding: .utf8)
+ if isGit { try FileManager.default.createDirectory(at: dir.appendingPathComponent(".git"), withIntermediateDirectories: true) }
+ return dir.path
+ }
+
+ private func makeStore(path: String? = nil, autoUpdate: Bool? = nil) -> RepoStore {
+ if let autoUpdate { defaults.set(autoUpdate, forKey: RepoStore.autoUpdateKey) }
+ return RepoStore(localizer: localizer, git: git, defaults: defaults, path: path ?? "", home: temporary.path,
+ buildRunning: { [unowned self] in building }, isReleaseApp: { [unowned self] in releaseApp },
+ log: { [unowned self] in log.append($0) }, didMove: { [unowned self] in moved += 1 })
+ }
+
+ private func t(_ key: String) -> String { localizer.t(key) }
+
+ // ---- State ----
+
+ func testThePathIsSavedAndTheSwitchIsOnByDefault() throws {
+ let dir = try makeCheckout()
+ let store = makeStore(path: dir)
+ XCTAssertTrue(store.autoUpdate)
+ XCTAssertTrue(store.isRepo)
+ XCTAssertTrue(store.isGit)
+ store.path = temporary.path
+ XCTAssertEqual(defaults.string(forKey: RepoStore.pathKey), temporary.path)
+ XCTAssertFalse(store.isRepo)
+ store.autoUpdate = false
+ XCTAssertEqual(defaults.object(forKey: RepoStore.autoUpdateKey) as? Bool, false)
+ XCTAssertFalse(makeStore().autoUpdate, "the next start reads the switch back")
+ }
+
+ func testAZipCopyIsARepositoryWithoutGit() throws {
+ let store = makeStore(path: try makeCheckout("zip", isGit: false))
+ XCTAssertTrue(store.isRepo)
+ XCTAssertFalse(store.isGit)
+ }
+
+ func testTheStoreIsTheRepoLocationOthersAskFor() throws {
+ let store = makeStore(path: try makeCheckout())
+ let location: RepoLocation = store
+ XCTAssertEqual(location.path, store.path)
+ XCTAssertTrue(location.isRepo)
+ }
+
+ func testTheHomeIsShownAsATilde() {
+ XCTAssertEqual(makeStore().shortPath(temporary.path + "/NX2Apple"), "~/NX2Apple")
+ XCTAssertEqual(makeStore().shortPath("/elsewhere/NX2Apple"), "/elsewhere/NX2Apple")
+ }
+
+ // ---- Check ----
+
+ func testTheCheckShowsHowFarBehindTheCheckoutIs() async throws {
+ git.behindCount = 3
+ let dir = try makeCheckout()
+ let store = makeStore(path: dir, autoUpdate: false)
+ let task = store.checkForUpdates()
+ XCTAssertTrue(store.busy, "set before the task runs")
+ XCTAssertEqual(store.status, t("repo.checking"))
+ await task.value
+ XCTAssertFalse(store.busy)
+ XCTAssertEqual(store.behind, 3)
+ XCTAssertEqual(store.status, String(format: t("repo.behind"), 3))
+ XCTAssertEqual(git.calls, ["behind " + dir])
+ }
+
+ func testACheckoutThatIsUpToDateSaysSo() async throws {
+ git.behindCount = 0
+ let store = makeStore(path: try makeCheckout())
+ await store.checkForUpdates().value
+ XCTAssertEqual(store.behind, 0)
+ XCTAssertEqual(store.status, t("repo.upToDate"))
+ }
+
+ func testAnOfflineCheckSaysSoAndLeavesTheCountUnknown() async throws {
+ git.behindCount = nil
+ let store = makeStore(path: try makeCheckout())
+ await store.checkForUpdates().value
+ XCTAssertNil(store.behind)
+ XCTAssertEqual(store.status, t("repo.netFail"))
+ }
+
+ func testASilentOfflineCheckSaysNothing() async throws {
+ git.behindCount = nil
+ let store = makeStore(path: try makeCheckout())
+ await store.checkForUpdates(silent: true).value
+ XCTAssertEqual(store.status, "")
+ }
+
+ func testASilentCheckPullsWhenTheSwitchIsOn() async throws {
+ git.behindCount = 2
+ git.autoPullResult = ProcessResult()
+ let store = makeStore(path: try makeCheckout(), autoUpdate: true)
+ await store.checkForUpdates(silent: true).value
+ XCTAssertEqual(store.autoPulled, 2)
+ XCTAssertEqual(store.behind, 0)
+ XCTAssertEqual(store.status, String(format: t("repo.autoPulled"), 2))
+ XCTAssertEqual(moved, 1, "the engine may be stale after a pull")
+ XCTAssertFalse(store.busy)
+ }
+
+ func testASilentCheckOnlyCountsWhenTheSwitchIsOff() async throws {
+ git.behindCount = 2
+ let store = makeStore(path: try makeCheckout(), autoUpdate: false)
+ await store.checkForUpdates(silent: true).value
+ XCTAssertEqual(store.behind, 2)
+ XCTAssertEqual(store.status, "")
+ XCTAssertNil(store.autoPulled)
+ XCTAssertEqual(moved, 0)
+ }
+
+ func testAMacWithoutGitIsToldSoAndNothingRuns() throws {
+ git.binary = nil
+ let store = makeStore(path: try makeCheckout())
+ store.checkForUpdates()
+ XCTAssertEqual(store.status, t("repo.gitMissing"))
+ XCTAssertFalse(store.busy)
+ XCTAssertTrue(git.calls.isEmpty)
+ }
+
+ func testNoCheckForAZipCopy() async throws {
+ let store = makeStore(path: try makeCheckout("zip", isGit: false))
+ await store.checkForUpdates().value
+ XCTAssertTrue(git.calls.isEmpty)
+ XCTAssertNil(store.behind)
+ }
+
+ // ---- Pull ----
+
+ func testAPullBringsTheCheckoutUpToDate() async throws {
+ git.pullResult = ProcessResult(status: 0, out: "Updating 1..2")
+ let dir = try makeCheckout()
+ let store = makeStore(path: dir)
+ store.behind = 4
+ let task = store.pull()
+ XCTAssertEqual(store.status, t("repo.pulling"))
+ await task.value
+ XCTAssertEqual(store.behind, 0)
+ XCTAssertEqual(store.status, t("repo.pulled"))
+ XCTAssertEqual(log, ["Updating 1..2\n"])
+ XCTAssertEqual(moved, 1)
+ XCTAssertEqual(git.calls, ["pull " + dir])
+ }
+
+ func testADivergedCheckoutGetsTheRepositoryPickerAdvice() async throws {
+ git.pullResult = ProcessResult(status: 128, out: "fatal: Not possible to fast-forward, aborting.")
+ let store = makeStore(path: try makeCheckout())
+ await store.pull().value
+ XCTAssertEqual(store.status, t("repo.pullDiverged"))
+ XCTAssertEqual(moved, 0)
+ XCTAssertEqual(log.count, 1, "git's words go to the log")
+ }
+
+ func testAnotherFailedPullSaysSo() async throws {
+ git.pullResult = ProcessResult(status: 1, out: "fatal: unable to access")
+ let store = makeStore(path: try makeCheckout())
+ await store.pull().value
+ XCTAssertEqual(store.status, t("repo.pullFail"))
+ }
+
+ // ---- The automatic update ----
+
+ func testTheAutomaticUpdateOfACheckoutOnABranchIsSkipped() async throws {
+ git.autoPullResult = nil
+ let store = makeStore(path: try makeCheckout())
+ await store.autoPull(2).value
+ XCTAssertEqual(store.status, t("repo.autoSkipped"))
+ XCTAssertNil(store.autoPulled)
+ XCTAssertFalse(store.busy)
+ }
+
+ func testAFailedAutomaticUpdateSaysWhy() async throws {
+ git.autoPullResult = ProcessResult(status: 128, out: "fatal: Not possible to fast-forward")
+ let store = makeStore(path: try makeCheckout())
+ await store.autoPull(2).value
+ XCTAssertEqual(store.status, t("repo.pullDiverged"))
+ XCTAssertNil(store.autoPulled)
+ }
+
+ // ---- A ZIP copy ----
+
+ func testAZipCopyIsAdoptedAtLaunch() async throws {
+ let dir = try makeCheckout("zip", isGit: false)
+ let store = makeStore(path: dir, autoUpdate: true)
+ await store.adoptAtLaunch(remote: "file:///origin").value
+ let branch = GitRules.zipCopyBranch()
+ XCTAssertEqual(git.calls, ["adopt \(dir) file:///origin \(branch)"])
+ XCTAssertTrue(store.isGit)
+ XCTAssertTrue(store.autoAdopted)
+ XCTAssertEqual(store.behind, 0)
+ XCTAssertEqual(store.status, String(format: t("repo.adoptedAuto"), branch))
+ XCTAssertEqual(moved, 1)
+ }
+
+ func testWithTheSwitchOffTheZipCopyIsLeftAlone() async throws {
+ let store = makeStore(path: try makeCheckout("zip", isGit: false), autoUpdate: false)
+ await store.adoptAtLaunch().value
+ XCTAssertTrue(git.calls.isEmpty)
+ XCTAssertEqual(store.status, "")
+ XCTAssertFalse(store.autoAdopted)
+ }
+
+ func testAZipCopyWaitsForTheBuild() async throws {
+ building = true
+ let store = makeStore(path: try makeCheckout("zip", isGit: false), autoUpdate: true)
+ await store.adoptAtLaunch().value
+ XCTAssertTrue(git.calls.isEmpty)
+ XCTAssertEqual(store.status, t("repo.zipWaits"))
+ }
+
+ func testAFailedAdoptionSaysSoAndKeepsTheCopy() async throws {
+ git.adoptResult = (false, "fatal: no network")
+ let dir = try makeCheckout("zip", isGit: false)
+ let store = makeStore(path: dir, autoUpdate: true)
+ await store.adoptAtLaunch().value
+ XCTAssertEqual(store.status, t("repo.adoptFailAuto"))
+ XCTAssertFalse(store.autoAdopted)
+ XCTAssertFalse(store.isGit)
+ XCTAssertTrue(store.isRepo)
+ XCTAssertEqual(log, ["fatal: no network\n"])
+ }
+
+ func testTheAdoptionByHandSaysSoInItsOwnWords() async throws {
+ let store = makeStore(path: try makeCheckout("zip", isGit: false), autoUpdate: false)
+ await store.adoptAsGit().value
+ XCTAssertEqual(store.status, String(format: t("repo.adopted"), GitRules.zipCopyBranch()))
+ XCTAssertFalse(store.autoAdopted, "only the launch-time adoption sets it")
+ }
+
+ // ---- Clone ----
+
+ func testACloneIsSelectedAndTheEngineIsToldItMoved() async throws {
+ git.cloneMakes = { dest in
+ let marker = URL(fileURLWithPath: dest).appendingPathComponent(EngineLayout.marker)
+ try? FileManager.default.createDirectory(at: marker.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? "x".write(to: marker, atomically: true, encoding: .utf8)
+ }
+ let store = makeStore()
+ let dest = temporary.path + "/NX2Apple"
+ let task = store.clone()
+ XCTAssertEqual(store.status, t("repo.downloading"))
+ XCTAssertEqual(log.first, "git clone --depth 1 \(RepoStore.url) \(dest)\n")
+ await task.value
+ XCTAssertEqual(store.path, dest)
+ XCTAssertEqual(store.status, String(format: t("repo.downloadDone"), "~/NX2Apple"))
+ XCTAssertEqual(moved, 1)
+ XCTAssertFalse(store.busy)
+ }
+
+ func testAFailedCloneLeavesNothingBehind() async throws {
+ git.cloneOK = false
+ git.cloneMakes = { try? FileManager.default.createDirectory(atPath: $0, withIntermediateDirectories: true) }
+ let store = makeStore()
+ await store.clone().value
+ XCTAssertEqual(store.status, t("repo.downloadFail"))
+ XCTAssertEqual(store.path, "")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: temporary.path + "/NX2Apple"))
+ XCTAssertEqual(moved, 0)
+ }
+
+ func testAFolderThatIsNotARepositoryIsNotCloned() async throws {
+ try FileManager.default.createDirectory(atPath: temporary.path + "/NX2Apple", withIntermediateDirectories: true)
+ let store = makeStore()
+ await store.clone().value
+ XCTAssertEqual(store.status, String(format: t("repo.destBusy"), "~/NX2Apple"))
+ XCTAssertTrue(git.calls.isEmpty)
+ }
+
+ func testAnExistingCheckoutIsSelectedAndChecked() async throws {
+ try makeCheckout("NX2Apple")
+ git.behindCount = 1
+ let store = makeStore(autoUpdate: false)
+ await store.clone().value
+ XCTAssertEqual(store.path, temporary.path + "/NX2Apple")
+ XCTAssertEqual(store.behind, 1)
+ XCTAssertEqual(git.calls, ["behind " + temporary.path + "/NX2Apple"])
+ }
+
+ // ---- Conditions ----
+
+ func testNothingRunsWhileABuildRuns() async throws {
+ building = true
+ let store = makeStore(path: try makeCheckout())
+ await store.checkForUpdates().value
+ await store.pull().value
+ await store.autoPull(1).value
+ await store.clone().value
+ XCTAssertTrue(git.calls.isEmpty)
+ XCTAssertFalse(store.busy)
+ }
+
+ func testAReleaseAppNeverRunsGit() async throws {
+ releaseApp = true
+ let store = makeStore(path: try makeCheckout("zip", isGit: false))
+ await store.clone().value
+ await store.pull().value
+ await store.autoPull(3).value
+ await store.adoptAsGit().value
+ await store.checkForUpdates().value
+ await store.adoptAtLaunch().value
+ XCTAssertTrue(git.calls.isEmpty)
+ XCTAssertFalse(store.busy)
+ XCTAssertEqual(store.status, "")
+ }
+
+ func testOneTaskAtATime() async throws {
+ let store = makeStore(path: try makeCheckout())
+ let first = store.checkForUpdates()
+ await store.pull().value // refused: the check is still in flight
+ await first.value
+ XCTAssertEqual(git.calls.count, 1)
+ XCTAssertFalse(git.calls.contains { $0.hasPrefix("pull") })
+ }
+}