@docupace/pipeline 1.0.62 → 1.0.64-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,472 @@
1
+ import { execSync } from 'child_process';
2
+ import { readFileSync, existsSync, mkdirSync } from 'fs';
3
+ import { join, dirname } from 'path';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ const __dirname = dirname(fileURLToPath(import.meta.url));
7
+
8
+ /**
9
+ * Read merge configuration from current directory
10
+ */
11
+ function readMergeConfig(verbose = false) {
12
+ const configPath = join(process.cwd(), 'merge-config.json');
13
+
14
+ if (!existsSync(configPath)) {
15
+ throw new Error('merge-config.json not found in current directory');
16
+ }
17
+
18
+ try {
19
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
20
+
21
+ if (!config.repositories || !Array.isArray(config.repositories)) {
22
+ throw new Error('Invalid config: repositories array is required');
23
+ }
24
+
25
+ // Validate repository objects
26
+ config.repositories.forEach((repo, index) => {
27
+ if (!repo.url) {
28
+ throw new Error(`Repository at index ${index} is missing 'url' field`);
29
+ }
30
+ if (!repo.buildScript) {
31
+ throw new Error(
32
+ `Repository at index ${index} is missing 'buildScript' field`,
33
+ );
34
+ }
35
+ if (!repo.name) {
36
+ throw new Error(`Repository at index ${index} is missing 'name' field`);
37
+ }
38
+ });
39
+
40
+ if (!config.mergeBranches || !Array.isArray(config.mergeBranches)) {
41
+ throw new Error('Invalid config: mergeBranches array is required');
42
+ }
43
+
44
+ // Validate merge branches
45
+ config.mergeBranches.forEach((branch, index) => {
46
+ if (!branch.from || !branch.to) {
47
+ throw new Error(
48
+ `Merge branch at index ${index} is missing 'from' or 'to' field`,
49
+ );
50
+ }
51
+ if (typeof branch.from !== 'object' || typeof branch.to !== 'object') {
52
+ throw new Error(
53
+ `Merge branch at index ${index}: 'from' and 'to' must be objects`,
54
+ );
55
+ }
56
+ if (!branch.from['*'] || !branch.to['*']) {
57
+ throw new Error(
58
+ `Merge branch at index ${index}: 'from' and 'to' must have '*' default value`,
59
+ );
60
+ }
61
+ });
62
+
63
+ if (verbose) {
64
+ console.log('šŸ“‹ Configuration loaded:');
65
+ console.log(` Repositories: ${config.repositories.length}`);
66
+ console.log(` Merge branches: ${config.mergeBranches.length}`);
67
+ }
68
+
69
+ return config;
70
+ } catch (error) {
71
+ throw new Error(`Failed to parse merge-config.json: ${error.message}`);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Extract repository name from git URL
77
+ */
78
+ function getRepoName(gitUrl) {
79
+ const match = gitUrl.match(/\/([^\/]+)\.git$/);
80
+ return match ? match[1] : gitUrl.split('/').pop().replace('.git', '');
81
+ }
82
+
83
+ /**
84
+ * Get branch name for a specific repository
85
+ */
86
+ function getBranchForRepo(branchConfig, repoName) {
87
+ // Check if there's a specific override for this repository
88
+ if (branchConfig[repoName]) {
89
+ return branchConfig[repoName];
90
+ }
91
+ // Fall back to the default branch
92
+ return branchConfig['*'];
93
+ }
94
+
95
+ /**
96
+ * Clone or update repository
97
+ */
98
+ function setupRepository(repository, reposDir, verbose = false) {
99
+ const repoName = getRepoName(repository.url);
100
+ const repoPath = join(reposDir, repoName);
101
+
102
+ if (existsSync(repoPath)) {
103
+ if (verbose) console.log(`šŸ“ Repository ${repoName} exists, updating...`);
104
+
105
+ execSync('git fetch --all', {
106
+ cwd: repoPath,
107
+ stdio: verbose ? 'inherit' : 'pipe',
108
+ });
109
+ } else {
110
+ if (verbose) console.log(`šŸ“„ Cloning repository ${repoName}...`);
111
+
112
+ execSync(`git clone ${repository.url} ${repoName}`, {
113
+ cwd: reposDir,
114
+ stdio: verbose ? 'inherit' : 'pipe',
115
+ });
116
+ }
117
+
118
+ return {
119
+ repoName,
120
+ repoPath,
121
+ buildScript: repository.buildScript,
122
+ configName: repository.name,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Run merge command in repository with specific flags
128
+ */
129
+ function runMergeCommand(
130
+ repoPath,
131
+ fromBranch,
132
+ toBranch,
133
+ buildScript,
134
+ flags = '',
135
+ verbose = false,
136
+ ) {
137
+ const cliPath = join(__dirname, 'cli.js');
138
+ const verboseFlag = verbose ? '--verbose' : '';
139
+
140
+ const command =
141
+ `node ${cliPath} merge ${fromBranch} ${toBranch} --build "${buildScript}" ${flags} ${verboseFlag}`.trim();
142
+
143
+ if (verbose) {
144
+ console.log(`šŸ“„ Running command in ${repoPath}`);
145
+ console.log(`Command: ${command}`);
146
+ }
147
+
148
+ try {
149
+ execSync(command, {
150
+ cwd: repoPath,
151
+ stdio: verbose ? 'inherit' : 'pipe',
152
+ encoding: 'utf8',
153
+ });
154
+
155
+ return { exitCode: 0, error: null };
156
+ } catch (error) {
157
+ // Extract exit code from error
158
+ const exitCode = error.status || 1;
159
+ return { exitCode, error: error.message };
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Run initial prepare-only phase for all repositories
165
+ */
166
+ async function runPreparePhase(
167
+ mergeBranch,
168
+ repositories,
169
+ reposDir,
170
+ verbose = false,
171
+ ) {
172
+ const { from: fromConfig, to: toConfig } = mergeBranch;
173
+ console.log(`\nšŸ”„ Phase 1: Running prepare-only for all repositories`);
174
+
175
+ const results = [];
176
+
177
+ for (let i = 0; i < repositories.length; i++) {
178
+ const repository = repositories[i];
179
+ const { repoName, repoPath, buildScript, configName } = setupRepository(
180
+ repository,
181
+ reposDir,
182
+ verbose,
183
+ );
184
+
185
+ // Get the specific branches for this repository
186
+ const fromBranch = getBranchForRepo(fromConfig, configName);
187
+ const toBranch = getBranchForRepo(toConfig, configName);
188
+
189
+ console.log(
190
+ `\nšŸ“¦ [${i + 1}/${repositories.length}] Testing ${configName} (${repoName}): ${fromBranch} → ${toBranch}`,
191
+ );
192
+
193
+ const result = runMergeCommand(
194
+ repoPath,
195
+ fromBranch,
196
+ toBranch,
197
+ buildScript,
198
+ '--prepare-only',
199
+ verbose,
200
+ );
201
+
202
+ results.push({
203
+ repository: repoName,
204
+ configName,
205
+ url: repository.url,
206
+ buildScript,
207
+ fromBranch,
208
+ toBranch,
209
+ exitCode: result.exitCode,
210
+ error: result.error,
211
+ repoPath,
212
+ });
213
+
214
+ // Log result based on exit code
215
+ switch (result.exitCode) {
216
+ case 0:
217
+ console.log(`āœ… ${configName}: Merge and build successful`);
218
+ break;
219
+ case 2:
220
+ console.log(`āš ļø ${configName}: Merge has unresolved conflicts`);
221
+ break;
222
+ case 3:
223
+ console.log(`āš ļø ${configName}: Build failed`);
224
+ break;
225
+ default:
226
+ console.log(
227
+ `āŒ ${configName}: Unknown error (exit code: ${result.exitCode})`,
228
+ );
229
+ }
230
+ }
231
+
232
+ return results;
233
+ }
234
+
235
+ /**
236
+ * Run follow-up phase based on prepare phase results
237
+ */
238
+ async function runFollowUpPhase(prepareResults, verbose = false) {
239
+ console.log(`\nšŸ”„ Phase 2: Running follow-up based on prepare phase results`);
240
+
241
+ // Check if all repositories passed
242
+ const allPassed = prepareResults.every((r) => r.exitCode === 0);
243
+
244
+ for (let i = 0; i < prepareResults.length; i++) {
245
+ const result = prepareResults[i];
246
+ console.log(
247
+ `\nšŸ“¦ [${i + 1}/${prepareResults.length}] Processing ${result.configName}`,
248
+ );
249
+
250
+ let flags = '';
251
+ let action = '';
252
+
253
+ if (allPassed) {
254
+ // All passed, merge successfully
255
+ flags = '--merge-success';
256
+ action = 'Merging successfully';
257
+ } else {
258
+ // At least one failed, determine the appropriate action
259
+ switch (result.exitCode) {
260
+ case 0:
261
+ // This one passed but others failed
262
+ flags = '--merge-fail "Waiting for success for other failed merges"';
263
+ action = 'Creating PR (waiting for other repos)';
264
+ break;
265
+ case 2:
266
+ // Merge failed
267
+ flags = '--merge-fail "Merge Failed"';
268
+ action = 'Creating PR (merge conflicts)';
269
+ break;
270
+ case 3:
271
+ // Build failed
272
+ flags = '--merge-fail "Build Failed"';
273
+ action = 'Creating PR (build failed)';
274
+ break;
275
+ default:
276
+ // Unknown error
277
+ flags = '--merge-fail "Unknown Error"';
278
+ action = 'Creating PR (unknown error)';
279
+ }
280
+ }
281
+
282
+ console.log(` Action: ${action}`);
283
+
284
+ const followUpResult = runMergeCommand(
285
+ result.repoPath,
286
+ result.fromBranch,
287
+ result.toBranch,
288
+ result.buildScript,
289
+ flags,
290
+ verbose,
291
+ );
292
+
293
+ // Update the result with follow-up information
294
+ result.followUpExitCode = followUpResult.exitCode;
295
+ result.followUpError = followUpResult.error;
296
+ result.followUpAction = action;
297
+
298
+ if (followUpResult.exitCode === 0) {
299
+ console.log(`āœ… ${result.configName}: ${action} completed`);
300
+ } else {
301
+ console.log(`āŒ ${result.configName}: ${action} failed`);
302
+ }
303
+ }
304
+
305
+ return prepareResults;
306
+ }
307
+
308
+ /**
309
+ * Process a single merge branch across all repositories
310
+ */
311
+ async function processMergeBranch(
312
+ mergeBranch,
313
+ repositories,
314
+ reposDir,
315
+ verbose = false,
316
+ ) {
317
+ console.log(`\nšŸ”€ Processing merge branches`);
318
+
319
+ // Phase 1: Run prepare-only for all repositories
320
+ const prepareResults = await runPreparePhase(
321
+ mergeBranch,
322
+ repositories,
323
+ reposDir,
324
+ verbose,
325
+ );
326
+
327
+ // Phase 2: Run follow-up based on results
328
+ const finalResults = await runFollowUpPhase(prepareResults, verbose);
329
+
330
+ // Summary
331
+ const allPassed = prepareResults.every((r) => r.exitCode === 0);
332
+ const mergeFailures = prepareResults.filter((r) => r.exitCode === 2);
333
+ const buildFailures = prepareResults.filter((r) => r.exitCode === 3);
334
+ const successes = prepareResults.filter((r) => r.exitCode === 0);
335
+
336
+ console.log(`\nšŸ“Š Merge summary:`);
337
+ console.log(` āœ… Successful: ${successes.length}/${repositories.length}`);
338
+ console.log(` āš ļø Merge conflicts: ${mergeFailures.length}`);
339
+ console.log(` āš ļø Build failures: ${buildFailures.length}`);
340
+
341
+ if (allPassed) {
342
+ console.log(` šŸŽ‰ All repositories merged successfully!`);
343
+ } else {
344
+ console.log(` āš ļø Some repositories require manual intervention via PRs`);
345
+ }
346
+
347
+ return {
348
+ success: allPassed,
349
+ results: finalResults,
350
+ summary: {
351
+ total: repositories.length,
352
+ successes: successes.length,
353
+ mergeFailures: mergeFailures.length,
354
+ buildFailures: buildFailures.length,
355
+ },
356
+ };
357
+ }
358
+
359
+ /**
360
+ * Main merge-all function
361
+ */
362
+ async function mergeAll(verbose = false) {
363
+ try {
364
+ // Read configuration
365
+ const config = readMergeConfig(verbose);
366
+
367
+ // Setup repos directory
368
+ const reposDir = join(process.cwd(), 'repos');
369
+ if (!existsSync(reposDir)) {
370
+ mkdirSync(reposDir, { recursive: true });
371
+ if (verbose) console.log(`šŸ“ Created repos directory: ${reposDir}`);
372
+ }
373
+
374
+ console.log(`šŸš€ Starting merge-all process`);
375
+ console.log(`Repositories: ${config.repositories.length}`);
376
+ console.log(`Merge branches: ${config.mergeBranches.length}`);
377
+
378
+ const allResults = [];
379
+
380
+ // Process each merge branch in sequence
381
+ for (let i = 0; i < config.mergeBranches.length; i++) {
382
+ const mergeBranch = config.mergeBranches[i];
383
+ console.log(`\n═══════════════════════════════════════`);
384
+ console.log(
385
+ `Processing merge branch set ${i + 1}/${config.mergeBranches.length}`,
386
+ );
387
+ console.log(`═══════════════════════════════════════`);
388
+
389
+ const branchResult = await processMergeBranch(
390
+ mergeBranch,
391
+ config.repositories,
392
+ reposDir,
393
+ verbose,
394
+ );
395
+
396
+ if (!branchResult.success) {
397
+ console.log(`Exiting due to failure of one or more merges`);
398
+ process.exit(1);
399
+ }
400
+
401
+ allResults.push({
402
+ mergeBranch,
403
+ ...branchResult,
404
+ });
405
+ }
406
+
407
+ // Final summary
408
+ console.log(`\n═══════════════════════════════════════`);
409
+ console.log(`šŸ“ˆ Final Summary:`);
410
+ console.log(`═══════════════════════════════════════`);
411
+
412
+ allResults.forEach((result, index) => {
413
+ const { from, to } = result.mergeBranch;
414
+ const status = result.success ? 'āœ…' : 'āš ļø';
415
+ console.log(`\n${status} Merge branch set ${index + 1}:`);
416
+
417
+ if (result.summary) {
418
+ console.log(` Total repositories: ${result.summary.total}`);
419
+ console.log(` Successful merges: ${result.summary.successes}`);
420
+ console.log(` Merge conflicts: ${result.summary.mergeFailures}`);
421
+ console.log(` Build failures: ${result.summary.buildFailures}`);
422
+ }
423
+
424
+ if (result.results && verbose) {
425
+ console.log(`\n Repository details:`);
426
+ result.results.forEach((repo) => {
427
+ let repoStatus = 'ā“';
428
+ if (repo.exitCode === 0) repoStatus = 'āœ…';
429
+ else if (repo.exitCode === 2) repoStatus = 'āš ļø (merge)';
430
+ else if (repo.exitCode === 3) repoStatus = 'āš ļø (build)';
431
+
432
+ console.log(
433
+ ` ${repoStatus} ${repo.configName}: ${repo.fromBranch} → ${repo.toBranch}`,
434
+ );
435
+ });
436
+ }
437
+ });
438
+
439
+ const overallSuccess = allResults.every((r) => r.success);
440
+ if (overallSuccess) {
441
+ console.log(`\nšŸŽ‰ All merge operations completed successfully!`);
442
+ } else {
443
+ console.log(
444
+ `\nāš ļø Some merge operations created PRs. Check the repositories for details.`,
445
+ );
446
+ }
447
+
448
+ return { success: overallSuccess, results: allResults };
449
+ } catch (error) {
450
+ console.error(`āŒ Merge-all failed: ${error.message}`);
451
+ throw error;
452
+ }
453
+ }
454
+
455
+ export function setupMergeAll(program) {
456
+ program
457
+ .command('merge-all')
458
+ .description(
459
+ 'Merge multiple branches across multiple repositories based on configuration',
460
+ )
461
+ .option('-v, --verbose', 'Verbose output')
462
+ .action(async (options) => {
463
+ try {
464
+ const { verbose } = options;
465
+
466
+ await mergeAll(verbose);
467
+ } catch (error) {
468
+ console.error(`āŒ merge-all command failed: ${error.message}`);
469
+ process.exit(1);
470
+ }
471
+ });
472
+ }