forked from ryanwholey/gulp-svg2png
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
99 lines (82 loc) · 2.06 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* gulp-svg2png
*
* Copyright(c) 2014 - present / André König <[email protected]>
* MIT Licensed
*
*/
/**
* @author André König <[email protected]>
*
*/
'use strict';
import path = require('path');
import gutil = require('gulp-util');
const map_limit = require('map-stream-limit');
const map = require('map-stream');
const svg2png = require('svg2png');
import { SVG } from './lib/index';
const PLUGIN_NAME = require('./package.json').name;
class Command {
constructor(private options: Object = {}, private verbose: boolean = true) { }
/**
* Wrapper around gutil logger.
* Logs if logging is enabled.
*
* @param {string} message The log message
*
*/
private log(message: string) {
if (this.verbose) {
gutil.log(message);
}
}
/**
* Just a global error function.
*
* @param {string} message The error message
*
*/
private error(message: string) {
throw new gutil.PluginError(PLUGIN_NAME, message);
}
/**
* Renames the SVG file to a PNG file (extension)
*
* @param {string} filename The file name of the SVG
*
* @return {string} The file name with the PNG file extension.
*
*/
private rename(filename: string) {
return filename.replace(path.extname(filename), '.png');
}
execute(source: any, cb: Function) {
if (!source.isBuffer()) {
return this.error('Streams are not supported by the underlying svg2png library.');
}
if (!SVG.is(source.contents)) {
return this.error('Source is not a SVG file.');
}
const buffer = source._contents ? source._contents : source;
svg2png(buffer, this.options)
.then((contents: Buffer) => {
cb(null, new gutil.File({
base: source.base,
path: this.rename(source.path),
contents
}))
})
.catch((err: Error) =>
cb(this.error(`Error while converting the image: ${err.message}`))
);
}
}
export = (options: Object = {}, verbose: boolean = true, concurrency: number = null) => {
const cmd = new Command(options, verbose);
if (concurrency) {
return map_limit(cmd.execute.bind(cmd), concurrency);
} else {
return map(cmd.execute.bind(cmd));
}
};