summaryrefslogtreecommitdiff
path: root/scripts/bind_package_version.js
blob: 35c662d3cc73742b5e08ccbfa48984b2435392eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import fs from 'node:fs';
import path from 'node:path';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { execSync } from 'node:child_process';

// Assuming script is run from a package directory (e.g., packages/cli)
const packageDir = process.cwd();
const rootDir = path.join(packageDir, '..', '..'); // Go up two directories to find the repo root

function getBaseVersion() {
  // Read root package.json
  const rootPackageJsonPath = path.join(rootDir, 'package.json');
  const rootPackage = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf8'));
  return rootPackage.version;
}

function getDefaultSuffix() {
  // Get latest commit hash
  const commitHash = execSync('git rev-parse --short HEAD', {
    encoding: 'utf8',
  }).trim();

  // Append dev suffix with commit hash
  return `dev-${commitHash}.0`;
}

const argv = yargs(hideBin(process.argv))
  .option('suffix', {
    type: 'string',
    description: 'Set the package version suffix',
  })
  .parse();

const baseVersion = getBaseVersion();
const suffix = argv['suffix'] ?? getDefaultSuffix();
const newVersion = `${baseVersion}${suffix.length ? '-' : ''}${suffix}`;
console.log(`Setting package version to: ${newVersion}`);

const packageJsonPath = path.join(packageDir, 'package.json');

if (fs.existsSync(packageJsonPath)) {
  console.log(`Updating version for ${packageJsonPath}`);
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  packageJson.version = newVersion;
  fs.writeFileSync(
    packageJsonPath,
    JSON.stringify(packageJson, null, 2) + '\n',
    'utf8',
  );
} else {
  console.error(
    `Error: package.json not found in the current directory: ${packageJsonPath}`,
  );
  process.exit(1);
}

console.log('Done.');