WEB/docs/部署-本地打包丢文件问题与修复.md
2026-10-10 18:04:26 +08:00

84 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 部署-本地打包丢文件问题与修复
## 现象
`npm run deploy` 在本地构建、上传都正常,最后报:
```
❌ 新版本 index.html 缺失或为空,取消切换
```
(来自 `scripts/remote/deploy.sh` 的打包完整性校验,`exit 1`;**线上版本未被切换,站点不受影响**。)
服务器上留下一个残缺版本目录(如 `releases/v20261010_175526_29776/`):
有 `assets/`(743 个文件)、`favicon.ico`、`hikvision/`、`logo/`,**唯独没有 `index.html`**。
## 根因
**本地 `tar` 打包时把 `dist/index.html` 静默丢掉了**,上传的 `dist.tar.gz` 里根本没有它。
Windows 自带的 `tar.exe` 是 bsdtar(libarchive)。libarchive 有一条「不要把归档文件加进归档自己」的保护:
```c
/* libarchive/archive_write_open_filename.c —— 打开输出文件时记录其身份 */
if (S_ISREG(st.st_mode))
archive_write_set_skip_file(a, st.st_dev, st.st_ino);
/* libarchive/archive_write.c —— 写入每条 entry 时比对 */
if (archive_entry_ino_is_set(entry) &&
archive_entry_dev(entry) == (dev_t)a->skip_file_dev &&
archive_entry_ino64(entry) == a->skip_file_ino) {
archive_set_error(&a->archive, EIO, "Can't add archive to itself");
return (ARCHIVE_FAILED); /* 只让这一条 entry 失败,tar 退出码仍是 0 */
}
```
Windows 下这组 `(dev, ino)` 文件身份信息不可靠:当**压缩包与被打包目录同处一个目录/同一个卷**时,
目录里某个普通文件会被误判成「归档自身」而被丢弃。实测丢的正好是 `dist/index.html`。
两个致命放大点:
1. **退出码 0**:只给该 entry 返回 `ARCHIVE_FAILED`,不是致命错误 → `deploy.mjs` 里 `run('tar', ...)` 判不出来。
2. **本地只校验 `dist/`,不校验压缩包** → 坏产物被上传,直到远端校验才失败。
## 复现与证据(本地实测)
```powershell
# 压缩包放在项目目录里(旧写法)——丢文件,但退出码 0
tar -czf dist.tar.gz -C dist .
# stderr: Can't add archive to itself
# 条目 780,无 ./index.html
# 压缩包换到别的位置(或换个不会被误判的名字)——正常
tar -czf "$env:TEMP\x.tar.gz" -C dist .
# 条目 781,含 ./index.html
```
两次归档**只差 `index.html` 一个文件**。
因为是文件身份信息「撞车」,取决于该目录的创建/删除历史(MFT 索引复用等),所以**表现为偶发**:
同样的命令换名/换目录/重跑就可能正常。
## 修复
改 `scripts/deploy.mjs`:
1. **压缩包改放系统临时目录**(`os.tmpdir()`)——跨卷时 `dev` 不同,不可能再被误判;
远端解压用的文件名仍是 `dist.tar.gz`(`TARBALL_NAME`),只是本地路径变了。
2. **打包后回读压缩包校验**(`tar -tzf`),规则与远端 `deploy.sh` 一致:
`index.html` + `index.html` 里引用的所有 `/assets/*.js|css` 必须齐全;缺文件则**重新打包一次**,仍缺才中止。
3. 本地 `index.html` 校验补上「非空」判断。
另外新增两个排查开关(不改线上行为):
```bash
npm run deploy -- --pack-only # 构建 + 打包 + 校验,不上传
npm run deploy -- --pack-only --skip-build # 复用已有 dist,只验证打包
```
## 排查/验证手法
- 看压缩包内容:`tar -tzf <归档> | findstr index.html`(**必须确认有此条目**)
- 看到 `Can't add archive to itself` 警告即为本条问题的特征
- 远端校验失败留下的版本目录可安全删除(脚本会按 KEEP 数量自然淘汰,不影响 `current`)