fix-transifex.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. const fs = require('fs');
  3. const fse = require('fs-extra');
  4. const DIR = '_locales/';
  5. const RX_LNG_CODE = /^\w\w(_\w{2,3})?$/; // like `en` or `en_GB`
  6. const makeFileName = lng => `${DIR}${lng}/messages.json`;
  7. const readLngJson = lng => fse.readJsonSync(makeFileName(lng));
  8. const sortAlpha = ([a], [b]) => a < b ? -1 : a > b;
  9. const src = readLngJson('en');
  10. for (const val of Object.values(src)) {
  11. const {placeholders} = val;
  12. if (placeholders) {
  13. const sorted = {};
  14. for (const [k, v] of Object.entries(placeholders).sort(sortAlpha)) {
  15. sorted[k] = v;
  16. }
  17. val.placeholders = sorted;
  18. }
  19. }
  20. let numTotal = 0;
  21. let numFixed = 0;
  22. for (const /**@type Dirent*/ entry of fs.readdirSync(DIR, {withFileTypes: true})) {
  23. const lng = entry.name;
  24. if (lng !== 'en' && entry.isDirectory() && RX_LNG_CODE.test(lng)) {
  25. numFixed += fixLngFile(lng) ? 1 : 0;
  26. numTotal++;
  27. }
  28. }
  29. console.log(`${numFixed} files fixed out of ${numTotal}`);
  30. function fixLngFile(lng) {
  31. let numUnknown = 0;
  32. let numUntranslated = 0;
  33. let numVarsFixed = 0;
  34. const json = readLngJson(lng);
  35. const res = {};
  36. for (const [key, val] of Object.entries(json).sort(sortAlpha)) {
  37. const {placeholders, message} = src[key] || {};
  38. if (!message) {
  39. numUnknown++;
  40. } else if (!val.message || val.message === message) {
  41. numUntranslated++;
  42. } else {
  43. delete val.description;
  44. if (placeholders && !val.placeholders) {
  45. numVarsFixed++;
  46. val.placeholders = placeholders;
  47. }
  48. res[key] = val;
  49. }
  50. }
  51. const jsonStr = JSON.stringify(json, null, 2);
  52. const resStr = JSON.stringify(res, null, 2);
  53. if (resStr !== jsonStr) {
  54. let err;
  55. if (resStr === '{}') {
  56. fs.rmdirSync(`${DIR}${lng}`, {recursive: true});
  57. err = 'no translations -> deleted';
  58. } else {
  59. fse.outputFileSync(makeFileName(lng), resStr + '\n');
  60. err = [
  61. numUnknown && `${numUnknown} unknown (dropped)`,
  62. numUntranslated && `${numUntranslated} untranslated (dropped)`,
  63. numVarsFixed && `${numVarsFixed} missing placeholders (restored)`,
  64. ].filter(Boolean).join(', ');
  65. }
  66. if (err) console.log(`${lng}: ${err}`);
  67. return err;
  68. }
  69. }