1 |
|
2 |
|
3 | (function () {
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | var _ = require('underscore'),
|
8 | through2 = require('through2'),
|
9 | fs = require('fs'),
|
10 | cheerio = require('cheerio'),
|
11 | gutil = require('gulp-util'),
|
12 | path = require('path'),
|
13 | async = require('async'),
|
14 | favicons = require('favicons');
|
15 |
|
16 | module.exports = function (params) {
|
17 |
|
18 | function updateDocument(document, code, callback) {
|
19 | var options = { encoding: 'utf8' };
|
20 | async.waterfall([
|
21 | function (callback) {
|
22 | fs.readFile(document, options, function (error, data) {
|
23 | return callback(error, data);
|
24 | });
|
25 | },
|
26 | function (data, callback) {
|
27 | var $ = cheerio.load(data, { decodeEntities: false });
|
28 | $('head').append(code.join('\n'));
|
29 | return callback(null, $.html());
|
30 | },
|
31 | function (html, callback) {
|
32 | fs.writeFile(document, html, options, function (error) {
|
33 | return callback(error);
|
34 | });
|
35 | }
|
36 | ], function (error) {
|
37 | return callback(error);
|
38 | });
|
39 | }
|
40 |
|
41 | return through2.obj(function (file, encoding, callback) {
|
42 |
|
43 | var self = this, documents, $;
|
44 |
|
45 | if (file.isNull()) {
|
46 | callback(null, file);
|
47 | return;
|
48 | }
|
49 |
|
50 | if (file.isStream()) {
|
51 | callback(new gutil.PluginError('gulp-favicons', 'Streaming not supported'));
|
52 | return;
|
53 | }
|
54 |
|
55 | favicons(file.contents, params, function (error, response) {
|
56 |
|
57 | _.each(response.images, function (image) {
|
58 | self.push(new gutil.File({
|
59 | path: image.name,
|
60 | contents: image.contents
|
61 | }));
|
62 | });
|
63 |
|
64 | _.each(response.files, function (file) {
|
65 | self.push(new gutil.File({
|
66 | path: file.name,
|
67 | contents: new Buffer(file.contents)
|
68 | }));
|
69 | });
|
70 |
|
71 | if (params.html) {
|
72 | documents = (typeof params.html === 'object' ? params.html : [params.html]);
|
73 | async.each(documents, function (document) {
|
74 | var filepath = path.join(__dirname, document);
|
75 | updateDocument(filepath, response.html, function (error) {
|
76 | return callback(error);
|
77 | })
|
78 | }, function (error2) {
|
79 | return callback(error || error2);
|
80 | });
|
81 | } else {
|
82 | return callback(error);
|
83 | }
|
84 | });
|
85 |
|
86 | });
|
87 |
|
88 | };
|
89 |
|
90 | }());
|