-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
98 lines (79 loc) · 2.27 KB
/
index.js
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
var Stream = require('stream')
, marked = require('marked')
, gutil = require('gulp-util')
, path = require('path')
, BufferStreams = require('bufferstreams')
, _ = require('lodash')
;
const PLUGIN_NAME = 'gulp-marked';
// File level transform function
function fileMarked(opt) {
// Return a callback function handling the buffered content
return function(err, buf, cb) {
// Handle any error
if(err) throw err;
// Create a new Renderer object
if (opt) {
opt.renderer = _.extend(new marked.Renderer(), opt.renderer)
}
// Use the buffered content
marked(String(buf), opt, function (err, content) {
// Report any error with the callback
if (err) {
cb(new gutil.PluginError(PLUGIN_NAME, err, {showStack: true}));
// Give the transformed buffer back
} else {
cb(null, content);
}
});
};
}
// Plugin function
function gulpMarked(opt) {
// Create a new Renderer object
if (opt) {
opt.renderer = _.extend(new marked.Renderer(), opt.renderer)
}
marked.setOptions(opt || {});
var stream = Stream.Transform({objectMode: true});
stream._transform = function(file, unused, done) {
// Do nothing when null
if(file.isNull()) {
stream.push(file); done();
return;
}
// If the ext doesn't match, pass it through
var ext = path.extname(file.path);
if('.md' !== ext && '.markdown' !== ext) {
stream.push(file); done();
return;
}
file.path = gutil.replaceExtension(file.path, ".html");
// Buffers
if(file.isBuffer()) {
marked(String(file.contents), function (err, content) {
if(err) {
stream.emit('error',
new gutil.PluginError(PLUGIN_NAME, err, {showStack: true}));
return done();
}
else if (cb) {
content = cb(err, content);
}
file.contents = Buffer(content);
stream.push(file);
done();
});
// Streams
} else {
file.contents = file.contents.pipe(new BufferStreams(fileMarked()));
stream.push(file);
done();
}
};
return stream;
};
// Export the file level transform function for other plugins usage
gulpMarked.fileTransform = fileMarked;
// Export the plugin main function
module.exports = gulpMarked;