| 640 | } |
| 641 | |
| 642 | export function replace(content: string, oldString: string, newString: string, replaceAll = false): string { |
| 643 | if (oldString === newString) { |
| 644 | throw new Error("oldString and newString must be different") |
| 645 | } |
| 646 | |
| 647 | let notFound = true |
| 648 | |
| 649 | for (const replacer of [ |
| 650 | SimpleReplacer, |
| 651 | LineTrimmedReplacer, |
| 652 | BlockAnchorReplacer, |
| 653 | WhitespaceNormalizedReplacer, |
| 654 | IndentationFlexibleReplacer, |
| 655 | EscapeNormalizedReplacer, |
| 656 | TrimmedBoundaryReplacer, |
| 657 | ContextAwareReplacer, |
| 658 | MultiOccurrenceReplacer, |
| 659 | ]) { |
| 660 | for (const search of replacer(content, oldString)) { |
| 661 | const index = content.indexOf(search) |
| 662 | if (index === -1) continue |
| 663 | notFound = false |
| 664 | if (replaceAll) { |
| 665 | return content.replaceAll(search, newString) |
| 666 | } |
| 667 | const lastIndex = content.lastIndexOf(search) |
| 668 | if (index !== lastIndex) continue |
| 669 | return content.substring(0, index) + newString + content.substring(index + search.length) |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | if (notFound) { |
| 674 | throw new Error("oldString not found in content") |
| 675 | } |
| 676 | throw new Error( |
| 677 | "Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match.", |
| 678 | ) |
| 679 | } |