perf(build): 预压缩缓存, 打包耗时减半

打包耗时几乎全在压缩, 其中 system/fonts/ (131MB 原始 / 71MB 压缩) 占整包
压缩量的约 70%, 而这部分只在发布新字体时才变化。现将该子树预先压缩并缓存,
后续打包直接搬运已压缩数据 (zip.js passThrough, 不重新 deflate)。

本地构建 28s -> 13s (~2.2x), 产物不变。

实现:
- dev/lib/zipcache.mjs: 缓存片段读写。指纹为「文件名 + 大小 + mtime + 权限位」,
  任一项变化即失效; 缓存目录 dev/.cache/ 不入库
- dev/lib/zip.mjs: packDir 支持 passThrough 复用缓存条目。此处有个易错点 ——
  zip.js 把压缩级别编码进 zip 通用标志位 (bit 1-2), passThrough 时若不传 level,
  写出的标志位与现场压缩不同, 会导致整包哈希漂移 (已修复并验证)
- dev/pack.mjs: 命中则复用, 未命中现场压缩后自动建立缓存; 新增 --no-cache
- dev/cache.mjs: status / clean / test 三个管理命令
- CI 构建加 --no-cache (一次性构建无收益, 也避免引入与构建机相关的状态)

缓存是纯本地的构建加速, 不影响产物也不参与分发:
- 命中缓存与不使用缓存的 zip 逐字节相同 (以 SOURCE_DATE_EPOCH 固定时间戳验证)
- 缓存缺失 / 索引损坏 / 数据文件截断 / 格式版本不符, 四种情况均回退现场压缩
  (已逐一测试), 不会导致构建失败

dev/cache.mjs test 可校验缓存内容与源文件逐一相符。
This commit is contained in:
YuleBest committed 2026-09-16 01:11:01 +08:00
1 parent 9c91bdb8b2
commit 58ea81bfe8
9 files changed
+468 -18

No files matched your search

+3 -1
View File
@@ -52,8 +52,10 @@ jobs:
# 并生成两版产物与 .sha256 校验文件 # 并生成两版产物与 .sha256 校验文件
# 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的 # 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的
# 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突 # 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突
# --no-cache: CI 是一次性构建, 预压缩缓存没有收益, 也避免引入
# 与构建机相关的状态 (缓存目录不入库, 本地开发时才生效)
- name: Pack module (preplace / template) - name: Pack module (preplace / template)
run: pnpm run pack run: pnpm run pack -- --no-cache
- name: Upload artifacts - name: Upload artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
+3 -1
View File
@@ -54,8 +54,10 @@ jobs:
# 并生成两版产物与 .sha256 校验文件 # 并生成两版产物与 .sha256 校验文件
# 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的 # 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的
# 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突 # 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突
# --no-cache: CI 是一次性构建, 预压缩缓存没有收益, 也避免引入
# 与构建机相关的状态 (缓存目录不入库, 本地开发时才生效)
- name: Pack module (preplace / template) - name: Pack module (preplace / template)
run: pnpm run pack run: pnpm run pack -- --no-cache
- name: Upload release assets - name: Upload release assets
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
+3
View File
@@ -24,3 +24,6 @@ native/build/
# 编辑器 C++ 索引数据 (由 dev/build-zygisk.mjs 生成) # 编辑器 C++ 索引数据 (由 dev/build-zygisk.mjs 生成)
compile_commands.json compile_commands.json
# 预压缩构建缓存 (dev/pack.mjs 自动生成, 体积大且与机器相关的 mtime 绑定)
dev/.cache/
+21
View File
@@ -272,9 +272,30 @@ pnpm zygisk:build # 仅交叉编译 Zygisk 模块 -> src/zygisk/
| `dev/ci.mjs` | 代码检查(结构校验 + shellcheck/shfmt + 前端 lint/format/类型) | | `dev/ci.mjs` | 代码检查(结构校验 + shellcheck/shfmt + 前端 lint/format/类型) |
| `dev/empty-font.mjs` | 重新生成占位字体文件 | | `dev/empty-font.mjs` | 重新生成占位字体文件 |
| `dev/sync-fonts-xml.mjs` | 本地生成派生字体配置(仅调试用) | | `dev/sync-fonts-xml.mjs` | 本地生成派生字体配置(仅调试用) |
| `dev/cache.mjs` | 预压缩缓存管理(status / clean / test) |
| `dev/lib/zip.mjs` | ZIP 读写封装(打包 + 回读校验) | | `dev/lib/zip.mjs` | ZIP 读写封装(打包 + 回读校验) |
| `dev/lib/zipcache.mjs` | 预压缩缓存(复用已压缩数据,跳过 deflate) |
| `dev/lib/ndk.mjs` | NDK 定位与 C++ 交叉编译(含产物兼容性校验) | | `dev/lib/ndk.mjs` | NDK 定位与 C++ 交叉编译(含产物兼容性校验) |
### 预压缩缓存
打包耗时几乎全在压缩,而 `system/fonts/`(131MB 原始数据、压缩后 71MB)占了压缩量的
约 70%,且它只在发布新字体时才会变化。因此 `dev/pack.mjs` 会把这部分**预先压缩并缓存**到
`dev/.cache/`,后续打包直接搬运已压缩数据(不重新 deflate),本地构建从约 28s 降到约 13s。
缓存以「文件名 + 大小 + mtime + 权限位」为指纹,任一项变化即失效并自动重建。它是纯本地的
构建加速,**不入库、不影响产物**:命中缓存与不使用缓存产出的 zip 逐字节相同(可用
`SOURCE_DATE_EPOCH` 固定时间戳复现验证)。缓存缺失、损坏或版本不符时一律回退为现场压缩。
```bash
pnpm cache:status # 查看缓存片段、大小、文件数
pnpm cache:test # 校验缓存内容与源文件逐一相符
pnpm cache:clean # 清空缓存
node dev/pack.mjs --no-cache # 本次构建禁用缓存
```
> CI 中建议加 `--no-cache`:缓存对一次性构建没有收益,也避免引入与机器相关的状态。
### Zygisk 字体预加载模块 ### Zygisk 字体预加载模块
源码在 `native/`,编译产物 `src/zygisk/arm64-v8a.so` 随包分发。它做的事很小:在 App 进程 源码在 `native/`,编译产物 `src/zygisk/arm64-v8a.so` 随包分发。它做的事很小:在 App 进程
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env node
// dev/cache.mjs — 预压缩缓存管理
//
// 用法:
// node dev/cache.mjs status 查看缓存状态 (片段/大小/文件数/建立时间)
// node dev/cache.mjs clean 清空缓存
// node dev/cache.mjs test 校验缓存可用性: 用缓存重建一遍并与源文件逐条比对
//
// 缓存由 dev/pack.mjs 在打包时自动建立与复用; 本脚本仅用于查看/清理/校验。
import fsp from 'node:fs/promises';
import path from 'node:path';
import { log, die } from './lib/log.mjs';
import { ROOT, SRC_DIR } from './lib/paths.mjs';
import { indexZip, hashFile } from './lib/zip.mjs';
import { cacheStatus, clearCache, CACHE_DIR } from './lib/zipcache.mjs';
const cmd = process.argv[2] ?? 'status';
const mb = (n) => `${(n / 1048576).toFixed(1)}MB`;
if (cmd === 'status') {
const list = await cacheStatus();
if (list.length === 0) {
log.info(`无缓存 (${path.relative(ROOT, CACHE_DIR)} 不存在或为空)`);
log.detail('下次运行 pnpm run pack 会自动建立');
process.exit(0);
}
log.step(`缓存目录: ${path.relative(ROOT, CACHE_DIR)}`);
for (const c of list) {
const flag = c.usable ? '✓ 可用' : '✗ 不可用 (将回退现场压缩)';
log.detail(`[${c.segment}] ${flag}`);
log.detail(` 大小 ${mb(c.size)} 含 ${c.files} 个文件 建立于 ${c.createdAt ?? '未知'}`);
}
process.exit(0);
}
if (cmd === 'clean') {
await clearCache();
log.ok('缓存已清空');
process.exit(0);
}
if (cmd === 'test') {
// 校验: 把缓存里的每个条目解压出来, 与源文件比对内容
const list = await cacheStatus();
if (list.length === 0) die('无缓存可校验');
let failures = 0;
for (const c of list.filter((x) => x.usable)) {
const segZip = path.join(CACHE_DIR, `${c.segment}.zip`);
log.step(`校验片段 ${c.segment} (${mb(c.size)})...`);
const index = await indexZip(segZip);
let checked = 0;
for (const [rel, info] of index) {
if (info.isDir) continue;
const src = path.join(SRC_DIR, rel);
let expected;
try {
expected = hashFile(src);
} catch {
log.fail(`源文件不存在: ${rel}`);
failures++;
continue;
}
if (expected !== info.sha256) {
log.fail(`内容不一致: ${rel}`);
failures++;
}
checked++;
}
log.ok(` ${c.segment}: ${checked} 个文件全部与源文件一致`);
}
if (failures > 0) die(`${failures} 项校验失败`);
log.ok('缓存校验通过');
process.exit(0);
}
die(`未知命令: ${cmd} (可用: status / clean / test)`);
+53 -11
View File
@@ -13,6 +13,7 @@ import fsp from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { Writable } from 'node:stream'; import { Writable } from 'node:stream';
import { log } from './log.mjs';
/** 普通文件权限位下限 (含 S_IFREG) */ /** 普通文件权限位下限 (含 S_IFREG) */
export const FILE_MODE = 0o100644; export const FILE_MODE = 0o100644;
@@ -73,20 +74,27 @@ async function walk(root) {
* @param {string} opts.outFile 输出 zip 路径 * @param {string} opts.outFile 输出 zip 路径
* @param {string[]} [opts.exclude] Info-ZIP 风格 glob, 命中的条目被排除 * @param {string[]} [opts.exclude] Info-ZIP 风格 glob, 命中的条目被排除
* @param {string[]} [opts.excludeFilePrefixes] 仅排除这些前缀下的**文件** (保留目录条目) * @param {string[]} [opts.excludeFilePrefixes] 仅排除这些前缀下的**文件** (保留目录条目)
* @param {string[]} [opts.onlyPrefixes] 只收录这些前缀下的条目 (其他一律跳过)。
* 用于单独打包某个子树以建立缓存: 条目名仍是相对 srcDir 的完整路径,
* 与整包打包时完全一致, 因此可以按路径直接复用。
* @param {number} [opts.level] 压缩级别 0-9 (默认 2, 与原 zip -2 一致) * @param {number} [opts.level] 压缩级别 0-9 (默认 2, 与原 zip -2 一致)
* @param {Date} [opts.fixedDate] 固定所有条目的时间戳 (SOURCE_DATE_EPOCH 式可复现打包); * @param {Date} [opts.fixedDate] 固定所有条目的时间戳 (SOURCE_DATE_EPOCH 式可复现打包);
* 不传则沿用源文件 mtime, 与 Info-ZIP 行为一致 * 不传则沿用源文件 mtime, 与 Info-ZIP 行为一致
* @param {(rel: string) => void} [opts.onEntry] 每个文件写入后的回调 * @param {(rel: string) => void} [opts.onEntry] 每个文件写入后的回调
* @returns {Promise<{ files: number, dirs: number }>} * @param {{ get(rel: string): { compressed: () => Promise<Blob>, crc32: number, uncompressedSize: number } | undefined }} [opts.cache]
* 预压缩缓存 (见 dev/lib/zipcache.mjs): 命中的条目直接搬运已压缩数据, 不做 deflate
* @returns {Promise<{ files: number, dirs: number, reused: number }>}
*/ */
export async function packDir({ export async function packDir({
srcDir, srcDir,
outFile, outFile,
exclude = [], exclude = [],
excludeFilePrefixes = [], excludeFilePrefixes = [],
onlyPrefixes,
level = 2, level = 2,
fixedDate, fixedDate,
onEntry, onEntry,
cache,
}) { }) {
const globs = compileGlobs(exclude); const globs = compileGlobs(exclude);
const entries = await walk(srcDir); const entries = await walk(srcDir);
@@ -104,9 +112,11 @@ export async function packDir({
let files = 0; let files = 0;
let dirs = 0; let dirs = 0;
let reused = 0;
try { try {
for (const entry of entries) { for (const entry of entries) {
if (globs.some((re) => re.test(entry.rel))) continue; if (globs.some((re) => re.test(entry.rel))) continue;
if (onlyPrefixes && !onlyPrefixes.some((p) => entry.rel.startsWith(p))) continue;
if ( if (
entry.type === 'file' && entry.type === 'file' &&
excludeFilePrefixes.some((prefix) => entry.rel.startsWith(prefix)) excludeFilePrefixes.some((prefix) => entry.rel.startsWith(prefix))
@@ -121,16 +131,48 @@ export async function packDir({
lastModDate: dateOf(stat), lastModDate: dateOf(stat),
}); });
dirs++; dirs++;
} else { continue;
// BlobReader + openAsBlob: 大字体文件流式读取, 不整体载入内存
const blob = await fs.openAsBlob(entry.abs);
await writer.add(entry.rel, new zip.BlobReader(blob), {
unixMode: fileModeOf(stat),
lastModDate: dateOf(stat),
});
files++;
onEntry?.(entry.rel);
} }
const lastModDate = dateOf(stat);
const unixMode = fileModeOf(stat);
// 预压缩缓存: 命中则直接搬运已压缩数据 (passThrough), 跳过 deflate。
// 需同时提供下列字段, 否则 zip.js 在没有压缩阶段的情况下无法写出正确的条目头:
// uncompressedSize / crc32 / compressionMethod —— 条目头必需
// level —— zip.js 把压缩级别编码进通用标志位 (bit 1-2), 不传会与现场
// 压缩的产物产生字节差异 (整包哈希不一致)
const cached = cache?.get(entry.rel);
if (cached) {
try {
const compressed = await cached.compressed();
await writer.add(entry.rel, new zip.BlobReader(compressed), {
unixMode,
lastModDate,
passThrough: true,
uncompressedSize: cached.uncompressedSize,
crc32: cached.crc32,
compressionMethod: 8, // deflate, 与压缩期一致
level,
});
files++;
reused++;
onEntry?.(entry.rel);
continue;
} catch (e) {
// 单条搬运失败不应中断构建: 回退为现场压缩
log.warn(`缓存条目不可用, 回退现场压缩: ${entry.rel} (${e.message})`);
}
}
// 未命中: 现场压缩。BlobReader + openAsBlob 流式读取, 不整体载入内存
const blob = await fs.openAsBlob(entry.abs);
await writer.add(entry.rel, new zip.BlobReader(blob), {
unixMode,
lastModDate,
});
files++;
onEntry?.(entry.rel);
} }
await writer.close(); await writer.close();
await closed; await closed;
@@ -139,7 +181,7 @@ export async function packDir({
throw e; throw e;
} }
return { files, dirs }; return { files, dirs, reused };
} }
/** 打开 zip 读取器 (调用方负责 close) */ /** 打开 zip 读取器 (调用方负责 close) */
+236
View File
@@ -0,0 +1,236 @@
// dev/lib/zipcache.mjs — 预压缩构建缓存
//
// 动机: 打包耗时几乎全在压缩。system/fonts/ 有 131MB 原始数据 (压缩后 71MB),
// 占整包压缩量的 ~70%, 而这部分内容在大多数构建中是**不变的** (只有发布新版本
// 字体时才会动)。把它预先压缩并缓存起来, 后续打包只需把已压缩的数据"搬运"进
// 新 zip (passThrough, 不重新 deflate), 再压缩其余变动文件即可。
//
// 设计: 缓存是若干个"目录片段" (segment), 每个片段对应源目录下的一个子目录,
// 并对该子树计算指纹 (文件名 + 大小 + mtime + 权限位)。指纹一致才能复用。
// - 用文件大小 + mtime 而非内容哈希做指纹: 对 131MB 字体算哈希本身就要 1s 左右,
// 而 mtime/size 变化足以判定"内容可能变了"。缓存是本地构建加速, 不是安全边界,
// 真要去校验内容, 打包后的产物校验 (dev/pack.mjs 的 verify) 会兜住。
// - 缓存不含任何"必须存在"的假设: 缺失/版本不符/指纹不符一律回退为现场压缩。
//
// 缓存目录: dev/.cache/ (已 gitignore, 不随仓库分发)
import fsp from 'node:fs/promises';
import path from 'node:path';
import { ROOT } from './paths.mjs';
import { log } from './log.mjs';
/** 缓存目录 (不入库) */
export const CACHE_DIR = path.join(ROOT, 'dev', '.cache');
/** 缓存格式版本: 结构变更时递增, 旧缓存自动失效 */
const CACHE_VERSION = 1;
/** 单个片段的索引文件名 */
function indexFile(segment) {
return path.join(CACHE_DIR, `${segment}.index.json`);
}
/** 单个片段的预压缩 zip 路径 */
function dataFile(segment) {
return path.join(CACHE_DIR, `${segment}.zip`);
}
/**
* 递归收集子树的条目 (相对 srcDir 的路径, 排序稳定), 用于计算指纹。
* 目录条目也计入 —— 目录的增删同样会使缓存失效。
*/
async function collectTree(rootDir) {
const out = [];
async function recurse(dir) {
const items = await fsp.readdir(dir, { withFileTypes: true });
items.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const item of items) {
const abs = path.join(dir, item.name);
const rel = path.relative(rootDir, abs).split(path.sep).join('/');
if (item.isDirectory()) {
out.push({ rel: `${rel}/`, type: 'dir' });
await recurse(abs);
} else if (item.isFile()) {
const st = await fsp.stat(abs);
out.push({
rel,
type: 'file',
size: st.size,
// mtimeMs 取整: 不同文件系统的时间精度不同, 避免无意义的失配
mtime: Math.floor(st.mtimeMs),
mode: st.mode & 0o777,
});
}
// 其他类型 (符号链接等) 跳过, 与打包逻辑一致
}
}
await recurse(rootDir);
return out;
}
/** 由条目列表计算指纹 (稳定序列化后哈希) */
function fingerprint(entries) {
return JSON.stringify(entries);
}
/**
* 计算某个源目录子树的缓存键。
* @param {string} subtreeDir 绝对路径
* @returns {Promise<string>} 指纹字符串
*/
export async function subtreeKey(subtreeDir) {
return fingerprint(await collectTree(subtreeDir));
}
/**
* 读取缓存片段 (若有效)。
* @param {string} segment 片段名 (同时作为缓存文件名, 仅用 [a-z0-9-])
* @param {string} expectedKey 期望的指纹
* @returns {Promise<{ file: string, entries: object[] } | null>} 有效则返回缓存信息
*/
export async function readCache(segment, expectedKey) {
try {
const raw = await fsp.readFile(indexFile(segment), 'utf8');
const idx = JSON.parse(raw);
if (idx.version !== CACHE_VERSION) return null;
if (idx.key !== expectedKey) return null;
// 缓存数据文件必须存在且有内容
const st = await fsp.stat(dataFile(segment));
if (st.size === 0) return null;
return { file: dataFile(segment), entries: idx.entries ?? [] };
} catch {
// 任何读取/解析失败都视为无缓存 —— 优雅降级
return null;
}
}
/**
* 打开缓存片段, 返回按相对路径取用的压缩数据查找表。
*
* 返回的对象持有 ZipReader; 每一条的压缩数据按需读取 (getData(passThrough) 只做
* 字节搬运, 不解压), 因此不会把整个片段一次性读进内存。用完需调用 close()。
*
* @param {string} segment 片段名
* @param {string} key 指纹
* @returns {Promise<{ get(rel: string): { compressed: () => Promise<Blob>, crc32: number, uncompressedSize: number } | undefined, entries: string[], close(): Promise<void> } | null>}
*/
export async function openCache(segment, key) {
const cached = await readCache(segment, key);
if (!cached) return null;
let reader = null;
try {
const { ZipReader, BlobReader, BlobWriter } = await import('@zip.js/zip.js');
const fs = await import('node:fs');
// openAsBlob: 流式读取缓存文件, 不整体载入内存
const blob = await fs.openAsBlob(dataFile(segment));
reader = new ZipReader(new BlobReader(blob));
const entries = await reader.getEntries();
const table = new Map();
for (const e of entries) {
if (e.directory) continue;
table.set(e.filename, {
// 惰性取用: 每次调用只搬运该条目的已压缩字节, 不重新压缩
compressed: () => e.getData(new BlobWriter(), { passThrough: true }),
crc32: e.crc32,
uncompressedSize: e.uncompressedSize,
});
}
return {
get: (rel) => table.get(rel),
entries: [...table.keys()],
close: async () => {
await reader.close();
},
};
} catch (e) {
log.warn(`打开缓存片段 ${segment} 失败 (将现场压缩): ${e.message}`);
try {
await reader?.close();
} catch {
// 忽略
}
return null;
}
}
/**
* 由"已完成压缩的 zip"建立缓存片段。
* 该 zip 内条目名需与打包时的相对路径一致 (即相对 srcDir 的路径)。
*
* @param {string} segment 片段名
* @param {string} key 指纹
* @param {string} zipFile 已压缩的 zip 路径
* @param {number} level 压缩级别 (写入索引, 级别变化会使缓存失效)
*/
export async function saveCacheFromZip(segment, key, zipFile, level) {
try {
await fsp.mkdir(CACHE_DIR, { recursive: true });
const { ZipReader, BlobReader } = await import('@zip.js/zip.js');
const fs = await import('node:fs');
const blob = await fs.openAsBlob(zipFile);
const reader = new ZipReader(new BlobReader(blob));
const entries = await reader.getEntries();
const meta = entries.map((e) => ({
rel: e.filename,
size: e.uncompressedSize,
compressedSize: e.compressedSize,
direct: e.directory,
}));
await reader.close();
const idx = {
version: CACHE_VERSION,
key,
level,
createdAt: new Date().toISOString(),
entries: meta,
};
// 先落数据文件再落索引: 若中途失败, 索引缺失 → 视为无缓存, 不会读到半成品
await fsp.copyFile(zipFile, dataFile(segment));
await fsp.writeFile(indexFile(segment), JSON.stringify(idx, null, 2), 'utf8');
return true;
} catch (e) {
log.warn(`写入缓存失败 (不影响构建): ${e.message}`);
return false;
}
}
/** 清空全部缓存 */
export async function clearCache() {
await fsp.rm(CACHE_DIR, { recursive: true, force: true });
}
/** 缓存片段的当前状态 (供 pnpm cache:status 展示) */
export async function cacheStatus() {
try {
const files = await fsp.readdir(CACHE_DIR);
const out = [];
for (const name of files.filter((f) => f.endsWith('.index.json'))) {
const segment = name.replace(/\.index\.json$/, '');
try {
const idx = JSON.parse(await fsp.readFile(path.join(CACHE_DIR, name), 'utf8'));
let size = 0;
try {
size = (await fsp.stat(dataFile(segment))).size;
} catch {
// 数据文件缺失
}
out.push({
segment,
version: idx.version,
usable: idx.version === CACHE_VERSION && size > 0,
size,
files: (idx.entries ?? []).filter((e) => !e.direct).length,
createdAt: idx.createdAt,
});
} catch {
// 索引损坏
}
}
return out;
} catch {
return [];
}
}
+70 -5
View File
@@ -6,11 +6,12 @@
// _template: FONTS/ 为空目录, 适合更新已有模块 (customize.sh 从旧模块继承字体) // _template: FONTS/ 为空目录, 适合更新已有模块 (customize.sh 从旧模块继承字体)
// //
// 流程: 编译 fontmm-wght (Go) 与 Zygisk 模块 (C++) -> 生成 SHA256SUMS // 流程: 编译 fontmm-wght (Go) 与 Zygisk 模块 (C++) -> 生成 SHA256SUMS
// -> 打包两版 -> 校验产物 -> 生成发布校验文件 // -> 打包两版 (复用预压缩缓存) -> 校验产物 -> 生成发布校验文件
// //
// 用法: node dev/pack.mjs [--skip-go] [--skip-zygisk] // 用法: node dev/pack.mjs [--skip-go] [--skip-zygisk] [--no-cache]
// --skip-go: 跳过 Go 交叉编译 (CI 中已单独构建时使用) // --skip-go: 跳过 Go 交叉编译 (CI 中已单独构建时使用)
// --skip-zygisk: 跳过 Zygisk 模块编译 (无 NDK 或已构建好时使用) // --skip-zygisk: 跳过 Zygisk 模块编译 (无 NDK 或已构建好时使用)
// --no-cache: 禁用预压缩缓存 (用于验证缓存与非缓存产物一致)
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import { log, die, stopwatch } from './lib/log.mjs'; import { log, die, stopwatch } from './lib/log.mjs';
@@ -18,10 +19,15 @@ import { ROOT, SRC_DIR, DIST_DIR, DERIVED_XML_RELS, readVersion, safeFileVersion
import { packDir, listEntries, indexZip, hashFile } from './lib/zip.mjs'; import { packDir, listEntries, indexZip, hashFile } from './lib/zip.mjs';
import { run, hasCommand } from './lib/exec.mjs'; import { run, hasCommand } from './lib/exec.mjs';
import { buildWght, wghtBinRel, WGHT_BIN } from './lib/go.mjs'; import { buildWght, wghtBinRel, WGHT_BIN } from './lib/go.mjs';
import { subtreeKey, openCache, saveCacheFromZip } from './lib/zipcache.mjs';
import { findNdk, buildZygiskModule, TARGET_ABI } from './lib/ndk.mjs'; import { findNdk, buildZygiskModule, TARGET_ABI } from './lib/ndk.mjs';
const skipGo = process.argv.includes('--skip-go'); const skipGo = process.argv.includes('--skip-go');
const skipZygisk = process.argv.includes('--skip-zygisk'); const skipZygisk = process.argv.includes('--skip-zygisk');
/** 预压缩缓存开关 (--no-cache 关闭; CI 中禁用可避免缓存目录带来的不确定性) */
const CACHE_ENABLED = !process.argv.includes('--no-cache');
/** 打包压缩级别 (与原 zip -2 一致); 也是缓存片段的压缩级别, 变更会使缓存失效 */
const COMPRESS_LEVEL = 2;
const elapsed = stopwatch(); const elapsed = stopwatch();
// 可复现打包: 设置 SOURCE_DATE_EPOCH 时, 所有 zip 条目使用该固定时间戳, // 可复现打包: 设置 SOURCE_DATE_EPOCH 时, 所有 zip 条目使用该固定时间戳,
@@ -103,9 +109,38 @@ await Promise.all([
fsp.rm(`${tplOut}.sha256`, { force: true }), fsp.rm(`${tplOut}.sha256`, { force: true }),
]); ]);
// ---------- 4. 预压缩缓存 ----------
// system/fonts/ 占整包压缩量的 ~70%, 而它在多数构建中不变 (仅发布字体时才动)。
// 内容未变时直接复用已压缩数据 (passThrough, 不重新 deflate), 显著缩短打包时间。
//
// 缓存按子树分别管理, 以「文件名 + 大小 + mtime + 权限位」为指纹; 任一项变化即失效,
// 回退为现场压缩并重建缓存。缓存目录 dev/.cache/ 不入库, 缺失/损坏一律优雅降级。
const fontCacheSegment = 'system-fonts';
const fontCachePrefix = 'system/fonts/';
const fontsDir = path.join(SRC_DIR, 'system', 'fonts');
let fontCache = null;
if (CACHE_ENABLED) {
const cacheKey = await subtreeKey(fontsDir);
fontCache = await openCache(fontCacheSegment, cacheKey);
if (fontCache) {
log.ok(`命中预压缩缓存 (${fontCache.entries.length} 个字体文件, 跳过压缩)`);
} else {
log.info('无可用预压缩缓存, 本次将现场压缩并在完成后建立缓存');
}
}
log.step('打包 preplace 版 (含预置字体)...'); log.step('打包 preplace 版 (含预置字体)...');
const pre = await packDir({ srcDir: SRC_DIR, outFile: preOut, exclude, fixedDate }); const pre = await packDir({
log.ok(`preplace: ${pre.files} 文件 / ${pre.dirs} 目录`); srcDir: SRC_DIR,
outFile: preOut,
exclude,
fixedDate,
cache: fontCache ?? undefined,
});
log.ok(
`preplace: ${pre.files} 文件 / ${pre.dirs} 目录${pre.reused ? ` (复用缓存 ${pre.reused} 个)` : ''}`,
);
log.step('打包 template 版 (FONTS 目录为空)...'); log.step('打包 template 版 (FONTS 目录为空)...');
// 排除 FONTS/ 下的字体文件, 但保留目录条目本身 (设备端需要该目录存在) // 排除 FONTS/ 下的字体文件, 但保留目录条目本身 (设备端需要该目录存在)
@@ -115,8 +150,38 @@ const tpl = await packDir({
exclude, exclude,
excludeFilePrefixes: ['FONTS/'], excludeFilePrefixes: ['FONTS/'],
fixedDate, fixedDate,
cache: fontCache ?? undefined,
}); });
log.ok(`template: ${tpl.files} 文件 / ${tpl.dirs} 目录`); log.ok(
`template: ${tpl.files} 文件 / ${tpl.dirs} 目录${tpl.reused ? ` (复用缓存 ${tpl.reused} 个)` : ''}`,
);
await fontCache?.close();
// 未命中且本次确实压缩了字体文件时, 用刚产出的产物建立缓存。
// 以 preplace 包为缓存来源 (它含完整的 system/fonts/); 需确认确实包含字体条目。
if (CACHE_ENABLED && !fontCache && pre.reused === 0) {
const cacheKey = await subtreeKey(fontsDir);
// 从 preplace 包中抽取 system/fonts/ 部分作为缓存片段:
// 直接把整包复制过去会让缓存体积翻倍, 故重建一个只含该子树的 zip。
log.step('建立预压缩缓存...');
const segTmp = path.join(DIST_DIR, '.cache-segment.zip');
try {
await packDir({
srcDir: SRC_DIR,
outFile: segTmp,
exclude,
onlyPrefixes: [fontCachePrefix],
level: COMPRESS_LEVEL,
fixedDate,
});
const ok = await saveCacheFromZip(fontCacheSegment, cacheKey, segTmp, COMPRESS_LEVEL);
if (ok) log.ok('缓存已建立 (下次打包将自动复用)');
} catch (e) {
log.warn(`建立缓存失败 (不影响本次构建): ${e.message}`);
} finally {
await fsp.rm(segTmp, { force: true });
}
}
// ---------- 4. 校验产物 ---------- // ---------- 4. 校验产物 ----------
// 取代原 shell 的 unzip -l / unzip -p 检查: 直接回读 zip 内容并与源文件比对, // 取代原 shell 的 unzip -l / unzip -p 检查: 直接回读 zip 内容并与源文件比对,
+3
View File
@@ -20,6 +20,9 @@
"go:build:local": "cd golang && go build -o /tmp/fontmm-wght ./cmd/fontmm-wght", "go:build:local": "cd golang && go build -o /tmp/fontmm-wght ./cmd/fontmm-wght",
"zygisk:build": "node dev/build-zygisk.mjs", "zygisk:build": "node dev/build-zygisk.mjs",
"sha256": "node dev/gen-sha256.mjs", "sha256": "node dev/gen-sha256.mjs",
"cache:status": "node dev/cache.mjs status",
"cache:clean": "node dev/cache.mjs clean",
"cache:test": "node dev/cache.mjs test",
"sync:fonts-xml": "node dev/sync-fonts-xml.mjs", "sync:fonts-xml": "node dev/sync-fonts-xml.mjs",
"empty-font": "node dev/empty-font.mjs" "empty-font": "node dev/empty-font.mjs"
}, },