UNPKG

2.93 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path');
4var Stream = require('readable-stream');
5var gutil = require('gulp-util');
6var BufferStreams = require('bufferstreams');
7var svg2ttf = require('svg2ttf');
8
9var PLUGIN_NAME = 'gulp-svg2ttf';
10
11// File level transform function
12function svg2ttfTransform(options) {
13 // Return a callback function handling the buffered content
14 return function svg2ttfTransformCb(err, buf, cb) {
15
16 // Handle any error
17 if(err) {
18 return cb(new gutil.PluginError(PLUGIN_NAME, err, { showStack: true }));
19 }
20
21 // Use the buffered content
22 try {
23 buf = new Buffer(svg2ttf(String(buf), {
24 ts: options.timestamp,
25 copyright: options.copyright,
26 }).buffer);
27 return cb(null, buf);
28 } catch(err2) {
29 return cb(new gutil.PluginError(PLUGIN_NAME, err2, { showStack: true }));
30 }
31
32 };
33}
34
35// Plugin function
36function svg2ttfGulp(options) {
37 var stream = new Stream.Transform({ objectMode: true });
38
39 options = options || {};
40 options.ignoreExt = options.ignoreExt || false;
41 options.clone = options.clone || false;
42 options.timestamp = 'number' === typeof options.timestamp ?
43 options.timestamp :
44 {}.undef;
45 options.copyright = 'string' === typeof options.copyright ?
46 options.copyright :
47 {}.undef;
48
49 stream._transform = function svg2ttfTransformStream(file, unused, done) {
50 var cntStream;
51 var newFile;
52
53 // When null just pass through
54 if(file.isNull()) {
55 stream.push(file); done();
56 return;
57 }
58
59 // If the ext doesn't match, pass it through
60 if((!options.ignoreExt) && '.svg' !== path.extname(file.path)) {
61 stream.push(file); done();
62 return;
63 }
64
65 // Fix for the vinyl clone method...
66 // https://github.com/wearefractal/vinyl/pull/9
67 if(options.clone) {
68 if(file.isBuffer()) {
69 stream.push(file.clone());
70 } else {
71 cntStream = file.contents;
72 file.contents = null;
73 newFile = file.clone();
74 file.contents = cntStream.pipe(new Stream.PassThrough());
75 newFile.contents = cntStream.pipe(new Stream.PassThrough());
76 stream.push(newFile);
77 }
78 }
79
80 file.path = gutil.replaceExtension(file.path, '.ttf');
81
82 // Buffers
83 if(file.isBuffer()) {
84 try {
85 file.contents = new Buffer(svg2ttf(String(file.contents), {
86 ts: options.timestamp,
87 copyright: options.copyright,
88 }).buffer);
89 } catch(err) {
90 stream.emit('error',
91 new gutil.PluginError(PLUGIN_NAME, err, { showStack: true }));
92 }
93
94 // Streams
95 } else {
96 file.contents = file.contents.pipe(new BufferStreams(svg2ttfTransform(options)));
97 }
98
99 stream.push(file);
100 done();
101 };
102
103 return stream;
104
105}
106
107// Export the file level transform function for other plugins usage
108svg2ttfGulp.fileTransform = svg2ttfTransform;
109
110// Export the plugin main function
111module.exports = svg2ttfGulp;