작업실(studio): 작품 검색·수정·커밋·되돌리기 화면 (로컬 8081)
This commit is contained in:
1 parent
8248ba94d8
commit
6249317528
10 files changed
+1204
-1
No files matched your search
@@ -0,0 +1,493 @@
|
||||
#!/usr/bin/env python3
|
||||
"""한땀 작업실(studio) — 작품 md를 화면에서 찾아 고치는 로컬 관리 서버.
|
||||
|
||||
- 표준 라이브러리만 쓴다. 항상 127.0.0.1 에만 붙는다.
|
||||
- 저장 = md 파일 쓰기 -> build.py -> git commit (실패하면 원본 복원)
|
||||
- 이력 = git log, 되돌리기 = git revert -> 재빌드 -> (선택) 배포
|
||||
|
||||
실행: python3 studio/server.py [--port 8081] [--deploy-on-save]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import mimetypes
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.parse
|
||||
from datetime import datetime
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
BASE = Path(__file__).resolve().parent
|
||||
ROOT = BASE.parent
|
||||
PRODUCTS = ROOT / "content" / "products"
|
||||
ASSETS = ROOT / "assets"
|
||||
APP = BASE / "app.html"
|
||||
LIST_KEYS = {"gallery"}
|
||||
|
||||
# 폼에 노출할 필드와 순서. 여기 없는 키도 파일에 있으면 보존한다.
|
||||
FIELDS: List[Dict[str, str]] = [
|
||||
{"key": "title", "label": "제목", "type": "text"},
|
||||
{"key": "subtitle", "label": "부제", "type": "text"},
|
||||
{"key": "date", "label": "날짜", "type": "date"},
|
||||
{"key": "price", "label": "가격(원)", "type": "number"},
|
||||
{"key": "sold_out", "label": "품절 표시", "type": "bool"},
|
||||
{"key": "featured", "label": "첫 페이지 대표작", "type": "bool"},
|
||||
{"key": "image", "label": "대표 이미지", "type": "image"},
|
||||
{"key": "image_alt", "label": "이미지 설명(alt)", "type": "text"},
|
||||
{"key": "material", "label": "소재", "type": "text"},
|
||||
{"key": "size", "label": "규격", "type": "text"},
|
||||
{"key": "care", "label": "세탁", "type": "text"},
|
||||
{"key": "naver_url", "label": "네이버 링크", "type": "url"},
|
||||
{"key": "gallery", "label": "추가 이미지(한 줄에 하나)", "type": "lines"},
|
||||
]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ front matter
|
||||
|
||||
|
||||
def split_front(raw: str) -> Tuple[List[str], str]:
|
||||
if not raw.startswith("---"):
|
||||
raise ValueError("front matter 가 없습니다")
|
||||
parts = raw.split("---", 2)
|
||||
if len(parts) != 3:
|
||||
raise ValueError("front matter 가 닫히지 않았습니다")
|
||||
return parts[1].strip("\n").splitlines(), parts[2].lstrip("\n")
|
||||
|
||||
|
||||
def parse_value(text: str) -> Any:
|
||||
value = text.strip()
|
||||
if value in ("true", "false"):
|
||||
return value == "true"
|
||||
if value in ("", '""', "''"):
|
||||
return ""
|
||||
if re.fullmatch(r"-?\d+", value):
|
||||
return int(value)
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def parse_front(lines: List[str]) -> Tuple[List[str], Dict[str, Any]]:
|
||||
order: List[str] = []
|
||||
data: Dict[str, Any] = {}
|
||||
current = None
|
||||
for line in lines:
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("- ") and current:
|
||||
if not isinstance(data.get(current), list):
|
||||
data[current] = []
|
||||
data[current].append(parse_value(stripped[2:]))
|
||||
continue
|
||||
if ":" not in line:
|
||||
continue
|
||||
key, value = line.split(":", 1)
|
||||
key, value = key.strip(), value.strip()
|
||||
if key not in data:
|
||||
order.append(key)
|
||||
if value == "":
|
||||
data[key] = ""
|
||||
current = key
|
||||
else:
|
||||
data[key] = parse_value(value)
|
||||
current = None
|
||||
return order, data
|
||||
|
||||
|
||||
def render_value(value: Any) -> str:
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
if isinstance(value, int):
|
||||
return str(value)
|
||||
text = str(value)
|
||||
if text == "":
|
||||
return '""'
|
||||
needs_quote = (
|
||||
text != text.strip()
|
||||
or text.startswith(('"', "'", "-", "[", "{", "*", "&", "!", "|", ">", "%", "@", "`"))
|
||||
or ": " in text
|
||||
or text.endswith(":")
|
||||
or " #" in text
|
||||
)
|
||||
if needs_quote:
|
||||
return '"' + text.replace('"', "'") + '"'
|
||||
return text
|
||||
|
||||
|
||||
def as_list(value: Any) -> List[str]:
|
||||
if isinstance(value, list):
|
||||
return [str(item) for item in value]
|
||||
text = str(value or "")
|
||||
return [line.strip() for line in text.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def assemble(order: List[str], data: Dict[str, Any], body: str) -> str:
|
||||
out = ["---"]
|
||||
for key in order:
|
||||
value = data.get(key, "")
|
||||
if key in LIST_KEYS:
|
||||
items = as_list(value)
|
||||
out.append(f"{key}:")
|
||||
out.extend(f"- {item}" for item in items)
|
||||
elif isinstance(value, bool):
|
||||
out.append(f"{key}: {'true' if value else 'false'}")
|
||||
elif value == "" or value is None:
|
||||
out.append(f'{key}: ""')
|
||||
else:
|
||||
out.append(f"{key}: {render_value(value)}")
|
||||
out.append("---")
|
||||
text = body.strip("\n")
|
||||
return "\n".join(out) + "\n" + text + "\n"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------- git/shell
|
||||
|
||||
|
||||
def run(args: List[str], timeout: int = 120) -> Tuple[bool, str]:
|
||||
try:
|
||||
proc = subprocess.run(args, cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, f"시간 초과: {' '.join(args)}"
|
||||
log = (proc.stdout or "") + (proc.stderr or "")
|
||||
return proc.returncode == 0, log.strip()
|
||||
|
||||
|
||||
def git(*args: str) -> Tuple[bool, str]:
|
||||
return run(["git", *args], timeout=60)
|
||||
|
||||
|
||||
def head_sha() -> str:
|
||||
ok, out = git("rev-parse", "--short", "HEAD")
|
||||
return out.strip() if ok else "?"
|
||||
|
||||
|
||||
def git_commit(message: str, paths: List[str]) -> Tuple[bool, str]:
|
||||
"""지정한 경로만 스테이징해서 커밋한다(무관한 변경이 섞이지 않도록)."""
|
||||
git("add", "--", *paths)
|
||||
ok, staged = git("diff", "--cached", "--name-only", "--", *paths)
|
||||
if not staged.strip():
|
||||
return False, "스테이징된 변경 없음"
|
||||
ok, out = git("commit", "-m", message, "--", *paths)
|
||||
return ok, out.splitlines()[-1] if out else ""
|
||||
|
||||
|
||||
def history(limit: int = 20) -> List[Dict[str, str]]:
|
||||
ok, out = git("log", f"-n{limit}", "--date=format:%Y-%m-%d %H:%M", "--pretty=format:%h\x1f%ad\x1f%s")
|
||||
if not ok:
|
||||
return []
|
||||
rows = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split("\x1f")
|
||||
if len(parts) == 3:
|
||||
rows.append({"sha": parts[0], "date": parts[1], "subject": parts[2]})
|
||||
return rows
|
||||
|
||||
|
||||
def build() -> Tuple[bool, str]:
|
||||
return run([sys.executable, "build.py"], timeout=180)
|
||||
|
||||
|
||||
def deploy() -> Tuple[bool, str]:
|
||||
return run(["bash", "scripts/deploy.sh"], timeout=300)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- products io
|
||||
|
||||
|
||||
def product_path(slug: str) -> Path:
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slug or ""):
|
||||
raise ValueError("슬러그가 올바르지 않습니다")
|
||||
path = PRODUCTS / f"{slug}.md"
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"작품 파일이 없습니다: {slug}.md")
|
||||
return path
|
||||
|
||||
|
||||
def summaries() -> List[Dict[str, Any]]:
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for path in sorted(PRODUCTS.glob("*.md")):
|
||||
raw = path.read_text(encoding="utf-8")
|
||||
try:
|
||||
lines, body = split_front(raw)
|
||||
order, data = parse_front(lines)
|
||||
except ValueError:
|
||||
rows.append({"slug": path.stem, "title": f"{path.stem} (읽기 오류)", "broken": True})
|
||||
continue
|
||||
rows.append(
|
||||
{
|
||||
"slug": str(data.get("slug") or path.stem),
|
||||
"title": str(data.get("title") or path.stem),
|
||||
"subtitle": str(data.get("subtitle") or ""),
|
||||
"date": str(data.get("date") or ""),
|
||||
"price": data.get("price") if isinstance(data.get("price"), int) else 0,
|
||||
"sold_out": bool(data.get("sold_out")),
|
||||
"featured": bool(data.get("featured")),
|
||||
"image": str(data.get("image") or ""),
|
||||
"material": str(data.get("material") or ""),
|
||||
"size": str(data.get("size") or ""),
|
||||
"search": " ".join([str(data.get("title") or ""), path.stem, str(data.get("material") or ""), str(data.get("size") or ""), body]).lower(),
|
||||
"modified": datetime.fromtimestamp(path.stat().st_mtime).strftime("%m-%d %H:%M"),
|
||||
"mtime": path.stat().st_mtime,
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def load_product(slug: str) -> Dict[str, Any]:
|
||||
path = product_path(slug)
|
||||
lines, body = split_front(path.read_text(encoding="utf-8"))
|
||||
order, data = parse_front(lines)
|
||||
values = {}
|
||||
for field in FIELDS:
|
||||
key = field["key"]
|
||||
raw = data.get(key, "")
|
||||
if field["type"] == "bool":
|
||||
values[key] = bool(raw) if not isinstance(raw, str) else raw == "true"
|
||||
elif field["type"] == "number":
|
||||
values[key] = raw if isinstance(raw, int) else ""
|
||||
elif field["type"] == "lines":
|
||||
values[key] = "\n".join(as_list(raw))
|
||||
else:
|
||||
values[key] = "" if raw is None else str(raw)
|
||||
return {
|
||||
"slug": slug,
|
||||
"fields": values,
|
||||
"body": body,
|
||||
"raw": path.read_text(encoding="utf-8"),
|
||||
"extra_keys": [key for key in order if key not in {f["key"] for f in FIELDS} and key != "slug"],
|
||||
"modified": datetime.fromtimestamp(path.stat().st_mtime).strftime("%Y-%m-%d %H:%M"),
|
||||
}
|
||||
|
||||
|
||||
def coerce(field: Dict[str, str], value: Any) -> Any:
|
||||
kind = field["type"]
|
||||
if kind == "bool":
|
||||
return bool(value)
|
||||
if kind == "number":
|
||||
text = str(value).strip()
|
||||
return int(text) if re.fullmatch(r"-?\d+", text) else ""
|
||||
if kind == "lines":
|
||||
return as_list(value)
|
||||
return str(value if value is not None else "").strip()
|
||||
|
||||
|
||||
def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
slug = str(payload.get("slug", ""))
|
||||
path = product_path(slug)
|
||||
original = path.read_text(encoding="utf-8")
|
||||
lines, old_body = split_front(original)
|
||||
order, data = parse_front(lines)
|
||||
|
||||
incoming = payload.get("fields") or {}
|
||||
for field in FIELDS:
|
||||
key = field["key"]
|
||||
if key in incoming:
|
||||
value = coerce(field, incoming[key])
|
||||
if key not in order:
|
||||
order.append(key)
|
||||
data[key] = value
|
||||
|
||||
body = str(payload.get("body", old_body))
|
||||
updated = assemble(order, data, body)
|
||||
if updated == original:
|
||||
return {"ok": True, "changed": False, "message": "변경된 내용이 없습니다", "head": head_sha()}
|
||||
|
||||
path.write_text(updated, encoding="utf-8")
|
||||
built, build_log = build()
|
||||
if not built:
|
||||
path.write_text(original, encoding="utf-8")
|
||||
return {"ok": False, "stage": "build", "error": "빌드 실패 — 저장을 취소하고 원본을 되돌렸습니다", "log": build_log}
|
||||
|
||||
committed, commit_log = git_commit(f"작품 수정: {data.get('title') or slug}", [str(path.relative_to(ROOT))])
|
||||
if not committed:
|
||||
return {"ok": False, "stage": "git", "error": "git 커밋 실패 (파일은 저장됨)", "log": commit_log}
|
||||
|
||||
result: Dict[str, Any] = {
|
||||
"ok": True,
|
||||
"changed": True,
|
||||
"message": "저장 · 커밋 완료",
|
||||
"head": head_sha(),
|
||||
"commit": commit_log,
|
||||
"log": build_log,
|
||||
}
|
||||
if payload.get("deploy"):
|
||||
deployed, deploy_log = deploy()
|
||||
result["deploy"] = {"ok": deployed, "log": deploy_log}
|
||||
result["message"] = "저장 · 커밋 · 배포 완료" if deployed else "저장 · 커밋 완료 (배포 실패)"
|
||||
return result
|
||||
|
||||
|
||||
def revert(sha: str, redeploy: bool) -> Dict[str, Any]:
|
||||
if not re.fullmatch(r"[0-9a-f]{4,40}", sha or ""):
|
||||
return {"ok": False, "error": "커밋 해시가 올바르지 않습니다"}
|
||||
ok, log = git("revert", "--no-edit", sha)
|
||||
if not ok:
|
||||
git("revert", "--abort")
|
||||
return {"ok": False, "error": "되돌리기 실패", "log": log}
|
||||
built, build_log = build()
|
||||
if not built:
|
||||
return {"ok": False, "error": "되돌린 뒤 빌드 실패", "log": build_log}
|
||||
result: Dict[str, Any] = {"ok": True, "message": f"{sha} 되돌림", "head": head_sha(), "log": build_log}
|
||||
if redeploy:
|
||||
deployed, deploy_log = deploy()
|
||||
result["deploy"] = {"ok": deployed, "log": deploy_log}
|
||||
result["message"] += " · 배포 완료" if deployed else " (배포 실패)"
|
||||
return result
|
||||
|
||||
|
||||
def upload_image(name: str, data: bytes) -> Dict[str, Any]:
|
||||
if not data:
|
||||
return {"ok": False, "error": "이미지 데이터가 비었습니다"}
|
||||
ext = Path(name).suffix.lower()
|
||||
if ext not in (".jpg", ".jpeg"):
|
||||
return {"ok": False, "error": "JPG만 올릴 수 있습니다 (사이트가 JPEG 크기를 읽습니다)"}
|
||||
stem = re.sub(r"[^a-z0-9-]+", "-", Path(name).stem.lower()).strip("-") or "image"
|
||||
target_dir = ASSETS / "img"
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / f"{stem}{ext}"
|
||||
counter = 2
|
||||
while target.exists():
|
||||
target = target_dir / f"{stem}-{counter}{ext}"
|
||||
counter += 1
|
||||
target.write_bytes(data)
|
||||
return {"ok": True, "path": f"assets/img/{target.name}", "bytes": len(data)}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------ server
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "hanttam-studio"
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt: str, *args: Any) -> None:
|
||||
pass
|
||||
|
||||
# -- helpers ---------------------------------------------------------
|
||||
def send_body(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8") -> None:
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def send_json(self, obj: Any, code: int = 200) -> None:
|
||||
self.send_body(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"))
|
||||
|
||||
def read_json(self) -> Dict[str, Any]:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if not length:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.rfile.read(length).decode("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
|
||||
# -- GET -------------------------------------------------------------
|
||||
def do_GET(self) -> None:
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
path = parsed.path
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
|
||||
if path in ("/", "/index.html"):
|
||||
self.send_body(200, APP.read_bytes(), "text/html; charset=utf-8")
|
||||
return
|
||||
if path == "/api/state":
|
||||
rows = summaries()
|
||||
self.send_json(
|
||||
{
|
||||
"ok": True,
|
||||
"products": rows,
|
||||
"count": len(rows),
|
||||
"head": head_sha(),
|
||||
"history": history(8),
|
||||
"fields": FIELDS,
|
||||
"repo": str(ROOT),
|
||||
}
|
||||
)
|
||||
return
|
||||
if path == "/api/product":
|
||||
slug = (query.get("slug") or [""])[0]
|
||||
try:
|
||||
self.send_json({"ok": True, "product": load_product(slug)})
|
||||
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/history":
|
||||
self.send_json({"ok": True, "history": history(25), "head": head_sha()})
|
||||
return
|
||||
if path.startswith("/media/"):
|
||||
rel = urllib.parse.unquote(path[len("/media/"):])
|
||||
target = (ROOT / rel).resolve()
|
||||
try:
|
||||
target.relative_to(ASSETS.resolve())
|
||||
except ValueError:
|
||||
self.send_json({"ok": False, "error": "허용되지 않은 경로"}, 403)
|
||||
return
|
||||
if not target.is_file():
|
||||
self.send_json({"ok": False, "error": "파일 없음"}, 404)
|
||||
return
|
||||
ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
|
||||
self.send_body(200, target.read_bytes(), ctype)
|
||||
return
|
||||
self.send_json({"ok": False, "error": "없는 경로"}, 404)
|
||||
|
||||
# -- POST ------------------------------------------------------------
|
||||
def do_POST(self) -> None:
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
path = parsed.path
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
|
||||
if path == "/api/product":
|
||||
try:
|
||||
self.send_json(save_product(self.read_json()))
|
||||
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/revert":
|
||||
payload = self.read_json()
|
||||
self.send_json(revert(str(payload.get("sha", "")), bool(payload.get("deploy"))))
|
||||
return
|
||||
if path == "/api/upload":
|
||||
name = (query.get("name") or ["image.jpg"])[0]
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
data = self.rfile.read(length) if length else b""
|
||||
self.send_json(upload_image(name, data))
|
||||
return
|
||||
if path == "/api/build":
|
||||
ok, log = build()
|
||||
self.send_json({"ok": ok, "log": log, "head": head_sha()})
|
||||
return
|
||||
self.send_json({"ok": False, "error": "없는 경로"}, 404)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="한땀 작업실")
|
||||
parser.add_argument("--port", type=int, default=8081)
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not PRODUCTS.is_dir():
|
||||
raise SystemExit(f"작품 폴더가 없습니다: {PRODUCTS}")
|
||||
|
||||
server = ThreadingHTTPServer((args.host, args.port), Handler)
|
||||
print(f"한땀 작업실: http://{args.host}:{args.port} (repo {ROOT})")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\n종료")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user