Apply the Model's Edit Without Mangling the File
A coding agent edits a file by having the model return the block to replace and the block to put in its place. Implement apply_edit(text, old, new), which applies one such edit to the file's text and returns the new text.
- An exact match of
oldthat occurs once intextis replaced bynew. - A loose match. With no exact match, compare line by line ignoring each line's leading whitespace. The model often loses the indentation. Where that finds one block, replace it, and shift every line of
newby the difference between the file's indentation of the matched block's first line and the indentation ofold's first line. A blank line stays blank. - No match raises
EditError, and the message quotes the line of the file closest to the first line ofold(difflibfinds it). - More than one match, exact or loose, raises
EditError, and the message says how many places matched. - Line endings are kept. A file with
\r\nendings comes back with\r\nendings, even whenoldandnewuse\n. A file that ended with a newline still does, and one that did not still does not. - An empty
old(nothing but whitespace) raisesEditError: that is an insert, not an edit.
The catch. Rule 2 is not strip() on both sides. old's first line can carry indentation of its own, and new can carry nesting of its own: a line indented four spaces deeper than new's first line must still be four spaces deeper after the shift.