Open History to see the last commit
1// @ts-nocheck
2
3import fs from 'node:fs'
4import os from 'node:os'
5import path from 'node:path'
6import { execSync } from 'node:child_process'
7
8const rootDir = path.resolve(import.meta.dirname, '..')
9const packagesDir = path.join(rootDir, 'packages')
10const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN
11const isPrerelease = process.argv.includes('--prerelease')
12const isDryRun = process.argv.includes('--dry-run')
13
14function run(command, options = {}) {
15 return execSync(command, {
16 cwd: rootDir,
17 encoding: 'utf8',
18 stdio: ['pipe', 'pipe', 'pipe'],
19 ...options,
20 }).trim()
21}
22
23function maybeRun(command) {
24 try {
25 return run(command)
26 } catch {
27 return null
28 }
29}
30
31function getReleaseCommits() {
32 const output = maybeRun(
33 'git log --grep="ci: changeset release" --format=%H --no-merges',
34 )
35
36 if (!output) {
37 return []
38 }
39
40 return output.split('\n').filter(Boolean)
41}
42
43function getPreviousGitHubReleaseCommit() {
44 const output = maybeRun(
45 'git tag --list "v*" --list "release-*" --sort=-creatordate',
46 )
47
48 if (!output) {
49 return null
50 }
51
52 const [tag] = output
53 .split('\n')
54 .filter((candidate) => /^v\d+\.\d+\.\d+$/.test(candidate))
55 .concat(
56 output
57 .split('\n')
58 .filter((candidate) => candidate.startsWith('release-')),
59 )
60
61 if (!tag) {
62 return null
63 }
64
65 return maybeRun(`git rev-list -n 1 ${tag}`)
66}
67
68function getPackages() {
69 return fs
70 .readdirSync(packagesDir, { withFileTypes: true })
71 .filter((entry) => entry.isDirectory())
72 .map((entry) => {
73 const dir = entry.name
74 const packageJsonPath = path.join(packagesDir, dir, 'package.json')
75 const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
76
77 return {
78 dir,
79 packageJsonPath,
80 packageJson,
81 }
82 })
83 .filter(({ packageJson }) => !packageJson.private)
84}
85
86function getPreviousPackageJson(releaseCommit, packageJsonPath) {
87 if (!releaseCommit) {
88 return null
89 }
90
91 const relativePath = path.relative(rootDir, packageJsonPath)
92 const content = maybeRun(`git show ${releaseCommit}:'${relativePath}'`)
93
94 if (!content) {
95 return null
96 }
97
98 return JSON.parse(content)
99}
100
101function getChangedPackages(previousReleaseCommit) {
102 return getPackages()
103 .map(({ dir, packageJsonPath, packageJson }) => {
104 const previousPackageJson = getPreviousPackageJson(
105 previousReleaseCommit,
106 packageJsonPath,
107 )
108
109 if (
110 !previousPackageJson ||
111 previousPackageJson.version !== packageJson.version
112 ) {
113 return {
114 dir,
115 name: packageJson.name,
116 version: packageJson.version,
117 previousVersion: previousPackageJson?.version ?? null,
118 }
119 }
120
121 return null
122 })
123 .filter(Boolean)
124 .sort((left, right) => left.name.localeCompare(right.name))
125}
126
127function parseVersion(version) {
128 const match = version.match(/^(\d+)\.(\d+)\.(\d+)$/)
129
130 if (!match) {
131 return null
132 }
133
134 return match.slice(1).map(Number)
135}
136
137function compareVersions(leftVersion, rightVersion) {
138 const left = parseVersion(leftVersion)
139 const right = parseVersion(rightVersion)
140
141 if (!left || !right) {
142 return leftVersion.localeCompare(rightVersion)
143 }
144
145 for (let index = 0; index < left.length; index += 1) {
146 if (left[index] !== right[index]) {
147 return left[index] - right[index]
148 }
149 }
150
151 return 0
152}
153
154function isVersionInRange(version, previousVersion, currentVersion) {
155 if (compareVersions(version, currentVersion) > 0) {
156 return false
157 }
158
159 if (!previousVersion) {
160 return true
161 }
162
163 return compareVersions(version, previousVersion) > 0
164}
165
166function getChangelogSections(changelogPath, previousVersion, currentVersion) {
167 if (!fs.existsSync(changelogPath)) {
168 return []
169 }
170
171 const changelog = fs.readFileSync(changelogPath, 'utf8')
172 const sections = []
173 const headingPattern = /^## (\d+\.\d+\.\d+)\s*$/gm
174 const headings = Array.from(changelog.matchAll(headingPattern))
175
176 for (let index = 0; index < headings.length; index += 1) {
177 const heading = headings[index]
178 const version = heading[1]
179
180 if (!isVersionInRange(version, previousVersion, currentVersion)) {
181 continue
182 }
183
184 const nextHeading = headings[index + 1]
185 const bodyStart = changelog.indexOf('\n', heading.index)
186 const body = changelog.slice(bodyStart + 1, nextHeading?.index).trim()
187
188 sections.push({
189 version,
190 body: body || '- No changelog entries',
191 })
192 }
193
194 return sections
195}
196
197function buildReleaseNotes(changedPackages) {
198 const sections = changedPackages.map((pkg) => {
199 const changelogPath = path.join(packagesDir, pkg.dir, 'CHANGELOG.md')
200 const changelogSections = getChangelogSections(
201 changelogPath,
202 pkg.previousVersion,
203 pkg.version,
204 )
205 const content =
206 changelogSections
207 .map((section) => `### ${section.version}\n\n${section.body}`)
208 .join('\n\n') || '- No changelog entries'
209
210 return `#### ${pkg.name}\n\n${content}`
211 })
212
213 return sections.join('\n\n')
214}
215
216function createReleaseTag(changedPackages) {
217 const versions = [...new Set(changedPackages.map((pkg) => pkg.version))]
218 if (versions.length === 1) {
219 const version = versions[0]
220 return {
221 tag: `v${version}`,
222 title: `v${version}`,
223 }
224 }
225
226 const now = new Date().toISOString()
227 const tag = `release-${now.slice(0, 10)}-${now.slice(11, 13)}${now.slice(14, 16)}`
228 const title = `Release ${changedPackages
229 .map((pkg) => `${pkg.name}@${pkg.version}`)
230 .join(', ')}`
231
232 return { tag, title }
233}
234
235function createReleaseBody(title, changedPackages, notes) {
236 const packages = changedPackages
237 .map((pkg) => `- ${pkg.name}@${pkg.version}`)
238 .join('\n')
239
240 return `${title}\n\n## Changes\n\n${notes}\n\n## Packages\n\n${packages}`
241}
242
243function pushTag(tag) {
244 const exists = maybeRun(`git rev-parse ${tag}`)
245
246 if (exists) {
247 return false
248 }
249
250 run(`git tag -a ${tag} -m "${tag}"`)
251 run(`git push origin ${tag}`)
252 return true
253}
254
255function createGitHubRelease(tag, title, body) {
256 if (!token) {
257 throw new Error('Missing GH_TOKEN or GITHUB_TOKEN')
258 }
259
260 const notesFile = path.join(os.tmpdir(), `${tag}.md`)
261 fs.writeFileSync(notesFile, body)
262
263 const args = [
264 'gh',
265 'release',
266 'create',
267 tag,
268 '--title',
269 JSON.stringify(title),
270 '--notes-file',
271 JSON.stringify(notesFile),
272 ]
273
274 if (isPrerelease) {
275 args.push('--prerelease')
276 } else {
277 args.push('--latest')
278 }
279
280 try {
281 execSync(args.join(' '), {
282 cwd: rootDir,
283 stdio: 'inherit',
284 env: {
285 ...process.env,
286 GH_TOKEN: token,
287 GITHUB_TOKEN: token,
288 },
289 })
290 } finally {
291 fs.rmSync(notesFile, { force: true })
292 }
293}
294
295function rollbackTag(tag) {
296 maybeRun(`git push --delete origin ${tag}`)
297 maybeRun(`git tag -d ${tag}`)
298}
299
300function main() {
301 const [, previousReleaseCommit] = getReleaseCommits()
302 const changedPackages = getChangedPackages(
303 getPreviousGitHubReleaseCommit() || previousReleaseCommit,
304 )
305
306 if (changedPackages.length === 0) {
307 console.log('No changed packages found for GitHub release.')
308 return
309 }
310
311 const notes = buildReleaseNotes(changedPackages)
312 const { tag, title } = createReleaseTag(changedPackages)
313 const body = createReleaseBody(title, changedPackages, notes)
314
315 if (isDryRun) {
316 console.log(body)
317 return
318 }
319
320 let createdTag = false
321
322 try {
323 createdTag = pushTag(tag)
324 createGitHubRelease(tag, title, body)
325 } catch (error) {
326 if (createdTag) {
327 rollbackTag(tag)
328 }
329
330 throw error
331 }
332}
333
334main()