Files
build-go/go-module-zip.sh
2026-11-05 02:54:21 +00:00

42 lines
2.1 KiB
Bash
Executable File
Raw Permalink 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.
#!/usr/bin/env bash
# 把標籤(或 commit)對應的原始碼打包成 Go 模組 zip,在標準輸出印出 zip 的路徑。由 build-go 的 entrypoint.sh 呼叫。
# go-module-zip.sh <標籤> 標籤要已存在於本機(可以還沒推送)
# go-module-zip.sh <commit 或分支> <版本> 不建標籤也能打包,<版本> 用來命名,例如 v0.0.1
# 模組 zip 要含不在 git 裡的建置結果(例如編譯好的前端、go:embed 的執行檔):EMBED_PATHS 是換行或空白分隔的路徑清單(相對於儲存庫根目錄,檔案或目錄),
# 打包時從工作目錄複製進去,少了任何一個就失敗。
# zip 放在新的暫存目錄(ZIP_DIR 可改),呼叫端用完自行刪除;進度與錯誤訊息都輸出到標準錯誤。
set -euo pipefail
ref=${1:?用法:go-module-zip.sh <標籤,例如 v0.0.1> | <commit> <版本>}
tag=${2:-$ref}
module=$(sed -n 's/^module //p' go.mod)
if [ $# -lt 2 ]; then
git rev-parse -q --verify "refs/tags/$tag" >/dev/null || { echo "找不到標籤 $tag" >&2; exit 1; }
else
git rev-parse -q --verify "$ref^{commit}" >/dev/null || { echo "找不到 $ref" >&2; exit 1; }
fi
# shellcheck disable=SC2206 # 依空白與換行拆成清單
embed=(${EMBED_PATHS:-})
for f in "${embed[@]}"; do [ -e "$f" ] || { echo "$f 不存在:先執行建置前置(prebuild)" >&2; exit 1; }; done
out=${ZIP_DIR:-$(mktemp -d)}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
dir="$module@$tag"
mkdir -p "$work/$dir"
git archive "$ref" | tar -x -C "$work/$dir"
for f in "${embed[@]}"; do
rm -rf "${work:?}/$dir/$f" && mkdir -p "$work/$dir/$(dirname "$f")" && cp -r "$f" "$work/$dir/$f"
done
# 壓縮檔裡的路徑必須是完整的 <模組路徑>@<版本>/...(Gitea 用它決定套件名稱),所以不能用 python -m zipfile
python3 -I - "$work" "$dir" "$out/mod.zip" <<'PY'
import os, sys, zipfile
work, d, dest = sys.argv[1:4]
with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:
for root, _, files in os.walk(os.path.join(work, d)):
for f in sorted(files):
full = os.path.join(root, f)
z.write(full, os.path.relpath(full, work))
PY
echo "$out/mod.zip"