| 336 | } |
| 337 | |
| 338 | func ReplaceInFile(filePath string, edits []EditSpec) error { |
| 339 | fileInfo, err := os.Stat(filePath) |
| 340 | if err != nil { |
| 341 | return fmt.Errorf("failed to stat file: %w", err) |
| 342 | } |
| 343 | |
| 344 | if !fileInfo.Mode().IsRegular() { |
| 345 | return fmt.Errorf("not a regular file: %s", filePath) |
| 346 | } |
| 347 | |
| 348 | if fileInfo.Size() > MaxEditFileSize { |
| 349 | return fmt.Errorf("file too large for editing: %d bytes (max: %d)", fileInfo.Size(), MaxEditFileSize) |
| 350 | } |
| 351 | |
| 352 | contents, err := os.ReadFile(filePath) |
| 353 | if err != nil { |
| 354 | return fmt.Errorf("failed to read file: %w", err) |
| 355 | } |
| 356 | |
| 357 | modifiedContents, err := ApplyEdits(contents, edits) |
| 358 | if err != nil { |
| 359 | return err |
| 360 | } |
| 361 | |
| 362 | if err := os.WriteFile(filePath, modifiedContents, fileInfo.Mode()); err != nil { |
| 363 | return fmt.Errorf("failed to write file: %w", err) |
| 364 | } |
| 365 | |
| 366 | return nil |
| 367 | } |
| 368 | |
| 369 | // ReplaceInFilePartial applies edits incrementally up to the first failure. |
| 370 | // Returns the results for each edit and writes the partially modified content. |