-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparseExamples.js
101 lines (93 loc) · 3.51 KB
/
parseExamples.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
99
100
101
'use strict';
const fs = require('fs');
const yaml = require('yaml');
const xml2json = require('jgexml/xml2json').xml2json;
const abnf = require('abnf');
function parseExamples(s,options) {
var result = [];
let lines = s.split('\r').join('').split('\n');
let counter = 1;
let inFence = false;
let extension = 'txt';
let example = '';
let lineStart = 1;
for (let lineNo in lines) {
let line = lines[lineNo];
if (line.startsWith('```')) {
if (inFence) {
if ((extension === 'json') || (extension === 'yaml')) {
if ((extension === 'json') && (example.startsWith('"'))) {
example = '{'+example+'}';
}
if (extension === 'yaml') {
example = example.split('!include').join('#include');
}
var obj = {};
try {
obj = yaml.parse(example,{prettyErrors:true});
if (extension === 'yaml') {
example = yaml.stringify(obj);
}
else {
example = JSON.stringify(obj,null,2);
}
if (options.debug) console.log(example);
}
catch (ex) {
let entry = {};
entry.lineStart = parseInt(lineStart,10);
entry.lineEnd = parseInt(lineNo,10);
entry.extension = extension;
entry.message = ex.message;
result.push(entry);
return result;
}
}
if (extension === 'xml') {
let obj = xml2json(example);
if (options.debug) console.log(JSON.stringify(obj));
if (Object.keys(obj).length !== 1) {
let entry = {};
entry.lineStart = parseInt(lineStart,10);
entry.lineEnd = parseInt(lineNo,10);
entry.extension = extension;
entry.message = 'No root element found';
result.push(entry);
return result;
}
}
if (extension === 'abnf') {
abnf.Parse(example,function(err,rules){
if (err) {
let entry = {};
entry.lineStart = parseInt(lineStart,10);
entry.lineEnd = parseInt(lineNo,10);
entry.extension = extension;
entry.message = err;
result.push(entry);
return result;
}
});
}
example = '';
counter++;
extension = 'txt';
inFence = false;
}
else {
inFence = true;
lineStart = lineNo;
extension = line.split('`').pop().trim().toLowerCase();
if (extension === 'yml') extension = 'yaml';
if (!extension) extension = 'txt';
}
}
else if (inFence) {
example += line + '\n';
}
}
return result;
}
module.exports = {
parseExamples : parseExamples
};