change-version.mjs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env node
  2. 'use strict'
  3. import { execFile } from 'node:child_process'
  4. import fs from 'node:fs/promises'
  5. import process from 'node:process'
  6. const VERBOSE = process.argv.includes('--verbose')
  7. const DRY_RUN = process.argv.includes('--dry') || process.argv.includes('--dry-run')
  8. const FILES = [
  9. 'README.md',
  10. 'test.md',
  11. 'preview/_config.yml',
  12. 'core/scss/_banner.scss',
  13. 'core/js/base.js'
  14. ]
  15. function regExpQuote(string) {
  16. return string.replace(/[$()*+-.?[\\\]^{|}]/g, '\\$&')
  17. }
  18. function regExpQuoteReplacement(string) {
  19. return string.replace(/\$/g, '$$')
  20. }
  21. async function replaceRecursively(file, oldVersion, newVersion) {
  22. const originalString = await fs.readFile(file, 'utf8')
  23. const newString = originalString
  24. .replace(
  25. new RegExp(regExpQuote(oldVersion), 'g'),
  26. regExpQuoteReplacement(newVersion)
  27. )
  28. // Also replace the version used by the rubygem,
  29. // which is using periods (`.`) instead of hyphens (`-`)
  30. .replace(
  31. new RegExp(regExpQuote(oldVersion.replace(/-/g, '.')), 'g'),
  32. regExpQuoteReplacement(newVersion.replace(/-/g, '.'))
  33. )
  34. // No need to move any further if the strings are identical
  35. if (originalString === newString) {
  36. return
  37. }
  38. if (VERBOSE) {
  39. console.log(`Found ${oldVersion} in ${file}`)
  40. }
  41. if (DRY_RUN) {
  42. return
  43. }
  44. await fs.writeFile(file, newString, 'utf8')
  45. }
  46. function showUsage(args) {
  47. console.error('USAGE: change-version old_version new_version [--verbose] [--dry[-run]]')
  48. console.error('Got arguments:', args)
  49. process.exit(1)
  50. }
  51. function bumpPnpmVersion(newVersion) {
  52. if (DRY_RUN) {
  53. return
  54. }
  55. if (process.env.npm_package_version !== newVersion) {
  56. execFile('pnpm', ['version', '-r', newVersion, '--no-git-tag'], { shell: true }, error => {
  57. if (error) {
  58. console.error(error)
  59. process.exit(1)
  60. }
  61. })
  62. }
  63. }
  64. async function main(args) {
  65. let [oldVersion, newVersion] = args
  66. if (!oldVersion || !newVersion) {
  67. showUsage(args)
  68. }
  69. [oldVersion, newVersion] = [oldVersion, newVersion].map(arg => {
  70. return arg.startsWith('v') ? arg.slice(1) : arg
  71. })
  72. if (oldVersion === newVersion) {
  73. showUsage(args)
  74. }
  75. bumpPnpmVersion(newVersion)
  76. try {
  77. await Promise.all(
  78. FILES.map(file => replaceRecursively(file, oldVersion, newVersion))
  79. )
  80. } catch (error) {
  81. console.error(error)
  82. process.exit(1)
  83. }
  84. }
  85. main(process.argv.slice(2))