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