refactor: 优化发布流程,npm 发布失败或取消时自动回退版本号修改

This commit is contained in:
2026-06-11 15:16:29 +08:00
parent e0a54558a8
commit 824969ea25

View File

@@ -162,8 +162,7 @@ async function stepNpmPublish(): Promise<void> {
const answer = await ask("确认发布到 npm? [y/N]: ");
if (answer.toLowerCase() !== "y") {
console.log("已取消发布");
process.exit(0);
throw new CancelledError("已取消发布");
}
const proc = Bun.spawn(["bun", "publish", "--access", "public"], {
@@ -184,6 +183,24 @@ function writeVersion(version: string): void {
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
}
async function revertVersion(): Promise<void> {
console.log("\n回退 package.json 到原始状态...");
const proc = Bun.spawn(["git", "checkout", "package.json"], {
stdio: ["inherit", "inherit", "inherit"],
});
const exitCode = await proc.exited;
if (exitCode !== 0) {
throw new Error("git checkout package.json 失败,请手动检查工作区状态");
}
}
class CancelledError extends Error {
constructor(message: string) {
super(message);
this.name = "CancelledError";
}
}
async function main(): Promise<void> {
await checkWorkingTree();
@@ -196,10 +213,23 @@ async function main(): Promise<void> {
writeVersion(newVersion);
console.log(`[2/3] 版本号已更新: ${newVersion}`);
try {
await stepNpmPublish();
} catch (err) {
if (err instanceof CancelledError) {
console.log(err.message);
await revertVersion();
console.log("工作区已恢复,无事发生");
process.exit(0);
}
console.error("npm 发布失败,正在回退...");
await revertVersion();
throw err;
}
await stepGitCommitTag(newVersion);
console.log(`[3/3] git commit 和 tag v${newVersion} 完成`);
await stepNpmPublish();
console.log("npm 发布完成");
}