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