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

publish.js

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