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