(ctx context.Context, explanation, targetFile, search, replace, matchID string)
| 49 | } |
| 50 | |
| 51 | func (env *Environment) FileEdit(ctx context.Context, explanation, targetFile, search, replace, matchID string) error { |
| 52 | contents, err := env.container().File(targetFile).Contents(ctx) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | |
| 57 | // Find all matches of the search text |
| 58 | matches := []int{} |
| 59 | cursor := 0 |
| 60 | for { |
| 61 | index := strings.Index(contents[cursor:], search) |
| 62 | if index == -1 { |
| 63 | break |
| 64 | } |
| 65 | actualIndex := cursor + index |
| 66 | matches = append(matches, actualIndex) |
| 67 | cursor = actualIndex + 1 |
| 68 | } |
| 69 | |
| 70 | if len(matches) == 0 { |
| 71 | return fmt.Errorf("search text not found in file %s", targetFile) |
| 72 | } |
| 73 | |
| 74 | // If there are multiple matches and no matchID is provided, return an error with all matches |
| 75 | if len(matches) > 1 && matchID == "" { |
| 76 | var matchDescriptions []string |
| 77 | for i, matchIndex := range matches { |
| 78 | // Generate a unique ID for each match |
| 79 | id := generateMatchID(targetFile, search, replace, i) |
| 80 | |
| 81 | // Get context around the match (3 lines before and after) |
| 82 | context := getMatchContext(contents, matchIndex) |
| 83 | |
| 84 | matchDescriptions = append(matchDescriptions, fmt.Sprintf("Match %d (ID: %s):\n%s", i+1, id, context)) |
| 85 | } |
| 86 | |
| 87 | return fmt.Errorf("multiple matches found for search text in %s. Please specify which_match parameter with one of the following IDs:\n\n%s", |
| 88 | targetFile, strings.Join(matchDescriptions, "\n\n")) |
| 89 | } |
| 90 | |
| 91 | // Determine which match to replace |
| 92 | var targetMatchIndex int |
| 93 | if len(matches) == 1 { |
| 94 | targetMatchIndex = matches[0] |
| 95 | } else { |
| 96 | // Find the match with the specified ID |
| 97 | found := false |
| 98 | for i, matchIndex := range matches { |
| 99 | id := generateMatchID(targetFile, search, replace, i) |
| 100 | if id == matchID { |
| 101 | targetMatchIndex = matchIndex |
| 102 | found = true |
| 103 | break |
| 104 | } |
| 105 | } |
| 106 | if !found { |
| 107 | return fmt.Errorf("match ID %s not found", matchID) |
| 108 | } |
no test coverage detected