Langsung ke konten
Skillpedia
Pemrograman umum7.8k Β· #13056

idempotent-file-replace

Fungsinya

Skill ini memberi tahu agent AI untuk membaca file dan membandingkannya sebelum menggantinya. Skill ini ditujukan untuk orang yang build atau riwayat versinya akan terganggu oleh penulisan yang tidak perlu.

Kapan dipakai

  • βœ“Saat Anda meminta agent mengganti seluruh file dengan isi tertentu.
  • βœ“Saat perubahan file akan memicu build ulang atau hot reload tanpa alasan.
  • βœ“Saat Anda menginginkan riwayat versi yang bersih tanpa diff kosong.

Link skill

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œGanti file konfigurasi dengan isi ini, tetapi tulis hanya jika file itu benar-benar berbeda.”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Agent membaca file saat ini terlebih dahulu, lalu membandingkannya dengan isi yang diinginkan. Agent hanya menulis jika keduanya berbeda, dan dapat menampilkan diff untuk menjelaskan apa yang akan berubah.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari GitHub.

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())
# 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

Situation Handling
File does not exist read_file raises / returns empty β†’ treat as "" β†’ always write
Encoding differences Normalize to UTF-8 before comparison
Line-ending differences (CRLF vs LF) Normalize with .replace("\r\n", "\n") before comparing
Byte-exact requirement Skip .strip() and compare verbatim
Large files Compute 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.

Pertanyaan umum

Bagaimana jika file belum ada?

Skill ini menganggap isi saat ini kosong dan menulis file baru.

Apakah spasi berpengaruh?

Skill ini membandingkan isi secara ketat, dengan opsi untuk mengabaikan perbedaan satu baris baru di akhir.

Mengapa ini membantu build?

Melewati penulisan yang tidak berubah menjaga waktu file tetap stabil, sehingga watcher dan cache tidak terpicu.

Detail

Deskripsi asli dari pembuat

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.

repo: HKUDS/AgentPilot

Popularitas

Bintang GitHub
7.8k
Peringkat
#13056
Lisensi
MIT
Diperbarui
1/11/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa