Skip to content

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

Launcher: drop the repository source probe from this branch

v0lumehi979d0ef9d4fc
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index c37c9a83..3a57b6eb 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -359,12 +359,7 @@ final class BuildModel: ObservableObject {
// ---- Repository download and updates (a clone is the scripts' home; not everyone has git habits) ----
- static let repoURL = RepoEndpoints.github.url
- /// The source the last clone or fetch actually used (RepoSource.swift), for the status line and Copy
- /// diagnostics: "GitHub" normally, a mirror or proxy when this network cannot reach GitHub.
- @Published var repoSourceUsed = ""
- /// Remembered between launches, so a player whose network needs the mirror does not probe GitHub again.
- private static let repoSourceKey = "repoSource"
+ 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 = ""
@@ -420,27 +415,11 @@ final class BuildModel: ObservableObject {
return
}
repoBusy = true; repoStatus = t("repo.downloading")
- // A source is probed before the clone: 200 MB from an unreachable host is a long wait for a
- // failure, and `ls-remote` answers in a second. The winner is remembered (RepoSource.swift).
- let preferred = UserDefaults.standard.string(forKey: Self.repoSourceKey)
- let env = Self.gitEnv()
+ append("git clone --depth 1 \(Self.repoURL) \(dest)\n")
DispatchQueue.global().async {
- let source = RepoEndpoints.pick(preferred: preferred) { RepoEndpoints.answers($0, git: git, env: env) }
- guard let source else {
- DispatchQueue.main.async {
- self.repoBusy = false
- self.repoStatus = self.t("repo.netFail")
- }
- return
- }
- DispatchQueue.main.async {
- self.repoSourceUsed = source.name
- UserDefaults.standard.set(source.id, forKey: Self.repoSourceKey)
- self.append("git clone --depth 1 \(source.url) \(dest) (\(source.name))\n")
- }
// Shallow: a quarter of the bytes and a third of the time of a full clone, and fetch /
// pull keep working on it (verified); the history is of no use to someone who wants to build.
- let ok = Self.runCaptured([git, "clone", "--depth", "1", "--single-branch", "--progress", source.url, dest], env: env) {
+ let ok = Self.runCaptured([git, "clone", "--depth", "1", "--single-branch", "--progress", Self.repoURL, dest], env: Self.gitEnv()) {
line in DispatchQueue.main.async { self.append(line + "\n") }
}
DispatchQueue.main.async {
@@ -467,34 +446,16 @@ final class BuildModel: ObservableObject {
repoBusy = true
if !silent { repoStatus = t("repo.checking") }
let dir = repoPath
- let preferred = UserDefaults.standard.string(forKey: Self.repoSourceKey)
DispatchQueue.global().async {
- let env = Self.gitEnv()
- var fetched = Self.runQuiet([git, "-C", dir, "fetch", "origin", "main"], env: env)
- var used = ""
- if !fetched.ok {
- // `origin` is GitHub, which this network may not reach: fetch the same branch from
- // another source into the same remote-tracking ref, so everything downstream (the
- // behind count, the pull) keeps reading `origin/main`.
- for source in RepoEndpoints.ordered(preferred: preferred) where source.url != Self.repoURL {
- let r = Self.runQuiet([git, "-C", dir, "fetch", source.url, "+refs/heads/main:refs/remotes/origin/main"], env: env)
- if r.ok { fetched = r; used = source.name; break }
- }
- }
+ let fetched = Self.runQuiet([git, "-C", dir, "fetch", "origin", "main"], env: Self.gitEnv())
var behind = -1
if fetched.ok {
- let count = Self.runQuiet([git, "-C", dir, "rev-list", "--count", "HEAD..origin/main"], env: env)
+ let count = Self.runQuiet([git, "-C", dir, "rev-list", "--count", "HEAD..origin/main"], env: Self.gitEnv())
if count.ok { behind = Int(count.out.trimmingCharacters(in: .whitespacesAndNewlines)) ?? -1 }
}
DispatchQueue.main.async {
self.repoBusy = false
if behind >= 0 {
- if !used.isEmpty {
- self.repoSourceUsed = used
- if let s = RepoEndpoints.all.first(where: { $0.name == used }) {
- UserDefaults.standard.set(s.id, forKey: Self.repoSourceKey)
- }
- }
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
diff --git a/frontend/Sources/NSPortBuilder/Diagnostics.swift b/frontend/Sources/NSPortBuilder/Diagnostics.swift
index 079d3151..d4927395 100644
--- a/frontend/Sources/NSPortBuilder/Diagnostics.swift
+++ b/frontend/Sources/NSPortBuilder/Diagnostics.swift
@@ -16,8 +16,6 @@ struct Diagnostics {
var macOS: String
var chip: String
var repoPath: String
- /// The source the last clone or fetch used (RepoSource.swift): names the mirror when GitHub was unreachable.
- var repoSource: String = ""
var commit: String? // "<short hash> <subject>"
var branch: String?
var behind: [(ref: String, count: Int)] = [] // upstream/main, origin/main: the ones this checkout has
@@ -65,7 +63,6 @@ struct Diagnostics {
out.append("- macOS: \(i.macOS)")
out.append("- Chip: \(i.chip)")
out.append("- Repository: \(i.repoPath.isEmpty ? "not found" : i.repoPath)")
- if !i.repoSource.isEmpty { out.append("- Repository source: \(i.repoSource)") }
if let commit = i.commit {
var line = "- Commit: \(commit)" + (i.branch.map { " (branch \($0))" } ?? "")
if !i.behind.isEmpty {
@@ -295,7 +292,7 @@ extension BuildModel {
func diagnostics(game: LibraryGame? = nil, _ done: @escaping (String) -> Void) {
let repo = repoOK ? repoPath : "", python = pythonPath.isEmpty ? Self.findPython().path : pythonPath, dotnet = dotnetPath
let rows = depsChecked ? deps.map(Diagnostics.dependency) : [], checked = depsChecked
- let command = lastBuildCommand, log = logTail, xcrun = xcrunPath, repoSource = repoSourceUsed
+ let command = lastBuildCommand, log = logTail, xcrun = xcrunPath
DispatchQueue.global(qos: .userInitiated).async {
let git = Diagnostics.git(repo)
let env = ["HOME": NSHomeDirectory(), "PATH": "/usr/bin:/bin", "TMPDIR": NSTemporaryDirectory()]
@@ -307,7 +304,7 @@ extension BuildModel {
appVersion: Self.appVersion,
macOS: ProcessInfo.processInfo.operatingSystemVersionString,
chip: Diagnostics.chip(),
- repoPath: repo, repoSource: repoSource, commit: git.commit, branch: git.branch, behind: git.behind, lastFetch: git.lastFetch,
+ repoPath: repo, commit: git.commit, branch: git.branch, behind: git.behind, lastFetch: git.lastFetch,
python: python,
pythonVersion: Diagnostics.version(python, ["-c", "import sys; print(sys.version.split()[0])"], env: env),
pythonIsVenv: python == Self.venvPython(),
diff --git a/frontend/Sources/NSPortBuilder/RepoSource.swift b/frontend/Sources/NSPortBuilder/RepoSource.swift
deleted file mode 100644
index 76983d44..00000000
--- a/frontend/Sources/NSPortBuilder/RepoSource.swift
+++ /dev/null
@@ -1,80 +0,0 @@
-import Foundation
-#if canImport(Darwin)
-import Darwin
-#endif
-
-/// Where the project's repository comes from. One list, tried in order: a checkout that cannot reach
-/// GitHub should still download and update, so a mirror and a plain proxy sit behind it.
-///
-/// The list is data, not a switch in the UI: the first source that answers is used and remembered, and
-/// the next one is tried when a clone or a fetch fails. A source that only mirrors the files (a proxy)
-/// is harmless to fall back to — the checkout is the same repository at the same commit, and the build
-/// reads `dm/`, `patches/` and `.upstream-ref` from it.
-struct RepoSource: Equatable, Identifiable {
- /// Stable id, stored in UserDefaults: renaming what the player sees must not forget the choice.
- let id: String
- /// What the status line and Copy diagnostics call it ("GitHub", "GitCode", "gh-proxy").
- let name: String
- /// The clone URL (`git clone` and `git fetch` both take it).
- let url: String
-
- var host: String { URL(string: url)?.host ?? url }
-}
-
-enum RepoEndpoints {
- /// The official repository. Always first, always available.
- static let github = RepoSource(id: "github", name: "GitHub", url: "https://github.com/LNPANDY/NX2Apple.git")
-
- /// The mirror for networks that cannot reach GitHub. `nil` until the mirror exists: the id is
- /// remembered, so once it is set a player who already used it keeps it first.
- static let gitCode: RepoSource? = nil
-
- /// A plain prefix proxy over GitHub (public repositories only). Last, because a third party sees
- /// the requests: it is never given credentials, and it is only used to read.
- static let ghProxy = RepoSource(id: "gh-proxy", name: "gh-proxy", url: "https://gh-proxy.com/https://github.com/LNPANDY/NX2Apple.git")
-
- /// Every source, in the order they are tried when nothing is remembered.
- static var all: [RepoSource] { [github] + (gitCode.map { [$0] } ?? []) + [ghProxy] }
-
- static func source(id: String?) -> RepoSource? {
- guard let id else { return nil }
- return all.first { $0.id == id }
- }
-
- /// The sources to try: the remembered one first (when it is still in the list), then the rest.
- static func ordered(preferred id: String?) -> [RepoSource] {
- guard let first = source(id: id) else { return all }
- return [first] + all.filter { $0.id != first.id }
- }
-
- /// The first source `probe` accepts, in `ordered(preferred:)` order. Pure, so a test drives it
- /// without a network: the caller passes `answers(_:)` in the app.
- static func pick(preferred id: String?, probe: (RepoSource) -> Bool) -> RepoSource? {
- ordered(preferred: id).first(where: probe)
- }
-
- /// Whether `git ls-remote` answers for this source within `timeout` seconds. This is the cheap
- /// check before a multi-hundred-MB clone: it reads the refs and nothing else.
- ///
- /// `GIT_TERMINAL_PROMPT=0` so a source asking for credentials fails at once instead of waiting
- /// for input no one can give (the launcher has no terminal).
- static func answers(_ source: RepoSource, git: String, env: [String: String], timeout: TimeInterval = 8) -> Bool {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: git)
- p.arguments = ["ls-remote", "--heads", source.url]
- p.environment = env.merging(["GIT_TERMINAL_PROMPT": "0"]) { $1 }
- p.standardInput = FileHandle.nullDevice
- p.standardOutput = FileHandle.nullDevice
- p.standardError = FileHandle.nullDevice
- do { try p.run() } catch { return false }
- let deadline = Date().addingTimeInterval(timeout)
- while p.isRunning, Date() < deadline { usleep(50_000) }
- guard !p.isRunning else { // timed out: leave nothing running behind
- p.terminate()
- usleep(200_000)
- if p.isRunning { kill(p.processIdentifier, SIGKILL) }
- return false
- }
- return p.terminationStatus == 0
- }
-}
diff --git a/frontend/Tests/NSPortBuilderTests/RepoSourceTests.swift b/frontend/Tests/NSPortBuilderTests/RepoSourceTests.swift
deleted file mode 100644
index 3009e456..00000000
--- a/frontend/Tests/NSPortBuilderTests/RepoSourceTests.swift
+++ /dev/null
@@ -1,49 +0,0 @@
-import XCTest
-@testable import NSPortBuilder
-
-/// Which source the repository is downloaded from (RepoSource.swift). The probes are injected, so
-/// nothing here touches the network: `pick` is the decision, `answers` is the process in the app.
-final class RepoSourceTests: XCTestCase {
- private func names(_ sources: [RepoSource]) -> [String] { sources.map(\.name) }
-
- func testGitHubComesFirstWhenNothingIsRemembered() {
- XCTAssertEqual(RepoEndpoints.all.first, RepoEndpoints.github)
- XCTAssertEqual(names(RepoEndpoints.ordered(preferred: nil)), names(RepoEndpoints.all))
- XCTAssertEqual(names(RepoEndpoints.ordered(preferred: "nonsense")), names(RepoEndpoints.all))
- }
-
- func testTheRememberedSourceIsTriedFirstAndTheRestFollow() {
- let last = RepoEndpoints.all.last!
- let ordered = RepoEndpoints.ordered(preferred: last.id)
- XCTAssertEqual(ordered.first, last)
- XCTAssertEqual(ordered.count, RepoEndpoints.all.count)
- XCTAssertEqual(Set(ordered.map(\.id)), Set(RepoEndpoints.all.map(\.id)), "no source is dropped or duplicated")
- }
-
- func testTheFirstSourceThatAnswersWins() {
- let dead: Set<String> = [RepoEndpoints.github.id] // the network cannot reach GitHub
- let picked = RepoEndpoints.pick(preferred: nil) { !dead.contains($0.id) }
- XCTAssertNotEqual(picked?.id, RepoEndpoints.github.id)
- XCTAssertNotNil(picked, "a fallback is used rather than failing")
- }
-
- func testNothingAnsweringIsNil() {
- XCTAssertNil(RepoEndpoints.pick(preferred: nil) { _ in false })
- }
-
- /// A remembered source is preferred, but a silent one still falls through to GitHub.
- func testARememberedSourceThatStopsAnsweringFallsBackToTheRest() {
- guard let last = RepoEndpoints.all.last else { return XCTFail("no sources") }
- let picked = RepoEndpoints.pick(preferred: last.id) { $0.id == RepoEndpoints.github.id }
- XCTAssertEqual(picked, RepoEndpoints.github)
- }
-
- func testEverySourceIsACloneURLAndKeepsItsHost() {
- for s in RepoEndpoints.all {
- XCTAssertTrue(s.url.hasSuffix(".git"), s.url)
- XCTAssertFalse(s.host.isEmpty, s.url)
- XCTAssertFalse(s.name.isEmpty, s.id)
- }
- XCTAssertEqual(RepoEndpoints.github.host, "github.com")
- }
-}