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

publish.js

482 lines13.4 KB

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