본문으로 건너뛰기
Skillpedia
일반 코딩7.8k · #13056

idempotent-file-replace

하는 일

이 스킬은 파일을 교체하기 전에 읽고 비교하도록 AI 에이전트에게 알려 줍니다. 불필요한 쓰기로 빌드나 버전 기록이 흔들리면 안 되는 사람을 위한 스킬입니다.

사용하는 경우

  • ✓특정 내용으로 파일을 완전히 교체해 달라고 요청할 때.
  • ✓불필요한 파일 변경이 재빌드나 핫 리로드를 일으킬 때.
  • ✓빈 차이 없이 깔끔한 버전 기록을 원할 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/idempotent-file-replace/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“설정 파일을 이 내용으로 교체해 주세요. 다만 파일 내용이 실제로 다를 때만 저장해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 먼저 현재 파일을 읽은 다음 원하는 내용과 비교합니다. 두 내용이 다를 때만 쓰며, 무엇이 바뀌는지 설명하도록 diff를 보여 줄 수도 있습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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.

자주 묻는 질문

파일이 아직 없으면 어떻게 하나요?

스킬은 현재 내용을 빈 것으로 보고 새 파일을 씁니다.

공백은 중요한가요?

스킬은 내용을 엄격하게 비교하며, 끝의 줄바꿈 하나 차이는 무시하는 옵션도 제공합니다.

왜 빌드에 도움이 되나요?

변경되지 않은 쓰기를 건너뛰면 파일 시간이 유지되어 감시 도구와 캐시가 불필요하게 실행되지 않는다고 스킬은 설명합니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
7.8k
순위
#13056
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬