presets_extract_labels.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Creates a JSON file for Transifex to allow translation of XML presets.
  3. */
  4. const fs = require('fs');
  5. const parseString = require('xml2js').parseString;
  6. const Hash = require("object-hash");
  7. const PRESETS_DIR = "./public/presets";
  8. const LOCALES_DIR = "./src/config/locales/presets";
  9. const XML_RGX = /^[A-Za-z0-9_\-]+\.xml$/;
  10. const foundLabels = {};
  11. const entryToLabels = entry => {
  12. Object.entries(entry).forEach(e => {
  13. const [ k, v ] = e;
  14. if(k === "$") {
  15. Object.entries(v).forEach(ve => {
  16. const [ vk, vv ] = ve;
  17. if([ "text", "name", "display_values", "display_value"].includes(vk)) {
  18. foundLabels[Hash(vv)] = vv;
  19. }
  20. });
  21. }
  22. else {
  23. entryToLabels(v);
  24. }
  25. });
  26. };
  27. //Read translation files
  28. fs.readdirSync(PRESETS_DIR).forEach((file) => {
  29. if(XML_RGX.test(file)) {
  30. try {
  31. const xml = fs.readFileSync(PRESETS_DIR+"/"+file, 'utf8');
  32. // Parse XML content
  33. parseString(xml, (err, result) => {
  34. if (err) {
  35. throw new Error("Parse error", e.message);
  36. }
  37. else {
  38. entryToLabels(result);
  39. }
  40. });
  41. }
  42. catch(e) {
  43. throw new Error("Can't read file: "+file+" ("+e.message+")");
  44. }
  45. }
  46. else {
  47. console.log("[INFO] Ignored file "+file);
  48. }
  49. });
  50. // Export found labels
  51. fs.writeFile(LOCALES_DIR+"/en.json", JSON.stringify({ "en": foundLabels }, null, 2), function(err) {
  52. if(err) {
  53. throw new Error(err);
  54. }
  55. else {
  56. console.log("[INFO] Translation file for presets updated");
  57. }
  58. });