Skip to content
cccskills
FreePublished on GitHub

idempotent-file-replace

Compare a file’s current content with its intended replacement before writing. Skip matching files to avoid unnecessary rebuilds and timestamp changes, with guidance on readable diffs, line endings, encoding, and exact content requirements.

OriginalShow the original 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.

See how to install

Good for

  • Replacing configuration files only when content changes
  • Avoiding rebuilds caused by unchanged generated files
  • Reviewing differences before replacing a whole file
  • Comparing files with strict whitespace requirements

Files included (2)

  • SKILL.md3.8 KB
  • .skill_id37 B

SKILL.md (original)

Review the instructions the agent will receive before you install.

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 writesBenefit of idempotent check
Triggers filesystem watchers / hot-reload loopsNo spurious rebuild when content is unchanged
Wastes a tool call on a no-opOne extra read saves a write + all downstream costs
Pollutes VCS history with empty diffsClean commit history
Breaks CI caching layersStable 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())
# Use .strip() to tolerate a single trailing newline difference,
# or compare verbatim if byte-exact output is required.

Alternatively, a unified diff gives a human-readable explanation of what would change and is useful for logging:

import difflib, sys

diff = list(difflib.unified_diff(
    current.splitlines(keepends=True),
    desired.splitlines(keepends=True),
    fromfile="current",
    tofile="desired",
))

if not diff:
    print("Files are identical — skipping write.")
    needs_write = False
else:
    print("Diff detected:\n" + "".join(diff))
    needs_write = True

Step 3 — Conditional write

if needs_write:
    write_file(path="<target_file>", content=desired)
    print("File written.")
else:
    # Report completion immediately — no write needed.
    print("File already matches desired content. No action taken.")

Decision Flowchart

Task: "Replace <file> with <content>"
        │
        ▼
   read_file(<file>)
        │
        ▼
  content == desired?
   ┌────┴────┐
  YES       NO
   │         │
   ▼         ▼
 SKIP     write_file(<file>, desired)
 write        │
   │          ▼
   └──► Report COMPLETE

Complete Example

TARGET = "src/components/Panel.ts"
DESIRED_CONTENT = """// Auto-generated — do not edit
export const Panel = () => { ... };
"""

# Step 1: read
current = read_file(path=TARGET)          # tool call

# Step 2: compare
if current.strip() == DESIRED_CONTENT.strip():
    print(f"{TARGET} already matches. Skipping write.")
    # → COMPLETE
else:
    # Step 3: write
    write_file(path=TARGET, content=DESIRED_CONTENT)   # tool call
    print(f"{TARGET} updated.")
    # → COMPLETE

Edge Cases

SituationHandling
File does not existread_file raises / returns empty → treat as "" → always write
Encoding differencesNormalize to UTF-8 before comparison
Line-ending differences (CRLF vs LF)Normalize with .replace("\r\n", "\n") before comparing
Byte-exact requirementSkip .strip() and compare verbatim
Large filesCompute SHA-256 hash of both strings for efficiency before full diff

Key Principle

Never assume a file needs to be written. One cheap read prevents an expensive (and potentially harmful) write.

This pattern applies to any "replace entire file" task regardless of file type: source code, configuration, templates, lock files, generated assets, etc.

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Prepare audio stems, the separate parts of a track, for mixing by matching their durations with silence, loops, or crossfades. Verify each generated and processed file before moving to the next production step.

  • Match audio parts with different durations
  • Extend drums and melodic parts using suitable methods
  • Check audio specifications before mixing
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Produce audio in separate stems, meaning individual instrument tracks, and verify each output as you go. Align track lengths with silence, loops, or crossfades, then apply effects, mix a master, and package the files.

  • Align instrument tracks to a reference audio file
  • Choose how to extend tracks that are too short
  • Verify audio properties after generation and effects
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Build serverless endpoints that relay external API requests for a dashboard while keeping API keys on the server. Includes Vercel examples for input checks, caching, cross-origin access, and consistent JSON responses.

  • Connect a dashboard to external APIs without exposing API keys
  • Create endpoints for stock quotes and news
  • Standardize API responses and error handling
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Produce a master track and separate audio parts through a structured Python workflow. Apply filters and reverb, export WAV files with consistent settings, package them in a ZIP archive, and check that the deliverables meet the requested specifications.

  • Export a master track with separate audio parts
  • Apply filters and reverb to audio
  • Check duration and format across deliverables
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Keep document creation moving when web searches and page retrieval repeatedly fail. The skill preserves the original task, uses the model’s existing knowledge, and clearly identifies information that could not be checked against external sources.

  • Continue drafting after repeated web retrieval failures
  • Preserve task requirements during network errors
  • Mark information that could not be externally verified
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

When Python execution repeatedly fails in execute_code_sandbox, use a file-based alternative: save the script, run it through the shell, and capture results or errors. The guidance covers paths, imports, timeouts, structured output, and optional cleanup.

  • Retry Python work through the shell after repeated sandbox failures
  • Run longer tasks with an adjusted timeout
  • Execute Python work that needs multiple files or system utilities
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

See all skills by HKUDS

Report a problem with this skill