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

create-github-release.mjs

276 lines7.9 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/router/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: Version Packages" PR is merged,
58// so HEAD is the release commit.
59const releaseLogs = execSync(
60 'git log --oneline --grep="^ci: Version Packages" --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 (
163 subject.startsWith('ci: Version Packages') ||
164 subject.startsWith('ci: changeset release')
165 )
166 continue
167​
168 // Parse conventional commit: type(scope)!: message
169 const conventionalMatch = subject.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.*)$/)
170 const type = conventionalMatch ? conventionalMatch[1] : 'other'
171 const isBreaking = conventionalMatch ? !!conventionalMatch[3] : false
172 const scope = conventionalMatch ? conventionalMatch[2] || '' : ''
173 const message = conventionalMatch ? conventionalMatch[4] : subject
174​
175 // Only include user-facing change types
176 if (!['chore', 'feat', 'fix', 'perf', 'refactor', 'build'].includes(type))
177 continue
178​
179 // Extract PR number if present
180 const prMatch = message.match(/\(#(\d+)\)/)
181 const prNumber = prMatch ? prMatch[1] : null
182​
183 const bucket = isBreaking ? 'breaking' : type
184 if (!groups[bucket]) groups[bucket] = []
185 groups[bucket].push({ hash, email, scope, message, prNumber })
187​
188// Build markdown grouped by conventional commit type
189const sortedTypes = Object.keys(groups).sort(
190 (a, b) => typeIndex(a) - typeIndex(b),
192​
193let changelogMd = ''
194for (const type of sortedTypes) {
195 const label = typeLabels[type] || type.charAt(0).toUpperCase() + type.slice(1)
196 changelogMd += `### ${label}\n\n`
197​
198 for (const commit of groups[type]) {
199 const scopePrefix = commit.scope ? `${commit.scope}: ` : ''
200 const cleanMessage = commit.message.replace(/\s*\(#\d+\)/, '')
201 const prRef = commit.prNumber ? ` (#${commit.prNumber})` : ''
202 const username = commit.prNumber
203 ? await resolveAuthorForPR(commit.prNumber)
204 : await resolveUsername(commit.email)
205 const authorSuffix = username ? ` by @${username}` : ''
206​
207 changelogMd += `- ${scopePrefix}${cleanMessage}${prRef} (${commit.hash})${authorSuffix}\n`
208 }
209 changelogMd += '\n'
211​
212if (!changelogMd.trim()) {
213 changelogMd = '- No changelog entries\n\n'
215​
216const now = new Date()
217const date = now.toISOString().slice(0, 10)
218const time = now.toISOString().slice(11, 16).replace(':', '')
219const tagName = `release-${date}-${time}`
220const titleDate = `${date} ${now.toISOString().slice(11, 16)}`
221​
222const isPrerelease = process.argv.includes('--prerelease')
223const isLatest = process.argv.includes('--latest')
224​
225const body = `Release ${titleDate}
226​
227## Changes
228​
229${changelogMd}
230## Packages
231​
232${bumpedPackages.map((p) => `- ${p.name}@${p.version}`).join('\n')}
234​
235// Create the release
236// Check if tag already exists β€” if so, try to create the release for it
237// (handles retries where the tag was pushed but release creation failed)
238let tagExists = false
239try {
240 execSync(`git rev-parse ${tagName}`, { stdio: 'ignore' })
241 tagExists = true
242} catch {
243 // Tag doesn't exist yet
245​
246if (!tagExists) {
247 execSync(`git tag -a -m "${tagName}" ${tagName}`)
248 execSync('git push --tags')
250​
251const prereleaseFlag = isPrerelease ? '--prerelease' : ''
252const latestFlag = isLatest ? ' --latest' : ''
253const tmpFile = path.join(tmpdir(), `release-notes-${tagName}.md`)
254fs.writeFileSync(tmpFile, body)
255​
256try {
257 execSync(
258 `gh release create ${tagName} ${prereleaseFlag} --title "Release ${titleDate}" --notes-file ${tmpFile}${latestFlag}`,
259 { stdio: 'inherit' },
260 )
261 console.info(`GitHub release ${tagName} created.`)
262} catch (err) {
263 // Clean up the tag if we created it but release failed
264 if (!tagExists) {
265 console.info(`Release creation failed, cleaning up tag ${tagName}...`)
266 try {
267 execSync(`git push --delete origin ${tagName}`, { stdio: 'ignore' })
268 execSync(`git tag -d ${tagName}`, { stdio: 'ignore' })
269 } catch {
270 // Best effort cleanup
271 }
272 }
273 throw err
274} finally {
275 fs.unlinkSync(tmpFile)