| name | idempotent-file-replace |
| description | Read-then-diff before writing a file to ensure the write is skipped when the content already matches, preventing unnecessary modifications and downstream side effects. |
Idempotent File Replace
When tasked with completely replacing a file with specific content, always
perform a read-and-compare step before writing. Only write when the file
actually differs from the desired content.
Why This Matters
| Risk of blind writes | Benefit of idempotent check |
|---|
| Triggers filesystem watchers / hot-reload loops | No spurious rebuild when content is unchanged |
| Wastes a tool call on a no-op | One extra read saves a write + all downstream costs |
| Pollutes VCS history with empty diffs | Clean commit history |
| Breaks CI caching layers | Stable mtimes keep caches valid |
Procedure
Step 1 — Read the current file
Always read the file first, even when you are confident about the replacement.
read_file(path="<target_file>")
If the file does not yet exist, treat its current content as an empty
string and proceed to Step 3.
Step 2 — Compare current content to desired content
Perform an exact string comparison (whitespace-sensitive).
current = <content returned by read_file>
desired = <full replacement content>
needs_write = (current.strip() != desired.strip())
Alternatively, a unified diff gives a human-readable explanation of what
would change and is useful for logging: