generateLocalePacks.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // To avoid adding a lot of boilerplate, locale packs are
  2. // automatically generated here. These are written into the tmp/
  3. // directory and then used to generate locale_en.js, locale_fr.js, etc.
  4. const fs = require('fs');
  5. const path = require('path');
  6. const rimraf = require('rimraf');
  7. const mkdirp = require('mkdirp');
  8. const localesJsonPath = path.join(__dirname, '../../app/javascript/mastodon/locales');
  9. const locales = fs.readdirSync(localesJsonPath).filter(filename => {
  10. return /\.json$/.test(filename) &&
  11. !/defaultMessages/.test(filename) &&
  12. !/whitelist/.test(filename);
  13. }).map(filename => filename.replace(/\.json$/, ''));
  14. const outPath = path.join(__dirname, '../../tmp/packs');
  15. rimraf.sync(outPath);
  16. mkdirp.sync(outPath);
  17. const outPaths = [];
  18. locales.forEach(locale => {
  19. const localePath = path.join(outPath, `locale_${locale}.js`);
  20. const baseLocale = locale.split('-')[0]; // e.g. 'zh-TW' -> 'zh'
  21. const localeDataPath = [
  22. // first try react-intl
  23. `../../node_modules/react-intl/locale-data/${baseLocale}.js`,
  24. // then check locales/locale-data
  25. `../../app/javascript/mastodon/locales/locale-data/${baseLocale}.js`,
  26. // fall back to English (this is what react-intl does anyway)
  27. '../../node_modules/react-intl/locale-data/en.js',
  28. ].filter(filename => fs.existsSync(path.join(outPath, filename)))
  29. .map(filename => filename.replace(/..\/..\/node_modules\//, ''))[0];
  30. const localeContent = `//
  31. // locale_${locale}.js
  32. // automatically generated by generateLocalePacks.js
  33. //
  34. import messages from '../../app/javascript/mastodon/locales/${locale}.json';
  35. import localeData from ${JSON.stringify(localeDataPath)};
  36. import { setLocale } from '../../app/javascript/mastodon/locales';
  37. setLocale({messages, localeData});
  38. `;
  39. fs.writeFileSync(localePath, localeContent, 'utf8');
  40. outPaths.push(localePath);
  41. });
  42. module.exports = outPaths;