작품 삭제 기능: 수정 화면 DELETE — md·사진·페이지 제거, 되돌리기로 복구, 키트/마지막 작품 보호

This commit is contained in:
한땀 작업실 committed 2026-11-01 07:59:57 +00:00
1 parent bdbad3ec6d
commit 3d5a015400
3 files changed
+138

No files matched your search

+91
View File
@@ -440,6 +440,86 @@ def revert(sha: str, redeploy: bool) -> Dict[str, Any]:
return result
def restore_paths(paths: List[str]) -> None:
"""git rm 으로 지운 파일을 커밋 전(HEAD) 상태 그대로 되살린다."""
git("reset", "-q", "HEAD", "--", *paths)
git("checkout", "HEAD", "--", *paths)
def delete_product(slug: str, deploy_after: bool = False, force: bool = False) -> Dict[str, Any]:
"""작품 하나를 md·이미지 폴더와 함께 지운다.
- 빌드가 깨지면(예: 키트·대표작이 사라짐) 지운 파일을 HEAD 에서 되살리고 취소한다.
- 지운 사실은 `작품 삭제: 제목` 커밋으로 남는다 → 이력에서 revert 하면 그대로 복구된다.
"""
slug = str(slug or "").strip()
path = product_path(slug) # 슬러그 검증 + 파일 존재 확인
lines, _ = split_front(path.read_text(encoding="utf-8"))
_, data = parse_front(lines)
title = str(data.get("title") or slug)
if not [p for p in PRODUCTS.glob("*.md") if p.stem != slug]:
return {"ok": False, "error": "마지막 남은 작품은 지울 수 없습니다 — 첫 페이지가 비어 버립니다."}
try:
site = json.loads((ROOT / "content" / "site.json").read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
site = {}
kit_slug = str((site.get("shop") or {}).get("kit_slug") or "").strip()
if kit_slug and kit_slug == slug:
return {"ok": False, "error": "이 작품은 첫 페이지의 키트로 지정돼 있습니다. content/site.json 의 "
"shop.kit_slug 를 다른 작품으로 바꾼 뒤 지워 주세요."}
paths = [str(path.relative_to(ROOT))]
image_dir = ASSETS / "img" / slug
if image_dir.is_dir():
paths.append(str(image_dir.relative_to(ROOT)))
removed, rm_log = git("rm", "-r", "-f", "--quiet", "--", *paths)
if not removed:
return {"ok": False, "stage": "git_rm", "error": "작품 파일을 지우지 못했습니다", "log": rm_log}
built, build_log = build()
if not built:
restore_paths(paths)
build()
return {"ok": False, "stage": "build", "log": build_log[-800:],
"error": "빌드가 깨져 삭제를 취소하고 원래대로 되돌렸습니다"}
committed, commit_log = git("commit", "-m", f"작품 삭제: {title}", "--", *paths)
if not committed:
restore_paths(paths)
build()
return {"ok": False, "stage": "git", "error": "커밋에 실패해 삭제를 되돌렸습니다", "log": commit_log}
prune_empty_image_dirs()
summary = next((line for line in (build_log or "").splitlines() if line.startswith("검증")),
(build_log or "").splitlines()[0] if build_log else "")
result: Dict[str, Any] = {
"ok": True, "slug": slug, "title": title, "deployed": False, "pushed": False,
"message": f"삭제 · 커밋 완료 — {title}",
"commit": commit_log, "head": head_sha(),
"build_log": summary,
}
if os.environ.get("TEAMAT_PUSH", "").strip().lower() in ("1", "true", "yes"):
pushed, push_log = push()
result["pushed"] = pushed
result["push_log"] = push_log[-200:]
if deploy_after:
drafts = [d for d in reg.pending_drafts() if d != slug]
if drafts and not force:
result["drafts"] = drafts
result["deploy_log"] = ("커밋하지 않은 다른 초안이 있어 배포를 건너뛰었습니다: " + ", ".join(drafts)
+ " — 목록에서 [사이트에 올리기]로 마저 올려 주세요.")
else:
deployed, deploy_log = deploy()
result["deployed"] = deployed
result["deploy_log"] = deploy_log[-400:]
result["message"] += " · 사이트에 반영" if deployed else " (사이트 반영 실패)"
return result
def upload_image(name: str, data: bytes, slug: str = "") -> Dict[str, Any]:
"""이미지는 assets/img/<작품슬러그>/ 에 넣는다. 작품마다 폴더 하나."""
if not data:
@@ -867,6 +947,17 @@ class Handler(BaseHTTPRequestHandler):
except (RuntimeError, FileNotFoundError) as error:
self.send_json({"ok": False, "error": str(error)}, 500)
return
if path == "/api/delete":
payload = self.read_json()
try:
self.send_json(delete_product(str(payload.get("slug") or ""),
bool(payload.get("deploy")),
bool(payload.get("force"))))
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
return
if path == "/api/product":
try:
self.send_json(save_product(self.read_json()))