release-cli.mjs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { execFileSync } from 'node:child_process';
  2. import { readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
  3. import { tmpdir } from 'node:os';
  4. import path from 'node:path';
  5. import { fileURLToPath } from 'node:url';
  6. import { parseArgs } from 'node:util';
  7. import { cliBuildVersion, versionFromTag } from './lib/cli-release.mjs';
  8. const versionFiles = ['package.json', 'packages/tui/package.json'];
  9. export function compareVersions(left, right) {
  10. versionFromTag(`v${left}`); versionFromTag(`v${right}`);
  11. const parse = version => {
  12. const index = version.indexOf('-');
  13. return { core: (index < 0 ? version : version.slice(0, index)).split('.').map(BigInt),
  14. pre: index < 0 ? undefined : version.slice(index + 1).split('.') };
  15. };
  16. const a = parse(left), b = parse(right);
  17. const compare = (x, y) => x === y ? 0 : x > y ? 1 : -1;
  18. for (let i = 0; i < 3; i++) if (a.core[i] !== b.core[i]) return compare(a.core[i], b.core[i]);
  19. if (!a.pre || !b.pre) return compare(a.pre ? 0 : 1, b.pre ? 0 : 1);
  20. for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
  21. const x = a.pre[i], y = b.pre[i];
  22. if (x === y) continue;
  23. if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
  24. const nx = /^[0-9]+$/.test(x), ny = /^[0-9]+$/.test(y);
  25. return nx && ny ? compare(BigInt(x), BigInt(y)) : nx !== ny ? (nx ? -1 : 1) : compare(x, y);
  26. }
  27. return 0;
  28. }
  29. function githubCli(root) {
  30. for (const command of ['gh-axi', 'gh']) {
  31. try {
  32. execFileSync(command, ['--help'], { cwd: root, stdio: 'ignore' });
  33. return command;
  34. } catch { /* Try the standard GitHub CLI when the wrapper is unavailable. */ }
  35. }
  36. throw new Error('Install and authenticate gh (or gh-axi) to create the version PR.');
  37. }
  38. function createVersionPullRequest({ root, branch, version, tag }) {
  39. const temporary = mkdtempSync(path.join(tmpdir(), 'mcode-version-pr-'));
  40. try {
  41. const body = path.join(temporary, 'body.md');
  42. writeFileSync(body, `Update the root and TUI source versions to ${version}.\n\nTag \`${tag}\` points to this version commit. The tag-triggered CLI release workflow builds and validates the npm installation archive. Merge this PR to carry the released source version back to main; do not move or recreate the release tag.\n`);
  43. execFileSync(githubCli(root), ['pr', 'create', '--base', 'main', '--head', branch,
  44. '--title', `chore: release MiniMax Code ${version}`, '--body-file', body], { cwd: root, stdio: 'inherit' });
  45. } finally { rmSync(temporary, { recursive: true, force: true }); }
  46. }
  47. export function releaseCli({ root, version, dryRun = false, openPullRequest = createVersionPullRequest }) {
  48. const tag = `v${version}`;
  49. versionFromTag(tag);
  50. const branch = `release/${tag}`;
  51. const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  52. if (git('status', '--porcelain')) throw new Error('Release requires a clean working tree, including untracked files.');
  53. const current = cliBuildVersion(root, null);
  54. if (compareVersions(version, current) <= 0) throw new Error(`Release version must be newer than ${current}.`);
  55. git('fetch', '--no-tags', 'origin', 'main');
  56. const base = git('rev-parse', 'HEAD');
  57. if (base !== git('rev-parse', 'refs/remotes/origin/main')) throw new Error('Start the release from the latest origin/main commit.');
  58. for (const ref of [`refs/tags/${tag}`, `refs/heads/${branch}`]) {
  59. let exists = false;
  60. try { git('show-ref', '--verify', '--quiet', ref); exists = true; } catch (error) { if (error.status !== 1) throw error; }
  61. if (exists) throw new Error(`Release ref already exists locally: ${ref}`);
  62. }
  63. if (git('ls-remote', 'origin', `refs/tags/${tag}`, `refs/heads/${branch}`)) throw new Error('Release tag or branch already exists on origin.');
  64. const plan = { current, version, tag, branch, base, files: versionFiles };
  65. console.log(JSON.stringify({ ...plan, dryRun }, null, 2));
  66. if (dryRun) return plan;
  67. // Fail before making local commits if the required PR client is unavailable.
  68. if (openPullRequest === createVersionPullRequest)
  69. execFileSync(githubCli(root), ['api', 'user', '--jq', '.login'], { cwd: root, stdio: 'ignore' });
  70. git('switch', '-c', branch);
  71. for (const name of versionFiles) {
  72. const file = path.join(root, name);
  73. const manifest = JSON.parse(readFileSync(file, 'utf8'));
  74. manifest.version = version;
  75. writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n');
  76. }
  77. git('add', '--', ...versionFiles);
  78. git('commit', '-m', `chore: release MiniMax Code ${version}`);
  79. if (git('status', '--porcelain')) throw new Error('Working tree changed during the version commit; inspect it before tagging.');
  80. if (git('diff', '--name-only', base, 'HEAD') !== [...versionFiles].sort().join('\n')) throw new Error('Version commit must change only the two package manifests.');
  81. cliBuildVersion(root, tag);
  82. git('tag', '-a', tag, '-m', `MiniMax Code ${version}`);
  83. // Push both refs or neither. Never force an existing tag or update main.
  84. git('push', '--atomic', '--set-upstream', 'origin', `refs/heads/${branch}:refs/heads/${branch}`, `refs/tags/${tag}:refs/tags/${tag}`);
  85. console.log(`Pushed ${branch} and ${tag}; CI will build and publish the archive after validation.`);
  86. openPullRequest({ root, branch, version, tag });
  87. return { ...plan, revision: git('rev-parse', 'HEAD') };
  88. }
  89. if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  90. const { values } = parseArgs({ options: { version: { type: 'string' }, 'dry-run': { type: 'boolean', default: false } } });
  91. if (!values.version) throw new Error('Usage: pnpm release:cli --version X.Y.Z [--dry-run]');
  92. releaseCli({ root: fileURLToPath(new URL('../', import.meta.url)), version: values.version, dryRun: values['dry-run'] });
  93. }