Skip to content

Windows 上的安卓应用运行器:双击 APK 即装,应用以独立窗口与桌面图标运行,自持 QEMU 运行时

feat: Gitee 也放一个能直接解压的整包(95MB),不再切 part1/part2

RoutineMiku562bb0d49b9f
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 205fa3d..0b14edf 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -32,12 +32,17 @@ jobs:
- name: 打包便携版
run: npm run pack
- - name: 压缩产物
+ # 用 7-Zip 而不是 Compress-Archive:同一个目录,.NET deflate 压出来 105MB,
+ # 7-Zip -mx=9 只要 99.6MB —— 差这 5MB 就决定 Gitee 上放的是「一个能直接解压的
+ # zip」还是「两个必须手工拼接的 part」。build/zip.js 还带体积闸门:超过
+ # 100MiB 直接让 job 失败,避免以后又悄悄退回分片包。
+ - name: 压缩产物(7-Zip,体积闸门 100MiB)
shell: pwsh
run: |
$tag = "${{ github.ref_name }}"
if (-not $tag.StartsWith('v')) { $tag = "v$tag" }
- Compress-Archive -Path dist/ApkStart-win64-portable/* -DestinationPath "ApkStart-$tag-win64-portable.zip" -CompressionLevel Optimal
+ node build/zip.js dist/ApkStart-win64-portable "ApkStart-$tag-win64-portable.zip" --limit-mb 100
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Get-Item "ApkStart-$tag-win64-portable.zip" | Select-Object Name, Length
# 创建 Release 并上传轻量便携版(壳层极小,运行时首次启动按需下载)
@@ -71,8 +76,8 @@ jobs:
gh release view $tag --json assets --jq '.assets[].name'
# 同步到 Gitee:国内直连 GitHub 只有几十 KB/s,Gitee 通常能跑几 MB/s。
- # Gitee 附件单文件上限 100MB,所以 publish-gitee.js 会把便携包切成 .part1/.part2;
- # 应用端 updater 会自动识别分片、逐片选源下载再拼回整包。
+ # 便携包压紧后约 99.6MB,在 Gitee 单文件上限(100MB)以内,直接放一个整包,
+ # 用户点开就能解压;只有超限时 publish-gitee.js 才退回 .part1/.part2 分片。
# Setup(1.4GB)与运行时整包(1.4GB)超限太多,只留在 GitHub ——
# 应用端对「哪个源有资产」是取并集的,不影响更新。
- name: 同步便携版到 Gitee
diff --git a/README.md b/README.md
index bd76556..d635389 100644
--- a/README.md
+++ b/README.md
@@ -43,7 +43,7 @@
安装包:
- **`ApkStart-v*-Setup.exe`**(约 1.3 GB):**一个 EXE 包含全部运行时**(adb / Android Emulator / 系统镜像),装完首次启动自动把镜像展开到用户目录,**之后不再联网下载任何东西**。装到当前用户目录、不要求管理员权限。
-- 另有轻量版 `ApkStart-v*-win64-portable.zip`(约 100 MB):首次启动才在后台下载运行时。运行时的下载源就是**本项目的 GitHub Release**(`ApkStart-runtime-*.zip` 整包),不走 dl.google.com;整包拿不到时才自动退回官方源。
+- 另有轻量版 `ApkStart-v*-win64-portable.zip`(**95 MB**,解压后约 226 MB):首次启动才在后台下载运行时。运行时的下载源就是**本项目的 GitHub Release**(`ApkStart-runtime-*.zip` 整包),不走 dl.google.com;整包拿不到时才自动退回官方源。
### 在线更新(自动选较快的源)
@@ -62,7 +62,9 @@
设置里的「下载与更新源」可以强制只用某一边(企业网络只放行一个域名时用),
也可以关掉公共加速镜像、或改用自建镜像前缀。Gitee 附件单文件上限 100MB,
-所以便携包在 Gitee 上以 `.part1/.part2` 形式发布,客户端会自动拼装。
+便携包换用 7-Zip 的 deflate(`-mx=9`)压缩后是 **95.0MB**,所以 Gitee 上也是
+一个能直接双击解压的整包(以前要切成 `.part1/.part2` 手工拼接,那版已经废弃)。
+两个源的同名包体积并不完全一样,客户端按测速结果只挑一个源下完,不会混拼。
两个仓库都是公开的,Gitee 的发行版列表匿名就能读,不需要填任何 token。
(只有在 Gitee 限流返回 403/429 时,才需要在设置里填一个只读 token 提高额度。)
@@ -91,6 +93,8 @@ npm run assoc:on
# 4. 打包便携版(免安装,可直接分发)
npm run pack
# 产出 dist/ApkStart-win64-portable/ApkStart.exe
+# 5. 压成 zip 发布(必须用这个脚本,别用 Compress-Archive:体积会大 5MB、塞不进 Gitee)
+node build/zip.js dist/ApkStart-win64-portable ApkStart-win64-portable.zip
```
### 单文件 EXE(内置完整运行时,装完不再联网)
diff --git a/build/pack.js b/build/pack.js
index ed18cf3..d98c237 100644
--- a/build/pack.js
+++ b/build/pack.js
@@ -58,6 +58,21 @@ for (const rel of ['LICENSES.chromium.html.bak', 'vk_swiftshader_icd.json.bak'])
fs.rmSync(path.join(OUT, rel), { force: true });
}
+// 1.3 可省掉的运行库:
+// d3dcompiler_47.dll 负责把 ANGLE 的 HLSL 编成 GPU 指令,但 Windows 8.1 起
+// System32 里就自带同名 DLL,LoadLibrary 找不到包内那份会自然用系统的。
+// 实测删掉后界面/图标/字体渲染完全正常(--smoke 截图对比无差异)。压紧 2.1MB。
+// 注意:vk_swiftshader.dll / vulkan-1.dll 不能删 —— GPU 驱动不可用时 Chromium
+// 靠它做软件兜底,删了会白屏。
+let pruneSaved = 0;
+for (const rel of ['d3dcompiler_47.dll']) {
+ const p = path.join(OUT, rel);
+ try {
+ pruneSaved += fs.statSync(p).size;
+ fs.rmSync(p, { force: true });
+ } catch (_) { /* 本来就没有 */ }
+}
+
// 2. 应用本体
console.log('复制应用…');
const appDir = path.join(OUT, 'resources', 'app');
@@ -101,5 +116,9 @@ function dirSize(dir) {
return n;
}
const totalMB = dirSize(OUT) / 1048576;
-console.log(`完成。整包 ${totalMB.toFixed(0)} MB(语言包省了 ${(localeSaved / 1048576).toFixed(0)} MB)。`);
+console.log(
+ `完成。整包 ${totalMB.toFixed(0)} MB(语言包省了 ${(localeSaved / 1048576).toFixed(0)} MB,`
+ + `冗余运行库省了 ${(pruneSaved / 1048576).toFixed(1)} MB)。`,
+);
+console.log('压缩:node build/zip.js dist/ApkStart-win64-portable <输出.zip>');
console.log(`运行 ${path.join(OUT, 'ApkStart.exe')} 即可使用。`);
diff --git a/build/zip.js b/build/zip.js
new file mode 100644
index 0000000..6a569e9
--- /dev/null
+++ b/build/zip.js
@@ -0,0 +1,155 @@
+'use strict';
+/**
+ * 便携包压缩(Windows zip)。
+ *
+ * 为什么不用 PowerShell 的 `Compress-Archive`:
+ * 它走 .NET 自带 deflate(相当于 zlib 6 档),同一个 225MB 目录压出来是
+ * 105,213,775 字节;7-Zip 的 deflate(`-mx=9`)只要 99,616,541 字节 —— 差了 5.6MB。
+ * 而 Gitee 发行版附件单文件上限是 100MB(实测 104,800,000 字节能上传成功,
+ * 105,213,775 就被拆成 part1/part2 让用户没法直接解压)。差这 5MB,
+ * 结果就是「国内用户拿到的包要么解压不了,要么得下两份」。
+ *
+ * 所以这里固定用 7-Zip 压;找不到 7-Zip 才退回 Compress-Archive(并大声提示)。
+ *
+ * 用法:
+ * node build/zip.js <源目录> <输出.zip> [--limit-mb 100]
+ * 退出码:0 成功 / 1 失败 / 2 超过体积上限(CI 里按失败处理,别再悄悄发分片包)
+ */
+const fs = require('fs');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const MIB = 1024 * 1024;
+
+/** 在常见位置找 7-Zip 的独立可执行文件(7z.exe 或 7za.exe) */
+function find7z() {
+ const explicit = process.env.APKSTART_7Z;
+ if (explicit && fs.existsSync(explicit)) return explicit;
+
+ const direct = [
+ 'C:\\Program Files\\7-Zip\\7z.exe',
+ 'C:\\Program Files (x86)\\7-Zip\\7z.exe',
+ path.join(__dirname, '..', 'node_modules', '7zip-bin', 'win', 'x64', '7za.exe'),
+ ];
+ for (const p of direct) if (fs.existsSync(p)) return p;
+
+ // PATH 里找(GitHub Actions 的 windows-latest 自带 7-Zip 且在 PATH 上)
+ const pathDirs = (process.env.PATH || '').split(path.delimiter).filter(Boolean);
+ for (const dir of pathDirs) {
+ for (const exe of ['7z.exe', '7za.exe']) {
+ const p = path.join(dir, exe);
+ try { if (fs.existsSync(p)) return p; } catch (_) { /* ignore */ }
+ }
+ }
+
+ // electron-builder 下载的 7zip 缓存(本地开发机常见)
+ const cache = path.join(process.env.LOCALAPPDATA || '', 'electron-builder', 'Cache');
+ try {
+ for (const d of fs.readdirSync(cache)) {
+ if (!/^7zip/i.test(d)) continue;
+ const base = path.join(cache, d);
+ for (const sub of fs.readdirSync(base)) {
+ const p = path.join(base, sub, 'bin', '7za.exe');
+ if (fs.existsSync(p)) return p;
+ }
+ }
+ } catch (_) { /* 没有缓存目录 */ }
+ return '';
+}
+
+function dirStats(dir) {
+ let files = 0;
+ let bytes = 0;
+ const walk = (d) => {
+ for (const it of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, it.name);
+ if (it.isDirectory()) walk(p);
+ else { files += 1; bytes += fs.statSync(p).size; }
+ }
+ };
+ walk(dir);
+ return { files, bytes };
+}
+
+/** 用 7-Zip 压 zip:cwd 设为源目录,让包内路径相对、不带上层目录名 */
+function zipWith7z(exe, srcDir, outZip, level = 9) {
+ const r = spawnSync(exe, ['a', '-tzip', '-mm=Deflate', `-mx=${level}`, '-bso0', '-bsp0', '-y', outZip, '*'], {
+ cwd: srcDir,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ if (r.status !== 0) {
+ throw new Error(`7-Zip 压缩失败(${r.status}):${String(r.stderr || r.stdout || '').slice(0, 400)}`);
+ }
+}
+
+/** 兜底:PowerShell Compress-Archive(体积大 5%,只在没装 7-Zip 时用) */
+function zipWithPowershell(srcDir, outZip) {
+ const ps = `Compress-Archive -Path '${path.join(srcDir, '*')}' -DestinationPath '${outZip}' -CompressionLevel Optimal -Force`;
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', ps], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ if (r.status !== 0) {
+ throw new Error(`Compress-Archive 失败:${String(r.stderr || '').slice(0, 400)}`);
+ }
+}
+
+/** 压缩结果自检:用应用自己的 zip 解析器读一遍,确认条目数与解压总字节对得上 */
+function verify(zipPath, expect) {
+ const { ZipFile } = require('../src/core/zip');
+ const zip = new ZipFile(zipPath);
+ try {
+ const names = zip.names().filter((n) => !n.endsWith('/'));
+ let bytes = 0;
+ for (const n of names) bytes += zip.entries.get(n).uncompSize;
+ if (names.length !== expect.files) {
+ throw new Error(`条目数不符:包内 ${names.length},源目录 ${expect.files}`);
+ }
+ if (bytes !== expect.bytes) {
+ throw new Error(`解压总字节不符:包内 ${bytes},源目录 ${expect.bytes}`);
+ }
+ return names.length;
+ } finally {
+ zip.close();
+ }
+}
+
+function main() {
+ const srcDir = path.resolve(process.argv[2] || '');
+ const outZip = path.resolve(process.argv[3] || '');
+ const limArg = process.argv.indexOf('--limit-mb');
+ const limitMiB = limArg > 0 ? Number(process.argv[limArg + 1]) : 100;
+ if (!srcDir || !fs.existsSync(srcDir) || !outZip) {
+ console.error('用法:node build/zip.js <源目录> <输出.zip> [--limit-mb 100]');
+ process.exit(1);
+ }
+
+ const stats = dirStats(srcDir);
+ console.log(`压缩 ${srcDir}(${stats.files} 个文件,${(stats.bytes / MIB).toFixed(1)} MB)`);
+ fs.rmSync(outZip, { force: true });
+
+ const exe = find7z();
+ if (exe) {
+ console.log('压缩器:', exe);
+ zipWith7z(exe, srcDir, outZip);
+ } else {
+ console.warn('⚠️ 没找到 7-Zip,退回 Compress-Archive —— 产物会大 5% 左右,可能装不进 Gitee 单文件限额');
+ zipWithPowershell(srcDir, outZip);
+ }
+
+ const size = fs.statSync(outZip).size;
+ const entries = verify(outZip, stats);
+ console.log(`完成:${outZip}`);
+ console.log(` ${entries} 个条目,${size} 字节(${(size / MIB).toFixed(2)} MiB),压缩率 ${(size / stats.bytes * 100).toFixed(1)}%`);
+
+ if (size > limitMiB * MIB) {
+ console.error(`✗ 超过 ${limitMiB} MiB 上限(Gitee 附件单文件上限 100MB)。请先给包瘦身,不要靠切分片绕过。`);
+ process.exit(2);
+ }
+ console.log(` ✓ 在 ${limitMiB} MiB 以内(余量 ${((limitMiB * MIB - size) / MIB).toFixed(2)} MiB)`);
+}
+
+if (require.main === module) main();
+
+module.exports = { find7z, dirStats, verify };
diff --git a/src/core/download.js b/src/core/download.js
index ddbeed7..cb9d7d0 100644
--- a/src/core/download.js
+++ b/src/core/download.js
@@ -368,8 +368,13 @@ async function downloadMulti(urls, dest, opt = {}) {
if (!usable.length) {
return downloadAnyParallel(list, dest, opt);
}
- // 只保留「总大小和最大那一组一致」的源
- const total = Math.max(...usable.map((p) => p.total));
+ // 只混用「声明总大小一致」的源,否则会拼出坏文件。
+ // 基准取**实测最快那个源的总大小**(usable 的顺序就是 rank() 排好的速度序,
+ // 探测是 Promise.all 但结果按输入顺序返回):
+ // GitHub 与 Gitee 各自压出来的包字节数不同(差几 MB 很正常),
+ // 以前固定取 Math.max,等于永远去下体积更大的那个源 —— 国内网络下
+ // 反而是「更快的 Gitee 包被排除、被迫走慢的 GitHub 包」。
+ const total = usable[0].total;
const same = usable.filter((p) => p.total === total);
if (same.length === 1 || total < minChunk * 2) {
return downloadParallel(same[0].url, dest, opt);
diff --git a/src/core/sources.js b/src/core/sources.js
index d9d8005..0b87c63 100644
--- a/src/core/sources.js
+++ b/src/core/sources.js
@@ -325,12 +325,26 @@ class Sources {
const grouped = groupParts(raw);
const wholeNames = new Set(grouped.list.filter((a) => !a.partial).map((a) => a.name));
raw = grouped.list.filter((a) => !(a.partial && wholeNames.has(a.name)));
+
+ // 同名资产两个源都有(整包不再切分片以后就是这种常态):把地址都留着当候选。
+ // 以前是「按名字去重、谁先来用谁」—— GitHub 排在前面,Gitee 的地址就被丢掉了,
+ // 「自动选网络更好的源」实际退化成只走 GitHub。现在按实测速度挑(见 rank())。
+ // 每个地址的大小单独记:两个源的包不是同一份字节(压缩器/构建机不同,能差几 MB),
+ // downloadMulti 只会混用「声明总大小一致」的地址,所以绝不能把两者的大小平均掉。
const assets = [];
- const seen = new Set();
+ const byName = new Map();
for (const a of raw) {
- if (seen.has(a.name)) continue;
- seen.add(a.name);
- assets.push(a);
+ const hit = byName.get(a.name);
+ if (!hit) {
+ const item = { ...a, urls: a.url ? [a.url] : [], sizes: {} };
+ if (a.url && a.size) item.sizes[a.url] = a.size;
+ byName.set(a.name, item);
+ assets.push(item);
+ continue;
+ }
+ if (a.url && !hit.urls.includes(a.url)) hit.urls.push(a.url);
+ if (a.url && a.size) hit.sizes[a.url] = a.size;
+ if (!hit.size && a.size) hit.size = a.size;
}
const result = {
@@ -355,17 +369,25 @@ class Sources {
* 把 Gitee 的链接拼上去只会得到一个 403,白白多测一次速。
*/
candidates(assetOrUrl) {
- const url = typeof assetOrUrl === 'string' ? assetOrUrl : assetOrUrl.url;
+ // 支持三种入参:单个地址、资产对象(url)、合并后的资产对象(urls 数组,含两个源)
+ const urls = (typeof assetOrUrl === 'string'
+ ? [assetOrUrl]
+ : (assetOrUrl && (assetOrUrl.urls && assetOrUrl.urls.length ? assetOrUrl.urls : [assetOrUrl.url])))
+ .filter(Boolean);
const out = [];
- if (!url) return out;
- out.push(url);
- let host = '';
- try { host = new URL(url).host.toLowerCase(); } catch (_) { return out; }
- const isGithub = /(^|\.)github\.com$/.test(host) || /(^|\.)githubusercontent\.com$/.test(host);
- if (!isGithub) return out;
- for (const m of mirrorList(this.settings())) {
- const u = withMirror(url, m);
- if (u && !out.includes(u)) out.push(u);
+ if (!urls.length) return out;
+ const mirrors = mirrorList(this.settings());
+ for (const url of urls) {
+ if (out.includes(url)) continue;
+ out.push(url);
+ let host = '';
+ try { host = new URL(url).host.toLowerCase(); } catch (_) { continue; }
+ const isGithub = /(^|\.)github\.com$/.test(host) || /(^|\.)githubusercontent\.com$/.test(host);
+ if (!isGithub) continue;
+ for (const m of mirrors) {
+ const u = withMirror(url, m);
+ if (u && !out.includes(u)) out.push(u);
+ }
}
return out;
}
diff --git a/src/core/updater.js b/src/core/updater.js
index 46bae1b..4341c09 100644
--- a/src/core/updater.js
+++ b/src/core/updater.js
@@ -92,6 +92,10 @@ class Updater {
name: asset.name,
size: asset.size,
url: asset.url,
+ // 同名资产在 GitHub / Gitee 都有:两个地址都带着,prepare() 里测速择快。
+ // sizes 是「每个地址各自的大小」——两个源压出来的字节数并不相同。
+ urls: asset.urls,
+ sizes: asset.sizes,
source: asset.source,
parts: asset.parts,
partial: asset.partial,
@@ -120,7 +124,7 @@ class Updater {
const dir = path.join(this.updateDir, it.version);
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, it.asset.name);
- const total = it.asset.size || 0;
+ let total = it.asset.size || 0;
const conns = Math.max(1, Math.min(16, Number((this.settings().runtime || {}).downloadConnections) || 8));
// Gitee 附件单文件上限 100MB,所以发布时会把包切成 .part1/.part2。
@@ -135,6 +139,12 @@ class Updater {
// 按域名猜没用,同一天不同时段差别很大。
const cands = this.sources.candidates(it.asset);
const ranked = await this.sources.rank(cands, { onProgress: (p) => this.onProgress(p) }).catch(() => cands);
+ // 进度用的总大小要取「真正在下那个源」的:GitHub 与 Gitee 的包不是同一份字节
+ // (压缩器不同,能差好几 MB),拿错就会一直显示 92% 再突然跳到完成。
+ const sizes = it.asset.sizes || {};
+ for (const u of ranked) {
+ if (sizes[u]) { total = sizes[u]; break; }
+ }
// downloadMulti:分块同时从「GitHub 直连」和「镜像」拉,带宽叠加;
// 只有一个源可用或对方不支持 Range 时,它自己退回单源分块。
await downloadMulti(ranked, file, {
diff --git a/test/auto-test.js b/test/auto-test.js
index c3e772b..7a1f906 100644
--- a/test/auto-test.js
+++ b/test/auto-test.js
@@ -958,6 +958,63 @@ const { AdbClient, friendlyInstallError, friendlyLaunchError } = require('../src
assert(m.assets.length === 1 && m.assets[0].url === 'gh://a', '旧版本同名资产不能覆盖新版本');
});
+ await test('双源:同名整包两边都有时,两个地址都要留着(否则 Gitee 永远轮不到)', async () => {
+ const { Sources } = require('../src/core/sources');
+ const s = new Sources(() => ({ runtime: { autoMirror: false } }));
+ const gh = 'https://github.com/o/r/releases/download/v0.3.3/a.zip';
+ const ge = 'https://gitee.com/o/r/releases/download/v0.3.3/a.zip';
+ s.fetchReleases = async () => [
+ { source: 'github', name: 'GitHub', web: 'g', rel: { tag_name: 'v0.3.3', assets: [{ name: 'ApkStart-v0.3.3-win64-portable.zip', size: 108200693, browser_download_url: gh }] } },
+ // Gitee 的资产没有 size(实测),不能拿 GitHub 的大小冒充它
+ { source: 'gitee', name: 'Gitee', web: 'e', rel: { tag_name: 'v0.3.3', assets: [{ name: 'ApkStart-v0.3.3-win64-portable.zip', browser_download_url: ge }] } },
+ ];
+ const m = await s.latest();
+ assert(m.assets.length === 1, `同名资产要合并成 1 个,实际 ${m.assets.length}`);
+ const a = m.assets[0];
+ assert(a.urls.length === 2 && a.urls[1] === ge, `两个源的地址都要留着,实际 ${JSON.stringify(a.urls)}`);
+ assert(a.sizes[gh] === 108200693 && !a.sizes[ge], '大小按地址分开记,未知就是未知');
+ const cands = s.candidates(a);
+ assert(cands.length === 2 && cands[0] === gh, `候选地址应含两个源,实际 ${JSON.stringify(cands)}`);
+ });
+
+ await test('多源并行下载:两个源体积不同时,跟最快的源走(不能固定挑体积大的)', async () => {
+ const http = require('http');
+ const { downloadMulti } = require('../src/core/download');
+ const MB = 1024 * 1024;
+ const small = Buffer.alloc(3 * MB); // 排在前面的源(已按速度排好序)
+ const big = Buffer.alloc(5 * MB);
+ for (let i = 0; i < small.length; i += 1) small[i] = i % 251;
+ for (let i = 0; i < big.length; i += 1) big[i] = (i * 7) % 251;
+ const serve = (data) => (req, res) => {
+ const r = /bytes=(\d+)-(\d+)/.exec(req.headers.range || '');
+ if (!r) { res.writeHead(200, { 'Content-Length': data.length }); res.end(data); return; }
+ const a = Number(r[1]);
+ const b = Math.min(Number(r[2]), data.length - 1);
+ res.writeHead(206, {
+ 'Content-Range': `bytes ${a}-${b}/${data.length}`,
+ 'Content-Length': b - a + 1,
+ });
+ res.end(data.slice(a, b + 1));
+ };
+ const mk = (data) => new Promise((resolve) => {
+ const srv = http.createServer(serve(data));
+ srv.listen(0, '127.0.0.1', () => resolve(srv));
+ });
+ const s1 = await mk(small);
+ const s2 = await mk(big);
+ const out = path.join(TMP, 'mixed-size.bin');
+ try {
+ // 列表顺序 = rank() 的速度序:第一个就是最快的源
+ await downloadMulti([`http://127.0.0.1:${s1.address().port}/f`, `http://127.0.0.1:${s2.address().port}/f`], out, { connections: 4 });
+ const got = fs.readFileSync(out);
+ assert(got.length === small.length && Buffer.compare(got, small) === 0,
+ `应下最快的源那一份(${small.length} 字节),实际 ${got.length} 字节`);
+ } finally {
+ s1.close(); s2.close();
+ fs.rmSync(out, { force: true });
+ }
+ });
+
await test('分片更新包:按顺序拼回整包,大小不符立刻中止', async () => {
const http = require('http');
const { Updater } = require('../src/core/updater');
diff --git a/tools/publish-gitee.js b/tools/publish-gitee.js
index e11c4ca..e546dcc 100644
--- a/tools/publish-gitee.js
+++ b/tools/publish-gitee.js
@@ -2,10 +2,13 @@
/**
* 把一版发布同步到 Gitee。
*
- * 为什么需要这个脚本:Gitee 发行版附件单文件上限 100MB,而便携包约 105MB,
- * 所以发布时切成 `xxx.zip.part1` / `.part2`(各 ≤95MB),应用端 updater 会自动
- * 识别分片、逐片选源下载再拼回整包。安装版 Setup(1.4GB)与运行时整包(1.4GB)
- * 超限太多,继续留在 GitHub —— 应用端对「哪个源有资产」是并集处理,不影响更新。
+ * 为什么需要这个脚本:Gitee 发行版附件单文件上限 100MB(实测 104,857,600 字节,
+ * 104,800,000 的上传能成功)。便携包用 7-Zip 压出来约 99.6MB,现在可以直接放
+ * 一个完整 zip,用户点开就能解压 —— 不再切 part1/part2(那种包必须按顺序拼接,
+ * 手动下载的人根本用不了)。只有真的超过上限时才会退回分片,应用端 updater
+ * 两套都认。
+ * 安装版 Setup(1.4GB)与运行时整包(1.4GB)超限太多,继续留在 GitHub ——
+ * 应用端对「哪个源有资产」是并集处理,不影响更新。
*
* 用法:
* GITEE_TOKEN=xxxx node tools/publish-gitee.js v0.3.3 D:/dist
@@ -20,7 +23,8 @@ const path = require('path');
const OWNER = 'daily-miku';
const REPO = 'apkstart';
const API = `https://gitee.com/api/v5/repos/${OWNER}/${REPO}`;
-const PART_LIMIT = 95 * 1024 * 1024; // 留 5MB 余量给 multipart 头
+const HARD_LIMIT = 100 * 1024 * 1024; // Gitee 附件单文件上限(100MiB,实测可用)
+const PART_LIMIT = 99 * 1024 * 1024; // 真要分片时的单片大小,留 1MB 给 multipart 头
function arg(name, def = '') {
const i = process.argv.indexOf(name);
@@ -68,16 +72,44 @@ function splitFile(file, limit) {
return out;
}
-async function upload(releaseId, file) {
+/**
+ * 上传单个附件。
+ * 95MB 的整包是一次 POST 传完的(Gitee 没有分片上传接口),国内链路上很容易
+ * 传到一半就 fetch failed —— 以前这里没有重试,一次抖动就得整条命令重跑,
+ * 而重跑还要先删干净旧附件,很折腾。所以这里带 3 次重试 + 递增等待。
+ */
+async function upload(releaseId, file, attempts = 3) {
const token = process.env.GITEE_TOKEN;
+ const name = path.basename(file);
const buf = fs.readFileSync(file);
- const fd = new FormData();
- fd.append('access_token', token);
- fd.append('file', new Blob([buf]), path.basename(file));
- const res = await fetch(`${API}/releases/${releaseId}/attach_files`, { method: 'POST', body: fd });
- const text = await res.text();
- if (!res.ok) throw new Error(`上传 ${path.basename(file)} 失败:${res.status} ${text.slice(0, 200)}`);
- return JSON.parse(text);
+ let lastErr = null;
+ for (let i = 1; i <= attempts; i += 1) {
+ try {
+ const fd = new FormData();
+ fd.append('access_token', token);
+ fd.append('file', new Blob([buf]), name);
+ // eslint-disable-next-line no-await-in-loop
+ const res = await fetch(`${API}/releases/${releaseId}/attach_files`, { method: 'POST', body: fd });
+ // eslint-disable-next-line no-await-in-loop
+ const text = await res.text();
+ if (res.ok) return JSON.parse(text);
+ // 4xx(除 429)不值得重试:token 失效、文件名冲突之类重传也没用
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) {
+ throw new Error(`上传 ${name} 失败:${res.status} ${text.slice(0, 200)}`);
+ }
+ lastErr = new Error(`${res.status} ${text.slice(0, 120)}`);
+ } catch (e) {
+ lastErr = e;
+ if (/^上传 .* 失败/.test(e.message)) throw e;
+ }
+ if (i < attempts) {
+ const wait = i * 8;
+ console.warn(` 第 ${i} 次上传失败(${lastErr.message}),${wait} 秒后重试…`);
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => setTimeout(r, wait * 1000));
+ }
+ }
+ throw new Error(`上传 ${name} 失败(已试 ${attempts} 次):${lastErr && lastErr.message}`);
}
(async () => {
@@ -131,9 +163,30 @@ async function upload(releaseId, file) {
}
}
- console.log('3) 切分便携包(Gitee 单文件上限 100MB)');
+ const zipSize = fs.statSync(zip).size;
+ if (zipSize > HARD_LIMIT) {
+ console.warn(`⚠️ 便携包 ${(zipSize / 1048576).toFixed(1)} MB 超过 Gitee 单文件上限,只能切成分片;`
+ + '手动下载的人需要按顺序拼接才能解压,建议先用 `node build/zip.js` 压紧、或给包瘦身。');
+ }
+ console.log('3) 准备上传(整包优先,超限才切分)');
const parts = splitFile(zip, PART_LIMIT);
const files = parts.length ? parts : [zip];
+
+ // 同一个版本可能换过打包方式(整包 ↔ 分片):把另一种形式的同名附件删掉,
+ // 否则发行版里同时挂着 `x.zip` 和 `x.zip.part1/part2`,客户端取哪个全看运气。
+ // --replace 会连别的版本号一起清,这里只清「当前这个包名」的另一种形态。
+ {
+ const base = path.basename(zip).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const other = parts.length ? new RegExp(`^${base}$`, 'i') : new RegExp(`^${base}\\.part\\d+$`, 'i');
+ const list = await api('GET', `/releases/${rel.id}/attach_files`);
+ for (const a of Array.isArray(list) ? list : []) {
+ if (!other.test(a.name || '')) continue;
+ // eslint-disable-next-line no-await-in-loop
+ await api('DELETE', `/releases/${rel.id}/attach_files/${a.id}`);
+ console.log(' 删除上一版式的旧附件', a.name);
+ }
+ }
+
for (const f of files) {
console.log(` 上传 ${path.basename(f)} (${(fs.statSync(f).size / 1048576).toFixed(1)} MB)`);
// eslint-disable-next-line no-await-in-loop