(
&self,
content: &str,
old_string: &str,
new_string: &str,
replace_all: bool,
)
| 608 | } |
| 609 | |
| 610 | pub fn replace( |
| 611 | &self, |
| 612 | content: &str, |
| 613 | old_string: &str, |
| 614 | new_string: &str, |
| 615 | replace_all: bool, |
| 616 | ) -> Result<String, String> { |
| 617 | if old_string == new_string { |
| 618 | return Err("No changes to apply: oldString and newString are identical.".to_string()); |
| 619 | } |
| 620 | |
| 621 | let mut not_found = true; |
| 622 | |
| 623 | for replacer in &self.replacers { |
| 624 | for search in replacer.find(content, old_string) { |
| 625 | if let Some(index) = content.find(&search) { |
| 626 | not_found = false; |
| 627 | if replace_all { |
| 628 | return Ok(content.replace(&search, new_string)); |
| 629 | } |
| 630 | let last_index = content.rfind(&search); |
| 631 | if last_index != Some(index) { |
| 632 | continue; |
| 633 | } |
| 634 | let mut result = |
| 635 | String::with_capacity(content.len() - search.len() + new_string.len()); |
| 636 | result.push_str(&content[..index]); |
| 637 | result.push_str(new_string); |
| 638 | result.push_str(&content[index + search.len()..]); |
| 639 | return Ok(result); |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | if not_found { |
| 645 | Err("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings.".to_string()) |
| 646 | } else { |
| 647 | Err("Found multiple matches for oldString. Provide more surrounding context to make the match unique.".to_string()) |
| 648 | } |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | pub fn normalize_line_endings(text: &str) -> String { |
no test coverage detected