| 1 | import { ContinueError, ContinueErrorReason } from "../../util/errors"; |
| 2 | |
| 3 | export const FOUND_MULTIPLE_FIND_STRINGS_ERROR = |
| 4 | "Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences."; |
| 5 | |
| 6 | /** |
| 7 | * Validates a single edit operation |
| 8 | */ |
| 9 | export function validateSingleEdit( |
| 10 | oldString: string, |
| 11 | newString: string, |
| 12 | index?: number, |
| 13 | ): void { |
| 14 | const context = index !== undefined ? `edit at index ${index}: ` : ""; |
| 15 | |
| 16 | if (!oldString && oldString !== "") { |
| 17 | throw new ContinueError( |
| 18 | ContinueErrorReason.FindAndReplaceMissingOldString, |
| 19 | `${context}old_string is required`, |
| 20 | ); |
| 21 | } |
| 22 | if (newString === undefined) { |
| 23 | throw new ContinueError( |
| 24 | ContinueErrorReason.FindAndReplaceMissingNewString, |
| 25 | `${context}new_string is required`, |
| 26 | ); |
| 27 | } |
| 28 | if (oldString === newString) { |
| 29 | throw new ContinueError( |
| 30 | ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings, |
| 31 | `${context}old_string and new_string must be different`, |
| 32 | ); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | export function trimEmptyLines({ |
| 37 | lines, |
| 38 | fromEnd, |
| 39 | }: { |
| 40 | lines: string[]; |
| 41 | fromEnd: boolean; |
| 42 | }): string[] { |
| 43 | lines = fromEnd ? lines.slice().reverse() : lines.slice(); |
| 44 | const newLines: string[] = []; |
| 45 | let shouldContinueRemoving = true; |
| 46 | for (let index = 0; index < lines.length; index++) { |
| 47 | const line = lines[index]; |
| 48 | if (shouldContinueRemoving && line.trim() === "") continue; |
| 49 | shouldContinueRemoving = false; |
| 50 | newLines.push(line); |
| 51 | } |
| 52 | return fromEnd ? newLines.reverse() : newLines; |
| 53 | } |