refactor: simplify bump function and improve version handling
This commit is contained in:
@@ -2,47 +2,34 @@
|
|||||||
|
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
import semver from 'semver';
|
import semver from 'semver';
|
||||||
|
|
||||||
function bump(fileName) {
|
function bump(fileName, version) {
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const filePath = path.resolve(process.cwd(), fileName);
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
|
|
||||||
const filePath = path.resolve(__dirname, '..', fileName);
|
|
||||||
|
|
||||||
if (!bump.nextVersion) {
|
|
||||||
const packageJsonPath = path.resolve(__dirname, '../package.json');
|
|
||||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
|
||||||
const version = packageJson.version;
|
|
||||||
|
|
||||||
if (typeof version !== 'string') {
|
|
||||||
throw new Error('package.json does not contain a string "version" field.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextVersion = semver.inc(version, 'patch');
|
|
||||||
|
|
||||||
if (!nextVersion) {
|
|
||||||
throw new Error(`Unsupported semver format: "${version}"`);
|
|
||||||
}
|
|
||||||
|
|
||||||
bump.nextVersion = nextVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!fs.existsSync(filePath)) {
|
if (!fs.existsSync(filePath)) {
|
||||||
throw new Error(`File not found: ${filePath}`);
|
throw new Error(`File not found: ${filePath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const json = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
const json = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||||
json.version = bump.nextVersion;
|
const currentVersion = json.version;
|
||||||
|
|
||||||
if (path.basename(filePath) === 'package-lock.json' && json.packages?.['']) {
|
if (typeof currentVersion !== 'string') {
|
||||||
json.packages[''].version = bump.nextVersion;
|
throw new Error(`${fileName} does not contain a string "version" field.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const nextVersion = version ?? semver.inc(currentVersion, 'patch');
|
||||||
|
|
||||||
|
if (!nextVersion) {
|
||||||
|
throw new Error(`Unsupported semver format: "${currentVersion}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
json.version = nextVersion;
|
||||||
|
|
||||||
fs.writeFileSync(filePath, `${JSON.stringify(json, null, 4)}\n`, 'utf8');
|
fs.writeFileSync(filePath, `${JSON.stringify(json, null, 4)}\n`, 'utf8');
|
||||||
console.log(`Bumped version in ${fileName} to ${bump.nextVersion}`);
|
console.log(`Bumped version in ${fileName} to ${nextVersion}`);
|
||||||
|
return nextVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
bump('package.json');
|
const bumpedVersion = bump('package.json');
|
||||||
bump('package-lock.json');
|
bump('package-lock.json', bumpedVersion);
|
||||||
|
|||||||
Reference in New Issue
Block a user