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

0% Statements 0/77
0% Branches 0/36
0% Functions 0/8
0% Lines 0/73

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                                                                                                                                                                                                                                                                                                                                                                                       
import { execFileSync } from 'child_process';
import { readFileSync, writeFileSync, existsSync, mkdtempSync } from 'fs';
import path from 'path';
import os from 'os';
import chalk from 'chalk';
import { enforceBranchGuardrail } from '../lib/branch.js';
import { getCurrentBranch, gitPushBranch } from '../lib/git.js';
import { detectBumps } from '../lib/bumps.js';
import { getConfig, getRepoRoot } from '../lib/config.js';
import { resolveWorkItem } from '../lib/release-config.js';
import { heading, info, success, warn, error, setDryRun, isDryRun, dryRunAction } from '../lib/log.js';
 
export function registerPrCommand(program) {
  program
    .command('pr')
    .description('Push the current release branch and open a PR with templated title/body/labels')
    .option('--base <branch>', 'Base branch for the PR (default from config)')
    .option('--title <title>', 'Override the PR title')
    .option('--work-item <id>', 'GUS work item (e.g. W-12345). Falls back to env / .release-config.')
    .option('--labels <list>', 'Comma-separated label list (overrides config)')
    .option('--no-push', 'Skip pushing the branch (assume already pushed)')
    .option('--draft', 'Create PR as draft')
    .option('--allow-branch <pattern>', 'Additive branch pattern override')
    .option('--no-branch-check', 'Bypass branch guardrail entirely')
    .option('--dry-run', 'Print planned actions without executing')
    .action(async (opts) => {
      if (opts.dryRun) setDryRun(true);
      try {
        await runPr(opts);
      } catch (e) {
        error(e.message);
        process.exit(1);
      }
    });
}
 
function formatDate() {
  const d = new Date();
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  const yy = String(d.getFullYear()).slice(-2);
  return `${mm}-${dd}-${yy}`;
}
 
function loadPrTemplate(repoRoot, templatePath) {
  const fullPath = path.join(repoRoot, templatePath);
  if (!existsSync(fullPath)) return null;
  return readFileSync(fullPath, 'utf8');
}
 
function buildBody({ template, workItem, bumps, baseRef }) {
  const bumpList = bumps.map((b) => `- \`${b.name}\`: ${b.from} ➡️ ${b.to}`).join('\n');
 
  const workItemLink = workItem
    ? `[${workItem}](https://gus.my.salesforce.com/apex/ADM_WorkLocator?bugorworknumber=${workItem})`
    : '_(no work item provided)_';
 
  const summary = [
    'Bumps the following packages for Nexus publish:',
    '',
    bumpList || '_(no version changes detected vs base)_',
    '',
    'See `CHANGELOG.md` updates in each package for details.',
  ].join('\n');
 
  if (!template) {
    return [
      '### What ticket is this PR for?',
      workItemLink,
      '',
      '### What does this PR do?',
      summary,
      '',
      '### Background context and special instructions (if appropriate)',
      `Routine package version bump targeting \`${baseRef}\`. Auto-generated by \`yarn package-release pr\`.`,
      '',
    ].join('\n');
  }
 
  let body = template;
  body = body.replace(
    /\[W-xxxxxxxx\]\(https:\/\/gus\.my\.salesforce\.com\/apex\/ADM_WorkLocator\?bugorworknumber=W-xxxxxxxx\)/,
    workItemLink,
  );
  body = body.replace(/(### What does this PR do\?\n)<!--[^>]*-->\n?/, `$1${summary}\n`);
  return body;
}
 
async function runPr(opts) {
  if (opts.branchCheck !== false) {
    enforceBranchGuardrail('pr', {
      noBranchCheck: false,
      allowBranch: opts.allowBranch,
    });
  }
 
  const config = getConfig();
  const repoRoot = getRepoRoot();
  const branch = getCurrentBranch();
  const base = opts.base || config.pr.base;
 
  const workItem = resolveWorkItem({
    explicit: opts.workItem,
    envVar: config.pr.workItemEnv,
    releaseConfigPath: config.pr.releaseConfigPath,
  });
 
  if (!workItem) {
    warn(
      `No work item found.\n` +
        `  Tried: --work-item, $${config.pr.workItemEnv}, ${config.pr.releaseConfigPath}\n` +
        `  PR title will fall back to a generic prefix.`,
    );
  }
 
  const date = formatDate();
  const title =
    opts.title ||
    config.pr.titleFormat.replace('{workItem}', workItem || 'no-work-item').replace('{date}', date);
 
  const labels = opts.labels
    ? opts.labels
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
    : config.pr.labels;
 
  const bumps = detectBumps(`origin/${base}`);
  const template = loadPrTemplate(repoRoot, config.pr.templatePath);
  const body = buildBody({ template, workItem, bumps, baseRef: base });
 
  heading('PR Plan');
  info(`  Branch:    ${chalk.bold(branch)}`);
  info(`  Base:      ${chalk.dim(base)}`);
  info(`  Title:     ${chalk.bold(title)}`);
  info(`  Labels:    ${chalk.dim(labels.join(', '))}`);
  info(`  Work item: ${chalk.dim(workItem || '(none)')}`);
  info(`  Bumps:`);
  if (bumps.length === 0) {
    info(`    ${chalk.yellow('(none detected)')}`);
  } else {
    for (const b of bumps) {
      info(`    ${chalk.bold(b.name)}: ${b.from} ➡️ ${chalk.green(b.to)}`);
    }
  }
 
  if (opts.push !== false) {
    info('');
    if (dryRunAction(`git push -u origin ${branch}`)) {
      // dry-run only
    } else {
      gitPushBranch(branch, { setUpstream: true });
      success(`Pushed ${branch}`);
    }
  } else {
    info(chalk.dim('  (skipping push: --no-push)'));
  }
 
  if (isDryRun()) {
    heading('PR body (dry-run)');
    info(body);
    return;
  }
 
  const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'package-release-pr-'));
  const bodyFile = path.join(tmpDir, 'body.md');
  writeFileSync(bodyFile, body);
 
  const args = ['pr', 'create', '-t', title, '-a', '@me', '-B', base, '-F', bodyFile];
  for (const label of labels) {
    args.push('-l', label);
  }
  if (opts.draft) args.push('--draft');
 
  try {
    const out = execFileSync('gh', args, {
      cwd: repoRoot,
      encoding: 'utf8',
      stdio: ['inherit', 'pipe', 'pipe'],
    });
    success('PR created');
    info(out.trim());
  } catch (e) {
    error(`gh pr create failed: ${e.stderr || e.message}`);
    process.exit(1);
  }
}