gulp-removeShaderComments.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. var through = require('through2');
  3. var PluginError = require('gulp-util').PluginError;
  4. var singleComment = 1;
  5. var multiComment = 2;
  6. function uncomment(str, opts) {
  7. opts = opts || {};
  8. var currentChar;
  9. var nextChar;
  10. var insideString = false;
  11. var insideComment = 0;
  12. var offset = 0;
  13. var ret = '';
  14. str = str.replace(/\r\n/g, '\n');
  15. str = str.replace(/[ \f\t\v]+/g, ' ');
  16. str = str.replace(/^\s*\n/gm, '');
  17. str = str.replace(/ \+ /g, '+');
  18. str = str.replace(/ \- /g, '-');
  19. str = str.replace(/ \/ /g, '/');
  20. str = str.replace(/ \* /g, '*');
  21. str = str.replace(/ > /g, '>');
  22. str = str.replace(/ < /g, '<');
  23. str = str.replace(/ >= /g, '>=');
  24. str = str.replace(/ <= /g, '<=');
  25. str = str.replace(/ \+= /g, '+=');
  26. str = str.replace(/ \-= /g, '-=');
  27. str = str.replace(/ \/= /g, '/=');
  28. str = str.replace(/ \*= /g, '*=');
  29. str = str.replace(/ = /g, '=');
  30. str = str.replace(/, /g, ',');
  31. str = str.replace(/\n\n/g, '\n');
  32. str = str.replace(/\n /g, '\n');
  33. for (var i = 0; i < str.length; i++) {
  34. currentChar = str[i];
  35. nextChar = str[i + 1];
  36. if (!insideComment && currentChar === '"') {
  37. var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\';
  38. if (!escaped) {
  39. insideString = !insideString;
  40. }
  41. }
  42. if (insideString) {
  43. continue;
  44. }
  45. if (!insideComment && currentChar + nextChar === '//') {
  46. ret += str.slice(offset, i);
  47. offset = i;
  48. insideComment = singleComment;
  49. i++;
  50. } else if (insideComment === singleComment && currentChar === '\n') {
  51. insideComment = 0;
  52. offset = i;
  53. } else if (!insideComment && currentChar + nextChar === '/*') {
  54. ret += str.slice(offset, i);
  55. offset = i;
  56. insideComment = multiComment;
  57. i++;
  58. continue;
  59. } else if (insideComment === multiComment && currentChar + nextChar === '*/') {
  60. i++;
  61. insideComment = 0;
  62. offset = i + 1;
  63. continue;
  64. }
  65. }
  66. return ret + (insideComment ? '' : str.substr(offset));
  67. }
  68. function gulpUncomment(options) {
  69. return main(options, uncomment);
  70. }
  71. function main(options, func) {
  72. return through.obj(function (file, enc, cb) {
  73. if (file.isNull()) {
  74. cb(null, file);
  75. return;
  76. }
  77. if (file.isStream()) {
  78. cb(new PluginError("Remove Shader Comments", "Streaming not supported."));
  79. }
  80. file.contents = new Buffer(func(file.contents.toString(), options));
  81. this.push(file);
  82. return cb();
  83. });
  84. }
  85. module.exports = gulpUncomment;