extract-translations.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const path = require('path');
  2. const fs = require('fs-extra');
  3. const spawn = require('cross-spawn');
  4. const MESSAGES_DIR = path.join(__dirname, '../src/lib/static/i18n-messages');
  5. extractTranslations().then(
  6. () => {
  7. process.exit(0);
  8. },
  9. (error) => {
  10. console.log(error);
  11. process.exit(1);
  12. },
  13. );
  14. async function extractTranslations() {
  15. const locales = fs.readdirSync(MESSAGES_DIR).map((file) => path.basename(file).replace('.json', ''));
  16. for (const locale of locales) {
  17. const outputPath = path.join(
  18. path.relative(path.join(__dirname, '..'), MESSAGES_DIR),
  19. `${locale}.json`,
  20. );
  21. console.log(`Extracting translation tokens for "${outputPath}"`);
  22. try {
  23. await runExtraction(locale);
  24. const { tokenCount, translatedCount, percentage } = getStatsForLocale(locale);
  25. console.log(`${locale}: ${translatedCount} of ${tokenCount} tokens translated (${percentage}%)`);
  26. console.log('');
  27. } catch (e) {
  28. console.log(e);
  29. }
  30. }
  31. }
  32. function runExtraction(locale) {
  33. const command = 'npm';
  34. const args = getNgxTranslateExtractCommand(locale);
  35. return new Promise((resolve, reject) => {
  36. try {
  37. const child = spawn(`yarnpkg`, args, { stdio: ['pipe', 'pipe', process.stderr] });
  38. child.on('close', (x) => {
  39. resolve();
  40. });
  41. child.on('error', (err) => {
  42. reject(err);
  43. });
  44. } catch (e) {
  45. reject(e);
  46. }
  47. });
  48. }
  49. function getStatsForLocale(locale) {
  50. const content = fs.readJsonSync(path.join(MESSAGES_DIR, `${locale}.json`), 'utf-8');
  51. let tokenCount = 0;
  52. let translatedCount = 0;
  53. for (const section of Object.keys(content)) {
  54. const sectionTranslations = Object.values(content[section]);
  55. tokenCount += sectionTranslations.length;
  56. translatedCount += sectionTranslations.filter((val) => val !== '').length;
  57. }
  58. const percentage = Math.round((translatedCount / tokenCount) * 100);
  59. return {
  60. tokenCount,
  61. translatedCount,
  62. percentage,
  63. };
  64. }
  65. function getNgxTranslateExtractCommand(locale) {
  66. return [
  67. `ngx-translate-extract`,
  68. '--input',
  69. './src',
  70. '--output',
  71. `./src/lib/static/i18n-messages/${locale}.json`,
  72. `--clean`,
  73. `--sort`,
  74. `--format`,
  75. `namespaced-json`,
  76. `--format-indentation`,
  77. `" "`,
  78. `-m`,
  79. `_`,
  80. ];
  81. }