From 5d662bb5db3894d159160e469395a61327221b08 Mon Sep 17 00:00:00 2001 From: Ben Woosley Date: Mon, 25 Dec 2017 23:30:08 -0600 Subject: [PATCH] Fix repeated headers to be bounded properly Previously, the field lookup occurred from the beginning of the line so would repeated find the same line location if the same string or a substring of a header was searched more than once. Instead track the current end index of the previous field to base the search state location on. --- lib/index.js | 5 +++-- test/output/ps-repeated-header.log | 4 ++++ test/spec.js | 31 ++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 test/output/ps-repeated-header.log diff --git a/lib/index.js b/lib/index.js index e72c671..7e1fd82 100644 --- a/lib/index.js +++ b/lib/index.js @@ -44,14 +44,15 @@ module.exports.parse = function (output) { // Treat the first line as the title fields line if (index == 0) { var fields = line.split(/\s+/); + var currentIndex = 0; // record the beginning and ending for each field fields.forEach(function (field, idx) { if (field) { var info = titleInfo[field] = {}; - var indexBegin = line.indexOf(field); - var indexEnd = indexBegin + field.length; + var indexBegin = line.indexOf(field, currentIndex); + var indexEnd = currentIndex = (indexBegin + field.length); if (idx == 0) { info.titleBegin = 0; diff --git a/test/output/ps-repeated-header.log b/test/output/ps-repeated-header.log new file mode 100644 index 0000000..16ad0df --- /dev/null +++ b/test/output/ps-repeated-header.log @@ -0,0 +1,4 @@ +PPID PID COMMAND + 1 338 /usr/sbin/distnoted agent + 1 341 /usr/libexec/trustd --agent + 1 342 /usr/libexec/lsd diff --git a/test/spec.js b/test/spec.js index a2562b8..5187549 100644 --- a/test/spec.js +++ b/test/spec.js @@ -44,6 +44,37 @@ describe('tabler-parser', function () { Assert.deepEqual(result, expectResult); }); + it('with a repeated header', function () { + var output = GetOutput('ps-repeated-header.log'); + var result = TableParser.parse(output); + + var expectResult = [ + { + 'PID': ['338'], + 'PPID': ['1'], + 'COMMAND': [ + '/usr/sbin/distnoted', + 'agent' + ] + }, + { + 'PID': ['341'], + 'PPID': ['1'], + 'COMMAND': [ + '/usr/libexec/trustd', + '--agent' + ] + }, + { + 'PID': ['342'], + 'PPID': ['1'], + 'COMMAND': ['/usr/libexec/lsd'] + }, + ]; + + Assert.deepEqual(result, expectResult); + }); + it('a windows output', function () { var output = GetOutput('wmic.log'); var result = TableParser.parse(output);