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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 | #!/usr/bin/env node
/**
* Workstream Branch Merge Wizard
*
* Security Note: This script uses a hybrid approach for command execution:
* - execSync for safe commands (no user input, simple operations) with absolute paths
* - spawnSync for commands with user input to prevent command injection
* - Absolute paths are used for git and gh commands to prevent PATH manipulation attacks
* All user inputs are sanitized and validated. The safeExecSync wrapper automatically
* chooses the appropriate execution method based on command safety and uses absolute
* paths to prevent PATH-based security vulnerabilities.
*/
import { execSync, spawnSync } from 'child_process';
import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import { program } from 'commander';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import os from 'os';
// Handle both Node.js execution and Jest testing environments
let __filename, __dirname;
if (typeof import.meta !== 'undefined' && import.meta.url) {
__filename = fileURLToPath(import.meta.url);
__dirname = path.dirname(__filename);
} else {
// Fallback for Jest/testing environment
__filename = process.argv[1] || '';
__dirname = path.dirname(__filename);
}
// Configuration
const CONFIG = {
defaultBranchPrefix: 'merge',
// Eligible branches for merging
eligibleBranches: ['develop', 'main', 'main-patch', 'site-docs'],
// Regex pattern for develop-2xx-patch branches (even numbers 200-298)
developPatchPattern: /^develop-(\d{3})-patch$/,
developPatchRange: { min: 200, max: 298 },
prTemplate: {
title: '@{workItem} chore(merge): {source} ➡️ {target}',
body: `## Automated Workstream Branch Merge
This PR was created automatically by the Release Branch Merge Wizard.
**Work Item:** [{workItem}](https://gus.my.salesforce.com/apex/ADM_WorkLocator?bugorworknumber={workItem})
**Source Branch:** [{source}](https://github.com/salesforce-experience-platform-emu/salesforce-design-system/tree/{source})
**Target Branch:** [{target}](https://github.com/salesforce-experience-platform-emu/salesforce-design-system/tree/{target})
**Merge Branch:** [{mergeBranch}](https://github.com/salesforce-experience-platform-emu/salesforce-design-system/tree/{mergeBranch})
### Changes
- Automated merge of {source} into {target}
- Created for testing and review
### Testing
Please review the changes and run tests before merging.
`,
},
prLabels: ['chore', 'workstream-branch-merge'],
// State file configuration
stateFile: path.join(os.tmpdir(), 'workstream-merge-wizard-state.json'),
};
class BranchMergeWizard {
constructor(options = {}) {
this.repoPath = process.cwd();
this.branches = [];
this.selectedBranches = {};
this.workItemNumber = null;
this.resumeMode = options.resume || false;
this.verbose = options.verbose || false;
this.originalBranch = null;
}
async init() {
if (this.resumeMode) {
console.log(chalk.blue.bold('\n🔄 Branch Merge Wizard (Resume Mode)\n'));
console.log(chalk.gray('Resuming from saved state after merge conflict resolution.\n'));
} else {
console.log(chalk.blue.bold('\n🚀 Branch Merge Wizard\n'));
console.log(chalk.gray('This tool will help you merge workstream branches safely.\n'));
}
// Check if we're in a git repository
if (!(await this.isGitRepo())) {
console.error(chalk.red('❌ Not in a git repository. Please run this from your project root.'));
process.exit(1);
}
// Record the original branch so we can restore it on exit
try {
this.originalBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
if (this.verbose && this.originalBranch) {
console.log(chalk.gray(`📌 Original branch: ${this.originalBranch}`));
}
} catch {
// ignore
}
// Capture the initially checked out branch so we can restore it in cleanup
try {
this.initialBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
} catch {
this.initialBranch = '';
}
// Check if GitHub CLI is installed
if (!(await this.isGhCliInstalled())) {
console.error(chalk.red('❌ GitHub CLI (gh) is not installed. Please install it first.'));
console.log(chalk.yellow('Install with: brew install gh (macOS) or visit https://cli.github.com/'));
process.exit(1);
}
// Check if user is authenticated with GitHub CLI
if (!(await this.isGhAuthenticated())) {
console.error(chalk.red('❌ Not authenticated with GitHub CLI. Please run: gh auth login'));
process.exit(1);
}
}
async isGitRepo() {
try {
execSync('git rev-parse --git-dir', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
async isGhCliInstalled() {
try {
execSync('gh --version', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
async isGhAuthenticated() {
try {
execSync('gh auth status', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
async fetchBranches() {
const spinner = ora('Fetching branches...').start();
try {
// Fetch latest from remote
execSync('git fetch --all', { stdio: 'ignore' });
// Get all branches (local and remote)
const localBranches = execSync('git branch --format="%(refname:short)"', { encoding: 'utf8' })
.trim()
.split('\n')
.filter((b) => b && !b.includes('HEAD'));
const remoteBranches = execSync('git branch -r --format="%(refname:short)"', { encoding: 'utf8' })
.trim()
.split('\n')
.filter((b) => b && !b.includes('HEAD') && !b.includes('origin/HEAD'))
.map((b) => b.replace('origin/', ''));
// Combine and deduplicate
const allBranches = [...new Set([...localBranches, ...remoteBranches])];
// Filter to only eligible branches
const eligibleBranches = this.filterEligibleBranches(allBranches);
// Sort branches with special handling for develop patch branches
this.branches = eligibleBranches.sort((a, b) => {
// Check if both are develop patch branches
const aMatch = a.match(CONFIG.developPatchPattern);
const bMatch = b.match(CONFIG.developPatchPattern);
if (aMatch && bMatch) {
// Sort develop patch branches by number (descending - highest first)
const aNumber = parseInt(aMatch[1], 10);
const bNumber = parseInt(bMatch[1], 10);
return bNumber - aNumber;
} else if (aMatch) {
// Develop patch branches come after regular branches
return 1;
} else if (bMatch) {
// Regular branches come before develop patch branches
return -1;
} else {
// Regular branches sorted alphabetically
return a.localeCompare(b);
}
});
spinner.succeed(`Found ${this.branches.length} eligible branches`);
} catch (error) {
spinner.fail('Failed to fetch branches');
throw error;
}
}
filterEligibleBranches(allBranches) {
// Add develop-2xx-patch branches where 2xx is any even number between 200 and 298
const developPatchBranches = allBranches.filter((branch) => {
const match = branch.match(CONFIG.developPatchPattern);
if (match) {
const number = parseInt(match[1], 10);
// Check if it's an even number within the specified range
return (
number >= CONFIG.developPatchRange.min && number <= CONFIG.developPatchRange.max && number % 2 === 0
);
}
return false;
});
// Sort develop patch branches by number (descending) and take only the last 2 (highest numbers)
const sortedDevelopPatchBranches = developPatchBranches
.sort((a, b) => {
const aNumber = parseInt(a.match(CONFIG.developPatchPattern)[1], 10);
const bNumber = parseInt(b.match(CONFIG.developPatchPattern)[1], 10);
return bNumber - aNumber; // Descending order (highest first)
})
.slice(0, 2); // Take only the first 2 (highest numbers)
// Filter all branches to only include eligible ones
return allBranches.filter(
(branch) => CONFIG.eligibleBranches.includes(branch) || sortedDevelopPatchBranches.includes(branch),
);
}
async updateBranchesFromRemote(sourceBranch, targetBranch) {
const spinner = ora('Updating branches from remote...').start();
try {
// Get current branch to return to later
const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
// Get list of local branches
const localBranches = execSync('git branch --format="%(refname:short)"', { encoding: 'utf8' })
.trim()
.split('\n')
.filter((b) => b && !b.includes('HEAD'));
// Update source branch
if (this.branches.includes(sourceBranch)) {
try {
if (localBranches.includes(sourceBranch)) {
// Branch exists locally, checkout and pull
this.safeExecSync(`git checkout ${sourceBranch}`, { stdio: 'ignore' });
this.safeExecSync(`git pull origin ${sourceBranch}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Updated local source branch '${sourceBranch}'`));
} else {
// Branch doesn't exist locally, create it from remote
this.safeExecSync(`git checkout -b ${sourceBranch} origin/${sourceBranch}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Created local source branch '${sourceBranch}' from remote`));
}
} catch (error) {
console.log(chalk.yellow(`⚠️ Could not update source branch '${sourceBranch}': ${error.message}`));
// Check if remote branch exists
try {
execSync(`git ls-remote --heads origin ${sourceBranch}`, { stdio: 'ignore' });
console.log(chalk.gray(` Remote branch '${sourceBranch}' exists but couldn't be updated`));
console.log(chalk.gray(` This might be due to uncommitted changes or other Git state issues`));
} catch {
console.log(chalk.gray(` Remote branch '${sourceBranch}' may not exist`));
}
}
}
// Update target branch
if (this.branches.includes(targetBranch)) {
try {
if (localBranches.includes(targetBranch)) {
// Branch exists locally, checkout and pull
this.safeExecSync(`git checkout ${targetBranch}`, { stdio: 'ignore' });
this.safeExecSync(`git pull origin ${targetBranch}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Updated local target branch '${targetBranch}'`));
} else {
// Branch doesn't exist locally, create it from remote
this.safeExecSync(`git checkout -b ${targetBranch} origin/${targetBranch}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Created local target branch '${targetBranch}' from remote`));
}
} catch (error) {
console.log(chalk.yellow(`⚠️ Could not update target branch '${targetBranch}': ${error.message}`));
// Check if remote branch exists
try {
execSync(`git ls-remote --heads origin ${targetBranch}`, { stdio: 'ignore' });
console.log(chalk.gray(` Remote branch '${targetBranch}' exists but couldn't be updated`));
console.log(chalk.gray(` This might be due to uncommitted changes or other Git state issues`));
} catch {
console.log(chalk.gray(` Remote branch '${targetBranch}' may not exist`));
}
}
}
// Return to original branch
if (currentBranch) {
execSync(`git checkout ${currentBranch}`, { stdio: 'ignore' });
}
spinner.succeed('Branches updated from remote');
} catch (error) {
spinner.fail('Failed to update branches from remote');
console.log(chalk.yellow(`⚠️ Warning: Could not update all branches. Proceeding with current state.`));
console.log(chalk.gray(' The merge will use the current local state of the branches.'));
}
}
async cleanupExistingMergeBranch(mergeBranchName) {
const spinner = ora(`Checking for existing merge branch '${mergeBranchName}'...`).start();
try {
// Get current branch to return to later
const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
// Check if branch exists locally
const localBranches = execSync('git branch --format="%(refname:short)"', { encoding: 'utf8' })
.trim()
.split('\n')
.filter((b) => b && !b.includes('HEAD'));
const branchExistsLocally = localBranches.includes(mergeBranchName);
// Check if branch exists on remote
let branchExistsOnRemote = false;
try {
execSync(`git ls-remote --heads origin ${mergeBranchName}`, { stdio: 'ignore' });
branchExistsOnRemote = true;
} catch {
// Branch doesn't exist on remote
}
if (branchExistsLocally || branchExistsOnRemote) {
spinner.text = `Cleaning up existing merge branch '${mergeBranchName}'...`;
// Switch away from the branch if we're currently on it
if (currentBranch === mergeBranchName) {
execSync(`git checkout ${this.selectedBranches.targetBranch}`, { stdio: 'ignore' });
}
// Delete local branch if it exists
if (branchExistsLocally) {
try {
execSync(`git branch -D ${mergeBranchName}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Deleted local branch '${mergeBranchName}'`));
} catch (error) {
console.log(
chalk.yellow(`⚠️ Could not delete local branch '${mergeBranchName}': ${error.message}`),
);
}
}
// Delete remote branch if it exists
if (branchExistsOnRemote) {
try {
execSync(`git push origin --delete ${mergeBranchName}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Deleted remote branch '${mergeBranchName}'`));
} catch (error) {
console.log(
chalk.yellow(`⚠️ Could not delete remote branch '${mergeBranchName}': ${error.message}`),
);
}
}
spinner.succeed(`Cleaned up existing merge branch '${mergeBranchName}'`);
} else {
spinner.succeed(`No existing merge branch '${mergeBranchName}' found`);
}
// Return to original branch
if (currentBranch && currentBranch !== mergeBranchName) {
execSync(`git checkout ${currentBranch}`, { stdio: 'ignore' });
}
} catch (error) {
spinner.fail(`Failed to cleanup merge branch '${mergeBranchName}'`);
console.log(chalk.yellow(`⚠️ Warning: Could not cleanup existing branch. Proceeding anyway.`));
}
}
// Sanitize input to prevent command injection
sanitizeInput(input) {
// Remove any characters that could be used for command injection
return input.replace(/[;&|`$(){}[\]\\]/g, '');
}
// Validate branch name format
validateBranchName(branchName) {
// Git branch names should only contain alphanumeric, hyphens, underscores, and forward slashes
return /^[a-zA-Z0-9._/-]+$/.test(branchName);
}
// Find absolute path for a command to avoid PATH manipulation attacks
findCommandPath(commandName) {
try {
// Use 'which' command to find the absolute path
const result = execSync(`which ${commandName}`, { encoding: 'utf8', stdio: 'pipe' });
return result.trim();
} catch (error) {
// Fallback to the command name if which fails
console.warn(`Warning: Could not find absolute path for ${commandName}, using command name`);
return commandName;
}
}
// Parse command string into command and arguments array
parseCommand(command) {
// Simple command parsing - split by spaces but handle quoted arguments
const parts = [];
let current = '';
let inQuotes = false;
let quoteChar = '';
for (let i = 0; i < command.length; i++) {
const char = command[i];
if ((char === '"' || char === "'") && !inQuotes) {
inQuotes = true;
quoteChar = char;
} else if (char === quoteChar && inQuotes) {
inQuotes = false;
quoteChar = '';
} else if (char === ' ' && !inQuotes) {
if (current.trim()) {
parts.push(current.trim());
current = '';
}
} else {
current += char;
}
}
if (current.trim()) {
parts.push(current.trim());
}
return parts;
}
// Safe wrapper that uses spawnSync for commands with user input, execSync for safe commands
safeExecSync(command, options = {}) {
// Validate that the command doesn't contain dangerous shell operators or destructive commands
// Allow parentheses, brackets, and braces as they are common in quoted markdown bodies
const dangerousPatterns = [/[;&|`]/, /\brm\s+-rf\b/, /\bsudo\b/, /\bchmod\b/, /\bchown\b/];
for (const pattern of dangerousPatterns) {
if (pattern.test(command)) {
throw new Error(`Potentially dangerous command detected: ${command}`);
}
}
// Get absolute paths for commands to avoid PATH manipulation attacks
const gitPath = this.findCommandPath('git');
const ghPath = this.findCommandPath('gh');
// Commands that are safe to use with execSync (no user input, simple operations)
// Using absolute paths to prevent PATH manipulation attacks
const safeCommands = [
`${gitPath} rev-parse --git-dir`,
`${ghPath} --version`,
`${ghPath} auth status`,
`${gitPath} fetch --all`,
`${gitPath} branch --show-current`,
`${gitPath} branch --format="%(refname:short)"`,
`${gitPath} branch -r --format="%(refname:short)"`,
];
// Check if this is a safe command (exact match or starts with safe command)
const isSafeCommand = safeCommands.some(
(safeCmd) => command === safeCmd || command.startsWith(safeCmd + ' '),
);
if (isSafeCommand) {
// Use execSync for safe commands with absolute paths
return execSync(command, options);
} else {
// Use spawnSync for commands that might contain user input
const parts = this.parseCommand(command);
const [cmd, ...args] = parts;
// For spawnSync, also use absolute paths when possible
let absoluteCmd = cmd;
if (cmd === 'git') {
absoluteCmd = gitPath;
} else if (cmd === 'gh') {
absoluteCmd = ghPath;
}
const result = spawnSync(absoluteCmd, args, options);
// Handle spawnSync result format to match execSync behavior
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const error = new Error(`Command failed with exit code ${result.status}`);
error.status = result.status;
error.signal = result.signal;
throw error;
}
// Return stdout as string if encoding is specified, otherwise return the result object
if (options.encoding) {
return result.stdout.toString(options.encoding);
}
return result.stdout;
}
}
// State management methods for resume functionality
saveState() {
const state = {
workItemNumber: this.workItemNumber,
selectedBranches: this.selectedBranches,
repoPath: this.repoPath,
timestamp: new Date().toISOString(),
};
try {
fs.writeFileSync(CONFIG.stateFile, JSON.stringify(state, null, 2));
if (this.verbose) {
console.log(chalk.gray(`💾 State saved to: ${CONFIG.stateFile}`));
}
} catch (error) {
console.error(chalk.red('❌ Failed to save state:'), error.message);
}
}
loadState() {
try {
if (!fs.existsSync(CONFIG.stateFile)) {
return null;
}
const stateData = fs.readFileSync(CONFIG.stateFile, 'utf8');
const state = JSON.parse(stateData);
// Validate state has required properties
if (!state.workItemNumber || !state.selectedBranches) {
console.log(chalk.yellow('⚠️ Invalid state file found. Starting fresh.'));
this.clearState();
return null;
}
if (this.verbose) {
console.log(chalk.gray(`📂 State loaded from: ${CONFIG.stateFile}`));
console.log(chalk.gray(` Saved at: ${state.timestamp}`));
}
return state;
} catch (error) {
console.error(chalk.red('❌ Failed to load state:'), error.message);
this.clearState();
return null;
}
}
clearState() {
try {
if (fs.existsSync(CONFIG.stateFile)) {
fs.unlinkSync(CONFIG.stateFile);
if (this.verbose) {
console.log(chalk.gray('🗑️ State file cleared'));
}
}
} catch (error) {
console.error(chalk.red('❌ Failed to clear state:'), error.message);
}
}
hasValidState() {
return fs.existsSync(CONFIG.stateFile);
}
restoreFromState(state) {
this.workItemNumber = state.workItemNumber;
this.selectedBranches = state.selectedBranches;
this.repoPath = state.repoPath;
console.log(chalk.green('✅ State restored successfully!'));
console.log(chalk.cyan(` Work Item: ${this.workItemNumber}`));
console.log(chalk.cyan(` Source Branch: ${this.selectedBranches.sourceBranch}`));
console.log(chalk.cyan(` Target Branch: ${this.selectedBranches.targetBranch}`));
console.log(chalk.cyan(` Merge Branch: ${this.selectedBranches.mergeBranchName}`));
}
async checkMergeStatus() {
try {
// Check if we're currently on the merge branch
const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();
if (currentBranch !== this.selectedBranches.mergeBranchName) {
console.log(
chalk.yellow(`⚠️ Not on expected merge branch '${this.selectedBranches.mergeBranchName}'`),
);
console.log(chalk.gray(` Current branch: ${currentBranch}`));
const { switchBranch } = await inquirer.prompt([
{
type: 'confirm',
name: 'switchBranch',
message: `Switch to merge branch '${this.selectedBranches.mergeBranchName}'?`,
default: true,
},
]);
if (switchBranch) {
execSync(`git checkout ${this.selectedBranches.mergeBranchName}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Switched to '${this.selectedBranches.mergeBranchName}'`));
} else {
console.log(chalk.red('❌ Cannot continue without being on the merge branch'));
return false;
}
}
// Check if there are any unresolved conflicts
try {
execSync('git diff --check', { stdio: 'ignore' });
} catch {
console.log(chalk.red('❌ Merge conflicts still exist. Please resolve them first.'));
return false;
}
// Check if there are uncommitted changes
const status = execSync('git status --porcelain', { encoding: 'utf8' }).trim();
if (status) {
console.log(chalk.yellow('⚠️ There are uncommitted changes:'));
console.log(chalk.gray(status));
const { commitChanges } = await inquirer.prompt([
{
type: 'confirm',
name: 'commitChanges',
message: 'Commit these changes to complete the merge?',
default: true,
},
]);
if (commitChanges) {
execSync('git add .', { stdio: 'ignore' });
execSync(
`git commit -m "Resolve merge conflicts for ${this.selectedBranches.sourceBranch} into ${this.selectedBranches.targetBranch}"`,
{ stdio: 'ignore' },
);
console.log(chalk.green('✓ Changes committed'));
} else {
console.log(chalk.red('❌ Cannot continue without committing changes'));
return false;
}
}
return true;
} catch (error) {
console.error(chalk.red('❌ Error checking merge status:'), error.message);
return false;
}
}
async resumeMergeProcess() {
const { mergeBranchName } = this.selectedBranches;
console.log(chalk.blue('\n🔍 Checking merge status...'));
if (!(await this.checkMergeStatus())) {
console.log(chalk.red('❌ Cannot resume: merge conflicts not resolved or changes not committed'));
return false;
}
console.log(chalk.green('✓ Merge conflicts resolved and changes committed'));
// Push the merge branch if it hasn't been pushed yet
try {
// Check if the branch exists on remote
execSync(`git ls-remote --heads origin ${mergeBranchName}`, { stdio: 'ignore' });
console.log(chalk.green(`✓ Merge branch '${mergeBranchName}' already exists on remote`));
} catch {
// Branch doesn't exist on remote, push it
const spinner = ora(`Pushing '${mergeBranchName}' to remote`).start();
try {
this.safeExecSync(`git push origin ${mergeBranchName}`, { stdio: 'ignore' });
spinner.succeed(`Pushed '${mergeBranchName}' to remote`);
} catch (error) {
spinner.fail('Failed to push merge branch');
console.error(chalk.red('Error:'), error.message);
return false;
}
}
return true;
}
// Prompt flow used when --resume is passed but there is no saved state
async promptForResumeData() {
// Make sure we have the latest branch lists
await this.fetchBranches();
// Get local branches and suggest merge/* branches
const localBranches = execSync('git branch --format="%(refname:short)"', { encoding: 'utf8' })
.trim()
.split('\n')
.filter((b) => b && !b.includes('HEAD'));
const mergePrefix = `${CONFIG.defaultBranchPrefix}/`;
const mergeCandidates = localBranches.filter((b) => b.startsWith(mergePrefix));
const questions = [
{
type: 'list',
name: 'mergeBranchName',
message: 'Select the existing merge branch to resume:',
choices: mergeCandidates.length > 0 ? mergeCandidates : localBranches,
pageSize: 15,
when: () => localBranches.length > 0,
},
{
type: 'input',
name: 'mergeBranchName',
message: 'Enter the existing merge branch name to resume:',
when: () => localBranches.length === 0,
validate: (input) => {
const name = input.trim();
if (!name) return 'Merge branch name is required';
if (!this.validateBranchName(name)) {
return 'Branch name contains invalid characters.';
}
return true;
},
filter: (input) => this.sanitizeInput(input.trim()),
},
];
const resumeAnswers = await inquirer.prompt(questions);
const mergeBranchName = this.sanitizeInput(resumeAnswers.mergeBranchName);
// Try to infer source and target from naming convention: merge/{source}-into-{target}
let inferredSource = null;
let inferredTarget = null;
const mergeNamePattern = new RegExp(`^${mergePrefix.replace('/', '\\/')}(.*)-into-(.*)$`);
const match = mergeBranchName.match(mergeNamePattern);
if (match && match[1] && match[2]) {
inferredSource = match[1];
inferredTarget = match[2];
}
// If we cannot infer, prompt the user
let sourceBranch = inferredSource;
let targetBranch = inferredTarget;
if (!inferredSource || !inferredTarget) {
const pickAnswers = await inquirer.prompt([
{
type: 'list',
name: 'sourceBranch',
message: 'Select the source branch (branch merged FROM):',
choices: this.branches,
pageSize: 15,
validate: (input) => (input ? true : 'Please select a source branch'),
},
{
type: 'list',
name: 'targetBranch',
message: 'Select the target branch (branch merged INTO):',
choices: (answers) => this.branches.filter((b) => b !== answers.sourceBranch),
pageSize: 15,
validate: (input) => (input ? true : 'Please select a target branch'),
},
]);
sourceBranch = pickAnswers.sourceBranch;
targetBranch = pickAnswers.targetBranch;
}
// Gather work item and PR preference
const moreAnswers = await inquirer.prompt([
{
type: 'input',
name: 'workItemNumber',
message: 'Enter the work item number (e.g., W-19569318):',
validate: (input) => {
if (!input.trim()) return 'Work item number is required';
const workItemPattern = /^W-\d{5,10}$/;
if (!workItemPattern.test(input.trim())) {
return 'Work item number must match pattern W-XXXXX (5-10 digits after W-).';
}
return true;
},
filter: (input) => input.trim(),
},
{
type: 'confirm',
name: 'createPr',
message: 'Create a pull request now that conflicts are resolved?',
default: true,
},
]);
this.workItemNumber = this.sanitizeInput(moreAnswers.workItemNumber);
this.selectedBranches = {
sourceBranch,
targetBranch,
mergeBranchName,
createPr: moreAnswers.createPr,
};
console.log(chalk.green('✓ Resume data captured'));
console.log(chalk.cyan(` Work Item: ${this.workItemNumber}`));
console.log(chalk.cyan(` Merge Branch: ${mergeBranchName}`));
console.log(chalk.cyan(` Source Branch: ${sourceBranch}`));
console.log(chalk.cyan(` Target Branch: ${targetBranch}`));
}
async promptForWorkItem() {
const questions = [
{
type: 'input',
name: 'workItemNumber',
message: 'Enter the work item number (e.g., W-19569318):',
validate: (input) => {
if (!input.trim()) return 'Work item number is required';
const workItemPattern = /^W-\d{5,10}$/;
if (!workItemPattern.test(input.trim())) {
return 'Work item number must match pattern W-XXXXX (5-10 digits after W-)';
}
return true;
},
filter: (input) => input.trim(),
},
];
const result = await inquirer.prompt(questions);
this.workItemNumber = this.sanitizeInput(result.workItemNumber);
console.log(chalk.green(`✓ Work item: ${this.workItemNumber}`));
}
async promptForBranches() {
const questions = [
{
type: 'list',
name: 'sourceBranch',
message: 'Select the source branch (branch to merge FROM):',
choices: this.branches,
pageSize: 15,
validate: (input) => {
if (!input) return 'Please select a source branch';
return true;
},
},
{
type: 'list',
name: 'targetBranch',
message: 'Select the target branch (branch to merge INTO):',
choices: (answers) => {
return this.branches.filter((branch) => branch !== answers.sourceBranch);
},
pageSize: 15,
validate: (input) => {
if (!input) return 'Please select a target branch';
return true;
},
},
{
type: 'input',
name: 'mergeBranchName',
message: 'Enter name for the merge branch:',
default: (answers) =>
`${CONFIG.defaultBranchPrefix}/${answers.sourceBranch}-into-${answers.targetBranch}`,
validate: (input) => {
if (!input.trim()) return 'Merge branch name is required';
if (this.branches.includes(input)) return 'Branch already exists';
if (!this.validateBranchName(input.trim())) {
return 'Branch name contains invalid characters. Only alphanumeric, hyphens, underscores, and forward slashes are allowed.';
}
return true;
},
},
{
type: 'confirm',
name: 'createPr',
message: 'Create a pull request after merge?',
default: true,
},
];
const result = await inquirer.prompt(questions);
this.selectedBranches = {
...result,
mergeBranchName: this.sanitizeInput(result.mergeBranchName),
};
}
async confirmMerge() {
console.log(chalk.yellow('\n📋 Merge Summary:'));
console.log(chalk.gray('─'.repeat(50)));
console.log(chalk.cyan(`Work Item: ${this.workItemNumber}`));
console.log(chalk.cyan(`Source Branch: ${this.selectedBranches.sourceBranch}`));
console.log(chalk.cyan(`Target Branch: ${this.selectedBranches.targetBranch}`));
console.log(chalk.cyan(`Merge Branch: ${this.selectedBranches.mergeBranchName}`));
console.log(chalk.cyan(`Create PR: ${this.selectedBranches.createPr ? 'Yes' : 'No'}`));
console.log(chalk.gray('─'.repeat(50)));
const { confirmed } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirmed',
message: 'Proceed with the merge?',
default: false,
},
]);
return confirmed;
}
async performMerge() {
const { sourceBranch, targetBranch, mergeBranchName } = this.selectedBranches;
try {
// Step 1: Ensure both branches are up-to-date with their remotes
await this.updateBranchesFromRemote(sourceBranch, targetBranch);
// Step 2: Clean up existing merge branch if it exists
await this.cleanupExistingMergeBranch(mergeBranchName);
// Step 3: Create and checkout merge branch from target
const spinner1 = ora(`Creating merge branch '${mergeBranchName}' from '${targetBranch}'`).start();
this.safeExecSync(`git checkout -b ${mergeBranchName} ${targetBranch}`, { stdio: 'ignore' });
spinner1.succeed(`Created merge branch '${mergeBranchName}'`);
// Step 4: Merge source branch
const spinner2 = ora(`Merging '${sourceBranch}' into '${mergeBranchName}'`).start();
try {
this.safeExecSync(
`git merge ${sourceBranch} --no-ff -m "Merge ${sourceBranch} into ${targetBranch}"`,
{
stdio: 'ignore',
},
);
spinner2.succeed(`Successfully merged '${sourceBranch}'`);
} catch (mergeError) {
spinner2.fail(`Merge conflict detected`);
// Save state before exiting so user can resume
this.saveState();
console.log(chalk.yellow('\n⚠️ Merge conflicts detected. Please resolve them manually:'));
console.log(chalk.gray('1. Resolve conflicts in your editor'));
console.log(chalk.gray('2. Run: git add .'));
console.log(chalk.gray('3. Run: git commit'));
console.log(chalk.gray('4. Run: git push origin ' + mergeBranchName));
console.log(chalk.yellow('\n🔄 After resolving conflicts, resume with:'));
console.log(chalk.cyan(' node scripts/workstream-branch-merge-wizard.js --resume'));
console.log(chalk.gray('\n This will continue from where you left off and create the PR.'));
return false;
}
// Step 5: Push merge branch
const spinner3 = ora(`Pushing '${mergeBranchName}' to remote`).start();
this.safeExecSync(`git push origin ${mergeBranchName}`, { stdio: 'ignore' });
spinner3.succeed(`Pushed '${mergeBranchName}' to remote`);
return true;
} catch (error) {
console.error(chalk.red('❌ Error during merge:'), error.message);
return false;
}
}
async createPullRequest() {
if (!this.selectedBranches.createPr) return;
const { sourceBranch, targetBranch, mergeBranchName } = this.selectedBranches;
const prTitle = CONFIG.prTemplate.title
.replaceAll('{workItem}', this.workItemNumber)
.replaceAll('{source}', sourceBranch)
.replaceAll('{target}', targetBranch);
const prBody = CONFIG.prTemplate.body
.replaceAll('{workItem}', this.workItemNumber)
.replaceAll('{source}', sourceBranch)
.replaceAll('{target}', targetBranch)
.replaceAll('{mergeBranch}', mergeBranchName);
const prLabels = CONFIG.prLabels.join(',');
const spinner = ora('Creating pull request...').start();
try {
const prUrl = this.safeExecSync(
`gh pr create --title "${prTitle}" --body "${prBody}" --label "${prLabels}" --base ${targetBranch} --head ${mergeBranchName}`,
{ encoding: 'utf8' },
).trim();
spinner.succeed('Pull request created successfully!');
console.log(chalk.green(`🔗 PR URL: ${prUrl}`));
return prUrl;
} catch (error) {
spinner.fail('Failed to create pull request');
console.error(chalk.red('Error:'), error.message);
return null;
}
}
async cleanup() {
// Return to the originally checked out branch if we captured it
try {
if (this.initialBranch) {
execSync(`git checkout ${this.initialBranch}`, { stdio: 'ignore' });
}
} catch {
// If we cannot restore, stay on current branch
}
}
async run() {
try {
await this.init();
if (this.resumeMode) {
// Resume mode
if (this.hasValidState()) {
// Load existing state and continue
const state = this.loadState();
if (!state) {
console.log(chalk.red('❌ Failed to load saved state. Cannot resume.'));
process.exit(1);
}
this.restoreFromState(state);
} else {
// No saved state: prompt user for required data to resume
console.log(chalk.yellow('ℹ️ No saved state found. Prompting for resume details...'));
await this.promptForResumeData();
}
// Check if merge was completed and continue with PR creation
const resumeSuccess = await this.resumeMergeProcess();
if (resumeSuccess) {
const prUrl = await this.createPullRequest();
if (prUrl) {
console.log(chalk.green.bold('\n✅ Branch merge and PR creation completed successfully!'));
// Clear the state file since we're done
this.clearState();
} else {
console.log(chalk.red.bold('\n❌ PR creation failed. See error above.'));
}
} else {
console.log(
chalk.yellow.bold('\n⚠️ Could not resume merge process. Please check the instructions above.'),
);
}
} else {
// Normal mode: full workflow
await this.promptForWorkItem();
await this.fetchBranches();
await this.promptForBranches();
if (await this.confirmMerge()) {
const success = await this.performMerge();
if (success) {
const prUrl = await this.createPullRequest();
if (prUrl) {
console.log(chalk.green.bold('\n✅ Branch merge completed successfully!'));
// Clear any existing state file since we completed successfully
this.clearState();
} else {
console.log(chalk.red.bold('\n❌ PR creation failed. See error above.'));
}
} else {
console.log(chalk.yellow.bold('\n⚠️ Merge completed with conflicts. Please resolve manually.'));
// State was already saved in performMerge when conflict was detected
}
} else {
console.log(chalk.yellow('\n❌ Merge cancelled by user.'));
}
}
} catch (error) {
console.error(chalk.red('\n❌ Error:'), error.message);
process.exit(1);
} finally {
await this.cleanup();
}
}
}
// CLI Setup
program
.name('workstream-branch-merge-wizard')
.description('Interactive tool to merge workstream branches and create PRs')
.version('1.0.0')
.option('-v, --verbose', 'Enable verbose output')
.option('-r, --resume', 'Resume from saved state after resolving merge conflicts')
.action(async (options) => {
const wizard = new BranchMergeWizard(options);
await wizard.run();
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error(chalk.red('Unhandled Rejection at:'), promise, chalk.red('reason:'), reason);
process.exit(1);
});
// Export the class for testing
export { BranchMergeWizard };
// Run the program only if this file is executed directly
if (
typeof import.meta !== 'undefined' &&
import.meta.url &&
import.meta.url === `file://${process.argv[1]}`
) {
program.parse();
} else if (typeof import.meta === 'undefined' && require.main === module) {
// Fallback for CommonJS environments
program.parse();
}
|