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

publish.ts

505 lines14.1 KB

1import {
2 branchConfigs,
3 examplesDir,
4 latestBranch,
5 packages,
6 rootDir,
7} from './config'
8import { BranchConfig, Commit, Package } from './types'
9import { getPackageDir } from './utils'
10​
11// Originally ported to TS from https://github.com/remix-run/react-router/tree/main/scripts/{version,publish}.js
12import path from 'path'
13import { exec, execSync } from 'child_process'
14import fsp from 'fs/promises'
15import chalk from 'chalk'
16import jsonfile from 'jsonfile'
17import semver from 'semver'
18import currentGitBranch from 'current-git-branch'
19import parseCommit from '@commitlint/parse'
20import log from 'git-log-parser'
21import streamToArray from 'stream-to-array'
22import axios from 'axios'
23import { DateTime } from 'luxon'
24​
25import { PackageJson } from 'type-fest'
26​
27const releaseCommitMsg = (version: string) => `release: v${version}`
28​
29async function run() {
30 let branchName: string =
31 process.env.BRANCH ??
32 (process.env.PR_NUMBER ? `pr-${process.env.PR_NUMBER}` : currentGitBranch())
33​
34 const branchConfig: BranchConfig = branchConfigs[branchName] || {
35 prerelease: true,
36 ghRelease: false,
37 }
38​
39 const isLatestBranch = branchName === latestBranch
40 const npmTag = isLatestBranch ? 'latest' : branchName
41​
42 let remoteURL = execSync('git config --get remote.origin.url').toString()
43​
44 remoteURL = remoteURL.substring(0, remoteURL.indexOf('.git'))
45​
46 // Get tags
47 let tags: string[] = execSync('git tag').toString().split('\n')
48​
49 // Filter tags to our branch/pre-release combo
50 tags = tags
51 .filter(semver.valid)
52 .filter((tag) => {
53 if (isLatestBranch) {
54 return semver.prerelease(tag) == null
55 }
56​
57 return tag.includes(`-${branchName}`)
58 })
59 // sort by latest
60 .sort(semver.compare)
61​
62 // Get the latest tag
63 let latestTag = [...tags].pop()
64​
65 let range = `${latestTag}..HEAD`
66 // let range = ``;
67​
68 // If RELEASE_ALL is set via a commit subject or body, all packages will be
69 // released regardless if they have changed files matching the package srcDir.
70 let RELEASE_ALL = false
71​
72 if (!latestTag || process.env.TAG) {
73 if (process.env.TAG) {
74 if (!process.env.TAG.startsWith('v')) {
75 throw new Error(
76 `process.env.TAG must start with "v", eg. v0.0.0. You supplied ${process.env.TAG}`,
77 )
78 }
79 console.log(
80 chalk.yellow(
81 `Tag is set to ${process.env.TAG}. This will force release all packages. Publishing...`,
82 ),
83 )
84 RELEASE_ALL = true
85 latestTag = process.env.TAG
86 range = ''
87 } else {
88 throw new Error(
89 'Could not find latest tag! To make a release tag of v0.0.1, run with TAG=v0.0.1',
90 )
91 }
92 }
93​
94 // Get the commits since the latest tag
95 let commitsSinceLatestTag = (
96 await new Promise<Commit[]>((resolve, reject) => {
97 const strm = log.parse({
98 _: range,
99 })
100​
101 streamToArray(strm, function (err: any, arr: any[]) {
102 if (err) return reject(err)
103​
104 Promise.all(
105 arr.map(async (d) => {
106 const parsed = await parseCommit(d.subject)
107​
108 return { ...d, parsed }
109 }),
110 ).then((res) => resolve(res.filter(Boolean)))
111 })
112 })
113 ).filter((commit: Commit) => {
114 const exclude = [
115 commit.subject.startsWith('Merge branch '), // No merge commits
116 commit.subject.startsWith(releaseCommitMsg('')), // No example update commits
117 ].some(Boolean)
118​
119 return !exclude
120 })
121​
122 console.log(
123 `Parsing ${commitsSinceLatestTag.length} commits since ${latestTag}...`,
124 )
125​
126 // Pares the commit messsages, log them, and determine the type of release needed
127 const recommendedReleaseLevel: number = commitsSinceLatestTag.reduce(
128 (releaseLevel, commit) => {
129 if (['fix', 'refactor', 'perf'].includes(commit.parsed.type)) {
130 releaseLevel = Math.max(releaseLevel, 0)
131 }
132 if (['feat'].includes(commit.parsed.type)) {
133 releaseLevel = Math.max(releaseLevel, 1)
134 }
135 if (commit.body.includes('BREAKING CHANGE')) {
136 releaseLevel = Math.max(releaseLevel, 2)
137 }
138 if (
139 commit.subject.includes('RELEASE_ALL') ||
140 commit.body.includes('RELEASE_ALL')
141 ) {
142 RELEASE_ALL = true
143 }
144​
145 return releaseLevel
146 },
147 -1,
148 )
149​
150 const changedFiles: string[] = process.env.TAG
151 ? []
152 : execSync(`git diff ${latestTag} --name-only`)
153 .toString()
154 .split('\n')
155 .filter(Boolean)
156​
157 const changedPackages = RELEASE_ALL
158 ? packages
159 : changedFiles.reduce((changedPackages, file) => {
160 const pkg = packages.find((p) => file.startsWith(p.srcDir))
161 if (pkg && !changedPackages.find((d) => d.name === pkg.name)) {
162 changedPackages.push(pkg)
163 }
164 return changedPackages
165 }, [] as Package[])
166​
167 if (!process.env.TAG) {
168 if (recommendedReleaseLevel === 2) {
169 console.log(
170 `Major versions releases must be tagged and released manually.`,
171 )
172 return
173 }
174​
175 if (recommendedReleaseLevel === -1) {
176 console.log(
177 `There have been no changes since the release of ${latestTag} that require a new version. You're good!`,
178 )
179 return
180 }
181 }
182​
183 function getSorterFn<TItem>(sorters: ((d: TItem) => any)[]) {
184 return (a: TItem, b: TItem) => {
185 let i = 0
186​
187 sorters.some((sorter) => {
188 const sortedA = sorter(a)
189 const sortedB = sorter(b)
190 if (sortedA > sortedB) {
191 i = 1
192 return true
193 }
194 if (sortedA < sortedB) {
195 i = -1
196 return true
197 }
198 return false
199 })
200​
201 return i
202 }
203 }
204​
205 const changelogCommitsMd = process.env.TAG
206 ? `Manual Release: ${latestTag}`
207 : await Promise.all(
208 Object.entries(
209 commitsSinceLatestTag.reduce((acc, next) => {
210 const type = next.parsed.type?.toLowerCase() ?? 'other'
211​
212 return {
213 ...acc,
214 [type]: [...(acc[type] || []), next],
215 }
216 }, {} as Record<string, Commit[]>),
217 )
218 .sort(
219 getSorterFn([
220 ([d]) =>
221 [
222 'other',
223 'examples',
224 'docs',
225 'chore',
226 'refactor',
227 'perf',
228 'fix',
229 'feat',
230 ].indexOf(d),
231 ]),
232 )
233 .reverse()
234 .map(async ([type, commits]) => {
235 return Promise.all(
236 commits.map(async (commit) => {
237 let username = ''
238​
239 if (process.env.GH_TOKEN) {
240 const query = `${
241 commit.author.email ?? commit.committer.email
242 }`
243​
244 const res = await axios.get(
245 'https://api.github.com/search/users',
246 {
247 params: {
248 q: query,
249 },
250 headers: {
251 Authorization: `token ${process.env.GH_TOKEN}`,
252 },
253 },
254 )
255​
256 username = res.data.items[0]?.login
257 }
258​
259 const scope = commit.parsed.scope
260 ? `(${commit.parsed.scope}): `
261 : ''
262 const subject = commit.parsed.subject ?? commit.subject
263 // const commitUrl = `${remoteURL}/commit/${commit.commit.long}`;
264​
265 return `- ${scope}${subject} (${commit.commit.short}) ${
266 username
267 ? `by @${username}`
268 : `by ${commit.author.name ?? commit.author.email}`
269 }`
270 }),
271 ).then((commits) => [type, commits] as const)
272 }),
273 ).then((groups) => {
274 return groups
275 .map(([type, commits]) => {
276 return [`### ${capitalize(type)}`, commits.join('\n')].join('\n\n')
277 })
278 .join('\n\n')
279 })
280​
281 const releaseType = branchConfig.prerelease
282 ? 'prerelease'
283 : { 0: 'patch', 1: 'minor', 2: 'major' }[recommendedReleaseLevel]
284​
285 if (!releaseType) {
286 throw new Error(`Invalid release level: ${recommendedReleaseLevel}`)
287 }
288​
289 const version = process.env.TAG
290 ? semver.parse(process.env.TAG)?.version
291 : semver.inc(latestTag, releaseType, npmTag)
292​
293 if (!version) {
294 throw new Error(
295 `Invalid version increment from semver.inc(${[
296 latestTag,
297 recommendedReleaseLevel,
298 branchConfig.prerelease,
299 ].join(', ')}`,
300 )
301 }
302​
303 const changelogMd = [
304 `Version ${version} - ${DateTime.now().toLocaleString(
305 DateTime.DATETIME_SHORT,
306 )}`,
307 `## Changes`,
308 changelogCommitsMd,
309 `## Packages`,
310 changedPackages.map((d) => `- ${d.name}@${version}`).join('\n'),
311 ].join('\n\n')
312​
313 console.log('Generating changelog...')
314 console.log()
315 console.log(changelogMd)
316 console.log()
317​
318 console.log('Building packages...')
319 execSync(`yarn build`, { encoding: 'utf8' })
320​
321 console.log('Linking packages...')
322 execSync(`yarn linkAll`, { encoding: 'utf8' })
323​
324 console.log('Testing packages...')
325 execSync(`yarn test:ci`, { encoding: 'utf8' })
326 console.log('')
327​
328 console.log(
329 `Updating all changed packages and their dependencies to version ${version}...`,
330 )
331 // Update each package to the new version along with any dependencies
332 for (const pkg of changedPackages) {
333 console.log(` Updating ${pkg.name} version to ${version}...`)
334​
335 await updatePackageConfig(pkg.name, (config) => {
336 config.version = version
337 pkg.peerDependencies?.forEach((peerDep) => {
338 if (config.peerDependencies?.[peerDep]) {
339 console.log(
340 ` Updating peerDependency on ${pkg.name} to version ${version}.`,
341 )
342 config.peerDependencies[peerDep] = version
343 }
344 })
345 })
346 }
347​
348 console.log(`Updating examples dependencies...`)
349 let examples = await fsp.readdir(examplesDir)
350 for (const example of examples) {
351 let stat = await fsp.stat(path.join(examplesDir, example))
352 if (!stat.isDirectory()) continue
353​
354 console.log(` Updating example ${example} to version ${version}...`)
355​
356 await updateExamplesPackageConfig(example, (config) => {
357 changedPackages.forEach((pkg) => {
358 if (config.dependencies?.[pkg.name]) {
359 console.log(
360 ` Updating dependency ${pkg.name} to version ${version}...`,
361 )
362 config.dependencies[pkg.name] = version
363 }
364 })
365 })
366 }
367​
368 if (!process.env.CI) {
369 console.warn(
370 `This is a dry run for version ${version}. Push to CI to publish for real or set CI=true to override!`,
371 )
372 return
373 }
374​
375 // Tag and commit
376 console.log(`Creating new git tag v${version}`)
377 execSync(`git tag -a -m "v${version}" v${version}`)
378​
379 let taggedVersion = getTaggedVersion()
380 if (!taggedVersion) {
381 throw new Error(
382 'Missing the tagged release version. Something weird is afoot!',
383 )
384 }
385​
386 console.log()
387 console.log(`Verifying packages are on version ${version}`)
388​
389 // Ensure packages are up to date and ready
390 await Promise.all(
391 changedPackages.map(async (pkg) => {
392 let file = path.join(
393 rootDir,
394 'packages',
395 getPackageDir(pkg.name),
396 'package.json',
397 )
398 let json = (await jsonfile.readFile(file)) as PackageJson
399​
400 if (json.version !== version) {
401 throw new Error(
402 `Package ${pkg.name} is on version ${json.version}, but should be on ${version}`,
403 )
404 }
405​
406 ;(pkg.peerDependencies ?? []).forEach((peerDependency) => {
407 if (json.peerDependencies?.[peerDependency]) {
408 if (json.peerDependencies[peerDependency] !== version) {
409 throw new Error(
410 `Package ${pkg.name}'s peerDependency of ${peerDependency} is on version ${json.peerDependencies[peerDependency]}, but should be on ${version}`,
411 )
412 }
413 }
414 })
415 }),
416 )
417​
418 console.log()
419 console.log(`Publishing all packages to npm with tag "${npmTag}"`)
420​
421 // Publish each package
422 changedPackages.map((pkg) => {
423 let packageDir = path.join(rootDir, 'packages', getPackageDir(pkg.name))
424 const cmd = `cd ${packageDir} && yarn publish --tag ${npmTag} --access=public`
425 console.log(
426 ` Publishing ${pkg.name}@${version} to npm with tag "${npmTag}"...`,
427 )
428 execSync(`${cmd} --token ${process.env.NPM_TOKEN}`, { stdio: 'inherit' })
429 })
430​
431 console.log(`Pushing new tags to branch.`)
432 execSync(`git push --tags`)
433 console.log(` Pushed tags to branch.`)
434​
435 if (branchConfig.ghRelease) {
436 console.log(`Creating github release...`)
437 // Stringify the markdown to excape any quotes
438 execSync(
439 `gh release create v${version} ${
440 isLatestBranch ? '--prerelease' : ''
441 } --notes '${changelogMd}'`,
442 )
443 console.log(` Github release created.`)
444​
445 console.log(`Committing changes...`)
446 execSync(`git add -A && git commit -m "${releaseCommitMsg(version)}"`)
447 console.log()
448 console.log(` Committed Changes.`)
449 console.log(`Pushing changes...`)
450 execSync(`git push`)
451 console.log()
452 console.log(` Changes pushed.`)
453 } else {
454 console.log(`Skipping github release and change commit.`)
455 }
456​
457 console.log(`Pushing tags...`)
458 execSync(`git push --tags`)
459 console.log()
460 console.log(` Tags pushed.`)
461 console.log(`All done!`)
463​
464run().catch((err) => {
465 console.log(err)
466 process.exit(1)
467})
468​
469function capitalize(str: string) {
470 return str.slice(0, 1).toUpperCase() + str.slice(1)
472​
473async function updatePackageConfig(
474 packageName: string,
475 transform: (json: PackageJson) => void,
476) {
477 let file = packageJson(packageName)
478 let json = await jsonfile.readFile(file)
479 transform(json)
480 await jsonfile.writeFile(file, json, { spaces: 2 })
482​
483async function updateExamplesPackageConfig(
484 example: string,
485 transform: (json: PackageJson) => void,
486) {
487 let file = packageJson(example, 'examples')
488 let json = await jsonfile.readFile(file)
489 transform(json)
490 await jsonfile.writeFile(file, json, { spaces: 2 })
492​
493function packageJson(packageName: string, directory = 'packages') {
494 return path.join(
495 rootDir,
496 directory,
497 getPackageDir(packageName),
498 'package.json',
499 )
501​
502function getTaggedVersion() {
503 let output = execSync('git tag --list --points-at HEAD').toString()
504 return output.replace(/^v|\n+$/g, '')