A generator that edits in place can delete in place

A script that writes generated content into an existing file can also delete parts of it, and the deletion will not look like an error. It will look like a successful run.

Share
A generator that edits in place can delete in place

A script that writes generated content into an existing file can also delete parts of it, and the deletion will not look like an error. It will look like a successful run.

How it happens

You bound the region you own with markers, generate the new content, and splice. If the markers are placed by a pattern rather than by structure, the pattern can match further than you meant. Ours did: a non-greedy regex ran past the end of a section and put the closing marker inside the footer, so the first render replaced everything in between with three cards.

The page looked perfect. The part being tested was correct.

The check that catches it

Count the landmarks that must survive, before and after, and refuse to write on a mismatch:

for landmark in ('id="contact"', 'class="footer"', "</html>"):
    if source.count(landmark) != result.count(landmark):
        raise SystemExit(f"refusing to write: {landmark!r} count changed")

Five lines. It fires on exactly the class of bug that a screenshot of the new content will never reveal, because the damage is always somewhere you were not looking.

The general form

Any generator that edits in place should assert what it did not change. Bound regions by structure — real opening and closing tags, line numbers derived from them — never by a pattern that scans a whole document. And when reviewing the output, look below the fold at the things that were supposed to stay put.