Skip to content

Commit

Permalink
chore(cli): tweak version inlining
Browse files Browse the repository at this point in the history
  • Loading branch information
P0lip committed Sep 20, 2023
1 parent 68aacd6 commit 9e92f34
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -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",
Expand Down
49 changes: 46 additions & 3 deletions packages/cli/scripts/inline-version.mjs
Expand Up @@ -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;
}

0 comments on commit 9e92f34

Please sign in to comment.