Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

create-github-release.mjs

275 lines7.9 KB

1// @ts-nocheck
2import fs, { globSync } from 'node:fs'
3import path from 'node:path'
4import { execFileSync, execSync } from 'node:child_process'
5import { tmpdir } from 'node:os'
6​
7const rootDir = path.join(import.meta.dirname, '..')
8const ghToken = process.env.GITHUB_TOKEN
9​
10// Resolve GitHub usernames from commit author emails
11const usernameCache = {}
12async function resolveUsername(email) {
13 if (!ghToken || !email) return null
14 if (usernameCache[email] !== undefined) return usernameCache[email]
15​
16 try {
17 const res = await fetch(`https://api.github.com/search/users?q=${email}`, {
18 headers: { Authorization: `token ${ghToken}` },
19 })
20 const data = await res.json()
21 const login = data?.items?.[0]?.login || null
22 usernameCache[email] = login
23 return login
24 } catch {
25 usernameCache[email] = null
26 return null
27 }
29​
30// Resolve author from a PR number via GitHub API
31const prAuthorCache = {}
32async function resolveAuthorForPR(prNumber) {
33 if (prAuthorCache[prNumber] !== undefined) return prAuthorCache[prNumber]
34​
35 if (!ghToken) {
36 prAuthorCache[prNumber] = null
37 return null
38 }
39​
40 try {
41 const res = await fetch(
42 `https://api.github.com/repos/TanStack/query/pulls/${prNumber}`,
43 { headers: { Authorization: `token ${ghToken}` } },
44 )
45 const data = await res.json()
46 const login = data?.user?.login || null
47 prAuthorCache[prNumber] = login
48 return login
49 } catch {
50 prAuthorCache[prNumber] = null
51 return null
52 }
54​
55// Get the previous release commit to diff against.
56// This script runs right after the "ci: Version Packages" PR is merged,
57// so HEAD is the release commit.
58const releaseLogs = execSync(
59 'git log --oneline --grep="^ci: Version Packages" --grep="^ci: changeset release" --format=%H',
61 .toString()
62 .trim()
63 .split('\n')
64 .filter(Boolean)
65​
66const currentRelease = releaseLogs[0] || 'HEAD'
67const previousRelease = releaseLogs[1]
68​
69// Find packages that were actually bumped by comparing versions
70const packagesDir = path.join(rootDir, 'packages')
71const allPkgJsonPaths = globSync('*/package.json', { cwd: packagesDir })
72​
73const bumpedPackages = []
74for (const relPath of allPkgJsonPaths) {
75 const fullPath = path.join(packagesDir, relPath)
76 const currentPkg = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))
77 if (currentPkg.private) continue
78​
79 // Get the version from the previous release commit
80 if (previousRelease) {
81 try {
82 const prevContent = execFileSync(
83 'git',
84 ['show', `${previousRelease}:packages/${relPath}`],
85 { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },
86 )
87 const prevPkg = JSON.parse(prevContent)
88 if (prevPkg.version !== currentPkg.version) {
89 bumpedPackages.push({
90 name: currentPkg.name,
91 version: currentPkg.version,
92 prevVersion: prevPkg.version,
93 dir: path.dirname(relPath),
94 })
95 }
96 } catch {
97 // Package didn't exist in previous release β€” it's new
98 bumpedPackages.push({
99 name: currentPkg.name,
100 version: currentPkg.version,
101 prevVersion: null,
102 dir: path.dirname(relPath),
103 })
104 }
105 } else {
106 // No previous release β€” include all non-private packages
107 bumpedPackages.push({
108 name: currentPkg.name,
109 version: currentPkg.version,
110 prevVersion: null,
111 dir: path.dirname(relPath),
112 })
113 }
115​
116bumpedPackages.sort((a, b) => a.name.localeCompare(b.name))
117​
118// Build changelog from git log between releases (conventional commits)
119const rangeFrom = previousRelease || `${currentRelease}~1`
120const rawLog = execSync(
121 `git log ${rangeFrom}..${currentRelease} --pretty=format:"%h %ae %s" --no-merges`,
122 { encoding: 'utf-8' },
123).trim()
124​
125const typeOrder = [
126 'breaking',
127 'feat',
128 'fix',
129 'perf',
130 'refactor',
131 'docs',
132 'chore',
133 'test',
134 'ci',
136const typeLabels = {
137 breaking: '⚠️ Breaking Changes',
138 feat: 'Features',
139 fix: 'Fix',
140 perf: 'Performance',
141 refactor: 'Refactor',
142 docs: 'Documentation',
143 chore: 'Chore',
144 test: 'Tests',
145 ci: 'CI',
147const typeIndex = (t) => {
148 const i = typeOrder.indexOf(t)
149 return i === -1 ? 99 : i
151​
152const groups = {}
153const commits = rawLog ? rawLog.split('\n') : []
154​
155for (const line of commits) {
156 const match = line.match(/^(\w+)\s+(\S+)\s+(.*)$/)
157 if (!match) continue
158 const [, hash, email, subject] = match
159​
160 // Skip release commits
161 if (
162 subject.startsWith('ci: Version Packages') ||
163 subject.startsWith('ci: changeset release')
164 )
165 continue
166​
167 // Parse conventional commit: type(scope)!: message
168 const conventionalMatch = subject.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.*)$/)
169 const type = conventionalMatch ? conventionalMatch[1] : 'other'
170 const isBreaking = conventionalMatch ? !!conventionalMatch[3] : false
171 const scope = conventionalMatch ? conventionalMatch[2] || '' : ''
172 const message = conventionalMatch ? conventionalMatch[4] : subject
173​
174 // Only include user-facing change types
175 if (!['feat', 'fix', 'perf', 'refactor', 'build', 'chore'].includes(type))
176 continue
177​
178 // Extract PR number if present
179 const prMatch = message.match(/\(#(\d+)\)/)
180 const prNumber = prMatch ? prMatch[1] : null
181​
182 const bucket = isBreaking ? 'breaking' : type
183 if (!groups[bucket]) groups[bucket] = []
184 groups[bucket].push({ hash, email, scope, message, prNumber })
186​
187// Build markdown grouped by conventional commit type
188const sortedTypes = Object.keys(groups).sort(
189 (a, b) => typeIndex(a) - typeIndex(b),
191​
192let changelogMd = ''
193for (const type of sortedTypes) {
194 const label = typeLabels[type] || type.charAt(0).toUpperCase() + type.slice(1)
195 changelogMd += `### ${label}\n\n`
196​
197 for (const commit of groups[type]) {
198 const scopePrefix = commit.scope ? `${commit.scope}: ` : ''
199 const cleanMessage = commit.message.replace(/\s*\(#\d+\)/, '')
200 const prRef = commit.prNumber ? ` (#${commit.prNumber})` : ''
201 const username = commit.prNumber
202 ? await resolveAuthorForPR(commit.prNumber)
203 : await resolveUsername(commit.email)
204 const authorSuffix = username ? ` by @${username}` : ''
205​
206 changelogMd += `- ${scopePrefix}${cleanMessage}${prRef} (${commit.hash})${authorSuffix}\n`
207 }
208 changelogMd += '\n'
210​
211if (!changelogMd.trim()) {
212 changelogMd = '- No changelog entries\n\n'
214​
215const now = new Date()
216const date = now.toISOString().slice(0, 10)
217const time = now.toISOString().slice(11, 16).replace(':', '')
218const tagName = `release-${date}-${time}`
219const titleDate = `${date} ${now.toISOString().slice(11, 16)}`
220​
221const isPrerelease = process.argv.includes('--prerelease')
222const isLatest = process.argv.includes('--latest')
223​
224const body = `Release ${titleDate}
225​
226## Changes
227​
228${changelogMd}
229## Packages
230​
231${bumpedPackages.map((p) => `- ${p.name}@${p.version}`).join('\n')}
233​
234// Create the release
235// Check if tag already exists β€” if so, try to create the release for it
236// (handles retries where the tag was pushed but release creation failed)
237let tagExists = false
238try {
239 execSync(`git rev-parse ${tagName}`, { stdio: 'ignore' })
240 tagExists = true
241} catch {
242 // Tag doesn't exist yet
244​
245if (!tagExists) {
246 execSync(`git tag -a -m "${tagName}" ${tagName}`)
247 execSync(`git push origin ${tagName}`)
249​
250const prereleaseFlag = isPrerelease ? '--prerelease' : ''
251const latestFlag = isLatest ? ' --latest' : ''
252const tmpFile = path.join(tmpdir(), `release-notes-${tagName}.md`)
253fs.writeFileSync(tmpFile, body)
254​
255try {
256 execSync(
257 `gh release create ${tagName} ${prereleaseFlag} --title "Release ${titleDate}" --notes-file ${tmpFile}${latestFlag}`,
258 { stdio: 'inherit' },
259 )
260 console.info(`GitHub release ${tagName} created.`)
261} catch (err) {
262 // Clean up the tag if we created it but release failed
263 if (!tagExists) {
264 console.info(`Release creation failed, cleaning up tag ${tagName}...`)
265 try {
266 execSync(`git push --delete origin ${tagName}`, { stdio: 'ignore' })
267 execSync(`git tag -d ${tagName}`, { stdio: 'ignore' })
268 } catch {
269 // Best effort cleanup
270 }
271 }
272 throw err
273} finally {
274 fs.unlinkSync(tmpFile)