UNPKG

2.16 kBJavaScriptView Raw
1/** @module Node Pom Parser */
2
3"use strict";
4
5var fs = require("fs");
6var sax = require("../lib/sax_parser.js");
7var expat = require("../lib/expat_parser.js");
8
9/**
10 * Load xml file contents using the sync mode.
11 * @param {object} opt Is the options with filePath in it.
12 * @return {object} The xml content with timer with load time.
13 */
14module.exports.loadXmlFileContents = function(opt) {
15 if (!opt.filePath) {
16 throw new Error("You must provide the opt.filePath");
17 }
18
19 var loadStart = process.hrtime();
20 var pomXmlContent = fs.readFileSync(opt.filePath, "utf8");
21 var loadPomTime = process.hrtime(loadStart);
22 return {
23 xmlContent: pomXmlContent,
24 timers: {
25 load: (loadPomTime[1] / 1000000) + "ms"
26 }
27 };
28};
29
30/**
31 * Extremely FAST pom header reader using node-expat c library.
32 * @param {object} opt Is the option with the filePath or xmlContent and the optional format.
33 * @return {object} The pom object along with the timers.
34 */
35module.exports.parsePom = function(opt) {
36 if (!opt) {
37 throw new Error("You must provide options: opt.filePath and [opt.format=(*json|text)]");
38 }
39 if (!opt.xmlContent && !opt.filePath) {
40 throw new Error("You must provide the opt.filePath or the opt.xmlContent");
41 }
42 if (!opt.format) {
43 opt.format = "json";
44
45 } else if (opt.format !== "text" && opt.format !== "json") {
46 throw new Error("You must provide the opt.format = (json | text)");
47 }
48
49 // Use or load the content from the filePath
50 var pom = { timers: { load: 0, parse: 0 } }
51 if (!opt.xmlContent) {
52 pom = this.loadXmlFileContents(opt);
53 }
54
55 var loadTimer = pom.timers;
56
57 // parse the pom, erasing all
58 var parsePomStart = process.hrtime();
59 pom = sax.parse(pom.xmlContent);
60 //pom = expat.parse(pom.xmlContent); // EXTREMELY FASTER, BUT BROKEN!
61
62 pom.timers = {};
63 var parsePomTime = process.hrtime(parsePomStart);
64 pom.timers.parse = (parsePomTime[1] / 1000000) + "ms";
65
66 // Update the ref to the timer
67 pom.timers.load = loadTimer.load;
68
69 // Depending on the requested format, format it or not.
70 return opt.format === "json" ? pom : (pom.groupId + ":" + pom.artifactId + ":" + pom.version);
71};