release-cherry-pick 0.0.0-stage → 1.0.1
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.
- package/.atl/.skill-registry.cache.json +3 -0
- package/.atl/skill-registry.md +55 -0
- package/.husky/pre-commit +1 -0
- package/CLAUDE.md +74 -0
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/eslint.config.js +34 -0
- package/openspec/changes/archive/.gitkeep +0 -0
- package/openspec/changes/node-cli-release-cherry-pick/.openspec.yaml +2 -0
- package/openspec/changes/node-cli-release-cherry-pick/design.md +126 -0
- package/openspec/changes/node-cli-release-cherry-pick/proposal.md +39 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/branch-selection/spec.md +42 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/cherry-pick-orchestration/spec.md +49 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/cli-core/spec.md +37 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/config-management/spec.md +52 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/documentation-generation/spec.md +38 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/gitlab-integration/spec.md +49 -0
- package/openspec/changes/node-cli-release-cherry-pick/specs/release-summary/spec.md +37 -0
- package/openspec/changes/node-cli-release-cherry-pick/tasks.md +70 -0
- package/openspec/config.yaml +32 -0
- package/openspec/specs/.gitkeep +0 -0
- package/package.json +48 -4
- package/scripts/sandbox/harness.js +130 -0
- package/scripts/sandbox/make-sandbox.sh +90 -0
- package/scripts/sandbox/run-config.js +26 -0
- package/scripts/sandbox/run-release.js +26 -0
- package/scripts/sandbox/test-package.js +571 -0
- package/skills-lock.json +11 -0
- package/src/cli/index.js +13 -0
- package/src/config/ai-providers.js +285 -0
- package/src/config/defaults.js +45 -0
- package/src/config/loader.js +127 -0
- package/src/config/setup.js +463 -0
- package/src/config/validator.js +80 -0
- package/src/doc/agents-generator.js +83 -0
- package/src/doc/rpd-generator.js +87 -0
- package/src/git/branch-parser.js +88 -0
- package/src/git/branch-selector.js +97 -0
- package/src/git/cherry-pick.js +216 -0
- package/src/git/git-auth.js +43 -0
- package/src/git/instance.js +17 -0
- package/src/git/release-branch.js +106 -0
- package/src/git/release-status.js +121 -0
- package/src/git/remote-url.js +34 -0
- package/src/git/repo-state.js +153 -0
- package/src/gitlab/ai-description.js +157 -0
- package/src/gitlab/client.js +324 -0
- package/src/gitlab/mr-creator.js +55 -0
- package/src/gitlab/reviewer-selector.js +52 -0
- package/src/index.js +58 -0
- package/src/report/summary.js +91 -0
- package/src/utils/errors.js +47 -0
- package/src/utils/logger.js +36 -0
- package/src/utils/prompts.js +59 -0
- package/src/utils/secrets.js +24 -0
- package/src/workflow/release.js +464 -0
- package/test-e2e.js +56 -0
|
@@ -0,0 +1,87 @@
|
|
|
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
|
+
|
|
8
|
+
async function generateRpdMd(projectPath, releaseStatus, forceOverwrite = false) {
|
|
9
|
+
const outputPath = path.join(projectPath, 'RPD.md');
|
|
10
|
+
|
|
11
|
+
if (fs.existsSync(outputPath) && !forceOverwrite) {
|
|
12
|
+
const { overwrite } = await inquirer.prompt([
|
|
13
|
+
{
|
|
14
|
+
type: 'confirm',
|
|
15
|
+
name: 'overwrite',
|
|
16
|
+
message: 'RPD.md already exists. Overwrite?',
|
|
17
|
+
default: false
|
|
18
|
+
}
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
if (!overwrite) {
|
|
22
|
+
logger.info('Skipping RPD.md generation');
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const content = generateRpdContent(releaseStatus);
|
|
28
|
+
fs.writeFileSync(outputPath, content, 'utf8');
|
|
29
|
+
logger.success('RPD.md generated successfully');
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function generateRpdContent(releaseStatus) {
|
|
34
|
+
const summary = releaseStatus.getSummary();
|
|
35
|
+
|
|
36
|
+
let content = `# RPD - Release Process Document\n\n`;
|
|
37
|
+
content += `**Date:** ${new Date().toLocaleString('es-ES')}\n\n`;
|
|
38
|
+
|
|
39
|
+
content += `## Summary\n\n`;
|
|
40
|
+
content += `| Metric | Value |\n`;
|
|
41
|
+
content += `|--------|-------|\n`;
|
|
42
|
+
content += `| Total Branches | ${summary.total} |\n`;
|
|
43
|
+
content += `| Successful (PROCEDE) | ${summary.procede} |\n`;
|
|
44
|
+
content += `| Failed (NO PROCEDE) | ${summary.noProcede} |\n\n`;
|
|
45
|
+
|
|
46
|
+
content += `## Release Details\n\n`;
|
|
47
|
+
|
|
48
|
+
for (const result of summary.results) {
|
|
49
|
+
content += `### ${result.taskId}\n\n`;
|
|
50
|
+
content += `- **Branch:** \`${result.branch}\`\n`;
|
|
51
|
+
content += `- **Status:** ${result.status}\n`;
|
|
52
|
+
content += `- **Timestamp:** ${result.timestamp}\n`;
|
|
53
|
+
|
|
54
|
+
if (result.mrLink) {
|
|
55
|
+
content += `- **MR:** [View Merge Request](${result.mrLink})\n`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (result.conflicts.length > 0) {
|
|
59
|
+
content += `- **Conflicting Files:**\n`;
|
|
60
|
+
for (const file of result.conflicts) {
|
|
61
|
+
content += ` - \`${file}\`\n`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
content += `\n`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
content += `## Process Steps\n\n`;
|
|
69
|
+
content += `1. Branch selection (manual or from file)\n`;
|
|
70
|
+
content += `2. Release branch creation from staging\n`;
|
|
71
|
+
content += `3. Cherry-pick commits from source branches\n`;
|
|
72
|
+
content += `4. Conflict detection and resolution\n`;
|
|
73
|
+
content += `5. GitLab MR creation\n`;
|
|
74
|
+
content += `6. Summary generation\n\n`;
|
|
75
|
+
|
|
76
|
+
content += `## Notes\n\n`;
|
|
77
|
+
content += `- All PROCEDE branches have been merged to staging\n`;
|
|
78
|
+
content += `- NO PROCEDE branches require manual conflict resolution\n`;
|
|
79
|
+
content += `- Review MRs before final merge\n`;
|
|
80
|
+
|
|
81
|
+
return content;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = {
|
|
85
|
+
generateRpdMd,
|
|
86
|
+
generateRpdContent
|
|
87
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { AppError } = require('../utils/errors');
|
|
6
|
+
|
|
7
|
+
function parseBranchListFile(filePath) {
|
|
8
|
+
const fullPath = path.resolve(filePath);
|
|
9
|
+
|
|
10
|
+
if (!fs.existsSync(fullPath)) {
|
|
11
|
+
throw new AppError(`Branch list file not found: ${fullPath}`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const content = fs.readFileSync(fullPath, 'utf8');
|
|
15
|
+
const lines = content.split('\n').filter(line => line.trim());
|
|
16
|
+
|
|
17
|
+
const branches = [];
|
|
18
|
+
|
|
19
|
+
for (const line of lines) {
|
|
20
|
+
const parsed = parseBranchLine(line);
|
|
21
|
+
if (parsed) {
|
|
22
|
+
branches.push(parsed);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return branches;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function parseBranchLine(line) {
|
|
30
|
+
// Pattern: *TASK-ID*: Description
|
|
31
|
+
// Example: *PB-I3217*: Al gestionar autos de una póliza...
|
|
32
|
+
const match = line.match(/^\*?([A-Z]+-[A-Z0-9]+)\*?:\s*(.+)$/);
|
|
33
|
+
|
|
34
|
+
if (match) {
|
|
35
|
+
return {
|
|
36
|
+
taskId: match[1],
|
|
37
|
+
description: match[2].trim(),
|
|
38
|
+
raw: line.trim()
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function getBranchNameFromTaskId(taskId, prefix = 'feature/') {
|
|
46
|
+
return `${prefix}${taskId.toLowerCase()}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function stripKnownPrefix(branchName, branchPrefix = {}) {
|
|
50
|
+
for (const prefix of Object.values(branchPrefix)) {
|
|
51
|
+
if (prefix && branchName.startsWith(prefix)) {
|
|
52
|
+
return branchName.slice(prefix.length);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return branchName;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Extracts the task ID from a branch name, e.g. "feature/PB-123-list-user" -> "PB-123".
|
|
59
|
+
// Returns null if the branch name (after stripping a known prefix) doesn't start with a task ID.
|
|
60
|
+
function extractTaskIdFromBranch(branchName, branchPrefix = {}) {
|
|
61
|
+
const match = stripKnownPrefix(branchName, branchPrefix).match(/^([A-Z]+-[A-Z]*\d[A-Z0-9]*)(?=[-_]|$)/i);
|
|
62
|
+
return match ? match[1].toUpperCase() : null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Human-readable description from the part of the branch name after the task ID, e.g.
|
|
66
|
+
// "feature/PB-123-list-user" -> "List user". Falls back to the branch name if nothing follows the ID.
|
|
67
|
+
function describeBranch(branchName, branchPrefix = {}) {
|
|
68
|
+
const words = stripKnownPrefix(branchName, branchPrefix)
|
|
69
|
+
.replace(/^[A-Z]+-[A-Z]*\d[A-Z0-9]*(?=[-_]|$)/i, '')
|
|
70
|
+
.split(/[-_]+/)
|
|
71
|
+
.filter(Boolean)
|
|
72
|
+
.join(' ');
|
|
73
|
+
return words ? words.charAt(0).toUpperCase() + words.slice(1) : branchName;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// True if the value looks like a bare task ID ("PB-I3217") rather than a branch name.
|
|
77
|
+
function isTaskId(value) {
|
|
78
|
+
return /^[A-Z]+-[A-Z]*\d[A-Z0-9]*$/i.test(value);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = {
|
|
82
|
+
parseBranchListFile,
|
|
83
|
+
parseBranchLine,
|
|
84
|
+
getBranchNameFromTaskId,
|
|
85
|
+
extractTaskIdFromBranch,
|
|
86
|
+
describeBranch,
|
|
87
|
+
isTaskId
|
|
88
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const inquirer = require('inquirer');
|
|
4
|
+
const { createGit } = require('./instance');
|
|
5
|
+
const logger = require('../utils/logger');
|
|
6
|
+
const { searchableCheckbox } = require('../utils/prompts');
|
|
7
|
+
const { defaultConfig } = require('../config/defaults');
|
|
8
|
+
|
|
9
|
+
const git = createGit();
|
|
10
|
+
|
|
11
|
+
// Prefixes of the branches a release can be cut from (every configured prefix except release)
|
|
12
|
+
// (falls back to the defaults when none are configured).
|
|
13
|
+
function getSourcePrefixes(branchPrefix) {
|
|
14
|
+
const prefixes = Object.entries(branchPrefix || {})
|
|
15
|
+
.filter(([type, prefix]) => type !== 'release' && prefix)
|
|
16
|
+
.map(([, prefix]) => prefix);
|
|
17
|
+
return prefixes.length > 0 ? prefixes : getSourcePrefixes(defaultConfig.git.branchPrefix);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function selectBranchesInteractively(branchPrefix) {
|
|
21
|
+
logger.header('Branch Selection');
|
|
22
|
+
|
|
23
|
+
const branches = await getRemoteBranches(branchPrefix);
|
|
24
|
+
|
|
25
|
+
if (branches.length === 0) {
|
|
26
|
+
logger.warn('No feature or hotfix branches found');
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const { selectedBranches } = await inquirer.prompt([
|
|
31
|
+
searchableCheckbox({
|
|
32
|
+
name: 'selectedBranches',
|
|
33
|
+
message: 'Select branches for release (type to search):',
|
|
34
|
+
pageSize: 15
|
|
35
|
+
}, branches)
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
return selectedBranches;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function getRemoteBranches(branchPrefix) {
|
|
42
|
+
const prefixes = getSourcePrefixes(branchPrefix);
|
|
43
|
+
try {
|
|
44
|
+
await git.fetch();
|
|
45
|
+
const result = await git.branch(['-r']);
|
|
46
|
+
const branches = result.all
|
|
47
|
+
.filter(branch => branch.startsWith('origin/'))
|
|
48
|
+
.map(branch => branch.replace('origin/', ''))
|
|
49
|
+
.filter(branch => prefixes.some(prefix => branch.startsWith(prefix)))
|
|
50
|
+
.sort();
|
|
51
|
+
|
|
52
|
+
return branches;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
logger.error(`Error getting branches: ${error.message}`);
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function escapeRegex(string) {
|
|
60
|
+
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Finds real remote branch(es) whose feature/hotfix name starts with the given task ID
|
|
64
|
+
// (case-insensitive), e.g. taskId "PB-I3245" matches "hotfix/PB-I3245-favicon-incorrect-payments".
|
|
65
|
+
async function resolveBranchNameForTaskId(taskId, branches = null, branchPrefix) {
|
|
66
|
+
const list = branches || (await getRemoteBranches(branchPrefix));
|
|
67
|
+
const prefixes = getSourcePrefixes(branchPrefix).map(escapeRegex).join('|');
|
|
68
|
+
const re = new RegExp(`^(?:${prefixes})${escapeRegex(taskId)}(?:[-_]|$)`, 'i');
|
|
69
|
+
return list.filter(branch => re.test(branch));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function searchBranches(searchTerm, branchPrefix) {
|
|
73
|
+
const branches = await getRemoteBranches(branchPrefix);
|
|
74
|
+
return branches.filter(branch =>
|
|
75
|
+
branch.toLowerCase().includes(searchTerm.toLowerCase())
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function validateBranchExists(branchName) {
|
|
80
|
+
try {
|
|
81
|
+
const result = await git.branch(['-r']);
|
|
82
|
+
return result.all.some(branch =>
|
|
83
|
+
branch === `origin/${branchName}` || branch === branchName
|
|
84
|
+
);
|
|
85
|
+
} catch {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = {
|
|
91
|
+
getSourcePrefixes,
|
|
92
|
+
selectBranchesInteractively,
|
|
93
|
+
getRemoteBranches,
|
|
94
|
+
resolveBranchNameForTaskId,
|
|
95
|
+
searchBranches,
|
|
96
|
+
validateBranchExists
|
|
97
|
+
};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createGit } = require('./instance');
|
|
4
|
+
const logger = require('../utils/logger');
|
|
5
|
+
const { GitError } = require('../utils/errors');
|
|
6
|
+
|
|
7
|
+
const git = createGit();
|
|
8
|
+
|
|
9
|
+
// Cherry-picks `commits` (in order) onto the current branch; when not given, the ones tagged
|
|
10
|
+
// "[taskId]" on sourceBranch that aren't on baseBranch (see getCommitsToCherryPick).
|
|
11
|
+
async function cherryPickCommits(sourceBranch, taskId, baseBranch = null, commitsToPick = null) {
|
|
12
|
+
logger.info(`Cherry-picking from ${sourceBranch}`);
|
|
13
|
+
|
|
14
|
+
try {
|
|
15
|
+
const commits = commitsToPick || await getCommitsToCherryPick(sourceBranch, taskId, baseBranch);
|
|
16
|
+
|
|
17
|
+
if (commits.length === 0) {
|
|
18
|
+
logger.warn(`No commits tagged "[${taskId}]" found on ${sourceBranch} that aren't already on ${baseBranch || 'the base branch'}`);
|
|
19
|
+
return { success: true, commitsCherryPicked: 0, commitsAlreadyApplied: 0, conflicts: [], commits: [] };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
logger.info(`Found ${commits.length} commits to cherry-pick`);
|
|
23
|
+
|
|
24
|
+
const conflicts = [];
|
|
25
|
+
let pickedCount = 0;
|
|
26
|
+
let emptyCount = 0;
|
|
27
|
+
|
|
28
|
+
for (const commit of commits) {
|
|
29
|
+
try {
|
|
30
|
+
// simple-git has no dedicated cherryPick() method; use raw() for the actual git command.
|
|
31
|
+
await git.raw(['cherry-pick', commit.hash]);
|
|
32
|
+
pickedCount++;
|
|
33
|
+
logger.info(`Cherry-picked: ${commit.message.substring(0, 50)}...`);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
const conflictedFiles = await getConflictingFiles();
|
|
36
|
+
|
|
37
|
+
if (error.message.includes('is now empty') && conflictedFiles.length === 0) {
|
|
38
|
+
// Not a real conflict: the patch applied cleanly but produced no net change, meaning
|
|
39
|
+
// this commit's changes are already present in the current tree (e.g. the same fix
|
|
40
|
+
// landed some other way). Skip it and keep going — nothing to resolve here.
|
|
41
|
+
logger.warn(`Commit ${commit.hash} is already applied (empty diff) — skipping: ${commit.message.substring(0, 60)}`);
|
|
42
|
+
await git.raw(['cherry-pick', '--skip']);
|
|
43
|
+
emptyCount++;
|
|
44
|
+
} else if (error.message.includes('CONFLICT') || conflictedFiles.length > 0) {
|
|
45
|
+
conflicts.push({
|
|
46
|
+
commit: commit.hash,
|
|
47
|
+
message: commit.message,
|
|
48
|
+
files: conflictedFiles
|
|
49
|
+
});
|
|
50
|
+
logger.error(`Conflict detected in commit: ${commit.hash}`);
|
|
51
|
+
|
|
52
|
+
// Abort the cherry-pick and stop touching this branch further
|
|
53
|
+
await git.raw(['cherry-pick', '--abort']);
|
|
54
|
+
break;
|
|
55
|
+
} else {
|
|
56
|
+
throw new GitError(`Cherry-pick failed: ${error.message}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
success: conflicts.length === 0,
|
|
63
|
+
commitsCherryPicked: pickedCount,
|
|
64
|
+
commitsAlreadyApplied: emptyCount,
|
|
65
|
+
conflicts,
|
|
66
|
+
commits: conflicts.length === 0 ? commits : []
|
|
67
|
+
};
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new GitError(`Cherry-pick operation failed: ${error.message}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function escapeRegex(string) {
|
|
74
|
+
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Selects only the commits that belong to this specific task, identified by the team's own
|
|
78
|
+
// "[TASK-ID] description" commit message convention — NOT by diffing sourceBranch against a
|
|
79
|
+
// base branch. A plain range diff (e.g. staging..sourceBranch) is unreliable in practice:
|
|
80
|
+
// branches are often cut from a different/older base than the current staging, so the range
|
|
81
|
+
// can include hundreds of unrelated commits, or (if the branch is already absorbed into e.g.
|
|
82
|
+
// develop) miss the target commit entirely. Matching by task-id tag, restricted to commits not
|
|
83
|
+
// already reachable from baseBranch, reliably isolates just this task's own commit(s) regardless
|
|
84
|
+
// of the branch's real topology.
|
|
85
|
+
// `excludeMerges` defaults to true for the real cherry-pick path, where a tagged merge commit
|
|
86
|
+
// can't be picked as a plain single-parent diff and must be left out with a warning. Callers that
|
|
87
|
+
// only read the commit list for text (e.g. an MR description, when nothing is actually being
|
|
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 } = {}) {
|
|
90
|
+
try {
|
|
91
|
+
await git.fetch();
|
|
92
|
+
|
|
93
|
+
const args = [
|
|
94
|
+
`origin/${sourceBranch}`,
|
|
95
|
+
`--grep=^\\[${escapeRegex(taskId)}\\]`,
|
|
96
|
+
'--extended-regexp',
|
|
97
|
+
'--regexp-ignore-case'
|
|
98
|
+
];
|
|
99
|
+
if (baseBranch) {
|
|
100
|
+
args.push('--not', `origin/${baseBranch}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// git's --grep matches any line of the message, so a commit whose body (not title) has a line
|
|
104
|
+
// starting with "[TASK-ID]" would match too; keep only the ones tagged in the title
|
|
105
|
+
// (simple-git's `message` is the subject line).
|
|
106
|
+
const tagged = taggedSubjectRegex(taskId);
|
|
107
|
+
|
|
108
|
+
if (excludeMerges) {
|
|
109
|
+
// A merge commit tagged "[TASK-ID] ..." (e.g. the merge GitLab creates for the MR itself)
|
|
110
|
+
// can't be cherry-picked as a plain single-parent diff — `git cherry-pick` requires an
|
|
111
|
+
// explicit `-m <parent>` for it, and blindly picking "the first parent" would silently apply
|
|
112
|
+
// the wrong diff. Warn about it and leave it out rather than failing the whole branch.
|
|
113
|
+
const merges = await git.log([...args, '--merges', '--reverse']);
|
|
114
|
+
const mergeMatches = merges.all.filter(commit => tagged.test(commit.message));
|
|
115
|
+
if (mergeMatches.length > 0) {
|
|
116
|
+
const list = mergeMatches.map(c => `${c.hash.slice(0, 8)} ${c.message}`).join('; ');
|
|
117
|
+
logger.warn(`${mergeMatches.length} merge commit(s) on ${sourceBranch} are tagged "[${taskId}] ..." but can't be cherry-picked directly (a merge needs "-m <parent>") — skipped: ${list}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// git log lists newest-first by default; --reverse gives chronological (oldest-first)
|
|
122
|
+
// order, which is required for cherry-picking a sequence of dependent commits correctly.
|
|
123
|
+
const log = await git.log([...args, ...(excludeMerges ? ['--no-merges'] : []), '--reverse']);
|
|
124
|
+
return log.all
|
|
125
|
+
.filter(commit => tagged.test(commit.message))
|
|
126
|
+
.map(commit => ({
|
|
127
|
+
hash: commit.hash,
|
|
128
|
+
message: commit.message,
|
|
129
|
+
date: commit.date
|
|
130
|
+
}));
|
|
131
|
+
} catch (error) {
|
|
132
|
+
throw new GitError(`Failed to get commits: ${error.message}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Title follows the convention for this task: "[TASK-ID] ..." (case-insensitive)
|
|
137
|
+
function taggedSubjectRegex(taskId) {
|
|
138
|
+
return new RegExp(`^\\[${escapeRegex(taskId)}\\]`, 'i');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Title follows the convention for *some* task, e.g. "[PB-701] ..."
|
|
142
|
+
const ANY_TASK_TAG = /^\[[A-Z]+-[A-Z]*\d[A-Z0-9]*\]/i;
|
|
143
|
+
|
|
144
|
+
// Commits on sourceBranch (not yet on baseBranch) whose message mentions taskId without following the
|
|
145
|
+
// "[TASK-ID] ..." convention — e.g. "PB-700: fix", "(PB-700) fix", "fix PB-700" — so they'd be left
|
|
146
|
+
// out of the release silently. Excluded: merge commits (they mention branch names and can't be
|
|
147
|
+
// cherry-picked as-is), titles tagged for another task ("[PB-701] ... PB-700"), and IDs that are
|
|
148
|
+
// just a prefix of another one (PB-700 vs PB-7000). Commits with no ID at all can't be told apart
|
|
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) {
|
|
151
|
+
const id = escapeRegex(taskId);
|
|
152
|
+
const args = [
|
|
153
|
+
`origin/${sourceBranch}`,
|
|
154
|
+
`--grep=(^|[^A-Za-z0-9])${id}([^A-Za-z0-9]|$)`,
|
|
155
|
+
'--extended-regexp',
|
|
156
|
+
'--regexp-ignore-case',
|
|
157
|
+
'--no-merges'
|
|
158
|
+
];
|
|
159
|
+
if (baseBranch) {
|
|
160
|
+
args.push('--not', `origin/${baseBranch}`);
|
|
161
|
+
}
|
|
162
|
+
args.push('--reverse');
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const log = await git.log(args);
|
|
166
|
+
const mentions = new RegExp(`(^|[^A-Za-z0-9])${id}(?![A-Za-z0-9])`, 'i');
|
|
167
|
+
// Title or body (a "[TASK-ID] ..." line only in the body doesn't count as tagged, so it's loose
|
|
168
|
+
// too); simple-git splits the subject into `message` and the rest into `body`
|
|
169
|
+
return log.all
|
|
170
|
+
.filter(commit => (mentions.test(commit.message) || mentions.test(commit.body || '')) && !ANY_TASK_TAG.test(commit.message))
|
|
171
|
+
.map(commit => ({ hash: commit.hash, message: commit.message, date: commit.date }));
|
|
172
|
+
} catch (error) {
|
|
173
|
+
throw new GitError(`Failed to look for commits mentioning ${taskId}: ${error.message}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Returns `commits` in the order they appear on sourceBranch (oldest first), as cherry-picking a
|
|
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}`];
|
|
181
|
+
if (baseBranch) {
|
|
182
|
+
args.push('--not', `origin/${baseBranch}`);
|
|
183
|
+
}
|
|
184
|
+
const order = (await git.raw(args)).trim().split('\n');
|
|
185
|
+
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
|
+
}
|
|
188
|
+
|
|
189
|
+
async function getConflictingFiles() {
|
|
190
|
+
try {
|
|
191
|
+
const status = await git.status();
|
|
192
|
+
return status.conflicted;
|
|
193
|
+
} catch {
|
|
194
|
+
return [];
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function abortCherryPick() {
|
|
199
|
+
try {
|
|
200
|
+
await git.raw(['cherry-pick', '--abort']);
|
|
201
|
+
logger.info('Cherry-pick aborted');
|
|
202
|
+
return true;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
logger.error(`Failed to abort cherry-pick: ${error.message}`);
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
module.exports = {
|
|
210
|
+
cherryPickCommits,
|
|
211
|
+
getCommitsToCherryPick,
|
|
212
|
+
findLooseTaskCommits,
|
|
213
|
+
orderCommitsByHistory,
|
|
214
|
+
getConflictingFiles,
|
|
215
|
+
abortCherryPick
|
|
216
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createGit } = require('./instance');
|
|
4
|
+
|
|
5
|
+
function getToken(config) {
|
|
6
|
+
return (config && config.gitlab && config.gitlab.token) || process.env.GITLAB_TOKEN || '';
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// Makes every git subprocess for the rest of this process authenticate to the `origin` remote
|
|
10
|
+
// with the configured GitLab token, so `git fetch`/`pull`/`push` over HTTPS don't fall back to
|
|
11
|
+
// git's own interactive username/password prompt — the whole point of configuring a token is to
|
|
12
|
+
// not be asked for credentials again. SSH origins already authenticate via the user's key and are
|
|
13
|
+
// left untouched. The header is injected only for this process, through env vars git itself reads
|
|
14
|
+
// (GIT_CONFIG_COUNT/KEY/VALUE, supported since Git 2.31) — it is never written to .git/config, so
|
|
15
|
+
// the token never lingers in the target repo once the CLI exits. simple-git v4 strips ambient GIT_*
|
|
16
|
+
// variables from the child process, so those three are allow-listed in ./instance.js — without it
|
|
17
|
+
// this header would be dropped silently. GitLab's git-over-HTTP Basic auth validates the token
|
|
18
|
+
// itself and doesn't check the username, so any non-blank placeholder works.
|
|
19
|
+
// No-op without a token configured, or when origin isn't http(s).
|
|
20
|
+
async function configureGitCredentials(config) {
|
|
21
|
+
const token = getToken(config);
|
|
22
|
+
if (!token) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let remoteUrl;
|
|
27
|
+
try {
|
|
28
|
+
remoteUrl = (await createGit().raw(['remote', 'get-url', 'origin'])).trim();
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!/^https?:\/\//i.test(remoteUrl)) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const basicAuth = Buffer.from(`oauth2:${token}`).toString('base64');
|
|
38
|
+
process.env.GIT_CONFIG_COUNT = '1';
|
|
39
|
+
process.env.GIT_CONFIG_KEY_0 = 'http.extraheader';
|
|
40
|
+
process.env.GIT_CONFIG_VALUE_0 = `Authorization: Basic ${basicAuth}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { configureGitCredentials, getToken };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { simpleGit } = require('simple-git');
|
|
4
|
+
|
|
5
|
+
// simple-git v4 strips ambient `GIT_*` variables from the environment of the git child process
|
|
6
|
+
// (they can change which program git runs), so they must be allowed explicitly. git-auth.js hands
|
|
7
|
+
// the GitLab token to git through GIT_CONFIG_COUNT/KEY/VALUE — injected per process, never written
|
|
8
|
+
// to disk — and those three would otherwise be dropped silently, sending every HTTPS fetch/pull/push
|
|
9
|
+
// back to git's interactive username/password prompt.
|
|
10
|
+
const ALLOWED_ENVIRONMENT = ['GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0'];
|
|
11
|
+
|
|
12
|
+
// Every simple-git instance in the app is created here so the allow-list above always applies.
|
|
13
|
+
function createGit() {
|
|
14
|
+
return simpleGit({ allowEnvironment: ALLOWED_ENVIRONMENT });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
module.exports = { createGit, ALLOWED_ENVIRONMENT };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createGit } = require('./instance');
|
|
4
|
+
const logger = require('../utils/logger');
|
|
5
|
+
const { GitError } = require('../utils/errors');
|
|
6
|
+
|
|
7
|
+
const git = createGit();
|
|
8
|
+
|
|
9
|
+
function buildReleaseBranchName(sourceBranch, branchPrefix = {}) {
|
|
10
|
+
let name = sourceBranch;
|
|
11
|
+
for (const prefix of Object.values(branchPrefix)) {
|
|
12
|
+
if (prefix && prefix !== branchPrefix.release && name.startsWith(prefix)) {
|
|
13
|
+
name = name.slice(prefix.length);
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return `${branchPrefix.release || 'release/'}${name}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function createReleaseBranch(sourceBranch, stagingBranch = 'staging', branchPrefix = {}) {
|
|
21
|
+
const releaseBranchName = buildReleaseBranchName(sourceBranch, branchPrefix);
|
|
22
|
+
|
|
23
|
+
logger.info(`Creating release branch: ${releaseBranchName}`);
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
// Fetch latest changes
|
|
27
|
+
await git.fetch();
|
|
28
|
+
|
|
29
|
+
// Check if release branch already exists (exact name match: a substring check would make
|
|
30
|
+
// e.g. release/PB-12 look taken just because release/PB-123 exists)
|
|
31
|
+
const remoteBranches = await git.branch(['-r']);
|
|
32
|
+
const existsOnOrigin = remoteBranches.all.includes(`origin/${releaseBranchName}`);
|
|
33
|
+
|
|
34
|
+
if (existsOnOrigin) {
|
|
35
|
+
// Deleting/overwriting a remote branch here would be a destructive action on shared
|
|
36
|
+
// state (it may already have commits or an open MR) — never do it automatically, even
|
|
37
|
+
// behind a confirmation prompt. Report it and let the user resolve it manually.
|
|
38
|
+
logger.error(`Release branch ${releaseBranchName} already exists on origin. Resolve this manually (delete it, or pick a different branch) and re-run.`);
|
|
39
|
+
return {
|
|
40
|
+
success: false,
|
|
41
|
+
branch: releaseBranchName,
|
|
42
|
+
reason: `Release branch ${releaseBranchName} already exists on origin — needs manual decision by the user`
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A local-only leftover (e.g. from an earlier run, possibly with manual work on it) is not
|
|
47
|
+
// deleted automatically either — same reasoning, and it's the user's work to decide about.
|
|
48
|
+
const localBranches = await git.branchLocal();
|
|
49
|
+
if (localBranches.all.includes(releaseBranchName)) {
|
|
50
|
+
logger.error(`Release branch ${releaseBranchName} already exists locally. If it's not needed, delete it with \`git branch -D ${releaseBranchName}\` and re-run.`);
|
|
51
|
+
return {
|
|
52
|
+
success: false,
|
|
53
|
+
branch: releaseBranchName,
|
|
54
|
+
reason: `Release branch ${releaseBranchName} already exists locally — delete it (\`git branch -D ${releaseBranchName}\`) if it's not needed and re-run`
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Checkout staging and create release branch
|
|
59
|
+
await git.checkout(stagingBranch);
|
|
60
|
+
await git.pull('origin', stagingBranch);
|
|
61
|
+
await git.checkoutLocalBranch(releaseBranchName);
|
|
62
|
+
|
|
63
|
+
logger.success(`Release branch ${releaseBranchName} created from ${stagingBranch}`);
|
|
64
|
+
|
|
65
|
+
return { success: true, created: true, branch: releaseBranchName };
|
|
66
|
+
} catch (error) {
|
|
67
|
+
throw new GitError(`Failed to create release branch: ${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function checkoutBranch(branchName) {
|
|
72
|
+
try {
|
|
73
|
+
await git.checkout(branchName);
|
|
74
|
+
logger.info(`Checked out branch: ${branchName}`);
|
|
75
|
+
return true;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
throw new GitError(`Failed to checkout branch: ${error.message}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function getLatestCommitHash(branchName) {
|
|
82
|
+
try {
|
|
83
|
+
const result = await git.log([branchName, '-1']);
|
|
84
|
+
return result.latest.hash;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
throw new GitError(`Failed to get commit hash: ${error.message}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function pushBranch(branchName) {
|
|
91
|
+
try {
|
|
92
|
+
await git.push(['-u', 'origin', branchName]);
|
|
93
|
+
logger.success(`Pushed ${branchName} to origin`);
|
|
94
|
+
return true;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw new GitError(`Failed to push branch ${branchName}: ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = {
|
|
101
|
+
buildReleaseBranchName,
|
|
102
|
+
createReleaseBranch,
|
|
103
|
+
checkoutBranch,
|
|
104
|
+
getLatestCommitHash,
|
|
105
|
+
pushBranch
|
|
106
|
+
};
|