This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
/
parser.js
464 lines (390 loc) · 16 KB
/
parser.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var util = require('util');
var iconv = require('iconv-lite');
var findFiles = require('./utils/find_files');
var ParameterError = require('./errors/parameter_error');
var ParserError = require('./errors/parser_error');
var app = {};
function Parser(_app) {
var self = this;
// global variables
app = _app;
// class variables
self.languages = {};
self.parsers = {};
self.parsedFileElements = [];
self.parsedFiles = [];
self.countDeprecated = {};
// load languages
var languages = Object.keys(app.languages);
languages.forEach(function(language) {
if (_.isObject( app.languages[language] )) {
app.log.debug('inject parser language: ' + language);
self.addLanguage(language, app.languages[language] );
} else {
var filename = app.languages[language];
app.log.debug('load parser language: ' + language + ', ' + filename);
self.addLanguage(language, require(filename));
}
});
// load parser
var parsers = Object.keys(app.parsers);
parsers.forEach(function(parser) {
if (_.isObject( app.parsers[parser] )) {
app.log.debug('inject parser: ' + parser);
self.addParser(parser, app.parsers[parser] );
} else {
var filename = app.parsers[parser];
app.log.debug('load parser: ' + parser + ', ' + filename);
self.addParser(parser, require(filename));
}
});
}
/**
* Inherit
*/
util.inherits(Parser, Object);
/**
* Exports
*/
module.exports = Parser;
/**
* Add a Language
*/
Parser.prototype.addLanguage = function(name, language) {
this.languages[name] = language;
};
/**
* Add a Parser
*/
Parser.prototype.addParser = function(name, parser) {
this.parsers[name] = parser;
};
/**
* Parse files in specified folder
*
* @param {Object} options The options used to parse and filder the files.
* @param {Object[]} parsedFiles List of parsed files.
* @param {String[]} parsedFilenames List of parsed files, with full path.
*/
Parser.prototype.parseFiles = function(options, parsedFiles, parsedFilenames) {
var self = this;
findFiles.setPath(options.src);
findFiles.setExcludeFilters(options.excludeFilters);
findFiles.setIncludeFilters(options.includeFilters);
var files = findFiles.search();
// Parser
for (var i = 0; i < files.length; i += 1) {
var filename = options.src + files[i];
var parsedFile = self.parseFile(filename, options.encoding);
if (parsedFile) {
app.log.verbose('parse file: ' + filename);
parsedFiles.push(parsedFile);
parsedFilenames.push(filename);
}
}
};
/**
* Execute Fileparsing
*/
Parser.prototype.parseFile = function(filename, encoding) {
var self = this;
if (typeof(encoding) === 'undefined')
encoding = 'utf8';
app.log.debug('inspect file: ' + filename);
self.filename = filename;
self.extension = path.extname(filename).toLowerCase();
// TODO: Not sure if this is correct. Without skipDecodeWarning we got string errors
// https://github.com/apidoc/apidoc-core/pull/25
var fileContent = fs.readFileSync(filename, { encoding: 'binary' });
iconv.skipDecodeWarning = true;
self.src = iconv.decode(fileContent, encoding);
app.log.debug('size: ' + self.src.length);
// unify line-breaks
self.src = self.src.replace(/\r\n/g, '\n');
self.blocks = [];
self.indexApiBlocks = [];
// determine blocks
self.blocks = self._findBlocks();
if (self.blocks.length === 0)
return;
app.log.debug('count blocks: ' + self.blocks.length);
// determine elements in blocks
self.elements = self.blocks.map(function(block, i) {
var elements = self.findElements(block, filename);
app.log.debug('count elements in block ' + i + ': ' + elements.length);
return elements;
});
if (self.elements.length === 0)
return;
// determine list of blocks with API elements
self.indexApiBlocks = self._findBlockWithApiGetIndex(self.elements);
if (self.indexApiBlocks.length === 0)
return;
return self._parseBlockElements(self.indexApiBlocks, self.elements, filename);
};
/**
* Parse API Elements with Plugins
*
* @param indexApiBlocks
* @param detectedElements
* @returns {Array}
*/
Parser.prototype._parseBlockElements = function(indexApiBlocks, detectedElements, filename) {
var self = this;
var parsedBlocks = [];
for (var i = 0; i < indexApiBlocks.length; i += 1) {
var blockIndex = indexApiBlocks[i];
var elements = detectedElements[blockIndex];
var blockData = {
global: {},
local : {}
};
var countAllowedMultiple = 0;
for (var j = 0; j < elements.length; j += 1) {
var element = elements[j];
var elementParser = self.parsers[element.name];
if ( ! elementParser) {
app.log.warn('parser plugin \'' + element.name + '\' not found in block: ' + blockIndex);
} else {
app.log.debug('found @' + element.sourceName + ' in block: ' + blockIndex);
// Deprecation warning
if (elementParser.deprecated) {
self.countDeprecated[element.sourceName] = self.countDeprecated[element.sourceName] ? self.countDeprecated[element.sourceName] + 1 : 1;
var message = '@' + element.sourceName + ' is deprecated';
if (elementParser.alternative)
message = '@' + element.sourceName + ' is deprecated, please use ' + elementParser.alternative;
if (self.countDeprecated[element.sourceName] === 1)
// show deprecated message only 1 time as warning
app.log.warn(message);
else
// show deprecated message more than 1 time as verbose message
app.log.verbose(message);
app.log.verbose('in file: ' + filename + ', block: ' + blockIndex);
}
var values;
var preventGlobal;
var allowMultiple;
var pathTo;
var attachMethod;
try {
// parse element and retrieve values
values = elementParser.parse(element.content, element.source);
// HINT: pathTo MUST be read after elementParser.parse, because of dynamic paths
// Add all other options after parse too, in case of a custom plugin need to modify params.
// check if it is allowed to add to global namespace
preventGlobal = elementParser.preventGlobal === true;
// allow multiple inserts into pathTo
allowMultiple = elementParser.allowMultiple === true;
// path to an array, where the values should be attached
pathTo = '';
if (elementParser.path) {
if (typeof elementParser.path === 'string')
pathTo = elementParser.path;
else
pathTo = elementParser.path(); // for dynamic paths
}
if ( ! pathTo)
throw new ParserError('pathTo is not defined in the parser file.', '', '', element.sourceName);
// method how the values should be attached (insert or push)
attachMethod = elementParser.method || 'push';
if (attachMethod !== 'insert' && attachMethod !== 'push')
throw new ParserError('Only push or insert are allowed parser method values.', '', '', element.sourceName);
// TODO: put this into "converters"
if (values) {
// Markdown.
if ( app.markdownParser &&
elementParser.markdownFields &&
elementParser.markdownFields.length > 0
) {
for (var markdownIndex = 0; markdownIndex < elementParser.markdownFields.length; markdownIndex += 1) {
var field = elementParser.markdownFields[markdownIndex];
if (values[field]) {
values[field] = app.markdownParser.render(values[field]);
// remove line breaks
values[field] = values[field].replace(/(\r\n|\n|\r)/g, ' ');
values[field] = values[field].trim();
// TODO: Little hacky, not sure to handle this here or in template
if ( elementParser.markdownRemovePTags &&
elementParser.markdownRemovePTags.length > 0 &&
elementParser.markdownRemovePTags.indexOf(field) !== -1
) {
// Remove p-Tags
values[field] = values[field].replace(/(<p>|<\/p>)/g, '');
}
}
}
}
}
} catch(e) {
if (e instanceof ParameterError) {
var extra = [];
if (e.definition)
extra.push({ 'Definition': e.definition });
if (e.example)
extra.push({ 'Example': e.example });
throw new ParserError(e.message,
self.filename, (blockIndex + 1), element.sourceName, element.source, extra);
}
throw new ParserError('Undefined error.',
self.filename, (blockIndex + 1), element.sourceName, element.source);
}
if ( ! values)
throw new ParserError('Empty parser result.',
self.filename, (blockIndex + 1), element.sourceName, element.source);
if (preventGlobal) {
// Check if count global namespace entries > count allowed
// (e.g. @successTitle is global, but should co-exist with @apiErrorStructure)
if (Object.keys(blockData.global).length > countAllowedMultiple)
throw new ParserError('Only one definition or usage is allowed in the same block.',
self.filename, (blockIndex + 1), element.sourceName, element.source);
}
// only one global allowed per block
if (pathTo === 'global' || pathTo.substr(0, 7) === 'global.') {
if (allowMultiple) {
countAllowedMultiple += 1;
} else {
if (Object.keys(blockData.global).length > 0)
throw new ParserError('Only one definition is allowed in the same block.',
self.filename, (blockIndex + 1), element.sourceName, element.source);
if (preventGlobal === true)
throw new ParserError('Only one definition or usage is allowed in the same block.',
self.filename, (blockIndex + 1), element.sourceName, element.source);
}
}
if ( ! blockData[pathTo])
self._createObjectPath(blockData, pathTo, attachMethod);
var blockDataPath = self._pathToObject(pathTo, blockData);
// insert Fieldvalues in Path-Array
if (attachMethod === 'push')
blockDataPath.push(values);
else
_.extend(blockDataPath, values);
// insert Fieldvalues in Mainpath
if (elementParser.extendRoot === true)
_.extend(blockData, values);
blockData.index = blockIndex + 1;
}
}
if (blockData.index && blockData.index > 0)
parsedBlocks.push(blockData);
}
return parsedBlocks;
};
/**
* Create a not existing Path in an Object
*
* @param src
* @param path
* @param {String} attachMethod Create last element as object or array: 'insert', 'push'
* @returns {Object}
*/
Parser.prototype._createObjectPath = function(src, path, attachMethod) {
if ( ! path)
return src;
var pathParts = path.split('.');
var current = src;
for (var i = 0; i < pathParts.length; i += 1) {
var part = pathParts[i];
if ( ! current[part]) {
if (i === (pathParts.length - 1) && attachMethod === 'push' )
current[part] = [];
else
current[part] = {};
}
current = current[part];
}
return current;
};
/**
* Return Path to Object
*/
Parser.prototype._pathToObject = function(path, src) {
if ( ! path)
return src;
var pathParts = path.split('.');
var current = src;
for (var i = 0; i < pathParts.length; i += 1) {
var part = pathParts[i];
current = current[part];
}
return current;
};
/**
* Determine Blocks
*/
Parser.prototype._findBlocks = function() {
var self = this;
var blocks = [];
var src = self.src;
// Replace Linebreak with Unicode
src = src.replace(/\n/g, '\uffff');
var regexForFile = this.languages[self.extension] || this.languages['default'];
var matches = regexForFile.docBlocksRegExp.exec(src);
while (matches) {
var block = matches[2] || matches[1];
// Reverse Unicode Linebreaks
block = block.replace(/\uffff/g, '\n');
block = block.replace(regexForFile.inlineRegExp, '');
blocks.push(block);
// Find next
matches = regexForFile.docBlocksRegExp.exec(src);
}
return blocks;
};
/**
* Return block indexes with active API-elements
*
* An @apiIgnore ignores the block.
* Other, non @api elements, will be ignored.
*/
Parser.prototype._findBlockWithApiGetIndex = function(blocks) {
var foundIndexes = [];
for (var i = 0; i < blocks.length; i += 1) {
var found = false;
for (var j = 0; j < blocks[i].length; j += 1) {
if (blocks[i][j].name.substr(0, 9) === 'apiignore') {
app.log.debug('apiIgnore found in block: ' + i);
found = false;
break;
}
if (blocks[i][j].name.substr(0, 3) === 'api')
found = true;
}
if (found) {
foundIndexes.push(i);
app.log.debug('api found in block: ' + i);
}
}
return foundIndexes;
};
/**
* Get Elements of Blocks
*/
Parser.prototype.findElements = function(block, filename) {
var elements = [];
// Replace Linebreak with Unicode
block = block.replace(/\n/g, '\uffff');
// Elements start with @
var elementsRegExp = /(@(\w*)\s?(.+?)(?=\uffff[\s\*]*@|$))/gm;
var matches = elementsRegExp.exec(block);
while (matches) {
var element = {
source : matches[1],
name : matches[2].toLowerCase(),
sourceName: matches[2],
content : matches[3]
};
// reverse Unicode Linebreaks
element.content = element.content.replace(/\uffff/g, '\n');
element.source = element.source.replace(/\uffff/g, '\n');
app.hook('parser-find-element-' + element.name, element, block, filename);
elements.push(element);
app.hook('parser-find-elements', elements, element, block, filename);
// next Match
matches = elementsRegExp.exec(block);
}
return elements;
};