# scripts/set-build-version.mjs · screen/aggregate-mail

[View on GitCafe](https://git.cafe/screen/aggregate-mail/blob/3fc4d30ec86fbc734552de25c1998bf9471858ac/scripts/set-build-version.mjs)

Repository: [screen/aggregate-mail](https://git.cafe/screen/aggregate-mail)

Visibility: public

Requested revision: 3fc4d30ec86fbc734552de25c1998bf9471858ac

Requested commit: 3fc4d30ec86fbc734552de25c1998bf9471858ac

Commit: 3fc4d30ec86fbc734552de25c1998bf9471858ac

Blob: 594da1734fa1e906274b25fcb33447db516478ce

Size: 1533 bytes

[Immutable source](https://git.cafe/screen/aggregate-mail/blob/3fc4d30ec86fbc734552de25c1998bf9471858ac/scripts/set-build-version.mjs?format=markdown)

```
import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";

export function ciVersion(version, env) {
  assert.match(version, /^\d+\.\d+\.\d+$/, "Commit a release version before building");
  if (env.GITHUB_REF?.startsWith("refs/tags/")) {
    assert.equal(env.GITHUB_REF, `refs/tags/v${version}`, "Release tag must match package.json");
    return version;
  }
  for (const key of ["GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT"])
    assert.match(env[key] ?? "", /^[1-9]\d*$/, `${key} must be a positive integer`);
  return `${version}-ci.${env.GITHUB_RUN_ID}.${env.GITHUB_RUN_ATTEMPT}`;
}

if (import.meta.main) {
  const pkg = JSON.parse(readFileSync("package.json", "utf8"));
  const lock = JSON.parse(readFileSync("package-lock.json", "utf8"));
  assert.equal(lock.version, pkg.version);
  assert.equal(lock.packages[""].version, pkg.version);
  const version = ciVersion(pkg.version, process.env);
  for (const key of ["GITHUB_RUN_NUMBER", "GITHUB_RUN_ATTEMPT"])
    assert.match(process.env[key] ?? "", /^[1-9]\d*$/, `${key} must be a positive integer`);
  pkg.version = lock.version = lock.packages[""].version = version;
  pkg.build.buildNumber = process.env.GITHUB_RUN_NUMBER;
  pkg.build.buildVersion = `${process.env.GITHUB_RUN_NUMBER}.${process.env.GITHUB_RUN_ATTEMPT}`;
  writeFileSync("package.json", `${JSON.stringify(pkg, null, 2)}\n`);
  writeFileSync("package-lock.json", `${JSON.stringify(lock, null, 2)}\n`);
  console.log(`Build version: ${version} (${pkg.build.buildVersion})`);
}

```
