UNPKG

1.98 kBJavaScriptView Raw
1// Copyright © 2017 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16const fs = require('fs');
17const stream = require('stream');
18const liner = require('./liner.js');
19
20var onLine = function(onCommand, batches) {
21 var change = new stream.Transform({ objectMode: true });
22 change._transform = function(line, encoding, done) {
23 if (line && line[0] === ':') {
24 var obj = {
25 command: null,
26 batch: null,
27 docs: []
28 };
29
30 var matches;
31
32 // extract command
33 matches = line.match(/^:([a-z_]+) ?/);
34 if (matches) {
35 obj.command = matches[1];
36 }
37
38 // extract batch
39 matches = line.match(/ batch([0-9]+)/);
40 if (matches) {
41 obj.batch = parseInt(matches[1]);
42 }
43
44 // if this is one we want
45 if (obj.command === 't' && batches.indexOf(obj.batch) > -1) {
46 var json = line.replace(/^.* batch[0-9]+ /, '').trim();
47 obj.docs = JSON.parse(json);
48 onCommand(obj);
49 }
50 }
51 done();
52 };
53 return change;
54};
55
56module.exports = function(log, batches, callback) {
57 // our sense of state
58 var retval = { };
59
60 // called with each line from the log file
61 var onCommand = function(obj) {
62 retval[obj.batch] = obj;
63 };
64
65 // stream through the previous log file
66 fs.createReadStream(log)
67 .pipe(liner())
68 .pipe(onLine(onCommand, batches))
69 .on('finish', function() {
70 callback(null, retval);
71 });
72};