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

create-github-release.mjs

272 lines7.8 KB

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