release-cherry-pick 1.0.3 → 1.1.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.
@@ -17,12 +17,12 @@ function getSourcePrefixes(branchPrefix) {
17
17
  return prefixes.length > 0 ? prefixes : getSourcePrefixes(defaultConfig.git.branchPrefix);
18
18
  }
19
19
 
20
- async function selectBranchesInteractively(branchPrefix) {
20
+ async function selectBranchesInteractively(branchPrefix, branches = null) {
21
21
  logger.header('Branch Selection');
22
22
 
23
- const branches = await getRemoteBranches(branchPrefix);
23
+ const list = branches || (await getRemoteBranches(branchPrefix));
24
24
 
25
- if (branches.length === 0) {
25
+ if (list.length === 0) {
26
26
  logger.warn('No feature or hotfix branches found');
27
27
  return [];
28
28
  }
@@ -32,7 +32,7 @@ async function selectBranchesInteractively(branchPrefix) {
32
32
  name: 'selectedBranches',
33
33
  message: 'Select branches for release (type to search):',
34
34
  pageSize: 15
35
- }, branches)
35
+ }, list)
36
36
  ]);
37
37
 
38
38
  return selectedBranches;
@@ -56,6 +56,74 @@ async function getRemoteBranches(branchPrefix) {
56
56
  }
57
57
  }
58
58
 
59
+ async function getLocalBranches(branchPrefix) {
60
+ const prefixes = getSourcePrefixes(branchPrefix);
61
+ try {
62
+ const result = await git.branchLocal();
63
+ return result.all
64
+ .filter(branch => prefixes.some(prefix => branch.startsWith(prefix)))
65
+ .sort();
66
+ } catch (error) {
67
+ logger.error(`Error getting local branches: ${error.message}`);
68
+ return [];
69
+ }
70
+ }
71
+
72
+ // Every source branch the release can be cut from, keyed by name: { local, remote } says where it
73
+ // exists. In 'local' mode both local branches and origin's are listed (a branch only on origin is
74
+ // still usable as a fallback); in 'remote' mode only origin's, as before local mode existed.
75
+ async function getBranchCatalog(branchPrefix, mode = 'local') {
76
+ const catalog = new Map();
77
+ const remote = await getRemoteBranches(branchPrefix);
78
+ for (const name of remote) {
79
+ catalog.set(name, { local: false, remote: true });
80
+ }
81
+ if (mode === 'local') {
82
+ for (const name of await getLocalBranches(branchPrefix)) {
83
+ catalog.set(name, { local: true, remote: catalog.has(name) });
84
+ }
85
+ }
86
+ return catalog;
87
+ }
88
+
89
+ // How many branches use each prefix ("feature/" -> 124), counting local and origin branches once
90
+ // per name. Reads the refs already present (no fetch), so it's instant and works offline; used by
91
+ // the setup wizard to suggest the prefixes this repo really uses. {} outside a git repo.
92
+ async function countBranchesByPrefix() {
93
+ try {
94
+ const out = await git.raw(['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes/origin']);
95
+ const names = new Set();
96
+ for (const ref of out.split('\n').map(line => line.trim())) {
97
+ const name = ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length)
98
+ : ref.startsWith('refs/remotes/origin/') ? ref.slice('refs/remotes/origin/'.length)
99
+ : null;
100
+ if (name && name !== 'HEAD') names.add(name);
101
+ }
102
+
103
+ const counts = {};
104
+ for (const name of names) {
105
+ const slash = name.indexOf('/');
106
+ if (slash > 0) {
107
+ const prefix = name.slice(0, slash + 1);
108
+ counts[prefix] = (counts[prefix] || 0) + 1;
109
+ }
110
+ }
111
+ return counts;
112
+ } catch {
113
+ return {};
114
+ }
115
+ }
116
+
117
+ // Number of commits reachable from `to` but not from `from` (0 if either ref is unknown).
118
+ async function countCommitsBetween(from, to) {
119
+ try {
120
+ const out = await git.raw(['rev-list', '--count', `${from}..${to}`]);
121
+ return parseInt(out.trim(), 10) || 0;
122
+ } catch {
123
+ return 0;
124
+ }
125
+ }
126
+
59
127
  function escapeRegex(string) {
60
128
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
61
129
  }
@@ -90,6 +158,10 @@ async function validateBranchExists(branchName) {
90
158
  module.exports = {
91
159
  getSourcePrefixes,
92
160
  selectBranchesInteractively,
161
+ getBranchCatalog,
162
+ countBranchesByPrefix,
163
+ countCommitsBetween,
164
+ getLocalBranches,
93
165
  getRemoteBranches,
94
166
  resolveBranchNameForTaskId,
95
167
  searchBranches,
@@ -86,12 +86,12 @@ function escapeRegex(string) {
86
86
  // can't be picked as a plain single-parent diff and must be left out with a warning. Callers that
87
87
  // only read the commit list for text (e.g. an MR description, when nothing is actually being
88
88
  // cherry-picked) pass `excludeMerges: false` so merge commits are neither dropped nor warned about.
89
- async function getCommitsToCherryPick(sourceBranch, taskId, baseBranch = null, { excludeMerges = true } = {}) {
89
+ async function getCommitsToCherryPick(sourceBranch, taskId, baseBranch = null, { excludeMerges = true, sourceRef = `origin/${sourceBranch}` } = {}) {
90
90
  try {
91
91
  await git.fetch();
92
92
 
93
93
  const args = [
94
- `origin/${sourceBranch}`,
94
+ sourceRef,
95
95
  `--grep=^\\[${escapeRegex(taskId)}\\]`,
96
96
  '--extended-regexp',
97
97
  '--regexp-ignore-case'
@@ -147,10 +147,10 @@ const ANY_TASK_TAG = /^\[[A-Z]+-[A-Z]*\d[A-Z0-9]*\]/i;
147
147
  // cherry-picked as-is), titles tagged for another task ("[PB-701] ... PB-700"), and IDs that are
148
148
  // just a prefix of another one (PB-700 vs PB-7000). Commits with no ID at all can't be told apart
149
149
  // from unrelated history (a branch cut from an old base may carry hundreds), so they're not reported.
150
- async function findLooseTaskCommits(sourceBranch, taskId, baseBranch = null) {
150
+ async function findLooseTaskCommits(sourceBranch, taskId, baseBranch = null, { sourceRef = `origin/${sourceBranch}` } = {}) {
151
151
  const id = escapeRegex(taskId);
152
152
  const args = [
153
- `origin/${sourceBranch}`,
153
+ sourceRef,
154
154
  `--grep=(^|[^A-Za-z0-9])${id}([^A-Za-z0-9]|$)`,
155
155
  '--extended-regexp',
156
156
  '--regexp-ignore-case',
@@ -176,14 +176,70 @@ async function findLooseTaskCommits(sourceBranch, taskId, baseBranch = null) {
176
176
 
177
177
  // Returns `commits` in the order they appear on sourceBranch (oldest first), as cherry-picking a
178
178
  // mix of tagged and loose commits must follow the branch's history, not the order they were found.
179
- async function orderCommitsByHistory(sourceBranch, commits, baseBranch = null) {
180
- const args = ['rev-list', '--reverse', `origin/${sourceBranch}`];
179
+ // Commits that aren't on the branch (given by hash from elsewhere) go last, in the order given.
180
+ async function orderCommitsByHistory(sourceBranch, commits, baseBranch = null, { sourceRef = `origin/${sourceBranch}` } = {}) {
181
+ const args = ['rev-list', '--reverse', sourceRef];
181
182
  if (baseBranch) {
182
183
  args.push('--not', `origin/${baseBranch}`);
183
184
  }
184
185
  const order = (await git.raw(args)).trim().split('\n');
185
186
  const position = new Map(order.map((hash, index) => [hash, index]));
186
- return [...commits].sort((a, b) => position.get(a.hash) - position.get(b.hash));
187
+ const rank = commit => (position.has(commit.hash) ? position.get(commit.hash) : order.length);
188
+ return [...commits].sort((a, b) => rank(a) - rank(b));
189
+ }
190
+
191
+ // True if `commit` is reachable from `ref`. `git merge-base --is-ancestor` only answers through its
192
+ // exit code, which simple-git's raw() doesn't surface (it rejects only when git writes to stderr),
193
+ // so this checks that the `ref..commit` range is empty instead.
194
+ async function isAncestor(commit, ref) {
195
+ const out = await git.raw(['rev-list', '--max-count=1', `${ref}..${commit}`]);
196
+ return out.trim() === '';
197
+ }
198
+
199
+ // Resolves commit hashes the user asked to include (task file "[+hash]", --commits, or the prompt)
200
+ // into { hash, message } commits. Returns:
201
+ // commits cherry-pickable ones (full hash + subject), in the order given
202
+ // alreadyOnBase reachable from origin/<baseBranch> already — nothing to pick
203
+ // offBranch subset of `commits` not reachable from sourceRef (the caller asks to confirm)
204
+ // errors unknown/ambiguous hashes and merge commits
205
+ async function resolveExtraCommits(hashes, { sourceRef, baseBranch = null } = {}) {
206
+ const result = { commits: [], alreadyOnBase: [], offBranch: [], errors: [] };
207
+ const seen = new Set();
208
+
209
+ for (const input of hashes) {
210
+ let full;
211
+ try {
212
+ // --quiet: an unknown hash prints nothing and exits non-zero, so `full` stays empty
213
+ full = (await git.raw(['rev-parse', '--verify', '--quiet', `${input}^{commit}`])).trim();
214
+ } catch {
215
+ full = '';
216
+ }
217
+ if (!full) {
218
+ result.errors.push(`${input} is not a commit in this repository, or is ambiguous (fetch, or use a longer hash)`);
219
+ continue;
220
+ }
221
+ if (seen.has(full)) continue;
222
+ seen.add(full);
223
+
224
+ const parents = (await git.raw(['rev-list', '--parents', '--max-count=1', full])).trim().split(/\s+/).length - 1;
225
+ if (parents > 1) {
226
+ result.errors.push(`${input} is a merge commit, which can't be cherry-picked directly`);
227
+ continue;
228
+ }
229
+
230
+ const message = (await git.raw(['log', '-1', '--format=%s', full])).trim();
231
+ const commit = { hash: full, message };
232
+ if (baseBranch && await isAncestor(full, `origin/${baseBranch}`)) {
233
+ result.alreadyOnBase.push(commit);
234
+ continue;
235
+ }
236
+ if (sourceRef && !(await isAncestor(full, sourceRef))) {
237
+ result.offBranch.push(commit);
238
+ }
239
+ result.commits.push(commit);
240
+ }
241
+
242
+ return result;
187
243
  }
188
244
 
189
245
  async function getConflictingFiles() {
@@ -211,6 +267,7 @@ module.exports = {
211
267
  getCommitsToCherryPick,
212
268
  findLooseTaskCommits,
213
269
  orderCommitsByHistory,
270
+ resolveExtraCommits,
214
271
  getConflictingFiles,
215
272
  abortCherryPick
216
273
  };
@@ -265,9 +265,35 @@ function usernamesToIds(usernames, memberList, role) {
265
265
  return ids;
266
266
  }
267
267
 
268
+ // Labels usable on the project's MRs, including the ones inherited from its parent groups
269
+ async function getProjectLabels(config) {
270
+ try {
271
+ const projectId = await getProjectPathId(config);
272
+ const labels = [];
273
+
274
+ for (let page = 1; page <= 50; page++) {
275
+ const batch = await apiRequest(
276
+ config,
277
+ `/projects/${projectId}/labels?include_ancestor_groups=true&per_page=100&page=${page}`
278
+ );
279
+ if (!Array.isArray(batch) || batch.length === 0) {
280
+ break;
281
+ }
282
+ labels.push(...batch.map((l) => ({ name: l.name, description: l.description || '' })));
283
+ if (batch.length < 100) {
284
+ break;
285
+ }
286
+ }
287
+
288
+ return labels;
289
+ } catch (error) {
290
+ throw new GitLabError(`Failed to list GitLab project labels: ${error.message}`);
291
+ }
292
+ }
293
+
268
294
  async function createMergeRequest(
269
295
  config,
270
- { sourceBranch, targetBranch, title, description, reviewers = [], assignees = [], squash = true, removeSourceBranch = true, members = null }
296
+ { sourceBranch, targetBranch, title, description, reviewers = [], assignees = [], labels = [], squash = true, removeSourceBranch = true, members = null }
271
297
  ) {
272
298
  try {
273
299
  const projectId = await getProjectPathId(config);
@@ -293,6 +319,10 @@ async function createMergeRequest(
293
319
  if (assigneeIds.length > 0) {
294
320
  body.assignee_ids = assigneeIds;
295
321
  }
322
+ if (labels.length > 0) {
323
+ // The MR API takes label names as one comma-separated string
324
+ body.labels = labels.join(',');
325
+ }
296
326
 
297
327
  const mr = await apiRequest(config, `/projects/${projectId}/merge_requests`, {
298
328
  method: 'POST',
@@ -316,6 +346,7 @@ module.exports = {
316
346
  checkAuthStatus,
317
347
  ensureAuthenticated,
318
348
  getProjectMembers,
349
+ getProjectLabels,
319
350
  createMergeRequest,
320
351
  getApiBase,
321
352
  getToken,
@@ -36,6 +36,7 @@ async function createMR(config, { sourceBranch, targetBranch, taskId, descriptio
36
36
  description: mrDescription,
37
37
  reviewers,
38
38
  assignees: config.release.defaultAssignees || [],
39
+ labels: config.release.defaultLabels || [],
39
40
  squash: config.release.mrSquash !== false,
40
41
  removeSourceBranch: config.release.mrRemoveSourceBranch !== false,
41
42
  members
package/src/index.js CHANGED
@@ -15,7 +15,15 @@ program
15
15
  .command('release')
16
16
  .description('Start the release process')
17
17
  .option('-f, --file <path>', 'Path to branch list file')
18
- .option('-b, --branches <branches>', 'Comma-separated list of branches')
18
+ .option('-b, --branches <branches>', 'Comma-separated task IDs or branch names, each optionally followed by extra commit hashes in brackets, e.g. "PB-123[abc1234,def5678],PB-124"')
19
+ .option('--local', 'Look up source branches locally first, falling back to origin (default unless git.branchSource is "remote")')
20
+ .option('--remote', 'Look up source branches on origin only')
21
+ .option(
22
+ '--commits <task=hashes>',
23
+ 'Extra commits to cherry-pick for a task, e.g. PB-123=abc1234,def5678 (repeatable) — for commits missing the "[TASK-ID]" tag',
24
+ (value, previous) => previous.concat([value]),
25
+ []
26
+ )
19
27
  .option('-l, --list-branches', 'Skip cherry-pick: create empty release branches from staging, open each MR from the source branch instead, and list the release branches created at the end')
20
28
  .action(async (options) => {
21
29
  try {