Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(breathe): `sprite-gen breathe` never touches its source — `out` and `frames` that are one folder or lie one inside the other are refused by file identity before anything is made, and the result is staged in a folder of the run's own, the only thing a run deletes
Soohong Kimf4115d1bae7b
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.pyindex f78650b..0a55607 100644--- a/sprite_gen/effects/breathe.py+++ b/sprite_gen/effects/breathe.py@@ -68,6 +68,9 @@ from __future__ import annotationsimport argparseimport jsonimport math+import os+import secrets+import shutilfrom pathlib import Pathfrom PIL import Image@@ -935,6 +938,31 @@ def _cells(text: str) -> list[int]:raise argparse.ArgumentTypeError(f"cell numbers separated by commas, not {text!r}")+def _same(a: Path, b: Path) -> bool:+ """같은 폴더인가 — 장치·inode 로 본다. 링크로 돌아 들어와도, 대소문자를 가리지 않는 볼륨에서 철자만+ 달라도 같은 폴더다."""+ return a.exists() and b.exists() and a.samefile(b)+++def _inside(path: Path, folder: Path) -> bool:+ """`path` 가 `folder` 안에 드는가 — 조상 가운데 `folder` 와 같은 폴더가 있다. `path` 는 아직 없어도 된다."""+ return any(_same(parent, folder) for parent in path.parents)+++def _new_stage(out: Path) -> Path:+ """`out` 옆에 이 실행만의 빈 임시 폴더 — 같은 볼륨이라 다 쓴 뒤 rename 한 번으로 내놓는다. 이름이 이미+ 있으면(원본이든 다른 실행의 것이든) 그 폴더는 건드리지 않고 다른 이름을 고른다. mkdtemp(0700)가 아니라+ mkdir 이라 내놓은 out 이 보통 폴더 권한을 갖는다."""+ for _ in range(100):+ stage = out.parent / f".{out.name}.{os.getpid()}-{secrets.token_hex(4)}.partial"+ try:+ stage.mkdir()+ except FileExistsError:+ continue+ return stage+ raise SystemExit(f"breathe: {out.parent} 에 임시 폴더 이름을 못 골랐다")++def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("frames", help="folder of the loop's frames (*.png, played in name order)")parser.add_argument("out", help="new folder for the breathing frames (same names) and breathe.json")@@ -1003,9 +1031,17 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =paths = sorted(src_dir.glob("*.png"))if not paths:raise SystemExit(f"breathe: {src_dir} 에 PNG 프레임이 없다")- if out_dir.resolve() == src_dir.resolve():+ # 무엇을 만들거나 지우기 전에 — 실경로와 폴더 동일성으로 본다(링크, 철자).+ src_real, out_real = src_dir.resolve(), out_dir.resolve()+ if _same(out_real, src_real):raise SystemExit("breathe: out 이 frames 와 같은 폴더다 — 원본 프레임 위에 덮어쓰지 않는다")- if out_dir.exists() and any(out_dir.iterdir()):+ if _inside(out_real, src_real):+ raise SystemExit(f"breathe: out 이 frames 안에 있다 ({out_real}) — 원본 폴더 안에는 쓰지 않는다")+ if _inside(src_real, out_real):+ raise SystemExit(f"breathe: frames 가 out 안에 있다 ({src_real}) — 원본이 든 폴더에 내놓지 않는다")+ if out_real.exists() and not out_real.is_dir():+ raise SystemExit(f"breathe: {out_dir} 는 폴더가 아니다")+ if out_real.exists() and any(out_real.iterdir()):raise SystemExit(f"breathe: {out_dir} 가 비어 있지 않다 — 새 폴더를 주라")images = []for path in paths:@@ -1015,22 +1051,24 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =raise SystemExit(f"breathe: 프레임 크기가 서로 다르다 — {sorted({im.size for im in images})}")resolved = anatomy_report(images, cfg)baked, phases = bake_breathe_sequence(images, cfg)- # 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다.- staging = out_dir.parent / f".{out_dir.name}.partial"- if staging.exists():- for stale in staging.iterdir():- stale.unlink()- staging.rmdir()- staging.mkdir(parents=True)- for path, frame in zip(paths, baked):- frame.save(staging / path.name)- report = {"frames": len(paths), "source": str(src_dir), "config": cfg, "phases": phases,- "resolved": resolved}- (staging / "breathe.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n",- encoding="utf-8")- if out_dir.exists():- out_dir.rmdir()- staging.rename(out_dir)+ # 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다. 같은 out 으로 도는+ # 실행들은 각자의 임시 폴더에 쓰고, rename 이 먼저 닿은 쪽이 내놓는다(늦은 쪽은 차 있는 out 에서 멈춘다).+ # 지우는 것은 이 실행의 임시 폴더뿐이고, 원본 폴더에는 아무것도 쓰지 않는다.+ out_real.parent.mkdir(parents=True, exist_ok=True)+ stage = _new_stage(out_real)+ try:+ for path, frame in zip(paths, baked):+ frame.save(stage / path.name)+ report = {"frames": len(paths), "source": str(src_dir), "config": cfg, "phases": phases,+ "resolved": resolved}+ (stage / "breathe.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8")+ if out_real.exists():+ out_real.rmdir() # 위에서 빈 것을 봤다 — 그새 무엇이 들어왔으면 OSError 로 멈춘다+ stage.rename(out_real)+ finally:+ if stage.exists():+ shutil.rmtree(stage)print(f"breathe: {len(paths)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "f"breaths {cfg['breaths']} -> {out_dir}")return 0