checkVariables.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Usage: node checkVariables.js <locale>
  2. const fs = require('fs')
  3. const Path = require('path')
  4. const GLOBALS = ['__appName__']
  5. const LOCALES = Path.join(__dirname, '../../locales')
  6. const baseLocalePath = Path.join(LOCALES, 'en.json')
  7. if (process.argv.length < 3) {
  8. console.error('Usage: node checkVariables.js <locale>')
  9. process.exit(1)
  10. }
  11. const localeName = process.argv[2]
  12. const localePath = Path.join(LOCALES, `${localeName}.json`)
  13. const baseLocale = JSON.parse(fs.readFileSync(baseLocalePath, 'utf-8'))
  14. const locale = JSON.parse(fs.readFileSync(localePath, 'utf-8'))
  15. function fetchKeys(str) {
  16. const matches = str.matchAll(/__.*?__/g)
  17. if (matches.length === 0) {
  18. return []
  19. }
  20. return Array.from(matches).map(match => match[0])
  21. }
  22. function difference(base, target) {
  23. const keysInBaseButNotInTarget = base.filter(key => !target.includes(key))
  24. const keysInTargetButNotInBase = target.filter(
  25. key => !base.includes(key) && !GLOBALS.includes(key)
  26. )
  27. return {
  28. keysInBaseButNotInTarget,
  29. keysInTargetButNotInBase,
  30. }
  31. }
  32. for (const key of Object.keys(locale)) {
  33. if (Object.prototype.hasOwnProperty.call(baseLocale, key)) {
  34. const keysInTranslation = fetchKeys(locale[key])
  35. const keysInBase = fetchKeys(baseLocale[key])
  36. const { keysInBaseButNotInTarget, keysInTargetButNotInBase } = difference(
  37. keysInBase,
  38. keysInTranslation
  39. )
  40. if (keysInBaseButNotInTarget.length) {
  41. console.warn(
  42. `Warning: Missing variables in key ${key}:`,
  43. keysInBaseButNotInTarget
  44. )
  45. }
  46. if (keysInTargetButNotInBase.length) {
  47. console.warn(
  48. `Warning: Extra variables in key ${key}:`,
  49. keysInTargetButNotInBase
  50. )
  51. }
  52. }
  53. }