작품 파일명 연-월-제목 + 작품별 이미지 폴더(assets/img/<slug>/)
This commit is contained in:
1 parent
4dff91b483
commit
767b2a30a3
19 files changed
+163
-40
No files matched your search
+3
-3
@@ -44,7 +44,7 @@ before_head = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd="/User
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
|
||||
# 1) 작품 수정 제안
|
||||
code, data = post("/api/ai", {"mode": "edit", "slug": "whitework-tea-mat",
|
||||
code, data = post("/api/ai", {"mode": "edit", "slug": "2026-10-whitework-tea-mat",
|
||||
"prompt": "부제를 더 담백하게, 20자 이내로. 본문은 그대로 둬."})
|
||||
check("edit 200", code == 200 and data.get("ok") is True, json.dumps(data, ensure_ascii=False)[:400])
|
||||
if data.get("ok"):
|
||||
@@ -57,7 +57,7 @@ if data.get("ok"):
|
||||
print(f" {k}: {str(v)[:120]}")
|
||||
|
||||
# 2) 본문 다시 쓰기
|
||||
code, data2 = post("/api/ai", {"mode": "edit", "slug": "whitework-tea-mat",
|
||||
code, data2 = post("/api/ai", {"mode": "edit", "slug": "2026-10-whitework-tea-mat",
|
||||
"prompt": "본문을 3문단으로 다시 써. 재료와 걸린 시간을 숫자로 넣어."})
|
||||
if data2.get("ok"):
|
||||
body = data2.get("changes", {}).get("body", "")
|
||||
@@ -77,7 +77,7 @@ if draft.get("ok"):
|
||||
print(" 초안:", fields.get("slug"), "|", fields.get("title"), "|", fields.get("price"), "|", fields.get("size"))
|
||||
|
||||
# 4) 빈 요청 거부
|
||||
code, bad = post("/api/ai", {"mode": "edit", "slug": "whitework-tea-mat", "prompt": ""})
|
||||
code, bad = post("/api/ai", {"mode": "edit", "slug": "2026-10-whitework-tea-mat", "prompt": ""})
|
||||
check("빈 요청 거부", code == 400, str(code))
|
||||
|
||||
# 5) AI 호출이 저장소를 건드리지 않아야 한다
|
||||
|
||||
+7
-4
@@ -391,7 +391,7 @@ function fieldHtml(f, value) {
|
||||
'<span class="img-line"><input type="text" id="' + id + '" data-key="' + f.key + '" value="' + esc(value) + '">' +
|
||||
'<img class="img-preview" id="' + id + '_prev" src="' + (value ? '/media/' + encodeURI(value) : '') + '" alt="">' +
|
||||
'<button type="button" class="ghost" id="' + id + '_pick">올리기</button></span>' +
|
||||
'<span class="drop-hint" id="' + id + '_hint">JPG를 여기로 끌어다 놓아도 됩니다 (assets/img 에 저장)</span></label>';
|
||||
'<span class="drop-hint" id="' + id + '_hint">JPG를 끌어다 놓으면 assets/img/<슬러그>/ 에 저장됩니다</span></label>';
|
||||
}
|
||||
const type = f.type === 'number' ? 'number' : (f.type === 'date' ? 'date' : (f.type === 'url' ? 'url' : 'text'));
|
||||
return '<label class="field' + wide + '"><span class="lbl">' + esc(f.label) + '</span>' +
|
||||
@@ -403,8 +403,8 @@ function renderEditor(p) {
|
||||
const isDraft = !!p.draft;
|
||||
if (isDraft) state.current = null;
|
||||
const slugField = isDraft
|
||||
? '<label class="field wide"><span class="lbl">슬러그 (주소·파일명, 영문 소문자·하이픈)</span>' +
|
||||
'<input type="text" id="f_slug" value="' + esc(p.slug || '') + '" placeholder="예: magnolia-tea-mat"></label>'
|
||||
? '<label class="field wide"><span class="lbl">슬러그 · 파일명 (연-월-제목, 영문 소문자)</span>' +
|
||||
'<input type="text" id="f_slug" value="' + esc(p.slug || '') + '" placeholder="예: 2026-11-magnolia-tea-mat"></label>'
|
||||
: '';
|
||||
const grid = slugField + state.fields.map((f) => fieldHtml(f, values[f.key])).join('');
|
||||
const extraKeys = p.extra_keys || [];
|
||||
@@ -455,8 +455,11 @@ function pickImage(target) {
|
||||
}
|
||||
|
||||
async function uploadImage(file, target) {
|
||||
const slugEl = $('f_slug');
|
||||
const slug = (slugEl ? slugEl.value.trim() : '') || state.current || '';
|
||||
if (!slug) { toast('슬러그를 먼저 정해야 이미지를 넣을 수 있습니다', 'err'); return; }
|
||||
$('state').textContent = '이미지 올리는 중…';
|
||||
const res = await fetch('/api/upload?name=' + encodeURIComponent(file.name), {
|
||||
const res = await fetch('/api/upload?name=' + encodeURIComponent(file.name) + '&slug=' + encodeURIComponent(slug), {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file,
|
||||
});
|
||||
const data = await res.json().catch(() => ({ ok: false, error: '업로드 실패' }));
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""새 작품 등록 왕복 테스트: AI 초안 -> 이미지 업로드(작품 폴더) -> 저장/커밋 -> 되돌리기."""
|
||||
import json
|
||||
import subprocess
|
||||
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"
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond, extra=""):
|
||||
print(("OK " if cond else "FAIL ") + name + (f"\n {extra}" if extra else ""))
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
def req(path, payload=None, raw=None):
|
||||
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(BASE + path, data=data, headers=headers,
|
||||
method="POST" if data else "GET")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=300) 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}
|
||||
|
||||
|
||||
# 1) AI 초안 — slug 에 연-월 접두가 붙어야 한다
|
||||
code, draft = req("/api/ai", {"mode": "draft",
|
||||
"prompt": "겨울 매화 티매트, 32×48cm, 린넨 100%, 62000원. 눈 내린 창가 분위기."})
|
||||
check("draft ok", code == 200 and draft.get("ok") is True, json.dumps(draft, ensure_ascii=False)[:300])
|
||||
slug = str(draft.get("fields", {}).get("slug", ""))
|
||||
check("slug 연-월 접두", bool(__import__("re").fullmatch(r"\d{4}-\d{2}-[a-z0-9-]+", slug)), slug)
|
||||
|
||||
# 2) 이미지 업로드 — 작품 폴더로
|
||||
source = ROOT / "assets/img/2026-10-whitework-tea-mat/cover.jpg"
|
||||
code, up = req("/api/upload?name=cover.jpg&slug=" + urllib.parse.quote(slug), raw=source.read_bytes())
|
||||
check("upload ok", up.get("ok") is True, json.dumps(up, ensure_ascii=False))
|
||||
check("upload 경로가 작품 폴더", str(up.get("path", "")).startswith(f"assets/img/{slug}/"), str(up.get("path")))
|
||||
check("업로드 파일 존재", (ROOT / str(up.get("path", ""))).is_file())
|
||||
|
||||
code, nope = req("/api/upload?name=cover.jpg&slug=", raw=b"\xff\xd8\xff")
|
||||
check("슬러그 없으면 업로드 거부", nope.get("ok") is False, json.dumps(nope, ensure_ascii=False))
|
||||
|
||||
# 3) 저장(새 작품)
|
||||
fields = dict(draft.get("fields") or {})
|
||||
fields["image"] = up.get("path")
|
||||
fields["image_alt"] = fields.get("image_alt") or "테스트 이미지"
|
||||
fields["date"] = fields.get("date") or "2026-11-01"
|
||||
body = draft.get("body") or "테스트 본문입니다."
|
||||
code, saved = req("/api/product", {"slug": slug, "fields": fields, "body": body, "create": True})
|
||||
check("새 작품 저장", saved.get("ok") is True and saved.get("changed") is True, json.dumps(saved, ensure_ascii=False)[:400])
|
||||
md = ROOT / "content/products" / f"{slug}.md"
|
||||
check("md 파일 생성", md.is_file(), str(md))
|
||||
check("dist 페이지 생성", (ROOT / "dist/p" / f"{slug}.html").is_file())
|
||||
if md.is_file():
|
||||
text = md.read_text(encoding="utf-8")
|
||||
check("front matter image 경로", f"image: assets/img/{slug}/" in text, text[:500])
|
||||
|
||||
log = subprocess.run(["git", "log", "-1", "--pretty=%s"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
|
||||
check("커밋 메시지 = 작품 추가", log.startswith("작품 추가:"), log)
|
||||
|
||||
# 4) 규칙 위반 슬러그는 거부
|
||||
code, bad = req("/api/product", {"slug": "no-date-slug", "fields": {"title": "x", "image": up.get("path")},
|
||||
"body": "x", "create": True})
|
||||
check("연-월 없는 새 슬러그 거부", code == 400, json.dumps(bad, ensure_ascii=False)[:200])
|
||||
|
||||
# 5) 되돌리기 -> 파일·이미지·페이지가 모두 사라져야 한다
|
||||
sha = saved.get("head")
|
||||
code, rev = req("/api/revert", {"sha": sha, "deploy": False})
|
||||
check("되돌리기", rev.get("ok") is True, json.dumps(rev, ensure_ascii=False)[:300])
|
||||
check("md 삭제", not md.exists(), str(md))
|
||||
check("dist 페이지 삭제", not (ROOT / "dist/p" / f"{slug}.html").exists())
|
||||
check("이미지 폴더 정리", not (ROOT / "assets/img" / slug).exists(), str(ROOT / "assets/img" / slug))
|
||||
|
||||
status = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
|
||||
check("작업 트리 깨끗", status == "", status)
|
||||
|
||||
print()
|
||||
print("실패 " + str(len(fails)) + "건: " + ", ".join(fails) if fails else "전부 통과")
|
||||
sys.exit(1 if fails else 0)
|
||||
+16
-5
@@ -297,6 +297,8 @@ def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
creating = not path.exists()
|
||||
if creating and not payload.get("create"):
|
||||
raise FileNotFoundError(f"작품 파일이 없습니다: {slug}.md")
|
||||
if creating and not re.fullmatch(r"\d{4}-\d{2}-[a-z0-9][a-z0-9-]*", slug):
|
||||
raise ValueError("새 작품 슬러그는 `연-월-제목` 형식이어야 합니다 (예: 2026-11-magnolia-tea-mat)")
|
||||
|
||||
if creating:
|
||||
original = None
|
||||
@@ -376,14 +378,18 @@ def revert(sha: str, redeploy: bool) -> Dict[str, Any]:
|
||||
return result
|
||||
|
||||
|
||||
def upload_image(name: str, data: bytes) -> Dict[str, Any]:
|
||||
def upload_image(name: str, data: bytes, slug: str = "") -> Dict[str, Any]:
|
||||
"""이미지는 assets/img/<작품슬러그>/ 에 넣는다. 작품마다 폴더 하나."""
|
||||
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"
|
||||
slug = slug.strip()
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slug or ""):
|
||||
return {"ok": False, "error": "슬러그를 먼저 정해야 이미지를 넣을 수 있습니다 (예: 2026-11-magnolia-tea-mat)"}
|
||||
stem = re.sub(r"[^a-z0-9-]+", "-", Path(name).stem.lower()).strip("-") or "photo"
|
||||
target_dir = ASSETS / "img" / slug
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / f"{stem}{ext}"
|
||||
counter = 2
|
||||
@@ -391,7 +397,7 @@ def upload_image(name: str, data: bytes) -> Dict[str, Any]:
|
||||
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)}
|
||||
return {"ok": True, "path": f"assets/img/{slug}/{target.name}", "bytes": len(data)}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- AI
|
||||
@@ -535,6 +541,10 @@ def ai_draft(prompt: str) -> Dict[str, Any]:
|
||||
slug = re.sub(r"[^a-z0-9-]+", "-", str(fields.get("slug") or "").lower()).strip("-")
|
||||
if not slug:
|
||||
slug = "work-" + datetime.now().strftime("%m%d-%H%M")
|
||||
prefix = str(fields.get("date") or datetime.now().strftime("%Y-%m-%d"))[:7]
|
||||
regex_prefix = re.compile(r"^\d{4}-\d{2}-")
|
||||
if not regex_prefix.match(slug):
|
||||
slug = f"{prefix}-{slug}"
|
||||
candidate, index = slug, 2
|
||||
while (PRODUCTS / f"{candidate}.md").exists():
|
||||
candidate = f"{slug}-{index}"
|
||||
@@ -667,9 +677,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
if path == "/api/upload":
|
||||
name = (query.get("name") or ["image.jpg"])[0]
|
||||
slug = (query.get("slug") or [""])[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))
|
||||
self.send_json(upload_image(name, data, slug))
|
||||
return
|
||||
if path == "/api/build":
|
||||
ok, log = build()
|
||||
|
||||
@@ -9,7 +9,7 @@ from pathlib import Path
|
||||
|
||||
BASE = "http://127.0.0.1:8081"
|
||||
ROOT = Path.home() / "Projects/teamat"
|
||||
SLUG = "whitework-tea-mat"
|
||||
SLUG = "2026-10-whitework-tea-mat"
|
||||
MD = ROOT / "content/products" / f"{SLUG}.md"
|
||||
|
||||
fails = []
|
||||
@@ -66,7 +66,7 @@ check("무변경 저장은 커밋 안 함", data["ok"] and data["changed"] is Fa
|
||||
fields = dict(fields0)
|
||||
fields["subtitle"] = "스모크 테스트 부제"
|
||||
fields["price"] = "59000"
|
||||
fields["gallery"] = "assets/img/work-whitework.jpg"
|
||||
fields["gallery"] = "assets/img/2026-10-whitework-tea-mat/cover.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", "")
|
||||
@@ -75,7 +75,7 @@ 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("목록 형식 유지(gallery)", "gallery:\n- assets/img/2026-10-whitework-tea-mat/cover.jpg" in text, text[:600])
|
||||
check("front matter 순서 유지", text.splitlines()[1].startswith("slug:"), text.splitlines()[1])
|
||||
|
||||
code, data = req("/api/history")
|
||||
|
||||
Reference in new issue
Block a user