등록 화면: 작품 수정(사진 재배치·삭제·추가, 항목 편집, 저장/배포) + 배포 시 재빌드
This commit is contained in:
1 parent
f2ae889795
commit
a6835e943a
4 files changed
+372
-15
No files matched your search
@@ -0,0 +1,166 @@
|
||||
"""등록된 작품 수정 — 발행(publish)과 같은 규칙으로 md·이미지·커밋을 다시 쓴다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
import register as reg
|
||||
|
||||
|
||||
def parse_front(raw: str) -> Tuple[Dict[str, Any], str]:
|
||||
if not raw.startswith("---"):
|
||||
raise ValueError("md 파일이 --- 로 시작하지 않습니다")
|
||||
parts = raw.split("---", 2)
|
||||
if len(parts) != 3:
|
||||
raise ValueError("front matter 가 닫히지 않았습니다")
|
||||
front, body = parts[1], parts[2].lstrip("\n")
|
||||
data: Dict[str, Any] = {}
|
||||
key = ""
|
||||
for line in front.splitlines():
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
if line.startswith("- ") or line.startswith(" - "):
|
||||
if key:
|
||||
if not isinstance(data.get(key), list):
|
||||
data[key] = []
|
||||
data[key].append(line.split("- ", 1)[1].strip().strip('"'))
|
||||
continue
|
||||
if ":" in line:
|
||||
key, value = line.split(":", 1)
|
||||
key, value = key.strip(), value.strip()
|
||||
if value == "":
|
||||
data[key] = []
|
||||
elif value in ("true", "false"):
|
||||
data[key] = value == "true"
|
||||
elif re.fullmatch(r"-?\d+", value):
|
||||
data[key] = int(value)
|
||||
else:
|
||||
data[key] = value.strip('"')
|
||||
return data, body
|
||||
|
||||
|
||||
def render(data: Dict[str, Any], body: str) -> str:
|
||||
order = [k for k in reg.DEFAULT_ORDER if k in data] + [k for k in data if k not in reg.DEFAULT_ORDER]
|
||||
lines = ["---"]
|
||||
for key in order:
|
||||
value = data.get(key, "")
|
||||
if key == "gallery":
|
||||
lines.append("gallery:")
|
||||
for item in value or []:
|
||||
lines.append(f"- {reg._value(item)}")
|
||||
continue
|
||||
lines.append(f"{key}: {reg._value(value)}")
|
||||
lines.append("---")
|
||||
return "\n".join(lines) + "\n" + body.rstrip() + "\n"
|
||||
|
||||
|
||||
def _restage_images(slug: str, items: List[Dict[str, Any]]) -> List[str]:
|
||||
"""items 순서대로 cover/detail-NN 으로 다시 배치한다. 기존 사진은 복사, 새 사진(uid)은 변환."""
|
||||
image_dir = reg.ASSETS / "img" / slug
|
||||
image_dir.mkdir(parents=True, exist_ok=True)
|
||||
staged: List[Path] = []
|
||||
inbox_sources: List[Path] = []
|
||||
|
||||
for index, item in enumerate(items):
|
||||
temp = image_dir / f".staging-{index:02d}.jpg"
|
||||
if item.get("uid"):
|
||||
source = reg.inbox_path(str(item["uid"]))
|
||||
reg._to_jpeg(source, temp)
|
||||
inbox_sources.append(source)
|
||||
else:
|
||||
rel = str(item.get("path") or "")
|
||||
existing = (reg.ROOT / rel).resolve()
|
||||
try:
|
||||
existing.relative_to(image_dir.resolve())
|
||||
except ValueError as error:
|
||||
raise ValueError("이 작품 폴더의 사진만 쓸 수 있습니다") from error
|
||||
if not existing.is_file():
|
||||
raise ValueError(f"사진이 없습니다: {rel}")
|
||||
shutil.copyfile(existing, temp)
|
||||
staged.append(temp)
|
||||
|
||||
final: List[str] = []
|
||||
for index, temp in enumerate(staged):
|
||||
name = "cover.jpg" if index == 0 else f"detail-{index:02d}.jpg"
|
||||
target = image_dir / name
|
||||
temp.replace(target)
|
||||
final.append(f"assets/img/{slug}/{name}")
|
||||
|
||||
keep = {Path(path).name for path in final}
|
||||
for old in image_dir.glob("*.jpg"):
|
||||
if old.name not in keep:
|
||||
old.unlink(missing_ok=True)
|
||||
|
||||
if reg.ARCHIVE and inbox_sources:
|
||||
archive_dir = reg.ARCHIVE / slug
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
for index, source in enumerate(inbox_sources):
|
||||
shutil.copyfile(source, archive_dir / f"added-{index:02d}.jpg")
|
||||
for source in inbox_sources:
|
||||
source.unlink(missing_ok=True)
|
||||
|
||||
return final
|
||||
|
||||
|
||||
def update_product(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
|
||||
slug = re.sub(r"[^a-z0-9-]+", "-", str(payload.get("slug") or "").lower()).strip("-")
|
||||
path = reg.PRODUCTS / f"{slug}.md"
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"작품을 찾을 수 없습니다: {slug}")
|
||||
|
||||
data, old_body = parse_front(path.read_text(encoding="utf-8"))
|
||||
|
||||
items = payload.get("images")
|
||||
if isinstance(items, list) and items:
|
||||
final = _restage_images(slug, items)
|
||||
data["image"] = final[0]
|
||||
data["gallery"] = final[1:]
|
||||
|
||||
for key in ("title", "subtitle", "price_note", "material", "size", "care", "image_alt", "naver_url"):
|
||||
if key in payload:
|
||||
data[key] = str(payload.get(key) or "").strip()
|
||||
if not str(data.get("title") or "").strip():
|
||||
raise ValueError("제목을 비울 수 없습니다")
|
||||
|
||||
if "price" in payload:
|
||||
digits = re.sub(r"[^0-9]", "", str(payload.get("price") or ""))
|
||||
data["price"] = int(digits) if digits and digits != "0" else ""
|
||||
for key in ("sold_out", "featured"):
|
||||
if key in payload:
|
||||
data[key] = bool(payload.get(key))
|
||||
if payload.get("date"):
|
||||
date = str(payload["date"])[:10]
|
||||
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
|
||||
data["date"] = date
|
||||
|
||||
body = str(payload.get("body") or "").strip() or old_body
|
||||
original = path.read_bytes()
|
||||
path.write_text(render(data, body), encoding="utf-8")
|
||||
|
||||
ok, log = helpers["build"]()
|
||||
if not ok:
|
||||
path.write_bytes(original)
|
||||
raise RuntimeError(f"빌드 실패로 수정을 되돌렸습니다: {log[-300:]}")
|
||||
|
||||
image_dir = reg.ASSETS / "img" / slug
|
||||
commit_ok, commit_log = helpers["git_commit"](
|
||||
f"작품 수정: {data.get('title')}",
|
||||
[str(path.relative_to(reg.ROOT)), str(image_dir.relative_to(reg.ROOT))])
|
||||
if not commit_ok:
|
||||
raise RuntimeError(f"커밋 실패: {commit_log}")
|
||||
|
||||
push_ok, push_log = True, ""
|
||||
if helpers.get("push"):
|
||||
push_ok, push_log = helpers["push"]()
|
||||
|
||||
deploy_ok, deploy_log = (True, "배포하지 않음")
|
||||
if payload.get("deploy"):
|
||||
deploy_ok, deploy_log = helpers["deploy"]()
|
||||
|
||||
return {"ok": True, "slug": slug, "commit": commit_log,
|
||||
"deployed": bool(payload.get("deploy")) and deploy_ok,
|
||||
"pushed": push_ok, "build_log": log[-300:], "deploy_log": deploy_log[-300:],
|
||||
"url": f"/p/{slug}.html"}
|
||||
Reference in new issue
Block a user