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