前面寫過〈同一個資料夾開好幾個 AI session〉,留了一個問題沒解:部署腳本在正式站資料夾裡 git pull 完直接 next build,build 讀的是資料夾裡的檔案,不是 git 裡的版本。別的 session 改到一半、還沒 commit 的檔案會被一起 build;build 失敗是小事,build 成功就直接上線了,git 裡卻沒有這份程式碼。
為什麼不是「在別處 build 再搬回來」
最直覺的做法是在暫存資料夾 build,再把輸出搬回正式站資料夾。但 Next.js 的 build 輸出裡寫死了 build 當下的絕對路徑,搬了位置,伺服器會去錯的地方找檔案。
所以反過來做:讓網站直接在乾淨的副本裡執行。
做法:.live 是一個 git worktree
git fetch origin main
git worktree add --detach .live origin/main # 第一次
git -C .live checkout -f --detach origin/main # 之後每次
.live 放在正式站資料夾裡面(加進 .gitignore),裡面只有 origin/main,也就是真的 push 上去的東西。build 輸出放在 .live/.next-a/.live/.next-b,兩個槽輪流用,跟以前一樣。
這樣放有一個好處:.live 沒有自己的 node_modules,Node 會往上一層找到正式站資料夾那份,不用每次部署重裝套件。只有 Turbopack 要另外處理,它只在「最近的 lockfile 那層」裡找檔案,會報 Could not find the Next.js package。在 next.config.ts 裡把 root 拉到有 node_modules 的那層就好:
function findWorktreeRoot(dir: string) {
if (existsSync(path.join(dir, "node_modules"))) return undefined;
for (let d = path.dirname(dir); d !== path.dirname(d); d = path.dirname(d)) {
if (existsSync(path.join(d, "node_modules", "next", "package.json"))) return d;
}
}
const root = findWorktreeRoot(process.cwd());
// nextConfig: ...(root && { turbopack: { root }, outputFileTracingRoot: root })
程式在 .live,資料留在原處
訪客統計、後台資料庫、log 這些都不在 git 裡,.live 沒有。伺服器啟動腳本拆成兩個目錄:
- appDir(
.live):Next.js 的程式、文章、架構圖,連/changelog讀的git log都在這裡 - projectDir(正式站資料夾):
data/、logs/、草稿、.env.local
用來指出上線槽的指標檔,從 .next-a 改成 .live/.next-a;伺服器看到有路徑就把前半段當 appDir。舊格式照樣認得,所以第一次切過去如果健檢沒過,退回的就是原本資料夾裡的舊槽。
排程工作執行的還是同一支 scripts/server.js,一行都不用改,所以不需要系統管理員權限,也不用停站維護。
演練
不能在正式站上試,所以先手動建好 .live,build 到 .live/.next-test,再用正式的啟動腳本在另一個 port 起來,跑完整的 E2E:171 個測試全過。頁面上的資料(後台待辦、草稿、雷達)都讀得到,.live 裡也沒有多長出 data/ 資料夾。
還有一個小坑
git 的 pre-commit hook 寫的是 node node_modules/typescript/bin/tsc,在 worktree 裡找不到。部署成功後會自動 commit 重新產生的履歷 PDF,這一步是在 .live 裡做的,hook 一跑就失敗。改成往上層找 node_modules:
root="$PWD"
while [ ! -d "$root/node_modules/typescript" ] && [ "$root" != "$(dirname "$root")" ]; do root="$(dirname "$root")"; done
node "$root/node_modules/typescript/bin/tsc" --noEmit
Claude Code 的 session worktree 也是同一個情況,一起解決了。