MyKindlebox/.githooks/bump-version.mjs

55 lines
2.2 KiB
JavaScript

// Pre-commit version bump. The app version lives in mykindlebox/client/
// package.json (shown in the sidebar footer); the server package is kept on
// the same number. Every commit that touches the app bumps the patch number
// (1.4.2 → 1.4.3) and stages the change, so each commit is a distinct version.
//
// A hand-made minor/major bump (`npm version minor --no-git-tag-version` in
// client/) is kept as-is instead of being bumped again, and copied to the
// server package.
//
// Skipped entirely when nothing under mykindlebox/ is staged (docs-only
// commits) or SKIP_VERSION_BUMP=1 is set.
import { execFileSync } from 'node:child_process'
import { readFileSync, writeFileSync } from 'node:fs'
const PACKAGES = ['mykindlebox/client', 'mykindlebox/server']
function git(...args) {
return execFileSync('git', args, { encoding: 'utf8' })
}
function versionAt(ref) {
try {
return JSON.parse(git('show', `${ref}:mykindlebox/client/package.json`)).version
} catch {
return null // no HEAD yet, or the file didn't exist
}
}
if (process.env.SKIP_VERSION_BUMP === '1') process.exit(0)
const staged = git('diff', '--cached', '--name-only').split('\n').filter(Boolean)
if (!staged.some((file) => file.startsWith('mykindlebox/'))) process.exit(0)
const headVersion = versionAt('HEAD')
const stagedVersion = versionAt('') // `git show :path` reads the index
const manualBump = Boolean(headVersion && stagedVersion && headVersion !== stagedVersion)
const [major, minor, patch] = (stagedVersion ?? '0.0.0').split('.').map(Number)
const next = manualBump ? stagedVersion : `${major}.${minor}.${patch + 1}`
// Also brings the server (and lockfiles) along after a client-only manual bump.
for (const dir of PACKAGES) {
for (const name of ['package.json', 'package-lock.json']) {
const path = `${dir}/${name}`
const json = JSON.parse(readFileSync(path, 'utf8'))
if (json.version === next && (!json.packages?.[''] || json.packages[''].version === next)) continue
json.version = next
if (json.packages?.['']) json.packages[''].version = next
writeFileSync(path, `${JSON.stringify(json, null, 2)}\n`)
git('add', path)
}
}
console.log(`MyKindlebox version ${manualBump ? 'set' : 'bumped'} to ${next}`)