index.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. var path = require('path');
  3. var consolidate = require('consolidate');
  4. var extend = require('node.extend');
  5. var PluginError = require('gulp-util').PluginError;
  6. var ES6Promise = global.Promise || require('es6-promise').Promise;
  7. var readFile = require('fs-readfile-promise');
  8. var through = require('through2');
  9. var tryit = require('tryit');
  10. var VinylBufferStream = require('vinyl-bufferstream');
  11. consolidate.requires.lodash = require('lodash');
  12. var PLUGIN_NAME = 'gulp-wrap';
  13. module.exports = function gulpWrap(opts, data, options) {
  14. var promise;
  15. if (typeof opts === 'object') {
  16. if (typeof opts.src !== 'string') {
  17. throw new PluginError(PLUGIN_NAME, new TypeError('Expecting `src` option.'));
  18. }
  19. promise = readFile(opts.src, 'utf8');
  20. } else {
  21. if (typeof opts !== 'string' && typeof opts !== 'function') {
  22. throw new PluginError(PLUGIN_NAME, 'Template must be a string or a function.');
  23. }
  24. promise = ES6Promise.resolve(opts);
  25. }
  26. return through.obj(function gulpWrapTransform(file, enc, cb) {
  27. function compile(contents, done) {
  28. if (typeof data === 'function') {
  29. data = data.call(null, file);
  30. }
  31. if (typeof options === 'function') {
  32. options = options.call(null, file);
  33. }
  34. data = data || {};
  35. options = options || {};
  36. if (!options.engine) {
  37. options.engine = 'lodash';
  38. }
  39. // attempt to parse the file contents for JSON or YAML files
  40. if (options.parse !== false) {
  41. var ext = path.extname(file.path).toLowerCase();
  42. tryit(function() {
  43. if (ext === '.json') {
  44. contents = JSON.parse(contents);
  45. } else if (ext === '.yml' || ext === '.yaml') {
  46. contents = require('js-yaml').safeLoad(contents);
  47. }
  48. }, function(err) {
  49. if (!err) {
  50. return;
  51. }
  52. throw new PluginError(PLUGIN_NAME, 'Error parsing ' + file.path);
  53. });
  54. }
  55. var newData = extend({file: file}, options, data, file.data, {contents: contents});
  56. promise.then(function(template) {
  57. if (typeof template === 'function') {
  58. template = template(newData);
  59. }
  60. consolidate[options.engine].render(template, newData, function(err, result) {
  61. if (err) {
  62. done(new PluginError(PLUGIN_NAME, err));
  63. return;
  64. }
  65. done(null, new Buffer(result));
  66. });
  67. }, done).catch(done);
  68. }
  69. var run = new VinylBufferStream(compile);
  70. var self = this;
  71. run(file, function(err, contents) {
  72. if (err) {
  73. self.emit('error', err);
  74. } else {
  75. file.contents = contents;
  76. self.push(file);
  77. }
  78. cb();
  79. });
  80. });
  81. };