Skip to content

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

Qt front end: 'Download repository' installs git too, on Windows

LNPANDY8112cee0b384
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index de5c8e15..974b5f6c 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -45,6 +45,8 @@ TABLE: dict[str, tuple[str, str]] = {
'repo.pulling': ('正在更新…(构建不受影响,之前的构建文件不在仓库里)', 'Updating… (your builds are safe — their files live outside the repository)'),
'repo.pulled': ('已更新到最新', 'Updated to the latest'),
'repo.pullFail': ('更新失败——详情见日志(本地文件被改过?)', 'Update failed — see the log (local changes?)'),
+ 'repo.gitInstalling': ('没找到 git,正在自动安装 PortableGit…(约 57 MB,无需管理员权限)', 'git not found — installing PortableGit… (about 57 MB, no administrator rights needed)'),
+ 'repo.gitInstallFail': ('git 自动安装失败:%@——可到 git-scm.com 手动安装', 'Could not install git: %@ — install it from git-scm.com'),
'repo.gitMissing': ('没找到 git:Windows 请到 git-scm.com 下载安装,macOS 运行 xcode-select --install', 'git not found: install it from git-scm.com (Windows), or run xcode-select --install (macOS)'),
'repo.netFail': ('检查更新失败(网络不通?)', 'Could not check for updates (offline?)'),
'data.title': ('游戏数据', 'Game data'),
diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py
index 4064ff7d..0b7da1fa 100644
--- a/frontend-qt/nspb_qt/model.py
+++ b/frontend-qt/nspb_qt/model.py
@@ -293,8 +293,13 @@ class Model(QObject):
REPO_URL = 'https://github.com/LNPANDY/NX2Apple.git'
def git_binary(self) -> str | None:
- return pu._which('git', [r'C:\Program Files\Git\cmd\git.exe',
- r'C:\Program Files\Git\bin\git.exe'] if pu.IS_WIN else [])
+ """The git to use: on Windows the app's own PortableGit first (it may have downloaded
+ one), then a system install; on macOS whatever PATH and the usual places give."""
+ if pu.IS_WIN:
+ from .win import toolchain as wtc
+ found = wtc.git_exe()
+ return str(found) if found else None
+ return pu._which('git')
def clone_repo(self, dest: str | None = None) -> None:
"""Shallow-clone the project into ~/NX2Apple (or `dest`) and select it.
@@ -304,8 +309,36 @@ class Model(QObject):
"""
git = self.git_binary()
if not git:
+ if not pu.IS_WIN:
+ self.repoChanged.emit()
+ self.logAppended.emit(self.t('repo.gitMissing') + '\n')
+ return
+ # Windows with no git at all: fetch PortableGit, then carry on with the clone. This is
+ # the one case where "one click" has to install something first; it needs no
+ # administrator rights and no installer.
+ self.repo_busy = True
self.repoChanged.emit()
- self.logAppended.emit(self.t('repo.gitMissing') + '\n')
+ self.logAppended.emit(self.t('repo.gitInstalling') + '\n')
+
+ def install_then_clone() -> None:
+ ok = False
+ try:
+ from .win import fetch as wf
+ path = wf.install_git(log=lambda s: self.logAppended.emit(str(s) + '\n'),
+ progress=lambda d, t_: self.logAppended.emit(
+ f' {d // 1048576} MB' +
+ (f' / {t_ // 1048576} MB ({d * 100 // t_}%)' if t_ else '') + '\n'))
+ ok = Path(path).is_file()
+ except Exception as e:
+ self.logAppended.emit(self.t('repo.gitInstallFail', str(e)) + '\n')
+ self.repo_busy = False
+ self.repoChanged.emit()
+ if ok:
+ self.clone_repo(dest) # now git exists: the normal path
+ else:
+ self.logAppended.emit(self.t('repo.gitMissing') + '\n')
+
+ threading.Thread(target=install_then_clone, daemon=True).start()
return
target = dest or str(Path.home() / 'NX2Apple')
if Path(target).exists():
diff --git a/frontend-qt/nspb_qt/win/fetch.py b/frontend-qt/nspb_qt/win/fetch.py
index 134d6c7a..2610458c 100644
--- a/frontend-qt/nspb_qt/win/fetch.py
+++ b/frontend-qt/nspb_qt/win/fetch.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import hashlib
import os
import shutil
+import subprocess
import sys
import time
import urllib.error
@@ -203,3 +204,87 @@ def sdk_hint() -> str:
return (f'the app downloads {tc.SDK_PINNED} from {tc.SDK_REPO}, or use your own '
'Xcode .xip (needs a free Apple ID)')
+
+def install_git(arch: str | None = None, dest: Path | None = None,
+ log: Callable[[str], None] | None = None,
+ progress: Callable[[int, int], None] | None = None) -> Path:
+ """Download PortableGit and unpack it, returning the git.exe to use.
+
+ PortableGit's .7z.exe is a self-extracting 7-Zip archive: `-o<dir> -y -Install` unpacks it
+ without an installer and without administrator rights, which is what makes this work from a
+ normal user account. After unpacking, `cmd/git.exe` sits in the target folder.
+
+ The archive hash is checked when one is pinned; an empty hash means the release was not
+ pinned yet, and the download is accepted with a note in the log rather than failing.
+ """
+ log = log or (lambda s: None)
+ key = arch or (_arch_key())
+ asset = tc.GIT_ASSETS.get(key) or tc.GIT_ASSETS['AMD64']
+ target = Path(dest or tc.git_dir())
+ exe = target / 'cmd' / 'git.exe'
+ if exe.is_file():
+ log(f'git is already installed: {exe}')
+ return exe
+ base = Path(__file__).resolve().parents[2]
+ cache = base / '.tools' / 'downloads'
+ cache.mkdir(parents=True, exist_ok=True)
+ url = f'{tc.GIT_RELEASE_URL}/{asset["name"]}'
+ log(f'downloading {asset["name"]} ({asset["size"] // 1048576 if asset["size"] else "~57"} MB)')
+ if asset['sha256']:
+ zpath = download(url, cache / asset['name'], asset['sha256'], asset['size'] or None,
+ log=log, progress=progress)
+ else:
+ zpath = _download_unverified(url, cache / asset['name'], log, progress)
+ log(f'unpacking {zpath.name} → {target}')
+ target.mkdir(parents=True, exist_ok=True)
+ # The self-extractor writes the tree directly into -o<dir>; -y answers any prompt, -Install
+ # skips the integration step (no registry, no PATH changes).
+ r = subprocess.run([str(zpath), f'-o{target}', '-y', '-Install'],
+ capture_output=True, text=True, errors='replace')
+ if r.returncode != 0 or not exe.is_file():
+ raise DownloadError(
+ f'PortableGit unpacking failed (exit {r.returncode}). '
+ f'Unpack {zpath} into {target} by hand, or install git from git-scm.com.'
+ + (f'\n{r.stderr[:300]}' if r.stderr else ''))
+ log(f'git installed: {exe}')
+ return exe
+
+
+def _arch_key() -> str:
+ import platform
+ m = platform.machine().lower()
+ return 'ARM64' if m in ('arm64', 'aarch64') else 'AMD64'
+
+
+def _download_unverified(url: str, dest: Path, log: Callable[[str], None],
+ progress: Callable[[int, int], None] | None) -> Path:
+ """Fetch a file whose hash is not pinned yet (used only for PortableGit until pinned)."""
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if dest.is_file() and dest.stat().st_size > 0:
+ log(f'already downloaded: {dest.name}')
+ return dest
+ tmp = dest.with_suffix(dest.suffix + '.part')
+ try:
+ req = urllib.request.Request(url, headers={'User-Agent': 'NS-Port-Builder'})
+ with urllib.request.urlopen(req, timeout=60) as r, open(tmp, 'wb') as f:
+ total = int(r.headers.get('Content-Length') or 0)
+ done = 0
+ last = 0.0
+ while True:
+ b = r.read(1 << 16)
+ if not b:
+ break
+ f.write(b)
+ done += len(b)
+ if progress and total:
+ now = time.time()
+ if now - last > 0.3:
+ progress(done, total)
+ last = now
+ if progress and total:
+ progress(total, total)
+ tmp.replace(dest)
+ return dest
+ except (urllib.error.URLError, OSError) as e:
+ tmp.unlink(missing_ok=True)
+ raise DownloadError(f'download failed: {url}: {e}') from e
diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.py
index cef89b55..4add7686 100644
--- a/frontend-qt/nspb_qt/win/toolchain.py
+++ b/frontend-qt/nspb_qt/win/toolchain.py
@@ -61,6 +61,50 @@ LLVM_MINGW_ASSETS = {
LLVM_MINGW_RELEASE_URL = ('https://github.com/mstorsjo/llvm-mingw/releases/download/'
+ LLVM_MINGW_VERSION)
+#: PortableGit, for a machine with no git at all. This is not a build requirement — the build
+#: only needs it to fetch the repository — but a Windows user who has never installed git should
+#: not have to leave the app. The .7z.exe is a self-extracting archive: running it with
+#: -o<dir> -y unpacks without an installer and without administrator rights. Sizes and hashes are
+#: pinned; a mismatch stops rather than unpacking a partial tree.
+GIT_VERSION = '2.56.0.4'
+GIT_ASSETS = {
+ 'AMD64': {
+ 'name': f'PortableGit-{GIT_VERSION}-64-bit.7z.exe',
+ 'sha256': 'b1f3e52216e2ed6882d1bebfd4d3fdf319bec40d2edbbf9fd26ec4fd3fce7ed1',
+ 'size': 57200000,
+ },
+ 'ARM64': {
+ 'name': f'PortableGit-{GIT_VERSION}-arm64.7z.exe',
+ 'sha256': '044110f9d951858452ddb5e4b5415ea0f2b5b2598e794d6fec77fe28b9aa8cc0',
+ 'size': 57100000,
+ },
+}
+# The tag is v<version>.windows.<n>, and GIT_VERSION already carries the patch number after the
+# last dot, so the tag is v2.56.0.windows.4 for GIT_VERSION 2.56.0.4 — spelled out here because
+# deriving it from GIT_VERSION would need to know which part is the Windows build number.
+GIT_RELEASE_TAG = 'v2.56.0.windows.4'
+GIT_RELEASE_URL = f'https://github.com/git-for-windows/git/releases/download/{GIT_RELEASE_TAG}'
+
+
+def git_dir() -> Path:
+ """Where the app keeps its own PortableGit, if it downloaded one."""
+ return Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local')) / \
+ 'NS Port Builder' / 'git'
+
+
+def git_exe() -> Path | None:
+ """The git to use: the app's own PortableGit first, then a system install."""
+ local = git_dir() / 'cmd' / 'git.exe'
+ if local.is_file():
+ return local
+ for c in (Path(r'C:\Program Files\Git\cmd\git.exe'),
+ Path(r'C:\Program Files\Git\bin\git.exe'),
+ Path(r'C:\Program Files (x86)\Git\cmd\git.exe')):
+ if c.is_file():
+ return c
+ found = shutil.which('git')
+ return Path(found) if found else None
+
#: The iPhoneOS SDK we pin. `xybp888/iOS-SDKs` is a plain git repository of SDK trees, so a
#: shallow clone is enough and the commit SHA pins the content. 26.0 is what `dm/ios/project.yml`
#: targets; 26.5 is accepted too, since a newer SDK still compiles against 26.0.
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 520ed101..ed125afb 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -85,6 +85,10 @@ enum L10n {
"repo.pulled": ("已更新到最新", "Updated to the latest"),
"repo.pullFail": ("更新失败——详情见日志(本地文件被改过?)",
"Update failed — see the log (local changes?)"),
+ "repo.gitInstalling": ("没找到 git,正在自动安装 PortableGit…(约 57 MB,无需管理员权限)",
+ "git not found — installing PortableGit… (about 57 MB, no administrator rights needed)"),
+ "repo.gitInstallFail": ("git 自动安装失败:%@——可到 git-scm.com 手动安装",
+ "Could not install git: %@ — install it from git-scm.com"),
"repo.gitMissing": ("没找到 git:Windows 请到 git-scm.com 下载安装,macOS 运行 xcode-select --install",
"git not found: install it from git-scm.com (Windows), or run xcode-select --install (macOS)"),
"repo.netFail": ("检查更新失败(网络不通?)", "Could not check for updates (offline?)"),