-
Notifications
You must be signed in to change notification settings - Fork 1
278 lines (245 loc) · 10.4 KB
/
Copy pathrelease-on-merge.yml
File metadata and controls
278 lines (245 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
name: Create Tag and Release on Merge
# This workflow creates a tag and GitHub Release when a release PR is merged to main
# It can also be triggered manually after a merge if the PR title was incorrect.
on:
pull_request:
types: [closed]
branches:
- main
workflow_dispatch:
jobs:
create-tag-and-release:
if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && startsWith(github.event.pull_request.title, 'release:'))
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: read
steps:
- name: Checkout main
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: main
- name: Checkout selected ref
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
- name: Enable Corepack
run: corepack enable
- name: Install dependencies
run: yarn install --immutable
- name: Extract version from package.json
id: version
run: |
VERSION=$(node -p "require('./package.json').version")
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "tag=v$VERSION" >> $GITHUB_OUTPUT
echo "✅ Detected version: $VERSION"
- name: Check if tag already exists
id: check-tag
run: |
TAG_NAME="${{ steps.version.outputs.tag }}"
if git rev-parse "$TAG_NAME" >/dev/null 2>&1; then
echo "exists=true" >> $GITHUB_OUTPUT
echo "⚠️ Tag $TAG_NAME already exists locally"
else
echo "exists=false" >> $GITHUB_OUTPUT
echo "✅ Tag $TAG_NAME does not exist, will create"
fi
- name: Create Git Tag
if: steps.check-tag.outputs.exists == 'false'
run: |
TAG_NAME="${{ steps.version.outputs.tag }}"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "$TAG_NAME" -m "Release $TAG_NAME"
git push origin "$TAG_NAME"
echo "✅ Tag $TAG_NAME created and pushed"
- name: Generate and Create GitHub Release
uses: actions/github-script@v7
with:
script: |
const { execSync } = require('child_process');
const fs = require('fs');
// Get version from package.json
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
const version = packageJson.version;
const tagName = `v${version}`;
console.log(`📦 Creating release for tag: ${tagName}`);
// Check if release already exists
try {
const existingRelease = await github.rest.repos.getReleaseByTag({
owner: context.repo.owner,
repo: context.repo.repo,
tag: tagName
});
console.log(`⚠️ Release ${tagName} already exists!`);
console.log(`Release URL: ${existingRelease.data.html_url}`);
return;
} catch (error) {
if (error.status !== 404) {
throw error;
}
console.log(`✅ No existing release found for ${tagName}, proceeding...`);
}
// Get previous tag
const { data: tags } = await github.rest.repos.listTags({
owner: context.repo.owner,
repo: context.repo.repo,
per_page: 10,
});
let previousTagName = '';
for (const tag of tags) {
if (tag.name !== tagName) {
previousTagName = tag.name;
break;
}
}
console.log(`Generating release notes from ${previousTagName || 'start'} to ${tagName}`);
// Get commits between tags
let commits = [];
try {
const { data: comparison } = await github.rest.repos.compareCommits({
owner: context.repo.owner,
repo: context.repo.repo,
base: previousTagName || 'HEAD~50',
head: tagName,
});
commits = comparison.commits;
console.log(`Found ${commits.length} commits between ${previousTagName || 'start'} and ${tagName}`);
} catch (error) {
console.log(`Could not compare commits: ${error.message}`);
commits = [];
}
// Get PRs for commits
const prMap = new Map();
for (const commit of commits) {
try {
const { data: prs } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner: context.repo.owner,
repo: context.repo.repo,
commit_sha: commit.sha,
});
for (const pr of prs) {
if (pr.merged_at &&
!prMap.has(pr.number) &&
!pr.title.toLowerCase().includes('release:')) {
prMap.set(pr.number, pr);
}
}
} catch (error) {
console.log(`Could not get PRs for commit ${commit.sha.substring(0, 7)}:`, error.message);
}
}
const prs = Array.from(prMap.values());
console.log(`Found ${prs.length} merged PRs between tags`);
// Categorize PRs by labels
const breaking = [];
const features = [];
const bugs = [];
const improvements = [];
const docs = [];
const dependencies = [];
const chores = [];
const other = [];
prs.forEach(pr => {
const labels = pr.labels.map(l => l.name);
const prLine = `- ${pr.title} (#${pr.number}) @${pr.user.login}`;
if (labels.includes('breaking')) {
breaking.push(prLine);
} else if (labels.includes('type: feature')) {
features.push(prLine);
} else if (labels.includes('type: bug')) {
bugs.push(prLine);
} else if (labels.includes('type: improvement')) {
improvements.push(prLine);
} else if (labels.includes('type: docs')) {
docs.push(prLine);
} else if (labels.includes('dependencies')) {
dependencies.push(prLine);
} else if (labels.includes('type: chore')) {
chores.push(prLine);
} else {
other.push(prLine);
}
});
// Build release notes
let releaseNotes = ``;
// Get CHANGELOG.md content for this version
let changelogContent = '';
try {
const changelogPath = './CHANGELOG.md';
if (fs.existsSync(changelogPath)) {
const changelogText = fs.readFileSync(changelogPath, 'utf8');
const versionNumber = version;
const escapedVersion = versionNumber.replace(/\./g, '\\.');
const versionRegex = new RegExp(`##\\s+${escapedVersion}\\s*\\n([\\s\\S]*?)(?=\\n##|$)`);
const match = changelogText.match(versionRegex);
if (match && match[1]) {
changelogContent = match[1].trim();
console.log(`✅ Found CHANGELOG.md content for version ${versionNumber}`);
}
}
} catch (error) {
console.log(`Could not read CHANGELOG.md: ${error.message}`);
}
// Use CHANGELOG.md if available
if (changelogContent) {
releaseNotes += changelogContent + '\n\n';
releaseNotes += `---\n\n`;
releaseNotes += `## Pull Requests\n\n`;
} else {
if (prs.length > 0) {
const totalPRs = prs.length;
releaseNotes += `This release includes ${totalPRs} ${totalPRs === 1 ? 'change' : 'changes'}.\n\n`;
}
}
if (breaking.length > 0) {
releaseNotes += `### Breaking Changes\n${breaking.join('\n')}\n\n`;
}
if (features.length > 0) {
releaseNotes += `### New Features\n${features.join('\n')}\n\n`;
}
if (bugs.length > 0) {
releaseNotes += `### Bug Fixes\n${bugs.join('\n')}\n\n`;
}
if (improvements.length > 0) {
releaseNotes += `### Improvements\n${improvements.join('\n')}\n\n`;
}
if (docs.length > 0) {
releaseNotes += `### Documentation\n${docs.join('\n')}\n\n`;
}
if (dependencies.length > 0) {
releaseNotes += `### Dependencies\n${dependencies.join('\n')}\n\n`;
}
if (chores.length > 0) {
releaseNotes += `### Chores\n${chores.join('\n')}\n\n`;
}
if (other.length > 0) {
releaseNotes += `### Other Changes\n${other.join('\n')}\n\n`;
}
if (prs.length === 0) {
releaseNotes += `No merged pull requests found for this release.\n\n`;
}
if (previousTagName) {
releaseNotes += `\n---\n**Full Changelog**: https://github.com/${context.repo.owner}/${context.repo.repo}/compare/${previousTagName}...${tagName}`;
}
// Create GitHub Release
const release = await github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: tagName,
name: `Release ${tagName}`,
body: releaseNotes,
draft: false,
prerelease: false,
make_latest: 'true'
});
console.log(`✅ Release ${tagName} created successfully!`);
console.log(`Release URL: ${release.data.html_url}`);