release-cherry-pick 0.0.0-stage → 1.0.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,59 @@
1
+ 'use strict';
2
+
3
+ const inquirer = require('inquirer');
4
+
5
+ let registered = false;
6
+
7
+ function ensureSearchPrompts() {
8
+ if (registered) return;
9
+ inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'));
10
+ inquirer.registerPrompt('checkbox-plus', require('inquirer-checkbox-plus-prompt'));
11
+ registered = true;
12
+ }
13
+
14
+ // Case-insensitive substring filter shared by searchable lists.
15
+ function filterChoicesByInput(choices, input) {
16
+ const query = String(input || '').toLowerCase().trim();
17
+ if (!query) return choices;
18
+ return choices.filter((choice) => {
19
+ const name = typeof choice === 'string' ? choice : choice.name;
20
+ const value = typeof choice === 'string' ? choice : choice.value;
21
+ return String(name).toLowerCase().includes(query)
22
+ || String(value).toLowerCase().includes(query);
23
+ });
24
+ }
25
+
26
+ function searchableList(question, choices) {
27
+ ensureSearchPrompts();
28
+ const normalized = choices.map((choice) => {
29
+ if (typeof choice === 'string') return { name: choice, value: choice };
30
+ return choice;
31
+ });
32
+ return {
33
+ type: 'autocomplete',
34
+ ...question,
35
+ source: (answersSoFar, input) => Promise.resolve(filterChoicesByInput(normalized, input))
36
+ };
37
+ }
38
+
39
+ function searchableCheckbox(question, choices) {
40
+ ensureSearchPrompts();
41
+ const normalized = choices.map((choice) => {
42
+ if (typeof choice === 'string') return { name: choice, value: choice };
43
+ return choice;
44
+ });
45
+ return {
46
+ type: 'checkbox-plus',
47
+ ...question,
48
+ multiple: true,
49
+ source: (answersSoFar, input) => Promise.resolve(filterChoicesByInput(normalized, input))
50
+ };
51
+ }
52
+
53
+ module.exports = {
54
+ ensureSearchPrompts,
55
+ filterChoicesByInput,
56
+ searchableList,
57
+ searchableCheckbox,
58
+ inquirer
59
+ };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // Well-known secret prefixes kept visible when masking, longest first: GitLab personal access
4
+ // tokens, Anthropic API keys and OpenAI(-compatible) API keys.
5
+ const KNOWN_PREFIXES = ['glpat-', 'sk-ant-', 'sk-'];
6
+
7
+ // Masks a secret for display, keeping only enough to recognize it: a known prefix and the last
8
+ // 4 characters. e.g. "glpat-AbCdEf123456WxYz" -> "glpat-****WxYz". Empty values stay empty.
9
+ function maskSecret(value) {
10
+ if (!value) {
11
+ return '';
12
+ }
13
+
14
+ const secret = String(value);
15
+ const prefix = KNOWN_PREFIXES.find(p => secret.startsWith(p)) || '';
16
+ const rest = secret.slice(prefix.length);
17
+ // Too short to reveal any characters without giving away most of it
18
+ if (rest.length <= 8) {
19
+ return `${prefix}****`;
20
+ }
21
+ return `${prefix}****${rest.slice(-4)}`;
22
+ }
23
+
24
+ module.exports = { maskSecret };
@@ -0,0 +1,464 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const inquirer = require('inquirer');
6
+ const logger = require('../utils/logger');
7
+ const { loadConfig, saveConfig } = require('../config/loader');
8
+ const { setupWizard, ensureAiSettings } = require('../config/setup');
9
+ const { parseBranchListFile, extractTaskIdFromBranch, describeBranch, isTaskId } = require('../git/branch-parser');
10
+ const { selectBranchesInteractively, getRemoteBranches, resolveBranchNameForTaskId } = require('../git/branch-selector');
11
+ const { buildReleaseBranchName, createReleaseBranch, pushBranch } = require('../git/release-branch');
12
+ const { captureStartingPoint, restoreStartingPoint, runInterruptible } = require('../git/repo-state');
13
+ const { cherryPickCommits, getCommitsToCherryPick, findLooseTaskCommits, orderCommitsByHistory } = require('../git/cherry-pick');
14
+ const gitlab = require('../gitlab/client');
15
+ const { configureGitCredentials } = require('../git/git-auth');
16
+ const { selectReviewer } = require('../gitlab/reviewer-selector');
17
+ const { createMR } = require('../gitlab/mr-creator');
18
+ const ReleaseStatus = require('../git/release-status');
19
+ const { generateMarkdownSummary } = require('../report/summary');
20
+ const { generateAgentsMd } = require('../doc/agents-generator');
21
+ const { generateRpdMd } = require('../doc/rpd-generator');
22
+
23
+ async function runRelease(options = {}) {
24
+ logger.header('Release Cherry-Pick');
25
+
26
+ // Fail fast (before any prompt) on uncommitted changes / a cherry-pick in progress, and remember
27
+ // where HEAD is so it can be restored once all branches are processed
28
+ const startingPoint = await captureStartingPoint();
29
+
30
+ // Check and setup configuration
31
+ let config = loadConfig();
32
+ if (!config) {
33
+ logger.warn('Configuration not found');
34
+ const { setupNow } = await inquirer.prompt([
35
+ {
36
+ type: 'confirm',
37
+ name: 'setupNow',
38
+ message: 'Do you want to set up configuration now?',
39
+ default: true
40
+ }
41
+ ]);
42
+
43
+ if (setupNow) {
44
+ config = await setupWizard();
45
+ if (!config) {
46
+ logger.error('Configuration setup cancelled');
47
+ return;
48
+ }
49
+ } else {
50
+ logger.error('Configuration is required');
51
+ return;
52
+ }
53
+ }
54
+
55
+ // Feature 1: if AI is enabled but provider/model were never saved, ask now and persist
56
+ config = await ensureAiSettings(config);
57
+
58
+ // Preflight: make sure we have a valid GitLab token before doing any GitLab work
59
+ if (config.release.autoCreateMR) {
60
+ await gitlab.ensureAuthenticated(config);
61
+ }
62
+
63
+ // If a GitLab token is configured (or entered just above), reuse it to authenticate git
64
+ // fetch/pull/push against origin too, so an HTTPS remote doesn't prompt for a username/password
65
+ // on every git operation for the rest of this run.
66
+ await configureGitCredentials(config);
67
+
68
+ // Get branches to process
69
+ let branches = [];
70
+
71
+ if (options.file) {
72
+ // Parse branches from file
73
+ try {
74
+ const branchList = parseBranchListFile(options.file);
75
+ logger.info(`Loaded ${branchList.length} task(s) from file, resolving real branch names...`);
76
+ branches = await resolveTasksToBranches(branchList, config.git.branchPrefix);
77
+ } catch (error) {
78
+ logger.error(error.message);
79
+ return;
80
+ }
81
+ } else if (options.branches) {
82
+ // Comma-separated list: each entry may be a bare task ID ("PB-123", resolved to its real
83
+ // remote branch) or a full branch name ("feature/PB-123-list-user")
84
+ const entries = options.branches.split(',').map(b => b.trim()).filter(Boolean);
85
+ const taskIds = entries.filter(isTaskId);
86
+ const resolved = await resolveTasksToBranches(
87
+ taskIds.map(taskId => ({ taskId })),
88
+ config.git.branchPrefix
89
+ );
90
+
91
+ for (const entry of entries) {
92
+ if (isTaskId(entry)) {
93
+ branches.push(resolved.find(b => b.taskId === entry.toUpperCase()));
94
+ } else {
95
+ const info = branchInfoFromName(entry, config);
96
+ if (info) {
97
+ branches.push(info);
98
+ }
99
+ }
100
+ }
101
+ } else {
102
+ // Feature 2: use branches saved in configuration when present; otherwise select interactively
103
+ const savedBranches = Array.isArray(config.release && config.release.branches)
104
+ ? config.release.branches
105
+ : [];
106
+
107
+ let selectedBranches = [];
108
+
109
+ if (savedBranches.length > 0) {
110
+ const { useSaved } = await inquirer.prompt([
111
+ {
112
+ type: 'confirm',
113
+ name: 'useSaved',
114
+ message: `Use ${savedBranches.length} branch(es) saved in configuration? (${savedBranches.join(', ')})`,
115
+ default: true
116
+ }
117
+ ]);
118
+
119
+ if (useSaved) {
120
+ const remoteBranches = await getRemoteBranches(config.git.branchPrefix);
121
+ for (const saved of savedBranches) {
122
+ if (remoteBranches.includes(saved)) {
123
+ selectedBranches.push(saved);
124
+ } else {
125
+ logger.warn(`Saved branch no longer exists on remote: ${saved} (skipped)`);
126
+ }
127
+ }
128
+
129
+ if (selectedBranches.length === 0) {
130
+ logger.warn('No saved branches still exist on the remote; falling back to interactive selection');
131
+ }
132
+ }
133
+ } else {
134
+ logger.info('No branches saved in configuration yet; select them interactively');
135
+ }
136
+
137
+ if (selectedBranches.length === 0) {
138
+ selectedBranches = await selectBranchesInteractively(config.git.branchPrefix);
139
+ if (selectedBranches.length === 0) {
140
+ logger.warn('No branches selected');
141
+ return;
142
+ }
143
+
144
+ const { saveSelection } = await inquirer.prompt([
145
+ {
146
+ type: 'confirm',
147
+ name: 'saveSelection',
148
+ message: 'Save this branch selection as default in configuration?',
149
+ default: true
150
+ }
151
+ ]);
152
+
153
+ if (saveSelection) {
154
+ if (!config.release || typeof config.release !== 'object') {
155
+ config.release = {};
156
+ }
157
+ config.release.branches = selectedBranches;
158
+ saveConfig(config);
159
+ logger.success(`Saved ${selectedBranches.length} branch(es) to configuration`);
160
+ }
161
+ }
162
+
163
+ branches = selectedBranches.map(branch => branchInfoFromName(branch, config)).filter(Boolean);
164
+ }
165
+
166
+ // Process each branch
167
+ const releaseStatus = new ReleaseStatus();
168
+ let projectMembers = null;
169
+ // Release branches created in this run that ended up with nothing worth keeping (conflict,
170
+ // skipped, error): they were never pushed and equal staging, so they're deleted at the end
171
+ const emptyBranches = [];
172
+ // The branch being processed right now, while it's still local-only; if Ctrl+C interrupts it
173
+ // midway, it's unfinished and unpushed, so it's discarded too
174
+ let unfinishedBranch = null;
175
+
176
+ // Cleanup (return to the starting branch, delete empty release branches) runs when the loop
177
+ // ends, if it throws, and on Ctrl+C
178
+ await runInterruptible(async (signal) => {
179
+ for (const branchInfo of branches) {
180
+ if (signal.interrupted) break;
181
+ logger.header(`Processing ${branchInfo.taskId}`);
182
+ let createdBranch = null;
183
+
184
+ try {
185
+ // Create release branch
186
+ const releaseBranch = await createReleaseBranch(
187
+ branchInfo.branchName,
188
+ config.git.stagingBranch,
189
+ config.git.branchPrefix
190
+ );
191
+
192
+ if (!releaseBranch.success) {
193
+ releaseStatus.markNoProcede(branchInfo.taskId, releaseBranch.branch, [releaseBranch.reason]);
194
+ continue;
195
+ }
196
+ createdBranch = releaseBranch.branch;
197
+ unfinishedBranch = createdBranch;
198
+ if (signal.interrupted) break;
199
+
200
+ if (options.listBranches) {
201
+ // -l: skip cherry-pick entirely. The release branch is left identical to staging —
202
+ // it's only a reserved name for this task — and the MR is opened straight from the
203
+ // original source branch into staging, so GitLab (not this tool) does the actual merge.
204
+ let mrLink = null;
205
+ if (config.release.autoCreateMR) {
206
+ try {
207
+ await pushBranch(releaseBranch.branch);
208
+ unfinishedBranch = null;
209
+ if (signal.interrupted) break;
210
+
211
+ if (!projectMembers) {
212
+ projectMembers = await gitlab.getProjectMembers(config);
213
+ }
214
+ const reviewers = await selectReviewer(projectMembers, config.release);
215
+ if (signal.interrupted) break;
216
+
217
+ // Commits are only read to build the MR description text, nothing is cherry-picked
218
+ // here — so merge commits are kept in the list instead of being excluded/warned
219
+ // about as "can't cherry-pick a merge", which wouldn't apply in this mode.
220
+ const commits = await getCommitsToCherryPick(branchInfo.branchName, branchInfo.taskId, config.git.stagingBranch, { excludeMerges: false });
221
+
222
+ const mr = await createMR(config, {
223
+ sourceBranch: branchInfo.branchName,
224
+ targetBranch: config.git.stagingBranch,
225
+ taskId: branchInfo.taskId,
226
+ description: branchInfo.description,
227
+ commits,
228
+ reviewers,
229
+ members: projectMembers
230
+ });
231
+ mrLink = mr.url;
232
+ } catch (error) {
233
+ if (signal.interrupted) break;
234
+ logger.warn(`Failed to create MR: ${error.message}`);
235
+ }
236
+ }
237
+
238
+ releaseStatus.markProcede(branchInfo.taskId, releaseBranch.branch, mrLink);
239
+ unfinishedBranch = null;
240
+ logger.success(`${branchInfo.taskId} completed successfully (no cherry-pick — MR opened from ${branchInfo.branchName})`);
241
+ continue;
242
+ }
243
+
244
+ // Cherry-pick only commits tagged "[taskId]" on this branch that aren't already on staging,
245
+ // plus — if the user agrees — the ones mentioning the task without following the convention
246
+ const commits = await selectTaskCommits(branchInfo, config, releaseStatus);
247
+ if (signal.interrupted) break;
248
+ const cherryPickResult = await cherryPickCommits(branchInfo.branchName, branchInfo.taskId, config.git.stagingBranch, commits);
249
+ if (signal.interrupted) break;
250
+
251
+ if (!cherryPickResult.success) {
252
+ const conflictFiles = cherryPickResult.conflicts.flatMap(c => c.files);
253
+ // Conflict: do nothing further for this branch (no push, no MR) — just record it.
254
+ releaseStatus.markConflict(branchInfo.taskId, releaseBranch.branch, conflictFiles);
255
+ emptyBranches.push(createdBranch);
256
+ unfinishedBranch = null;
257
+ continue;
258
+ }
259
+
260
+ if (cherryPickResult.commitsCherryPicked === 0) {
261
+ // No real commits landed (either none were found tagged for this task, or they were
262
+ // all already applied / empty diffs) — nothing to push or open an MR for.
263
+ const reason = cherryPickResult.commitsAlreadyApplied > 0
264
+ ? `Changes already present on ${config.git.stagingBranch} — nothing to release`
265
+ : `No commits tagged [${branchInfo.taskId}] found on ${branchInfo.branchName}`;
266
+ releaseStatus.markSkipped(branchInfo.taskId, releaseBranch.branch, reason);
267
+ logger.warn(`${branchInfo.taskId}: ${reason}`);
268
+ emptyBranches.push(createdBranch);
269
+ unfinishedBranch = null;
270
+ continue;
271
+ }
272
+
273
+ // Create MR if configured
274
+ let mrLink = null;
275
+ if (config.release.autoCreateMR) {
276
+ try {
277
+ await pushBranch(releaseBranch.branch);
278
+ // Pushed: from here on the branch is kept even if interrupted
279
+ unfinishedBranch = null;
280
+ if (signal.interrupted) break;
281
+
282
+ if (!projectMembers) {
283
+ projectMembers = await gitlab.getProjectMembers(config);
284
+ }
285
+ const reviewers = await selectReviewer(projectMembers, config.release);
286
+ if (signal.interrupted) break;
287
+
288
+ const mr = await createMR(config, {
289
+ sourceBranch: releaseBranch.branch,
290
+ targetBranch: config.git.stagingBranch,
291
+ taskId: branchInfo.taskId,
292
+ description: branchInfo.description,
293
+ commits: cherryPickResult.commits,
294
+ reviewers,
295
+ members: projectMembers
296
+ });
297
+ mrLink = mr.url;
298
+ } catch (error) {
299
+ if (signal.interrupted) break;
300
+ logger.warn(`Failed to create MR: ${error.message}`);
301
+ }
302
+ }
303
+
304
+ releaseStatus.markProcede(branchInfo.taskId, releaseBranch.branch, mrLink);
305
+ unfinishedBranch = null;
306
+ logger.success(`${branchInfo.taskId} completed successfully`);
307
+
308
+ } catch (error) {
309
+ // Ctrl+C also kills the running git command, so its error is expected — just stop
310
+ if (signal.interrupted) break;
311
+ logger.error(`Failed to process ${branchInfo.taskId}: ${error.message}`);
312
+ const branchLabel = createdBranch || buildReleaseBranchName(branchInfo.branchName, config.git.branchPrefix);
313
+ releaseStatus.markNoProcede(branchInfo.taskId, branchLabel, [error.message]);
314
+ // Errors before the push leave an unpushed branch behind (push failures are handled above
315
+ // and keep the branch as PROCEDE), so it's safe to discard
316
+ if (unfinishedBranch) {
317
+ emptyBranches.push(unfinishedBranch);
318
+ unfinishedBranch = null;
319
+ }
320
+ }
321
+ }
322
+ }, () => restoreStartingPoint(
323
+ startingPoint,
324
+ unfinishedBranch ? [...emptyBranches, unfinishedBranch] : emptyBranches
325
+ ));
326
+
327
+ // Display summary
328
+ releaseStatus.displaySummary();
329
+
330
+ // Optional final recap: just the release branches this run actually created and kept (PROCEDE),
331
+ // handy for scripting/copy-paste instead of parsing the full status report above.
332
+ if (options.listBranches) {
333
+ const createdBranches = releaseStatus.getCreatedBranches();
334
+ logger.header('Release Branches Created');
335
+ if (createdBranches.length === 0) {
336
+ logger.info('No release branches were created in this run');
337
+ } else {
338
+ for (const branch of createdBranches) {
339
+ logger.log(` - ${branch}`);
340
+ }
341
+ }
342
+ }
343
+
344
+ // Offer to save the report to a file so conflicts are visible outside the console too
345
+ const { saveReport } = await inquirer.prompt([
346
+ {
347
+ type: 'confirm',
348
+ name: 'saveReport',
349
+ message: 'Save release summary to release-summary.md?',
350
+ default: true
351
+ }
352
+ ]);
353
+
354
+ if (saveReport) {
355
+ const markdown = generateMarkdownSummary(releaseStatus);
356
+ const summaryPath = path.join(process.cwd(), 'release-summary.md');
357
+ fs.writeFileSync(summaryPath, markdown, 'utf8');
358
+ logger.success(`Saved ${summaryPath}`);
359
+ }
360
+
361
+ // Generate documentation
362
+ const { generateDocs } = await inquirer.prompt([
363
+ {
364
+ type: 'confirm',
365
+ name: 'generateDocs',
366
+ message: 'Generate AGENTS.md and RPD.md?',
367
+ default: true
368
+ }
369
+ ]);
370
+
371
+ if (generateDocs) {
372
+ await generateAgentsMd(process.cwd());
373
+ await generateRpdMd(process.cwd(), releaseStatus);
374
+ }
375
+
376
+ logger.success('Release process completed');
377
+ }
378
+
379
+ // Resolves each { taskId, description? } to its real remote branch; prompts when several match.
380
+ // Tasks without a description (bare IDs from -b) get one derived from the resolved branch name.
381
+ async function resolveTasksToBranches(tasks, branchPrefix = {}) {
382
+ if (tasks.length === 0) {
383
+ return [];
384
+ }
385
+
386
+ const remoteBranches = await getRemoteBranches(branchPrefix);
387
+ const branches = [];
388
+
389
+ for (const task of tasks) {
390
+ const taskId = task.taskId.toUpperCase();
391
+ const matches = await resolveBranchNameForTaskId(taskId, remoteBranches, branchPrefix);
392
+ let branchName;
393
+
394
+ if (matches.length === 1) {
395
+ branchName = matches[0];
396
+ logger.info(`${taskId} -> ${branchName}`);
397
+ } else if (matches.length > 1) {
398
+ logger.warn(`Multiple remote branches match ${taskId}: ${matches.join(', ')}`);
399
+ const { chosen } = await inquirer.prompt([
400
+ {
401
+ type: 'list',
402
+ name: 'chosen',
403
+ message: `Select the branch for ${taskId}:`,
404
+ choices: matches
405
+ }
406
+ ]);
407
+ branchName = chosen;
408
+ } else {
409
+ branchName = `${branchPrefix.feature || 'feature/'}${taskId.toLowerCase()}`;
410
+ logger.warn(`No remote branch found matching ${taskId}; guessing ${branchName} (may not exist)`);
411
+ }
412
+
413
+ const description = task.description || describeBranch(branchName, branchPrefix);
414
+ branches.push({ taskId, description, branchName });
415
+ }
416
+
417
+ return branches;
418
+ }
419
+
420
+ // The commits to release for a task: the ones tagged "[TASK-ID] ..." and, when some commits mention
421
+ // the task ID without following that convention (e.g. "PB-700: fix"), the user decides whether to
422
+ // include them too (default: no). Either way it's recorded as a note in the release summary, so a
423
+ // partially released task never goes unnoticed.
424
+ async function selectTaskCommits(branchInfo, config, releaseStatus) {
425
+ const { branchName, taskId } = branchInfo;
426
+ const base = config.git.stagingBranch;
427
+ const tagged = await getCommitsToCherryPick(branchName, taskId, base);
428
+ const loose = await findLooseTaskCommits(branchName, taskId, base);
429
+ if (loose.length === 0) {
430
+ return tagged;
431
+ }
432
+
433
+ const list = loose.map(c => `${c.hash.slice(0, 8)} ${c.message}`);
434
+ logger.warn(`${loose.length} commit(s) on ${branchName} mention ${taskId} but don't follow the "[${taskId}] ..." convention:`);
435
+ for (const line of list) {
436
+ logger.warn(` ${line}`);
437
+ }
438
+
439
+ const { includeLoose } = await inquirer.prompt([
440
+ {
441
+ type: 'confirm',
442
+ name: 'includeLoose',
443
+ message: `Include ${loose.length === 1 ? 'it' : 'them'} in the ${taskId} release too?`,
444
+ default: false
445
+ }
446
+ ]);
447
+
448
+ const outcome = includeLoose ? 'included at your request' : 'NOT included';
449
+ releaseStatus.addNote(taskId, `${loose.length} commit(s) mention ${taskId} without the "[${taskId}] ..." convention and were ${outcome}: ${list.join('; ')}`);
450
+
451
+ return includeLoose ? orderCommitsByHistory(branchName, [...tagged, ...loose], base) : tagged;
452
+ }
453
+
454
+ // Builds branch info from a full branch name, extracting its task ID; null (with a warning) if none.
455
+ function branchInfoFromName(branchName, config) {
456
+ const taskId = extractTaskIdFromBranch(branchName, config.git.branchPrefix);
457
+ if (!taskId) {
458
+ logger.warn(`Could not extract a task ID from ${branchName} — skipping it`);
459
+ return null;
460
+ }
461
+ return { taskId, description: describeBranch(branchName, config.git.branchPrefix), branchName };
462
+ }
463
+
464
+ module.exports = { runRelease };