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.
- package/LICENSE +21 -0
- package/README.md +186 -2
- package/package.json +64 -4
- 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 +41 -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
|
@@ -0,0 +1,83 @@
|
|
|
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 generateAgentsMd(projectPath, forceOverwrite = false) {
|
|
9
|
+
const outputPath = path.join(projectPath, 'AGENTS.md');
|
|
10
|
+
|
|
11
|
+
if (fs.existsSync(outputPath) && !forceOverwrite) {
|
|
12
|
+
const { overwrite } = await inquirer.prompt([
|
|
13
|
+
{
|
|
14
|
+
type: 'confirm',
|
|
15
|
+
name: 'overwrite',
|
|
16
|
+
message: 'AGENTS.md already exists. Overwrite?',
|
|
17
|
+
default: false
|
|
18
|
+
}
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
if (!overwrite) {
|
|
22
|
+
logger.info('Skipping AGENTS.md generation');
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const content = generateAgentsContent();
|
|
28
|
+
fs.writeFileSync(outputPath, content, 'utf8');
|
|
29
|
+
logger.success('AGENTS.md generated successfully');
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function generateAgentsContent() {
|
|
34
|
+
return `# AGENTS.md - Project Guidelines
|
|
35
|
+
|
|
36
|
+
## Project Overview
|
|
37
|
+
|
|
38
|
+
This project uses release-cherry-pick CLI tool for automating release processes.
|
|
39
|
+
|
|
40
|
+
## Architecture
|
|
41
|
+
|
|
42
|
+
- \`src/cli/\` - CLI entry points and commands
|
|
43
|
+
- \`src/config/\` - Configuration management
|
|
44
|
+
- \`src/git/\` - Git operations (branching, cherry-pick)
|
|
45
|
+
- \`src/gitlab/\` - GitLab API integration
|
|
46
|
+
- \`src/utils/\` - Utility functions and helpers
|
|
47
|
+
- \`src/report/\` - Report generation
|
|
48
|
+
- \`src/doc/\` - Documentation generation
|
|
49
|
+
|
|
50
|
+
## Development Guidelines
|
|
51
|
+
|
|
52
|
+
### Code Style
|
|
53
|
+
- Use CommonJS modules (require/module.exports)
|
|
54
|
+
- Follow ESLint recommended rules
|
|
55
|
+
- Use async/await for asynchronous operations
|
|
56
|
+
- Handle errors gracefully with custom error classes
|
|
57
|
+
|
|
58
|
+
### Git Workflow
|
|
59
|
+
- Feature branches: \`feature/*\`
|
|
60
|
+
- Hotfix branches: \`hotfix/*\`
|
|
61
|
+
- Release branches: \`release/*\`
|
|
62
|
+
|
|
63
|
+
### Testing
|
|
64
|
+
- Run tests with \`npm test\`
|
|
65
|
+
- Test configuration changes in isolation
|
|
66
|
+
|
|
67
|
+
## Configuration
|
|
68
|
+
|
|
69
|
+
The tool keeps its configuration outside the project, in \`~/.release-cherry-pick/<project>.json\` (it may contain API keys).
|
|
70
|
+
See \`src/config/defaults.js\` for default values.
|
|
71
|
+
|
|
72
|
+
## Commands
|
|
73
|
+
|
|
74
|
+
- \`release-cherry-pick release\` - Start release process
|
|
75
|
+
- \`release-cherry-pick config\` - Configure settings
|
|
76
|
+
- \`release-cherry-pick --help\` - Show help
|
|
77
|
+
`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = {
|
|
81
|
+
generateAgentsMd,
|
|
82
|
+
generateAgentsContent
|
|
83
|
+
};
|
|
@@ -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 simpleGit = require('simple-git');
|
|
5
|
+
const logger = require('../utils/logger');
|
|
6
|
+
const { searchableCheckbox } = require('../utils/prompts');
|
|
7
|
+
const { defaultConfig } = require('../config/defaults');
|
|
8
|
+
|
|
9
|
+
const git = simpleGit();
|
|
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 simpleGit = require('simple-git');
|
|
4
|
+
const logger = require('../utils/logger');
|
|
5
|
+
const { GitError } = require('../utils/errors');
|
|
6
|
+
|
|
7
|
+
const git = simpleGit();
|
|
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,41 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const simpleGit = require('simple-git');
|
|
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. GitLab's git-over-HTTP Basic auth
|
|
16
|
+
// validates the token itself and doesn't check the username, so any non-blank placeholder works.
|
|
17
|
+
// No-op without a token configured, or when origin isn't http(s).
|
|
18
|
+
async function configureGitCredentials(config) {
|
|
19
|
+
const token = getToken(config);
|
|
20
|
+
if (!token) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let remoteUrl;
|
|
25
|
+
try {
|
|
26
|
+
remoteUrl = (await simpleGit().raw(['remote', 'get-url', 'origin'])).trim();
|
|
27
|
+
} catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (!/^https?:\/\//i.test(remoteUrl)) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const basicAuth = Buffer.from(`oauth2:${token}`).toString('base64');
|
|
36
|
+
process.env.GIT_CONFIG_COUNT = '1';
|
|
37
|
+
process.env.GIT_CONFIG_KEY_0 = 'http.extraheader';
|
|
38
|
+
process.env.GIT_CONFIG_VALUE_0 = `Authorization: Basic ${basicAuth}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { configureGitCredentials, getToken };
|