-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
98 lines (85 loc) · 2.7 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
98
/*jshint node:true,strict:true,undef:true,unused:true*/
'use strict';
var raml2htmlLib = require('raml2html');
var through2 = require('through2');
var gutil = require('gulp-util');
var util = require('util');
var path = require('path');
var PLUGIN_NAME = 'gulp-raml2html';
var PluginError = gutil.PluginError;
var File = gutil.File;
function raml2html(filename, source, https, callback) {
var cwd = process.cwd();
var nwd = path.resolve(path.dirname(filename));
process.chdir(nwd);
var config = raml2htmlLib.getDefaultConfig();
config.https = https;
raml2htmlLib.render(source, config)
.then(function (html) {
process.chdir(cwd);
process.nextTick(function () {
callback(null, html);
});
},
function (ramlError) {
process.chdir(cwd);
process.nextTick(function () {
var mark = ramlError.problem_mark;
mark = mark ? ':' + (mark.line + 1) + ':' + (mark.column + 1) : '';
var context = ('' + [ramlError.context]).trim();
context = context ? ' ' + context : '';
var message = util.format('%s%s: Parse error%s: %s', filename, mark, context, ramlError.message);
callback(new Error(message));
});
});
}
function convertFile(file, source, https, self, callback) {
raml2html(file.path, source, https, function (error, html) {
if (error) {
self.emit('error', new PluginError(PLUGIN_NAME, error));
} else {
var htmlFile = new File({
base: file.base,
cwd: file.cwd,
path: gutil.replaceExtension(file.path, '.html'),
contents: new Buffer(html)
});
self.push(htmlFile);
}
callback();
});
}
function parseJSON(buffer) {
try {
return JSON.parse('' + buffer);
} catch (error) {
return undefined;
}
}
function gulpRaml2html(options) {
options = options || {};
var supportJsonInput = !!options.supportJsonInput;
var https = options.https || false;
return through2.obj(function (file, enc, callback) {
if (file.isNull()) {
// do nothing if no contents
}
if (file.isBuffer()) {
if (file.contents.slice(0, 11).toString('binary') === '#%RAML 0.8\n' ||
file.contents.slice(0, 12).toString('binary') === '#%RAML 0.8\r\n') {
return convertFile(file, file.contents, https, this, callback); // got RAML signature
} else if (supportJsonInput) {
var json = parseJSON(file.contents);
if (json) {
return convertFile(file, json, https, this, callback); // valid JSON
}
}
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
}
this.push(file);
return callback();
});
}
module.exports = gulpRaml2html;