gulp-split-translations.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. var through = require('through2');
  2. var gutil = require('gulp-util');
  3. var PluginError = gutil.PluginError;
  4. var path = require('path');
  5. var fs = require('fs');
  6. var pofile = require('pofile');
  7. var _ = require('lodash');
  8. const PLUGIN_NAME = 'gulp-split-translations.js';
  9. module.exports = function(sections) {
  10. // Creating a stream through which each file will pass
  11. var stream = through.obj(function(file, enc, callback) {
  12. if (file.isBuffer()) {
  13. // If we aren't splitting out sections, just pass through.
  14. if (!Object.keys(sections).length) {
  15. this.push(file);
  16. return callback();
  17. }
  18. var content = file.contents.toString();
  19. var parsed = JSON.parse(content);
  20. var lang = Object.keys(parsed)[0];
  21. var poContent = fs.readFileSync(
  22. path.resolve(
  23. __dirname,
  24. '../../../site-translations/' + lang + '/main.po'
  25. ),
  26. 'utf8'
  27. );
  28. var poParsed = pofile.parse(poContent);
  29. var poItems = _.indexBy(poParsed.items, 'msgid');
  30. _.forEach(
  31. sections,
  32. function(sectionPaths, sectionName) {
  33. var sectionReferenceRegex = new RegExp(
  34. '^(' + sectionPaths.join('|') + ')'
  35. );
  36. var sectionJson = {};
  37. sectionJson[lang] = {};
  38. // For each translation term in this language.
  39. for (var i in parsed[lang]) {
  40. var poItem = poItems[i];
  41. if (poItem) {
  42. var matchingReferences = 0;
  43. for (var j in poItem.references) {
  44. if (poItem.references[j].match(sectionReferenceRegex)) {
  45. ++matchingReferences;
  46. }
  47. }
  48. // We only pull it into the section if ALL the references belong to the section.
  49. // Otherwise we want to put it as part of the "common" translation file.
  50. if (matchingReferences == poItem.references.length) {
  51. sectionJson[lang][i] = parsed[lang][i];
  52. delete parsed[lang][i];
  53. }
  54. }
  55. }
  56. this.push(
  57. new gutil.File({
  58. cwd: file.cwd,
  59. base: file.base,
  60. path: path.join(path.dirname(file.path), sectionName + '.json'),
  61. contents: new Buffer(JSON.stringify(sectionJson), 'utf-8'),
  62. })
  63. );
  64. },
  65. this
  66. );
  67. file.contents = new Buffer(JSON.stringify(parsed), 'utf-8');
  68. } else if (file.isStream()) {
  69. // Streams not supported.
  70. this.emit(
  71. 'error',
  72. new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported.')
  73. );
  74. return callback();
  75. }
  76. // Anything else just falls through.
  77. this.push(file);
  78. return callback();
  79. });
  80. // returning the file stream
  81. return stream;
  82. };