#!/usr/bin/env python3 """한땀 정적 사이트 빌드. content/ + templates/ + assets/ -> dist/ 표준 라이브러리만 쓴다. 템플릿은 {{key}} 치환과 목록 반복만 지원한다. """ from __future__ import annotations import html import json import re import shutil import sys from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple ROOT = Path(__file__).resolve().parent CONTENT = ROOT / "content" TEMPLATES = ROOT / "templates" ASSETS = ROOT / "assets" DIST = ROOT / "dist" SITE_BASE = "https://teamat.lala.dedyn.io/" VAR_RE = re.compile(r"{{\s*(\w+)\s*}}") LOOP_RE = re.compile(r"{{#(\w+)}}(.*?){{/\1}}", re.S) BOLD_RE = re.compile(r"\*\*(.+?)\*\*") IMAGE_LINE_RE = re.compile(r"^!\[(.*?)\]\((.+?)\)$") def esc(value: Any) -> str: return html.escape(str(value), quote=True) def fail(message: str) -> None: print(f"빌드 오류: {message}", file=sys.stderr) raise SystemExit(1) # ---------------------------------------------------------------- front matter def parse_scalar(value: str) -> Any: value = value.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_markdown_file(path: Path) -> Tuple[Dict[str, Any], str]: raw = path.read_text(encoding="utf-8") if not raw.startswith("---"): fail(f"{path} 파일이 --- 로 시작하지 않습니다.") parts = raw.split("---", 2) if len(parts) != 3: fail(f"{path} 파일의 front matter가 닫히지 않았습니다.") front, body = parts[1], parts[2].lstrip("\n") data: Dict[str, Any] = {} current_key: Optional[str] = None for line in front.splitlines(): if not line.strip() or line.lstrip().startswith("#"): continue stripped = line.strip() if stripped.startswith("- ") and current_key: if data.get(current_key) is None: data[current_key] = [] if not isinstance(data[current_key], list): fail(f"{path} 의 {current_key} 는 목록이 아닙니다.") data[current_key].append(parse_scalar(stripped[2:])) continue if ":" not in line: fail(f"{path} 의 front matter 줄을 읽을 수 없습니다: {line}") key, value = line.split(":", 1) key = key.strip() value = value.strip() if value == "": data[key] = None current_key = key else: data[key] = parse_scalar(value) current_key = None for key, value in list(data.items()): if value is None: data[key] = "" return data, body # ------------------------------------------------------------------- markdown def inline_markdown(text: str) -> str: return BOLD_RE.sub(r"\1", esc(text)) def markdown_to_html(text: str, img_prefix: str = "") -> str: lines = text.replace("\r\n", "\n").split("\n") out: List[str] = [] paragraph: List[str] = [] index = 0 def flush_paragraph() -> None: if paragraph: out.append("
" + inline_markdown(" ".join(paragraph)) + "
") paragraph.clear() while index < len(lines): line = lines[index].strip() if not line: flush_paragraph() index += 1 continue if line.startswith("## "): flush_paragraph() out.append("판매 완료
' if product.get("sold_out") else "" items.append( { "href": f"p/{product['slug']}.html", "image": esc(image), "alt": esc(product.get("image_alt") or product["title"]), "width": str(width), "height": str(height), "title": esc(product["title"]), "subtitle": esc(product.get("subtitle", "")), "price_text": format_price(product.get("price")), "sold_html": sold_html, } ) return items def process_loop_items(steps: List[Dict[str, Any]]) -> List[Dict[str, Any]]: items: List[Dict[str, Any]] = [] for step in steps: image = str(step.get("image", "")) if image: image_html = figure_html( image, str(step.get("image_alt") or step["title"]), "step-figure", ) step_class = "process-step has-image" else: image_html = "" step_class = "process-step no-image" items.append( { "step": str(step["step"]), "title": esc(step["title"]), "body_html": markdown_to_html(step["body"]), "image_html": image_html, "step_class": step_class, } ) return items def build_index( site: Dict[str, Any], products: List[Dict[str, Any]], steps: List[Dict[str, Any]], shared: Dict[str, Any], brand: Dict[str, Any], ) -> str: featured = next((p for p in products if p.get("featured")), products[0]) hero_image = str(featured["image"]) hero_width, hero_height = image_size(hero_image) kit_slug = str(site.get("shop", {}).get("kit_slug", "")).strip() kit = next((p for p in products if p["slug"] == kit_slug), None) if kit_slug else None if kit is None: kit = next((p for p in products if p["slug"].endswith("kit-first-stitch")), None) if kit is None: fail("키트로 쓸 작품이 없습니다. content/site.json 의 shop.kit_slug 를 지정하세요.") kit_image = str(kit["image"]) kit_width, kit_height = image_size(kit_image) kit_body_html = markdown_to_html(kit["body"]) kit_excerpt = kit_body_html.split("", 1)[0] + "" if "" in kit_body_html else kit_body_html kit_url = str(site.get("shop", {}).get("kit_url", "")).strip() if kit_url: kit_action = f'네이버에서 키트 구매' else: kit_action = '네이버 스마트스토어 준비 중
' store_url = str(site.get("shop", {}).get("store_url", "")).strip() if store_url: store_note = ( f'네이버 스마트스토어' "에서 주문하실 수 있습니다." ) else: store_note = "온라인 주문은 준비 중입니다. 작품과 키트 문의는 메일로 받습니다." intro = collapse(brand["intro"]) title = f"{brand['name']} — {brand['tagline']}" context: Dict[str, Any] = dict(shared) context.update( { "title": esc(title), "description": esc(intro), "og_title": esc(title), "og_description": esc(intro), "og_image": esc(absolute_url(hero_image)), "og_type": "website", "body_class": "is-home", "intro": esc(intro), "hero_image": esc(hero_image), "hero_alt": esc(featured.get("image_alt") or featured["title"]), "hero_width": str(hero_width), "hero_height": str(hero_height), "hero_title": esc(featured["title"]), "hero_material": esc(featured.get("material", "")), "hero_href": f"p/{featured['slug']}.html", "works_note": esc(site.get("works_note", "")), "products": product_loop_items(products), "process": process_loop_items(steps), "process_intro": esc(site.get("process_intro", "")), "kit_title": esc(kit["title"]), "kit_subtitle": esc(kit.get("subtitle", "")), "kit_excerpt": kit_excerpt, "kit_note": esc(site.get("shop", {}).get("kit_note", "")), "kit_price": format_price(kit.get("price")), "kit_action": kit_action, "kit_href": f"p/{kit['slug']}.html", "kit_image": esc(kit_image), "kit_alt": esc(kit.get("image_alt") or kit["title"]), "kit_width": str(kit_width), "kit_height": str(kit_height), "shipping": [{"text": esc(item)} for item in site.get("shipping", [])], "care": [{"text": esc(item)} for item in site.get("care", [])], "store_note": store_note, } ) body = render((TEMPLATES / "index.html").read_text(encoding="utf-8"), context, "index.html") context["content"] = body return render((TEMPLATES / "base.html").read_text(encoding="utf-8"), context, "base.html") def pager_html(product: Optional[Dict[str, Any]], label: str, css_class: str) -> str: if product is None: return "" return ( f'' f'{esc(label)}' f'{esc(product["title"])}' "" ) def build_product_page( product: Dict[str, Any], products: List[Dict[str, Any]], shared: Dict[str, Any], brand: Dict[str, Any], index: int, ) -> str: image = str(product["image"]) width, height = image_size(image) if product.get("sold_out"): buy_html = '판매 완료 — 재제작을 원하시면 문의해 주세요
' else: naver_url = str(product.get("naver_url", "")).strip() if naver_url: buy_html = f'네이버 스토어에서 구매' else: buy_html = ( '" ) gallery = product.get("gallery") or [] gallery_figures: List[str] = [] for number, gallery_image in enumerate(gallery, start=1): gallery_figures.append( figure_html( str(gallery_image), f"{product['title']} 추가 이미지 {number}", "gallery-figure", prefix="../", ) ) gallery_html = '{esc(price_note)}
' if price_note else "" ) description = ". ".join(part for part in (subtitle, material) if part) title = f"{product['title']} — {brand['name']}" context: Dict[str, Any] = dict(shared) context.update( { "title": esc(title), "description": esc(description), "og_title": esc(title), "og_description": esc(description), "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), "height": str(height), "product_title": esc(product["title"]), "title_text": esc(product["title"]), "subtitle": esc(subtitle), "price_text": format_price(product.get("price")), "price_note_html": price_note_html, "sold_html": '판매 완료
' if product.get("sold_out") else "", "buy_html": buy_html, "material": esc(material) or "—", "size": esc(product.get("size", "")) or "—", "care": esc(product.get("care", "")) or "—", "body_html": markdown_to_html(product["body"], img_prefix="../"), "gallery_html": gallery_html, "prev_html": pager_html(prev_product, "이전 작품", "pager-link pager-link-prev") or list_fallback, "next_html": pager_html(next_product, "다음 작품", "pager-link pager-link-next") or list_fallback, } ) # {{title}} is used both by the page and by