|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const { |
| 4 | + Array, |
| 5 | + ArrayPrototypeJoin, |
| 6 | + ArrayPrototypeReverse, |
| 7 | + StringPrototypeCharCodeAt, |
| 8 | + StringPrototypeTrimEnd, |
| 9 | +} = primordials; |
| 10 | +const os = require('os'); |
| 11 | + |
| 12 | +const kBrackets = { '{': 1, '[': 1, '(': 1, '}': -1, ']': -1, ')': -1 }; |
| 13 | + |
| 14 | +function parseHistoryFromFile(historyText, historySize) { |
| 15 | + const lines = historyText.trimEnd().split(os.EOL); |
| 16 | + let linesLength = lines.length; |
| 17 | + if (linesLength > historySize) linesLength = historySize; |
| 18 | + |
| 19 | + const commands = new Array(linesLength); |
| 20 | + let commandsIndex = 0; |
| 21 | + const currentCommand = new Array(linesLength); |
| 22 | + let currentCommandIndex = 0; |
| 23 | + let bracketCount = 0; |
| 24 | + let inString = false; |
| 25 | + let stringDelimiter = ''; |
| 26 | + |
| 27 | + for (let lineIdx = linesLength - 1; lineIdx >= 0; lineIdx--) { |
| 28 | + const line = lines[lineIdx]; |
| 29 | + currentCommand[currentCommandIndex++] = line; |
| 30 | + |
| 31 | + let isConcatenation = false; |
| 32 | + let isArrowFunction = false; |
| 33 | + let lastChar = ''; |
| 34 | + |
| 35 | + for (let charIdx = 0, len = line.length; charIdx < len; charIdx++) { |
| 36 | + const char = line[charIdx]; |
| 37 | + |
| 38 | + if ((char === "'" || char === '"' || char === '`') && |
| 39 | + (charIdx === 0 || StringPrototypeCharCodeAt(line, charIdx - 1) !== 92)) { // 92 is '\\' |
| 40 | + if (!inString) { |
| 41 | + inString = true; |
| 42 | + stringDelimiter = char; |
| 43 | + } else if (char === stringDelimiter) { |
| 44 | + inString = false; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if (!inString) { |
| 49 | + const bracketValue = kBrackets[char]; |
| 50 | + if (bracketValue) bracketCount += bracketValue; |
| 51 | + } |
| 52 | + |
| 53 | + lastChar = char; |
| 54 | + } |
| 55 | + |
| 56 | + if (!inString) { |
| 57 | + const trimmedLine = StringPrototypeTrimEnd(line); |
| 58 | + isConcatenation = lastChar === '+'; |
| 59 | + isArrowFunction = lastChar === '>' && trimmedLine[trimmedLine.length - 2] === '='; |
| 60 | + } |
| 61 | + |
| 62 | + if (!inString && bracketCount <= 0 && !isConcatenation && !isArrowFunction) { |
| 63 | + commands[commandsIndex++] = ArrayPrototypeJoin(currentCommand.slice(0, currentCommandIndex), '\n'); |
| 64 | + currentCommandIndex = 0; |
| 65 | + bracketCount = 0; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + if (currentCommandIndex > 0) { |
| 70 | + commands[commandsIndex++] = ArrayPrototypeJoin(currentCommand.slice(0, currentCommandIndex), '\n'); |
| 71 | + } |
| 72 | + |
| 73 | + commands.length = commandsIndex; |
| 74 | + return ArrayPrototypeReverse(commands); |
| 75 | +} |
| 76 | + |
| 77 | +module.exports = { parseHistoryFromFile }; |
0 commit comments