|
| 1 | +module.exports = (inputStream, outputStream) => { |
| 2 | + const state = { |
| 3 | + watch: false, |
| 4 | + curr: { |
| 5 | + src: 0, |
| 6 | + dest: 0, |
| 7 | + }, |
| 8 | + }; |
| 9 | + |
| 10 | + const write = (...segs) => outputStream.write(segs.join("") + "\n"); |
| 11 | + |
| 12 | + const convertAndLog = { |
| 13 | + src: line => { |
| 14 | + write(String(state.curr.src).padEnd(4, " "), ":", line); |
| 15 | + ++state.curr.src; |
| 16 | + }, |
| 17 | + dest: line => { |
| 18 | + write(String(state.curr.dest).padEnd(4, " "), ":", line); |
| 19 | + ++state.curr.dest; |
| 20 | + }, |
| 21 | + neutral: line => { |
| 22 | + write(String(state.curr.dest).padEnd(4, " "), ":", line); |
| 23 | + ++state.curr.dest; |
| 24 | + ++state.curr.src; |
| 25 | + }, |
| 26 | + }; |
| 27 | + |
| 28 | + inputStream.on("data", data => { |
| 29 | + const lines = String(data).split("\n"); |
| 30 | + lines.forEach(line => { |
| 31 | + if (line.startsWith("@@")) { |
| 32 | + const [src, dest] = line |
| 33 | + .split(" ") |
| 34 | + .filter(x => x !== "@@") |
| 35 | + // Remove +, - |
| 36 | + .map(x => x.slice(1)) |
| 37 | + // Split to components |
| 38 | + .map(x => x.split(",")) |
| 39 | + // parse as Number |
| 40 | + .map(([start, end]) => ({ |
| 41 | + start: Number(start), |
| 42 | + end: Number(end), |
| 43 | + })); |
| 44 | + state.watch = true; |
| 45 | + // Reset counter to reflect current context |
| 46 | + Object.assign(state.curr, { src: src.start, dest: dest.start }); |
| 47 | + return write(line); |
| 48 | + } else if (state.watch) { |
| 49 | + if (line.startsWith(" ")) { |
| 50 | + convertAndLog.neutral(line); |
| 51 | + } |
| 52 | + if (line.startsWith("+")) { |
| 53 | + convertAndLog.dest(line); |
| 54 | + } |
| 55 | + if (line.startsWith("-")) { |
| 56 | + convertAndLog.src(line); |
| 57 | + } |
| 58 | + if (line.startsWith("diff")) { |
| 59 | + state.watch = false; |
| 60 | + write(line); |
| 61 | + } |
| 62 | + } else write(line); |
| 63 | + }); |
| 64 | + }); |
| 65 | + |
| 66 | + inputStream.on("end", () => outputStream.end()); |
| 67 | +}; |
0 commit comments