change-version.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env node
  2. /*!
  3. * Script to update version number references in the project.
  4. * Copyright 2017-2021 The Bootstrap Authors
  5. * Copyright 2017-2021 Twitter, Inc.
  6. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
  7. */
  8. 'use strict'
  9. const fs = require('fs').promises
  10. const path = require('path')
  11. const globby = require('globby')
  12. const VERBOSE = process.argv.includes('--verbose')
  13. const DRY_RUN = process.argv.includes('--dry') || process.argv.includes('--dry-run')
  14. // These are the filetypes we only care about replacing the version
  15. const GLOB = [
  16. '**/*.{css,html,js,json,md,scss,txt,yml}'
  17. ]
  18. const GLOBBY_OPTIONS = {
  19. cwd: path.join(__dirname, '..'),
  20. gitignore: true
  21. }
  22. // Blame TC39... https://github.com/benjamingr/RegExp.escape/issues/37
  23. function regExpQuote(string) {
  24. return string.replace(/[$()*+-.?[\\\]^{|}]/g, '\\$&')
  25. }
  26. function regExpQuoteReplacement(string) {
  27. return string.replace(/\$/g, '$$')
  28. }
  29. async function replaceRecursively(file, oldVersion, newVersion) {
  30. const originalString = await fs.readFile(file, 'utf8')
  31. const newString = originalString.replace(
  32. new RegExp(regExpQuote(oldVersion), 'g'), regExpQuoteReplacement(newVersion)
  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(`FILE: ${file}`)
  40. }
  41. if (DRY_RUN) {
  42. return
  43. }
  44. await fs.writeFile(file, newString, 'utf8')
  45. }
  46. async function main(args) {
  47. const [oldVersion, newVersion] = args
  48. if (!oldVersion || !newVersion) {
  49. console.error('USAGE: change-version old_version new_version [--verbose] [--dry[-run]]')
  50. console.error('Got arguments:', args)
  51. process.exit(1)
  52. }
  53. // Strip any leading `v` from arguments because otherwise we will end up with duplicate `v`s
  54. [oldVersion, newVersion].map(arg => arg.startsWith('v') ? arg.slice(1) : arg)
  55. try {
  56. const files = await globby(GLOB, GLOBBY_OPTIONS)
  57. await Promise.all(files.map(file => replaceRecursively(file, oldVersion, newVersion)))
  58. } catch (error) {
  59. console.error(error)
  60. process.exit(1)
  61. }
  62. }
  63. main(process.argv.slice(2))