All files / scripts/package-release/commands version.js

0% Statements 0/99
0% Branches 0/52
0% Functions 0/9
0% Lines 0/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { readFileSync, writeFileSync } from 'fs';
import chalk from 'chalk';
import { resolvePackages, discoverPackages } from '../lib/workspace.js';
import { classifyTier, tierLabel, isTier1 } from '../lib/tier.js';
import { enforceBranchGuardrail } from '../lib/branch.js';
import { resolveBump, parseBumpSpecs, lookupBumpSpec } from '../lib/bump.js';
import { getLastTagForPackage, gitAdd, gitCommit } from '../lib/git.js';
import { generateChangelogNotes, prependChangelog } from '../lib/changelog.js';
import { getConfig } from '../lib/config.js';
import { runHooksForPackage, getHooksFor } from '../lib/post-version-hooks.js';
import { resolveWorkItem } from '../lib/release-config.js';
import { heading, info, success, error, setDryRun, isDryRun, dryRunAction } from '../lib/log.js';
 
export function registerVersionCommand(program) {
  program
    .command('version')
    .description('Bump package versions, write changelogs, and commit')
    .option('--packages <list>', 'Comma-separated list of package names or paths')
    .option('--all-tier-1', 'Target every Tier 1 (release-cycle-aligned) package')
    .requiredOption(
      '--bump <specs>',
      'Bump spec. Either a global keyword/version (e.g. release-cycle, 2.264.0-beta.1) or per-package list (e.g. design-system:minor,sds-components:patch)',
    )
    .option('--since <ref>', 'Override commit-range start for changelog generation')
    .option('--no-changelog', 'Skip CHANGELOG.md writes')
    .option('--no-commit', 'Skip git commit (leave changes staged)')
    .option('--amend', 'Amend HEAD instead of creating a new commit')
    .option(
      '--commit-message <message>',
      'Override the full commit message (replaces default headline + auto body)',
    )
    .option(
      '--commit-headline <text>',
      'Override only the commit headline (default: "chore(release): publish")',
    )
    .option('--no-commit-body', 'Skip auto-generated body listing per-package version changes')
    .option('--verify', 'Run pre-commit / commit-msg hooks (default: skip, matching Lerna)')
    .option('--no-hooks', 'Skip releasePostVersionHooks (advanced; e.g. for partial reruns)')
    .option(
      '--work-item <id>',
      'GUS work item (e.g. W-12345). Auto-prefixes the commit headline. Falls back to env / .release-config.',
    )
    .option('--allow-branch <pattern>', 'Additive branch pattern override')
    .option('--no-branch-check', 'Bypass branch guardrail entirely')
    .option('--dry-run', 'Print planned actions without executing')
    .option('--yes', 'Skip confirmation prompt')
    .action(async (opts) => {
      if (opts.dryRun) setDryRun(true);
      try {
        await runVersion(opts);
      } catch (e) {
        error(e.message);
        process.exit(1);
      }
    });
}
 
async function runVersion(opts) {
  if (opts.branchCheck !== false) {
    enforceBranchGuardrail('version', {
      noBranchCheck: false,
      allowBranch: opts.allowBranch,
    });
  }
 
  if (!opts.packages && !opts.allTier1) {
    error('Must provide --packages <list> or --all-tier-1');
    process.exit(1);
  }
 
  let packages;
  if (opts.allTier1) {
    packages = discoverPackages().filter((p) => isTier1(p));
    if (packages.length === 0) {
      error('No Tier 1 packages found. Check "release-cycle-aligned-packages" in root package.json.');
      process.exit(1);
    }
  } else {
    const packageNames = opts.packages
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);
    packages = resolvePackages(packageNames);
  }
 
  const bumpSpecs = parseBumpSpecs(opts.bump);
  const config = getConfig();
 
  heading('Version Plan');
 
  const plan = [];
  for (const pkg of packages) {
    const tier = classifyTier(pkg);
    const shortName = pkg.name.split('/').pop();
    const spec = lookupBumpSpec(bumpSpecs, pkg);
 
    if (!spec) {
      error(
        `No bump spec for "${pkg.name}". ` +
          `Either add a per-package entry (e.g. --bump ${shortName}:release-cycle) ` +
          `or pass a single global spec (e.g. --bump release-cycle).`,
      );
      process.exit(1);
    }
 
    const newVersion = resolveBump(pkg, spec);
    const lastTag = getLastTagForPackage(pkg.name);
 
    plan.push({
      pkg,
      tier,
      spec,
      currentVersion: pkg.version,
      newVersion,
      lastTag,
    });
  }
 
  for (const entry of plan) {
    info(
      `  ${chalk.bold(entry.pkg.name)} ${chalk.dim(`(${tierLabel(entry.tier)})`)}\n` +
        `    ${entry.currentVersion} → ${chalk.green(entry.newVersion)} ` +
        `${chalk.dim(`[${entry.spec}]`)}`,
    );
  }
 
  if (!opts.yes && !isDryRun() && !process.env.CI) {
    const readline = await import('readline');
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    const answer = await new Promise((resolve) => {
      rl.question('\nProceed? (y/N) ', resolve);
    });
    rl.close();
    if (answer.toLowerCase() !== 'y') {
      info('Aborted.');
      process.exit(0);
    }
  }
 
  heading('Applying changes');
 
  const changedFiles = [];
 
  for (const entry of plan) {
    info(`Bumping ${entry.pkg.name} to ${entry.newVersion}...`);
 
    const manifestPath = entry.pkg.manifestPath;
    if (dryRunAction(`write ${entry.newVersion} to ${manifestPath}`)) {
      changedFiles.push(manifestPath);
    } else {
      const original = readFileSync(manifestPath, 'utf8');
      const updated = updateVersionInManifest(original, entry.newVersion);
      writeFileSync(manifestPath, updated);
      changedFiles.push(manifestPath);
      success(`Updated ${entry.pkg.relativePath}/package.json`);
    }
 
    if (opts.changelog !== false) {
      const sinceRef = opts.since || entry.lastTag;
      const notes = generateChangelogNotes(entry.pkg.name, entry.newVersion, sinceRef, [
        entry.pkg.relativePath,
      ]);
      const changelogPath = prependChangelog(entry.pkg.path, notes);
      changedFiles.push(changelogPath);
      if (!isDryRun()) {
        success(`Updated ${entry.pkg.relativePath}/CHANGELOG.md`);
      }
    }
 
    if (opts.hooks !== false) {
      const hooks = getHooksFor(entry.pkg.name);
      if (hooks.length > 0) {
        info(`Running ${hooks.length} releasePostVersionHook(s) for ${entry.pkg.name}…`);
        const hookFiles = runHooksForPackage({
          pkg: entry.pkg,
          newVersion: entry.newVersion,
          previousVersion: entry.currentVersion,
        });
        for (const f of hookFiles) changedFiles.push(f);
      }
    }
  }
 
  const commitMessage = buildCommitMessage(plan, opts, config);
 
  if (opts.commit !== false) {
    gitAdd(changedFiles);
    const noVerify = opts.verify !== true;
    gitCommit(commitMessage, { amend: opts.amend || false, noVerify });
    if (!isDryRun()) {
      success(`Committed: "${commitMessage.split('\n')[0]}"`);
    }
  } else {
    info('Skipping commit (--no-commit). Changed files are staged.');
    gitAdd(changedFiles);
  }
 
  heading('Summary');
  for (const entry of plan) {
    success(`${entry.pkg.name}: ${entry.currentVersion} → ${entry.newVersion}`);
  }
}
 
function buildCommitMessage(plan, opts, config) {
  if (opts.commitMessage) return opts.commitMessage;
 
  const baseHeadline = opts.commitHeadline || config.commitHeadline || 'chore(release): publish';
 
  // Auto-prefix the headline with the GUS work item ID so the commit shows up
  // in the work item's activity stream (matches the team's PR-title convention).
  // Skips the prefix only if the user already supplied one in --commit-headline.
  const workItem =
    !opts.commitHeadline &&
    resolveWorkItem({
      explicit: opts.workItem,
      envVar: config.pr.workItemEnv,
      releaseConfigPath: config.pr.releaseConfigPath,
    });
 
  const headline = workItem ? `@${workItem} ${baseHeadline}` : baseHeadline;
 
  if (opts.commitBody === false) return headline;
 
  const bodyLines = plan.map((e) => ` - ${e.pkg.name}: ${e.currentVersion} ➡️ ${e.newVersion}`);
 
  return `${headline}\n\n${bodyLines.join('\n')}`;
}
 
function updateVersionInManifest(content, newVersion) {
  const versionRegex = /^(\s*)"version"(\s*):(\s*)"([^"]+)"/m;
  const match = content.match(versionRegex);
  if (!match) {
    throw new Error('Could not find "version" field in package.json');
  }
  return content.replace(versionRegex, `$1"version"$2:$3"${newVersion}"`);
}