UNPKG

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