checkVariables.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import fs from 'fs'
  2. import Path from 'path'
  3. import { fileURLToPath } from 'node:url'
  4. import { loadLocale } from './utils.js'
  5. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  6. const GLOBALS = ['__appName__']
  7. const LOCALES = Path.join(__dirname, '../../locales')
  8. const baseLocale = loadLocale('en')
  9. const baseLocaleKeys = Object.keys(baseLocale)
  10. const IGNORE_ORPHANED_TRANSLATIONS = process.argv.includes(
  11. '--ignore-orphaned-translations'
  12. )
  13. const IGNORE_NESTING_FOR = {
  14. over_x_templates_easy_getting_started: ['__templates__'],
  15. all_packages_and_templates: ['__templatesLink__'],
  16. }
  17. function fetchKeys(str) {
  18. const matches = str.matchAll(/__.*?__/g)
  19. if (matches.length === 0) {
  20. return []
  21. }
  22. return Array.from(matches).map(match => match[0])
  23. }
  24. function difference(key, base, target) {
  25. const nesting = IGNORE_NESTING_FOR[key] || []
  26. const keysInBaseButNotInTarget = base.filter(
  27. key => !target.includes(key) && !nesting.includes(key)
  28. )
  29. const keysInTargetButNotInBase = target.filter(
  30. key => !base.includes(key) && !GLOBALS.includes(key)
  31. )
  32. return {
  33. keysInBaseButNotInTarget,
  34. keysInTargetButNotInBase,
  35. }
  36. }
  37. let violations = 0
  38. for (const localeName of fs.readdirSync(LOCALES)) {
  39. if (localeName === 'README.md') continue
  40. const locale = loadLocale(localeName.replace('.json', ''))
  41. for (const key of Object.keys(locale)) {
  42. if (!baseLocaleKeys.includes(key)) {
  43. if (IGNORE_ORPHANED_TRANSLATIONS) continue
  44. violations += 1
  45. console.warn(`[${localeName}] Orphaned key "${key}" not found in en.json`)
  46. continue
  47. }
  48. const keysInTranslation = fetchKeys(locale[key])
  49. const keysInBase = fetchKeys(baseLocale[key])
  50. const { keysInBaseButNotInTarget, keysInTargetButNotInBase } = difference(
  51. key,
  52. keysInBase,
  53. keysInTranslation
  54. )
  55. if (keysInBaseButNotInTarget.length) {
  56. violations += keysInBaseButNotInTarget.length
  57. console.warn(
  58. `[${localeName}] Missing variables in key "${key}":`,
  59. keysInBaseButNotInTarget
  60. )
  61. }
  62. if (keysInTargetButNotInBase.length) {
  63. violations += keysInTargetButNotInBase.length
  64. console.warn(
  65. `[${localeName}] Extra variables in key "${key}":`,
  66. keysInTargetButNotInBase
  67. )
  68. }
  69. }
  70. }
  71. if (violations) {
  72. console.warn('Variables are not in sync between translations.')
  73. process.exit(1)
  74. } else {
  75. console.log('Variables are in sync.')
  76. process.exit(0)
  77. }