release.ts•3.01 kB
import { execSync } from "child_process";
import fs from "fs";
import path from "path";
const VALID_RELEASE_TYPES = ["major", "minor", "patch"];
const parseArgs = (): { releaseType: string } => {
const args = process.argv.slice(2);
if (args.length !== 1) {
console.error("Error: Expected exactly 1 argument - release type");
console.log(`Usage: npx tsx release.ts <release-type>`);
console.log(` - release-type: ${VALID_RELEASE_TYPES.join(" | ")}`);
process.exit(1);
}
const [releaseType] = args;
if (!VALID_RELEASE_TYPES.includes(releaseType)) {
console.error(`Error: Invalid release type "${releaseType}"`);
console.log(`Valid release types: ${VALID_RELEASE_TYPES.join(", ")}`);
process.exit(1);
}
return { releaseType };
};
const bumpVersion = (currentVersion: string, releaseType: string): string => {
const [major, minor, patch] = currentVersion
.replace(/^v/, "")
.split(".")
.map(Number);
switch (releaseType) {
case "major":
return `${major + 1}.0.0`;
case "minor":
return `${major}.${minor + 1}.0`;
case "patch":
return `${major}.${minor}.${patch + 1}`;
default:
throw new Error(`Invalid release type: ${releaseType}`);
}
};
const updatePackageVersion = (releaseType: string): void => {
const packageJsonPath = path.resolve("./package.json");
if (!fs.existsSync(packageJsonPath)) {
console.error(`Error: Could not find package.json at ${packageJsonPath}`);
process.exit(1);
}
console.log(`Reading ${packageJsonPath}...`);
const packageJsonContent = fs.readFileSync(packageJsonPath, "utf-8");
const packageJson = JSON.parse(packageJsonContent);
const currentVersion = packageJson.version;
const newVersion = bumpVersion(currentVersion, releaseType);
console.log(`Updating version: ${currentVersion} -> ${newVersion}`);
packageJson.version = newVersion;
fs.writeFileSync(
packageJsonPath,
JSON.stringify(packageJson, null, 2) + "\n",
"utf-8"
);
try {
console.log("Staging changes...");
execSync(`git add ${packageJsonPath}`);
console.log(`Successfully staged changes`);
console.log(`Committing changes...`);
execSync(`git commit -m "chore: bump version to ${newVersion}"`);
console.log(`Successfully committed changes`);
console.log(`Pushing changes...`);
execSync(`git push origin`);
console.log(`Creating build...`);
execSync(`rm -rf ./build`);
execSync(`npm run build`);
console.log(`Successfully created build`);
console.log(`Pushing build changes to npm...`);
execSync(`npm publish`);
console.log(`Successfully published to npm`);
} catch (error) {
console.error(`Error: Failed to execute git commands`);
console.error(`Details: ${error.message}`);
process.exit(1);
}
};
// Main execution
try {
const { releaseType } = parseArgs();
updatePackageVersion(releaseType);
} catch (error) {
console.error("Error:", error.message);
process.exit(1);
}