( newLine: string, oldLines: string[], permissiveAboutIndentation = false, )
| 46 | * Also return a version of the line with correct indentation if needs fixing |
| 47 | */ |
| 48 | export function matchLine( |
| 49 | newLine: string, |
| 50 | oldLines: string[], |
| 51 | permissiveAboutIndentation = false, |
| 52 | ): MatchLineResult { |
| 53 | // Only match empty lines if it's the next one: |
| 54 | if (newLine.trim() === "" && oldLines[0]?.trim() === "") { |
| 55 | return { |
| 56 | matchIndex: 0, |
| 57 | isPerfectMatch: true, |
| 58 | newLine: newLine.trim(), |
| 59 | }; |
| 60 | } |
| 61 | |
| 62 | const isEndBracket = END_BRACKETS.includes(newLine.trim()); |
| 63 | |
| 64 | for (let i = 0; i < oldLines.length; i++) { |
| 65 | // trims trailing whitespaces from the lines before comparison |
| 66 | //this ensures trailing spaces don't affect matching. |
| 67 | const oldLineTrimmed = oldLines[i].trimEnd(); |
| 68 | const newLineTrimmed = newLine.trimEnd(); |
| 69 | |
| 70 | // Don't match end bracket lines if too far away |
| 71 | if (i > 4 && isEndBracket) { |
| 72 | return { matchIndex: -1, isPerfectMatch: false, newLine }; |
| 73 | } |
| 74 | |
| 75 | if (linesMatchPerfectly(newLineTrimmed, oldLineTrimmed)) { |
| 76 | return { matchIndex: i, isPerfectMatch: true, newLine }; |
| 77 | } |
| 78 | if (linesMatch(newLineTrimmed, oldLineTrimmed, i)) { |
| 79 | // This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines |
| 80 | if ( |
| 81 | newLineTrimmed.trimStart() === oldLineTrimmed.trimStart() && |
| 82 | (permissiveAboutIndentation || newLine.trim().length > 8) |
| 83 | ) { |
| 84 | return { |
| 85 | matchIndex: i, |
| 86 | isPerfectMatch: true, |
| 87 | newLine: oldLines[i], |
| 88 | }; |
| 89 | } |
| 90 | return { matchIndex: i, isPerfectMatch: false, newLine }; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | return { matchIndex: -1, isPerfectMatch: false, newLine }; |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Convert a stream of arbitrary chunks to a stream of lines |
no test coverage detected