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

create-github-release.mjs

349 lines9.2 KB

1// @ts-nocheck
2import { execFileSync, execSync } from 'node:child_process'
3import fs, { globSync } from 'node:fs'
4import { tmpdir } from 'node:os'
5import path from 'node:path'
6import { findReleaseForCommit, latestReleaseFlag } from './release-identity.mjs'
7​
8const rootDir = path.join(import.meta.dirname, '..')
9const ghToken = process.env.GH_TOKEN || process.env.GITHUB_TOKEN
10const workspaceDirs = ['packages', 'cli-aliases']
11​
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​
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/cli/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// This runs after the "ci: Version Packages" PR is merged, so HEAD is the
56// release commit.
57const releaseLogs = execSync(
58 'git log --oneline --grep="^ci: Version Packages" --grep="^ci: changeset release" --format=%H',
60 .toString()
61 .trim()
62 .split('\n')
63 .filter(Boolean)
64​
65const currentRelease = releaseLogs[0] || 'HEAD'
66const previousRelease = releaseLogs[1]
67​
68const releaseHead = execFileSync('git', ['rev-parse', 'HEAD'], {
69 encoding: 'utf8',
70}).trim()
71const releases = JSON.parse(
72 execFileSync(
73 'gh',
74 [
75 'api',
76 '--paginate',
77 '--slurp',
78 'repos/TanStack/cli/releases?per_page=100',
79 ],
80 { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 },
81 ),
82).flat()
83const resolveTagCommit = (tag) => {
84 try {
85 return execFileSync('git', ['rev-parse', '--verify', `${tag}^{commit}`], {
86 encoding: 'utf8',
87 stdio: ['pipe', 'pipe', 'ignore'],
88 }).trim()
89 } catch {
90 return execFileSync(
91 'gh',
92 [
93 'api',
94 `repos/TanStack/cli/commits/${encodeURIComponent(tag)}`,
95 '--jq',
96 '.sha',
97 ],
98 { encoding: 'utf8' },
99 ).trim()
100 }
102const existingRelease = await findReleaseForCommit(
103 releases,
104 releaseHead,
105 resolveTagCommit,
107if (existingRelease) {
108 if (existingRelease.draft) {
109 throw new Error(
110 `A draft release already exists for ${releaseHead}: ${existingRelease.html_url}`,
111 )
112 }
113 console.info(
114 `Release already exists for ${releaseHead}: ${existingRelease.html_url}`,
115 )
116 process.exit(0)
118​
119const bumpedPackages = []
120for (const workspaceDir of workspaceDirs) {
121 const absWorkspaceDir = path.join(rootDir, workspaceDir)
122 const pkgJsonPaths = globSync('*/package.json', { cwd: absWorkspaceDir })
123​
124 for (const relPath of pkgJsonPaths) {
125 const fullPath = path.join(absWorkspaceDir, relPath)
126 const currentPkg = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))
127 if (currentPkg.private) continue
128​
129 const repoRelPath = `${workspaceDir}/${relPath}`
130 if (previousRelease) {
131 try {
132 const prevContent = execFileSync(
133 'git',
134 ['show', `${previousRelease}:${repoRelPath}`],
135 { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },
136 )
137 const prevPkg = JSON.parse(prevContent)
138 if (prevPkg.version !== currentPkg.version) {
139 bumpedPackages.push({
140 name: currentPkg.name,
141 version: currentPkg.version,
142 prevVersion: prevPkg.version,
143 dir: path.dirname(repoRelPath),
144 })
145 }
146 } catch {
147 bumpedPackages.push({
148 name: currentPkg.name,
149 version: currentPkg.version,
150 prevVersion: null,
151 dir: path.dirname(repoRelPath),
152 })
153 }
154 } else {
155 bumpedPackages.push({
156 name: currentPkg.name,
157 version: currentPkg.version,
158 prevVersion: null,
159 dir: path.dirname(repoRelPath),
160 })
161 }
162 }
164​
165bumpedPackages.sort((a, b) => a.name.localeCompare(b.name))
166​
167const rangeFrom = previousRelease || `${currentRelease}~1`
168const rawLog = execSync(
169 `git log ${rangeFrom}..${currentRelease} --pretty=format:"%h %ae %s" --no-merges`,
170 { encoding: 'utf-8' },
171).trim()
172​
173const typeOrder = [
174 'breaking',
175 'feat',
176 'fix',
177 'perf',
178 'refactor',
179 'docs',
180 'chore',
181 'test',
182 'ci',
184const typeLabels = {
185 breaking: 'Breaking Changes',
186 feat: 'Features',
187 fix: 'Fix',
188 perf: 'Performance',
189 refactor: 'Refactor',
190 docs: 'Documentation',
191 chore: 'Chore',
192 test: 'Tests',
193 ci: 'CI',
195const typeIndex = (type) => {
196 const index = typeOrder.indexOf(type)
197 return index === -1 ? 99 : index
199​
200const groups = {}
201const commits = rawLog ? rawLog.split('\n') : []
202​
203for (const line of commits) {
204 const match = line.match(/^(\w+)\s+(\S+)\s+(.*)$/)
205 if (!match) continue
206 const [, hash, email, subject] = match
207​
208 if (
209 subject.startsWith('ci: Version Packages') ||
210 subject.startsWith('ci: changeset release')
211 ) {
212 continue
213 }
214​
215 const conventionalMatch = subject.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.*)$/)
216 const type = conventionalMatch ? conventionalMatch[1] : 'other'
217 const isBreaking = conventionalMatch ? Boolean(conventionalMatch[3]) : false
218 const scope = conventionalMatch ? conventionalMatch[2] || '' : ''
219 const message = conventionalMatch ? conventionalMatch[4] : subject
220​
221 if (!['chore', 'feat', 'fix', 'perf', 'refactor', 'build'].includes(type)) {
222 continue
223 }
224​
225 const prMatch = message.match(/\(#(\d+)\)/)
226 const prNumber = prMatch ? prMatch[1] : null
227​
228 const bucket = isBreaking ? 'breaking' : type
229 if (!groups[bucket]) groups[bucket] = []
230 groups[bucket].push({ hash, email, scope, message, prNumber })
232​
233const sortedTypes = Object.keys(groups).sort(
234 (a, b) => typeIndex(a) - typeIndex(b),
236​
237let changelogMd = ''
238for (const type of sortedTypes) {
239 const label = typeLabels[type] || type.charAt(0).toUpperCase() + type.slice(1)
240 changelogMd += `### ${label}\n\n`
241​
242 for (const commit of groups[type]) {
243 const scopePrefix = commit.scope ? `${commit.scope}: ` : ''
244 const cleanMessage = commit.message.replace(/\s*\(#\d+\)/, '')
245 const prRef = commit.prNumber ? ` (#${commit.prNumber})` : ''
246 const username = commit.prNumber
247 ? await resolveAuthorForPR(commit.prNumber)
248 : await resolveUsername(commit.email)
249 const authorSuffix = username ? ` by @${username}` : ''
250​
251 changelogMd += `- ${scopePrefix}${cleanMessage}${prRef} (${commit.hash})${authorSuffix}\n`
252 }
253 changelogMd += '\n'
255​
256if (!changelogMd.trim()) {
257 changelogMd = '- No changelog entries\n\n'
259​
260const now = new Date()
261const date = now.toISOString().slice(0, 10)
262const time = now.toISOString().slice(11, 16).replace(':', '')
263const tagName = `release-${date}-${time}`
264const titleDate = `${date} ${now.toISOString().slice(11, 16)}`
265​
266const isPrerelease = process.argv.includes('--prerelease')
267const isLatest = process.argv.includes('--latest')
268​
269const body = `Release ${titleDate}
270​
271## Changes
272​
273${changelogMd}
274## Packages
275​
276${bumpedPackages.map((pkg) => `- ${pkg.name}@${pkg.version}`).join('\n')}
278​
279let latestHead
280if (
281 isLatest &&
282 releases.some((release) => !release.draft && !release.prerelease)
283) {
284 const latestRelease = JSON.parse(
285 execFileSync('gh', ['api', 'repos/TanStack/cli/releases/latest'], {
286 encoding: 'utf8',
287 }),
288 )
289 latestHead = resolveTagCommit(latestRelease.tag_name)
291const latestOption = latestReleaseFlag({
292 requested: process.argv.includes('--latest=false')
293 ? 'false'
294 : isLatest
295 ? 'true'
296 : undefined,
297 releaseHead,
298 latestHead,
299 isAncestor: (older, newer) => {
300 try {
301 execFileSync('git', ['merge-base', '--is-ancestor', older, newer], {
302 stdio: 'ignore',
303 })
304 return true
305 } catch (error) {
306 if (error.status === 1) return false
307 throw error
308 }
309 },
310})
311const latestFlag = latestOption ? ` ${latestOption}` : ''
312​
313let tagExists = false
314try {
315 execSync(`git rev-parse ${tagName}`, { stdio: 'ignore' })
316 tagExists = true
317} catch {
318 // Tag does not exist yet.
320​
321if (!tagExists) {
322 execSync(`git tag -a -m "${tagName}" ${tagName}`)
323 execSync('git push --tags')
325​
326const prereleaseFlag = isPrerelease ? '--prerelease' : ''
327const tmpFile = path.join(tmpdir(), `release-notes-${tagName}.md`)
328fs.writeFileSync(tmpFile, body)
329​
330try {
331 execSync(
332 `gh release create ${tagName} ${prereleaseFlag} --title "Release ${titleDate}" --notes-file ${tmpFile}${latestFlag}`,
333 { stdio: 'inherit' },
334 )
335 console.info(`GitHub release ${tagName} created.`)
336} catch (error) {
337 if (!tagExists) {
338 console.info(`Release creation failed, cleaning up tag ${tagName}...`)
339 try {
340 execSync(`git push --delete origin ${tagName}`, { stdio: 'ignore' })
341 execSync(`git tag -d ${tagName}`, { stdio: 'ignore' })
342 } catch {
343 // Best effort cleanup.
344 }
345 }
346 throw error
347} finally {
348 fs.unlinkSync(tmpFile)