From 9e92f34e7af8fa97a4137cce03bdb02836687cbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ro=C5=BCek?= Date: Wed, 20 Sep 2023 20:36:07 +0200 Subject: [PATCH] chore(cli): tweak version inlining --- package.json | 2 +- packages/cli/scripts/inline-version.mjs | 49 +++++++++++++++++++++++-- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 22e2f7e14..2e6709c2f 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,7 @@ [ "@semantic-release/exec", { - "publishCmd": "node scripts/inline-version.mjs ${nextRelease.version}" + "publishCmd": "test -f scripts/inline-version.mjs && node scripts/inline-version.mjs --verbose ${nextRelease.version}" } ], "@semantic-release/npm", diff --git a/packages/cli/scripts/inline-version.mjs b/packages/cli/scripts/inline-version.mjs index d9089fa52..fe1177280 100644 --- a/packages/cli/scripts/inline-version.mjs +++ b/packages/cli/scripts/inline-version.mjs @@ -4,8 +4,51 @@ import { fileURLToPath } from 'node:url'; import { join } from 'node:path'; const cwd = join(fileURLToPath(import.meta.url), '../..'); +const filepath = join(cwd, 'src/version.ts'); -const version = - process.argv.length === 3 ? process.argv[2] : JSON.parse(fs.readFileSync(join(cwd, 'package.json'), 'utf8')).version; +const version = getVersionFromArgv() ?? JSON.parse(fs.readFileSync(join(cwd, 'package.json'), 'utf8')).version; -fs.writeFileSync(join(cwd, 'src/version.ts'), `export const VERSION = '${version}';\n`); +try { + const existingVersion = /VERSION = '([^']+)';/.exec(fs.readFileSync(filepath, 'utf8')); + if (existingVersion !== null && !isNewerVersion(existingVersion[1], version)) { + log(`Skipping inlining. Next version is not newer than the existing one: ${existingVersion[1]}.`); + process.exit(0); + } +} catch (ex) { + // no-op +} + +fs.writeFileSync(filepath, `export const VERSION = '${version}';\n`); + +log(`Inlined ${version} version.`); + +function isNewerVersion(current, next) { + const [curMajor, curMinor, curPatch] = current.split('.').map(Number); + const [nextMajor, nextMinor, nextPatch] = next.split('.').map(Number); + + return ( + nextMajor > curMajor || + (curMajor === nextMajor && (nextMinor > curMinor || (curMinor <= nextMinor && nextPatch > curPatch))) + ); +} + +function log(message) { + if (process.argv.includes('--verbose') || process.env.CI) { + process.stdout.write(`${message}\n`); + } +} + +function getVersionFromArgv() { + if (process.argv.length < 3) return null; + + const r = /^([0-9]+\.){2}[0-9]+$/; + + for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (r.exec(value)) { + return value; + } + } + + return null; +}