-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathcreate-github-release.mjs
More file actions
272 lines (236 loc) · 7.83 KB
/
create-github-release.mjs
File metadata and controls
272 lines (236 loc) · 7.83 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
// @ts-nocheck
import fs from 'fs'
import path from 'node:path'
import { globSync } from 'node:fs'
import { execSync, execFileSync } from 'node:child_process'
import { tmpdir } from 'node:os'
const rootDir = path.join(import.meta.dirname, '..')
const ghToken = process.env.GH_TOKEN || process.env.GITHUB_TOKEN
// Resolve GitHub usernames from commit author emails
const usernameCache = {}
async function resolveUsername(email) {
if (!ghToken || !email) return null
if (usernameCache[email] !== undefined) return usernameCache[email]
try {
const res = await fetch(`https://api.github.com/search/users?q=${email}`, {
headers: { Authorization: `token ${ghToken}` },
})
const data = await res.json()
const login = data?.items?.[0]?.login || null
usernameCache[email] = login
return login
} catch {
usernameCache[email] = null
return null
}
}
// Resolve author from a PR number via GitHub API
const prAuthorCache = {}
async function resolveAuthorForPR(prNumber) {
if (prAuthorCache[prNumber] !== undefined) return prAuthorCache[prNumber]
if (!ghToken) {
prAuthorCache[prNumber] = null
return null
}
try {
const res = await fetch(
`https://api.github.com/repos/TanStack/query/pulls/${prNumber}`,
{ headers: { Authorization: `token ${ghToken}` } },
)
const data = await res.json()
const login = data?.user?.login || null
prAuthorCache[prNumber] = login
return login
} catch {
prAuthorCache[prNumber] = null
return null
}
}
// Get the previous release commit to diff against.
// This script runs right after the "ci: changeset release" commit is pushed,
// so HEAD is the release commit.
const releaseLogs = execSync(
'git log --oneline --grep="ci: changeset release" --format=%H',
)
.toString()
.trim()
.split('\n')
.filter(Boolean)
const currentRelease = releaseLogs[0] || 'HEAD'
const previousRelease = releaseLogs[1]
// Find packages that were actually bumped by comparing versions
const packagesDir = path.join(rootDir, 'packages')
const allPkgJsonPaths = globSync('*/package.json', { cwd: packagesDir })
const bumpedPackages = []
for (const relPath of allPkgJsonPaths) {
const fullPath = path.join(packagesDir, relPath)
const currentPkg = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))
if (currentPkg.private) continue
// Get the version from the previous release commit
if (previousRelease) {
try {
const prevContent = execFileSync(
'git',
['show', `${previousRelease}:packages/${relPath}`],
{ encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },
)
const prevPkg = JSON.parse(prevContent)
if (prevPkg.version !== currentPkg.version) {
bumpedPackages.push({
name: currentPkg.name,
version: currentPkg.version,
prevVersion: prevPkg.version,
dir: path.dirname(relPath),
})
}
} catch {
// Package didn't exist in previous release — it's new
bumpedPackages.push({
name: currentPkg.name,
version: currentPkg.version,
prevVersion: null,
dir: path.dirname(relPath),
})
}
} else {
// No previous release — include all non-private packages
bumpedPackages.push({
name: currentPkg.name,
version: currentPkg.version,
prevVersion: null,
dir: path.dirname(relPath),
})
}
}
bumpedPackages.sort((a, b) => a.name.localeCompare(b.name))
// Build changelog from git log between releases (conventional commits)
const rangeFrom = previousRelease || `${currentRelease}~1`
const rawLog = execSync(
`git log ${rangeFrom}..${currentRelease} --pretty=format:"%h %ae %s" --no-merges`,
{ encoding: 'utf-8' },
).trim()
const typeOrder = [
'breaking',
'feat',
'fix',
'perf',
'refactor',
'docs',
'chore',
'test',
'ci',
]
const typeLabels = {
breaking: '⚠️ Breaking Changes',
feat: 'Features',
fix: 'Fix',
perf: 'Performance',
refactor: 'Refactor',
docs: 'Documentation',
chore: 'Chore',
test: 'Tests',
ci: 'CI',
}
const typeIndex = (t) => {
const i = typeOrder.indexOf(t)
return i === -1 ? 99 : i
}
const groups = {}
const commits = rawLog ? rawLog.split('\n') : []
for (const line of commits) {
const match = line.match(/^(\w+)\s+(\S+)\s+(.*)$/)
if (!match) continue
const [, hash, email, subject] = match
// Skip release commits
if (subject.startsWith('ci: changeset release')) continue
// Parse conventional commit: type(scope)!: message
const conventionalMatch = subject.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.*)$/)
const type = conventionalMatch ? conventionalMatch[1] : 'other'
const isBreaking = conventionalMatch ? !!conventionalMatch[3] : false
const scope = conventionalMatch ? conventionalMatch[2] || '' : ''
const message = conventionalMatch ? conventionalMatch[4] : subject
// Only include user-facing change types
if (!['feat', 'fix', 'perf', 'refactor', 'build', 'chore'].includes(type))
continue
// Extract PR number if present
const prMatch = message.match(/\(#(\d+)\)/)
const prNumber = prMatch ? prMatch[1] : null
const bucket = isBreaking ? 'breaking' : type
if (!groups[bucket]) groups[bucket] = []
groups[bucket].push({ hash, email, scope, message, prNumber })
}
// Build markdown grouped by conventional commit type
const sortedTypes = Object.keys(groups).sort(
(a, b) => typeIndex(a) - typeIndex(b),
)
let changelogMd = ''
for (const type of sortedTypes) {
const label = typeLabels[type] || type.charAt(0).toUpperCase() + type.slice(1)
changelogMd += `### ${label}\n\n`
for (const commit of groups[type]) {
const scopePrefix = commit.scope ? `${commit.scope}: ` : ''
const cleanMessage = commit.message.replace(/\s*\(#\d+\)/, '')
const prRef = commit.prNumber ? ` (#${commit.prNumber})` : ''
const username = commit.prNumber
? await resolveAuthorForPR(commit.prNumber)
: await resolveUsername(commit.email)
const authorSuffix = username ? ` by @${username}` : ''
changelogMd += `- ${scopePrefix}${cleanMessage}${prRef} (${commit.hash})${authorSuffix}\n`
}
changelogMd += '\n'
}
if (!changelogMd.trim()) {
changelogMd = '- No changelog entries\n\n'
}
const now = new Date()
const date = now.toISOString().slice(0, 10)
const time = now.toISOString().slice(11, 16).replace(':', '')
const tagName = `release-${date}-${time}`
const titleDate = `${date} ${now.toISOString().slice(11, 16)}`
const isPrerelease = process.argv.includes('--prerelease')
const isLatest = process.argv.includes('--latest')
const body = `Release ${titleDate}
## Changes
${changelogMd}
## Packages
${bumpedPackages.map((p) => `- ${p.name}@${p.version}`).join('\n')}
`
// Create the release
// Check if tag already exists — if so, try to create the release for it
// (handles retries where the tag was pushed but release creation failed)
let tagExists = false
try {
execSync(`git rev-parse ${tagName}`, { stdio: 'ignore' })
tagExists = true
} catch {
// Tag doesn't exist yet
}
if (!tagExists) {
execSync(`git tag -a -m "${tagName}" ${tagName}`)
execSync('git push --tags')
}
const prereleaseFlag = isPrerelease ? '--prerelease' : ''
const latestFlag = isLatest ? ' --latest' : ''
const tmpFile = path.join(tmpdir(), `release-notes-${tagName}.md`)
fs.writeFileSync(tmpFile, body)
try {
execSync(
`gh release create ${tagName} ${prereleaseFlag} --title "Release ${titleDate}" --notes-file ${tmpFile}${latestFlag}`,
{ stdio: 'inherit' },
)
console.info(`GitHub release ${tagName} created.`)
} catch (err) {
// Clean up the tag if we created it but release failed
if (!tagExists) {
console.info(`Release creation failed, cleaning up tag ${tagName}...`)
try {
execSync(`git push --delete origin ${tagName}`, { stdio: 'ignore' })
execSync(`git tag -d ${tagName}`, { stdio: 'ignore' })
} catch {
// Best effort cleanup
}
}
throw err
} finally {
fs.unlinkSync(tmpFile)
}