gulp-removeShaderComments.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. for (var i = 0; i < str.length; i++) {
  18. currentChar = str[i];
  19. nextChar = str[i + 1];
  20. if (!insideComment && currentChar === '"') {
  21. var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\';
  22. if (!escaped) {
  23. insideString = !insideString;
  24. }
  25. }
  26. if (insideString) {
  27. continue;
  28. }
  29. if (!insideComment && currentChar + nextChar === '//') {
  30. ret += str.slice(offset, i);
  31. offset = i;
  32. insideComment = singleComment;
  33. i++;
  34. } else if (insideComment === singleComment && currentChar === '\n') {
  35. insideComment = 0;
  36. offset = i;
  37. } else if (!insideComment && currentChar + nextChar === '/*') {
  38. ret += str.slice(offset, i);
  39. offset = i;
  40. insideComment = multiComment;
  41. i++;
  42. continue;
  43. } else if (insideComment === multiComment && currentChar + nextChar === '*/') {
  44. i++;
  45. insideComment = 0;
  46. offset = i + 1;
  47. continue;
  48. }
  49. }
  50. return ret + (insideComment ? '' : str.substr(offset));
  51. }
  52. function gulpUncomment(options) {
  53. return main(options, uncomment);
  54. }
  55. function main(options, func) {
  56. return through.obj(function (file, enc, cb) {
  57. if (file.isNull()) {
  58. cb(null, file);
  59. return;
  60. }
  61. if (file.isStream()) {
  62. cb(new PluginError("Remove Shader Comments", "Streaming not supported."));
  63. }
  64. file.contents = new Buffer(func(file.contents.toString(), options));
  65. this.push(file);
  66. return cb();
  67. });
  68. }
  69. module.exports = gulpUncomment;