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