From 62493175284ad2ae1a70c9129d955e372e4a81a2 Mon Sep 17 00:00:00 2001 From: koreafood Date: Sat, 31 Oct 2026 10:37:16 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9E=91=EC=97=85=EC=8B=A4(studio):=20?= =?UTF-8?q?=EC=9E=91=ED=92=88=20=EA=B2=80=EC=83=89=C2=B7=EC=88=98=EC=A0=95?= =?UTF-8?q?=C2=B7=EC=BB=A4=EB=B0=8B=C2=B7=EB=90=98=EB=8F=8C=EB=A6=AC?= =?UTF-8?q?=EA=B8=B0=20=ED=99=94=EB=A9=B4=20(=EB=A1=9C=EC=BB=AC=208081)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 6 + README.md | 20 +- assets/css/site.css | 20 ++ build.py | 1 + scripts/studio.sh | 8 + studio/app.html | 545 +++++++++++++++++++++++++++++++++++++++++ studio/server.py | 493 +++++++++++++++++++++++++++++++++++++ studio/smoke_test.py | 104 ++++++++ templates/base.html | 7 + templates/product.html | 1 + 10 files changed, 1204 insertions(+), 1 deletion(-) create mode 100755 scripts/studio.sh create mode 100644 studio/app.html create mode 100644 studio/server.py create mode 100644 studio/smoke_test.py diff --git a/CLAUDE.md b/CLAUDE.md index 0d31b7a..67826f6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,6 +6,7 @@ ## 0. 절대 규칙 1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지. + - 예외: `studio/` 는 사이트가 아니라 **아이맥 로컬 편집 도구**다(표준 라이브러리만, 127.0.0.1 전용, `dist/` 에 포함되지 않음). 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다. 2. **빌드는 `python3 build.py` 하나.** 표준 라이브러리만 사용. 3. **모든 링크·이미지 경로는 상대경로.** 사이트는 `https://home.lala.dedyn.io/teamat/` 서브패스에서 서빙된다. 4. **`dist/` 는 커밋하지 않는다.** 소스에서 언제든 재생성된다. 롤백 단위는 커밋 하나. @@ -36,6 +37,10 @@ scripts/ preview.sh 로컬 미리보기(빌드 후 8080 서빙) deploy.sh dist → QNAP 웹루트 rsync rollback.sh 커밋 되돌리기 + 재빌드·재배포 + studio.sh 로컬 편집 도구 실행(8081) +studio/ + server.py 작품 md 조회·수정 API (127.0.0.1 전용, 표준 라이브러리) + app.html 작업실 화면(목록+검색+편집+이력) dist/ 빌드 산출물(.gitignore) ``` @@ -148,6 +153,7 @@ image_alt: 조각보 ```bash python3 build.py # 빌드 bash scripts/preview.sh # 빌드 + http://localhost:8080 +bash scripts/studio.sh # 작품 편집 화면 http://localhost:8081 git add -A && git commit -m "작품 추가: 목련 티매트" git push bash scripts/deploy.sh # QNAP 배포 (rsync) diff --git a/README.md b/README.md index 7cf60b3..e213904 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,23 @@ bash scripts/rollback.sh 2f22e71 # 특정 커밋 시점으로 내용 되돌 | 네이버 스토어 링크 | `site.json` 의 `shop.store_url`·`shop.kit_url`, 작품별 `naver_url` | | 색·타이포 | `assets/css/site.css` 상단 `:root` 토큰 | +## 작업실 — 화면에서 작품 고치기 (studio) + +작품이 많아져 파일을 일일이 찾기 힘들 때 쓰는 **로컬 전용** 관리 화면이다. 사이트가 아니라 편집 도구다. + +```bash +bash scripts/studio.sh # http://localhost:8081 +``` + +- 왼쪽 목록: 검색(제목·슬러그·소재·본문) + 칩(판매중/품절/대표작/올해) + 정렬. 오른쪽: 편집 폼 +- 저장 = md 파일 쓰기 → `build.py` → `git commit`. **빌드가 실패하면 원본을 자동 복원**한다 +- `배포까지` 체크하면 저장과 동시에 `scripts/deploy.sh` 실행 +- 상단 `이력 / 되돌리기` = 최근 커밋 목록과 `git revert` +- 작품 상세 페이지의 `이 작품 고치기` 버튼은 localhost 에서만 보인다 (운영 사이트에서는 hidden) +- 이미지: JPG 를 끌어다 놓으면 `assets/img/` 에 저장되고 경로가 자동 입력된다 +- 단축키: `/` 검색, `↑↓` 이동, `⌘S` 저장 +- 서버는 `127.0.0.1` 에만 붙는다. 외부에서 접근되지 않는다 + ## 대화로 고치기 Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예: @@ -70,5 +87,6 @@ Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예: ## 아직 없는 것 (의도적으로) -결제·회원·장바구니·재고, 관리자 화면, 게시판·리뷰, 다국어, 검색, 분석 스크립트. +결제·회원·장바구니·재고, 게시판·리뷰, 다국어, 사이트 내 검색, 분석 스크립트. +관리자 화면도 없다 — 대신 아이맥 로컬 편집 도구 `studio/` 가 있다(위 항목). 구매는 네이버 스마트스토어로 넘긴다. diff --git a/assets/css/site.css b/assets/css/site.css index 81e1021..436652d 100644 --- a/assets/css/site.css +++ b/assets/css/site.css @@ -1233,3 +1233,23 @@ strong { gap: 12px; } } + +/* 작업실(studio) 편집 링크 — 로컬 미리보기에서만 노출된다 */ +.studio-edit { + display: inline-block; + margin-top: 12px; + padding: 5px 11px; + font-size: 12px; + letter-spacing: .04em; + color: var(--clay); + border: 1px solid var(--line); + text-decoration: none; +} + +.studio-edit:hover { + border-color: var(--clay); +} + +.studio-edit[hidden] { + display: none; +} diff --git a/build.py b/build.py index e5d21aa..f8245f1 100644 --- a/build.py +++ b/build.py @@ -571,6 +571,7 @@ def build_product_page( "og_image": esc(absolute_url(image)), "og_type": "product", "body_class": "is-product", + "slug": esc(product["slug"]), "image": esc(image), "alt": esc(product.get("image_alt") or product["title"]), "width": str(width), diff --git a/scripts/studio.sh b/scripts/studio.sh new file mode 100755 index 0000000..68b74b3 --- /dev/null +++ b/scripts/studio.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +# 작품을 화면에서 찾아 고치는 로컬 전용 편집 도구. +# 사이트가 아니라 관리 도구다. 127.0.0.1 에만 붙는다. +exec python3 studio/server.py "$@" diff --git a/studio/app.html b/studio/app.html new file mode 100644 index 0000000..8da5a8b --- /dev/null +++ b/studio/app.html @@ -0,0 +1,545 @@ + + + + + +한땀 작업실 + + + +
+

한땀 작업실

+ 불러오는 중… + + / 검색 · ↑↓ 이동 · ⌘S 저장 + +
+ +
+ + +
+
+

작품을 고르세요

+ + + +
+
+

왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.

+
+
+ + + — + + +
+
+
+ +
+
+
+

최근 이력

+ + + +
+
    +
    +
    + +
    + + + + diff --git a/studio/server.py b/studio/server.py new file mode 100644 index 0000000..0ea74b3 --- /dev/null +++ b/studio/server.py @@ -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() diff --git a/studio/smoke_test.py b/studio/smoke_test.py new file mode 100644 index 0000000..5bb0a01 --- /dev/null +++ b/studio/smoke_test.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""한땀 작업실 API 스모크 테스트 — 저장·커밋·되돌리기 왕복 검증.""" +import json +import sys +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +BASE = "http://127.0.0.1:8081" +ROOT = Path.home() / "Projects/teamat" +SLUG = "whitework-tea-mat" +MD = ROOT / "content/products" / f"{SLUG}.md" + +fails = [] + + +def check(name, cond, extra=""): + print(("OK " if cond else "FAIL ") + name + (f" {extra}" if extra and not cond else "")) + if not cond: + fails.append(name) + + +def req(path, payload=None, raw=None, method=None): + url = BASE + path + data = None + headers = {} + if payload is not None: + data = json.dumps(payload).encode() + headers["Content-Type"] = "application/json" + if raw is not None: + data = raw + headers["Content-Type"] = "application/octet-stream" + request = urllib.request.Request(url, data=data, headers=headers, method=method or ("POST" if data else "GET")) + try: + with urllib.request.urlopen(request, timeout=120) as res: + return res.status, json.loads(res.read().decode()) + except urllib.error.HTTPError as error: + body = error.read().decode() + try: + return error.code, json.loads(body) + except json.JSONDecodeError: + return error.code, {"raw": body} + + +original = MD.read_text(encoding="utf-8") + +# 1. 목록 +code, state = req("/api/state") +check("GET /api/state", code == 200 and state["ok"] and state["count"] >= 3, str(code)) +head0 = state["head"] + +# 2. 작품 열기 +code, data = req(f"/api/product?slug={SLUG}") +check("GET /api/product", code == 200 and data["product"]["fields"]["title"] == "목련 한 땀 티매트", str(code)) +fields0 = data["product"]["fields"] +body0 = data["product"]["body"] +check("본문 읽힘", len(body0) > 50) +check("추가 이미지 필드(빈 목록)", fields0["gallery"] == "") + +# 3. 변경 없이 저장 → 커밋하지 않아야 함 +code, data = req("/api/product", {"slug": SLUG, "fields": fields0, "body": body0}) +check("무변경 저장은 커밋 안 함", data["ok"] and data["changed"] is False, json.dumps(data)[:200]) + +# 4. 실제 수정 저장 (+ 추가 이미지 1장) +fields = dict(fields0) +fields["subtitle"] = "스모크 테스트 부제" +fields["price"] = "59000" +fields["gallery"] = "assets/img/work-whitework.jpg" +code, data = req("/api/product", {"slug": SLUG, "fields": fields, "body": body0}) +check("수정 저장 성공", data["ok"] and data.get("changed") is True, json.dumps(data)[:300]) +sha = data.get("head", "") +check("HEAD 이동", sha != head0, f"{head0} -> {sha}") + +text = MD.read_text(encoding="utf-8") +check("파일 반영(subtitle)", "subtitle: 스모크 테스트 부제" in text) +check("파일 반영(price 정수)", "price: 59000" in text, text[:400]) +check("목록 형식 유지(gallery)", "gallery:\n- assets/img/work-whitework.jpg" in text, text[:600]) +check("front matter 순서 유지", text.splitlines()[1].startswith("slug:"), text.splitlines()[1]) + +code, data = req("/api/history") +check("이력에 수정 커밋", any("목련 한 땀 티매트" in row["subject"] for row in data["history"]), str(data["history"][:2])) + +# 5. 이미지 업로드 거부 (JPG 아님) +code, data = req("/api/upload?name=x.png", raw=b"\x89PNG\r\n") +check("PNG 업로드 거부", data["ok"] is False, json.dumps(data)) + +# 6. 잘못된 슬러그 +code, data = req("/api/product?slug=../../etc/passwd") +check("경로 조작 차단", code in (400, 404), str(code)) + +# 7. 되돌리기 +code, data = req("/api/revert", {"sha": sha, "deploy": False}) +check("되돌리기 성공", data["ok"] is True, json.dumps(data)[:300]) +check("파일 원복", MD.read_text(encoding="utf-8") == original, "원본과 다름") + +# 8. 되돌린 뒤 무변경 저장은 다시 커밋하지 않아야 함 +code, data = req(f"/api/product?slug={SLUG}") +code, again = req("/api/product", {"slug": SLUG, "fields": data["product"]["fields"], "body": data["product"]["body"]}) +check("원복 후 무변경", again["ok"] and again["changed"] is False, json.dumps(again)[:200]) + +print() +print(f"{'실패 ' + str(len(fails)) + '건: ' + ', '.join(fails) if fails else '전부 통과'}") +sys.exit(1 if fails else 0) diff --git a/templates/base.html b/templates/base.html index d7343e9..9821951 100644 --- a/templates/base.html +++ b/templates/base.html @@ -61,5 +61,12 @@

    © {{since}} {{brand_name}}

    + + diff --git a/templates/product.html b/templates/product.html index e498534..2f97f9d 100644 --- a/templates/product.html +++ b/templates/product.html @@ -14,6 +14,7 @@

    {{price_text}}

    {{sold_html}} {{buy_html}} +