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