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

publish.ts

477 lines13.3 KB

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