Files
zhuiguang-ai/scripts/version-manager.mjs
T

91 lines
2.1 KiB
JavaScript

#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageJsonPath = path.join(__dirname, '../package.json');
function readVersion() {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
return packageJson.version;
}
function parseVersion(versionStr) {
const match = versionStr.match(/^v?(\d+)\.(\d+)\.(\d+)$/i);
if (!match) {
throw new Error(`无效的版本号格式: ${versionStr},应为 V{major}.{minor}.{patch}`);
}
return {
major: parseInt(match[1], 10),
minor: parseInt(match[2], 10),
patch: parseInt(match[3], 10)
};
}
function incrementVersion(currentVersion) {
const { major, minor, patch } = parseVersion(currentVersion);
if (patch >= 20) {
return {
major,
minor: minor + 1,
patch: 0
};
}
return {
major,
minor,
patch: patch + 1
};
}
function formatVersion({ major, minor, patch }) {
return `V${major}.${minor}.${patch}`;
}
function updatePackageJson(newVersion) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
packageJson.version = newVersion;
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n', 'utf8');
}
function main() {
try {
const currentVersion = readVersion();
console.log(`当前版本: ${currentVersion}`);
const newVersionObj = incrementVersion(currentVersion);
const newVersion = formatVersion(newVersionObj);
console.log(`新版本号: ${newVersion}`);
updatePackageJson(newVersion);
console.log(`package.json 已更新`);
console.log(`\n如需创建git tag,请执行:`);
console.log(`git tag ${newVersion.toLowerCase()}`);
console.log(`git push origin ${newVersion.toLowerCase()}`);
} catch (error) {
console.error(`错误: ${error.message}`);
process.exit(1);
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}
export {
readVersion,
parseVersion,
incrementVersion,
formatVersion,
updatePackageJson
};