|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Merge Previous Release Branches Script |
| 5 | + * |
| 6 | + * This script is triggered when a new release branch is created (e.g., release/2.1.2). |
| 7 | + * It finds previous release branches and merges them into the new release branch. |
| 8 | + * |
| 9 | + * Key behaviors: |
| 10 | + * - By default, only merges the MOST RECENT older release branch (e.g., 2.1.1 into 2.1.2) |
| 11 | + * - Set MERGE_ALL_OLDER_BRANCHES=true to merge ALL older branches |
| 12 | + * - For merge conflicts, favors the destination branch (new release) |
| 13 | + * - Both branches remain open after merge |
| 14 | + * - Fails fast on errors to prevent pushing partial merges |
| 15 | + * |
| 16 | + * Environment variables: |
| 17 | + * - NEW_RELEASE_BRANCH: The newly created release branch (e.g., release/2.1.2) |
| 18 | + * - MERGE_ALL_OLDER_BRANCHES: Set to 'true' to merge all older branches (default: false) |
| 19 | + */ |
| 20 | + |
| 21 | +const { promisify } = require('util'); |
| 22 | +const exec = promisify(require('child_process').exec); |
| 23 | + |
| 24 | +/** |
| 25 | + * Parse a release branch name to extract version components |
| 26 | + * @param {string} branchName - Branch name like "release/2.1.2" |
| 27 | + * @returns {object|null} - { major, minor, patch } or null if not a valid release branch |
| 28 | + */ |
| 29 | +function parseReleaseVersion(branchName) { |
| 30 | + // Match release/X.Y.Z format (does not match release candidates like release/2.1.2-rc.1) |
| 31 | + const match = branchName.match(/^release\/(\d+)\.(\d+)\.(\d+)$/); |
| 32 | + if (!match) { |
| 33 | + return null; |
| 34 | + } |
| 35 | + return { |
| 36 | + major: parseInt(match[1], 10), |
| 37 | + minor: parseInt(match[2], 10), |
| 38 | + patch: parseInt(match[3], 10), |
| 39 | + }; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Compare two version objects |
| 44 | + * @returns {number} - negative if a < b, positive if a > b, 0 if equal |
| 45 | + */ |
| 46 | +function compareVersions(a, b) { |
| 47 | + if (a.major !== b.major) return a.major - b.major; |
| 48 | + if (a.minor !== b.minor) return a.minor - b.minor; |
| 49 | + return a.patch - b.patch; |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Execute a git command and log it |
| 54 | + */ |
| 55 | +async function gitExec(command, options = {}) { |
| 56 | + const { ignoreError = false } = options; |
| 57 | + console.log(`Executing: git ${command}`); |
| 58 | + try { |
| 59 | + const { stdout, stderr } = await exec(`git ${command}`); |
| 60 | + if (stdout.trim()) console.log(stdout.trim()); |
| 61 | + if (stderr.trim()) console.log(stderr.trim()); |
| 62 | + return { stdout, stderr, success: true }; |
| 63 | + } catch (error) { |
| 64 | + if (ignoreError) { |
| 65 | + console.warn(`Warning: ${error.message}`); |
| 66 | + return { stdout: error.stdout, stderr: error.stderr, success: false, error }; |
| 67 | + } |
| 68 | + throw error; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +/** |
| 73 | + * Get all remote release branches |
| 74 | + */ |
| 75 | +async function getReleaseBranches() { |
| 76 | + await gitExec('fetch origin'); |
| 77 | + const { stdout } = await exec('git branch -r --list "origin/release/*"'); |
| 78 | + return stdout |
| 79 | + .split('\n') |
| 80 | + .map((branch) => branch.trim().replace('origin/', '')) |
| 81 | + .filter((branch) => branch && parseReleaseVersion(branch)); |
| 82 | +} |
| 83 | + |
| 84 | +/** |
| 85 | + * Check if a branch has already been merged into the current branch |
| 86 | + */ |
| 87 | +async function isBranchMerged(sourceBranch) { |
| 88 | + try { |
| 89 | + // Check if the source branch's HEAD is an ancestor of current HEAD |
| 90 | + const { stdout } = await exec( |
| 91 | + `git merge-base --is-ancestor origin/${sourceBranch} HEAD && echo "merged" || echo "not-merged"`, |
| 92 | + ); |
| 93 | + return stdout.trim() === 'merged'; |
| 94 | + } catch { |
| 95 | + // If the command fails, assume not merged |
| 96 | + return false; |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * Merge a source branch into the current branch, favoring current branch on conflicts |
| 102 | + * Uses approach similar to stable-sync.js |
| 103 | + */ |
| 104 | +async function mergeWithFavorDestination(sourceBranch, destBranch) { |
| 105 | + console.log(`\n${'='.repeat(60)}`); |
| 106 | + console.log(`Merging ${sourceBranch} into ${destBranch}`); |
| 107 | + console.log('='.repeat(60)); |
| 108 | + |
| 109 | + // Check if already merged |
| 110 | + const alreadyMerged = await isBranchMerged(sourceBranch); |
| 111 | + if (alreadyMerged) { |
| 112 | + console.log(`Branch ${sourceBranch} is already merged into ${destBranch}. Skipping.`); |
| 113 | + return { skipped: true }; |
| 114 | + } |
| 115 | + |
| 116 | + // Try to merge with "ours" strategy for conflicts (favors current branch) |
| 117 | + const mergeResult = await gitExec( |
| 118 | + `merge origin/${sourceBranch} -X ours --no-edit -m "Merge ${sourceBranch} into ${destBranch}"`, |
| 119 | + { ignoreError: true }, |
| 120 | + ); |
| 121 | + |
| 122 | + if (!mergeResult.success) { |
| 123 | + // If merge still fails (shouldn't happen with -X ours, but just in case) |
| 124 | + console.log('Merge had conflicts, resolving by favoring destination branch...'); |
| 125 | + |
| 126 | + // Add all files and resolve conflicts by keeping destination version |
| 127 | + await gitExec('add .'); |
| 128 | + |
| 129 | + // For any remaining conflicts, checkout our version |
| 130 | + try { |
| 131 | + const { stdout: conflictFiles } = await exec('git diff --name-only --diff-filter=U'); |
| 132 | + if (conflictFiles.trim()) { |
| 133 | + for (const file of conflictFiles.trim().split('\n')) { |
| 134 | + if (file) { |
| 135 | + console.log(`Resolving conflict in ${file} by keeping destination version`); |
| 136 | + await gitExec(`checkout --ours "${file}"`); |
| 137 | + await gitExec(`add "${file}"`); |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + } catch (e) { |
| 142 | + // No conflicts to resolve |
| 143 | + } |
| 144 | + |
| 145 | + // Complete the merge |
| 146 | + const { stdout: status } = await exec('git status --porcelain'); |
| 147 | + if (status.trim()) { |
| 148 | + const commitResult = await gitExec( |
| 149 | + `commit -m "Merge ${sourceBranch} into ${destBranch}" --no-verify`, |
| 150 | + { ignoreError: true }, |
| 151 | + ); |
| 152 | + if (!commitResult.success) { |
| 153 | + throw new Error(`Failed to commit merge of ${sourceBranch}: ${commitResult.error?.message}`); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + console.log(`Successfully merged ${sourceBranch} into ${destBranch}`); |
| 159 | + return { skipped: false }; |
| 160 | +} |
| 161 | + |
| 162 | +async function main() { |
| 163 | + const newReleaseBranch = process.env.NEW_RELEASE_BRANCH; |
| 164 | + const mergeAllOlderBranches = (process.env.MERGE_ALL_OLDER_BRANCHES || 'false').toLowerCase() === 'true'; |
| 165 | + |
| 166 | + if (!newReleaseBranch) { |
| 167 | + console.error('Error: NEW_RELEASE_BRANCH environment variable is not set'); |
| 168 | + process.exit(1); |
| 169 | + } |
| 170 | + |
| 171 | + console.log(`New release branch: ${newReleaseBranch}`); |
| 172 | + console.log(`Merge all older branches: ${mergeAllOlderBranches}`); |
| 173 | + |
| 174 | + const newVersion = parseReleaseVersion(newReleaseBranch); |
| 175 | + if (!newVersion) { |
| 176 | + console.error( |
| 177 | + `Error: ${newReleaseBranch} is not a valid release branch (expected format: release/X.Y.Z)`, |
| 178 | + ); |
| 179 | + process.exit(1); |
| 180 | + } |
| 181 | + |
| 182 | + console.log(`Parsed version: ${newVersion.major}.${newVersion.minor}.${newVersion.patch}`); |
| 183 | + |
| 184 | + // Get all release branches |
| 185 | + const allReleaseBranches = await getReleaseBranches(); |
| 186 | + console.log(`\nFound ${allReleaseBranches.length} release branches:`); |
| 187 | + allReleaseBranches.forEach((b) => console.log(` - ${b}`)); |
| 188 | + |
| 189 | + // Filter to only branches older than the new one, sorted from oldest to newest |
| 190 | + const olderBranches = allReleaseBranches |
| 191 | + .filter((branch) => { |
| 192 | + const version = parseReleaseVersion(branch); |
| 193 | + return version && compareVersions(version, newVersion) < 0; |
| 194 | + }) |
| 195 | + .sort((a, b) => { |
| 196 | + const versionA = parseReleaseVersion(a); |
| 197 | + const versionB = parseReleaseVersion(b); |
| 198 | + return compareVersions(versionA, versionB); |
| 199 | + }); |
| 200 | + |
| 201 | + if (olderBranches.length === 0) { |
| 202 | + console.log('\nNo older release branches found. Nothing to merge.'); |
| 203 | + return; |
| 204 | + } |
| 205 | + |
| 206 | + console.log(`\nOlder release branches found (oldest to newest):`); |
| 207 | + olderBranches.forEach((b) => console.log(` - ${b}`)); |
| 208 | + |
| 209 | + // Determine which branches to merge |
| 210 | + let branchesToMerge; |
| 211 | + if (mergeAllOlderBranches) { |
| 212 | + branchesToMerge = olderBranches; |
| 213 | + console.log(`\nWill merge ALL ${branchesToMerge.length} older branches.`); |
| 214 | + } else { |
| 215 | + // Only merge the most recent older branch (last in the sorted array) |
| 216 | + branchesToMerge = [olderBranches[olderBranches.length - 1]]; |
| 217 | + console.log(`\nWill merge only the most recent older branch: ${branchesToMerge[0]}`); |
| 218 | + } |
| 219 | + |
| 220 | + // We should already be on the new release branch (checkout was done in the workflow) |
| 221 | + // But let's verify and ensure we're on the right branch |
| 222 | + const { stdout: currentBranch } = await exec('git branch --show-current'); |
| 223 | + if (currentBranch.trim() !== newReleaseBranch) { |
| 224 | + console.log(`Switching to ${newReleaseBranch}...`); |
| 225 | + await gitExec(`checkout ${newReleaseBranch}`); |
| 226 | + } |
| 227 | + |
| 228 | + // Merge each branch (fail fast on errors) |
| 229 | + let mergedCount = 0; |
| 230 | + let skippedCount = 0; |
| 231 | + |
| 232 | + for (const olderBranch of branchesToMerge) { |
| 233 | + const result = await mergeWithFavorDestination(olderBranch, newReleaseBranch); |
| 234 | + if (result.skipped) { |
| 235 | + skippedCount++; |
| 236 | + } else { |
| 237 | + mergedCount++; |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + // Only push if we actually merged something |
| 242 | + if (mergedCount > 0) { |
| 243 | + console.log('\nPushing merged changes...'); |
| 244 | + await gitExec(`push origin ${newReleaseBranch}`); |
| 245 | + } else { |
| 246 | + console.log('\nNo new merges were made (all branches were already merged).'); |
| 247 | + } |
| 248 | + |
| 249 | + console.log('\n' + '='.repeat(60)); |
| 250 | + console.log('Merge complete!'); |
| 251 | + console.log(` Branches merged: ${mergedCount}`); |
| 252 | + console.log(` Branches skipped (already merged): ${skippedCount}`); |
| 253 | + console.log(`All source branches remain open as requested.`); |
| 254 | + console.log('='.repeat(60)); |
| 255 | +} |
| 256 | + |
| 257 | +main().catch((error) => { |
| 258 | + console.error(`\nFatal error: ${error.message}`); |
| 259 | + console.error('Aborting to prevent pushing partial merges.'); |
| 260 | + process.exit(1); |
| 261 | +}); |
0 commit comments