#!/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("

" + inline_markdown(line[3:].strip()) + "

") index += 1 continue if line.startswith("- "): flush_paragraph() items: List[str] = [] while index < len(lines) and lines[index].strip().startswith("- "): items.append("
  • " + inline_markdown(lines[index].strip()[2:].strip()) + "
  • ") index += 1 out.append("") continue image_match = IMAGE_LINE_RE.match(line) if image_match: flush_paragraph() alt, src = image_match.group(1), image_match.group(2).strip() out.append( '
    '
                + esc(alt)
                + '
    ' ) index += 1 continue paragraph.append(line) index += 1 flush_paragraph() return "\n".join(out) # --------------------------------------------------------------------- images def jpeg_size(path: Path) -> Tuple[int, int]: data = path.read_bytes() if data[:2] != b"\xff\xd8": fail(f"JPEG 파일이 아닙니다: {path}") sof_markers = set(range(0xC0, 0xC4)) | set(range(0xC5, 0xC8)) | set(range(0xC9, 0xCC)) | set(range(0xCD, 0xD0)) pos = 2 while pos + 9 < len(data): if data[pos] != 0xFF: pos += 1 continue marker = data[pos + 1] if marker in (0xD8, 0xD9): pos += 2 continue length = int.from_bytes(data[pos + 2 : pos + 4], "big") if marker in sof_markers: height = int.from_bytes(data[pos + 5 : pos + 7], "big") width = int.from_bytes(data[pos + 7 : pos + 9], "big") return width, height pos += 2 + length fail(f"이미지 크기를 읽을 수 없습니다: {path}") _image_sizes: Dict[str, Tuple[int, int]] = {} def image_size(rel_path: str) -> Tuple[int, int]: if not rel_path: fail("이미지 경로가 비어 있습니다.") if rel_path.startswith(("http://", "https://", "/")): fail(f"이미지 경로는 상대경로여야 합니다: {rel_path}") if rel_path not in _image_sizes: path = ROOT / rel_path if not path.is_file(): fail(f"이미지 파일이 없습니다: {rel_path}") _image_sizes[rel_path] = jpeg_size(path) return _image_sizes[rel_path] def img_tag( rel_path: str, alt: str, *, prefix: str = "", loading: str = "lazy", priority: bool = False, ) -> str: width, height = image_size(rel_path) extra = ' fetchpriority="high"' if priority else "" return ( f'{esc(alt)}' ) def figure_html( rel_path: str, alt: str, css_class: str, *, prefix: str = "", loading: str = "lazy", priority: bool = False, ) -> str: return ( f'
    ' + img_tag(rel_path, alt, prefix=prefix, loading=loading, priority=priority) + "
    " ) def absolute_url(rel_path: str) -> str: return SITE_BASE + rel_path.lstrip("/") # -------------------------------------------------------------------- helpers def format_price(value: Any) -> str: if value is None or value == "": return "문의" if isinstance(value, int): return f"{value:,}원" return esc(value) def collapse(text: str) -> str: return re.sub(r"\s+", " ", text).strip() def render(template: str, context: Dict[str, Any], name: str = "template") -> str: def replace_loop(match: re.Match) -> str: key, body = match.group(1), match.group(2) items = context.get(key, []) if items in (None, ""): items = [] if not isinstance(items, Iterable) or isinstance(items, (str, bytes, dict)): fail(f"{name} 의 {key} 는 목록이어야 합니다.") rendered: List[str] = [] for item in items: local = dict(context) if isinstance(item, dict): local.update(item) else: local["text"] = item rendered.append(VAR_RE.sub(lambda m: str(local.get(m.group(1), "")), body)) return "".join(rendered) output = LOOP_RE.sub(replace_loop, template) output = VAR_RE.sub(lambda m: str(context.get(m.group(1), "")), output) leftover = re.search(r"{{[^}]+}}", output) if leftover: fail(f"{name} 에 치환되지 않은 값이 있습니다: {leftover.group(0)}") return output def load_products() -> List[Dict[str, Any]]: products: List[Dict[str, Any]] = [] for path in sorted((CONTENT / "products").glob("*.md")): data, body = parse_markdown_file(path) slug = str(data.get("slug", "")).strip() if not slug: fail(f"{path.name} 에 slug 가 없습니다.") if slug != path.stem: fail(f"{path.name} 의 slug({slug})가 파일명과 다릅니다.") data["slug"] = slug data["body"] = body data["_path"] = path image_size(str(data.get("image", ""))) gallery = data.get("gallery") or [] if not isinstance(gallery, list): fail(f"{path.name} 의 gallery 는 목록이어야 합니다.") for gallery_image in gallery: image_size(str(gallery_image)) products.append(data) if not products: fail("content/products 에 작품이 없습니다.") return products def sort_products(products: List[Dict[str, Any]], order: str) -> List[Dict[str, Any]]: reverse = order != "oldest" return sorted(products, key=lambda p: (str(p.get("date", "")), p["slug"]), reverse=reverse) def load_process() -> List[Dict[str, Any]]: steps: List[Dict[str, Any]] = [] for path in sorted((CONTENT / "process").glob("*.md")): data, body = parse_markdown_file(path) if data.get("step") in ("", None): fail(f"{path.name} 에 step 이 없습니다.") data["step"] = int(data["step"]) data["body"] = body if data.get("image"): image_size(str(data["image"])) steps.append(data) if not steps: fail("content/process 에 단계가 없습니다.") return sorted(steps, key=lambda s: s["step"]) def build_shared(site: Dict[str, Any], home: str, asset_prefix: str) -> Dict[str, Any]: brand = site["brand"] contact = site["contact"] email = str(contact.get("email", "")).strip() instagram = str(contact.get("instagram", "")).strip() if email: email_href = "mailto:" + email email_html = f'{esc(email)}' else: email_href = "" email_html = '메일 준비 중' if instagram: instagram_link = f'인스타그램' else: instagram_link = '인스타그램 준비 중' credits = [ { "title": esc(item.get("title", "")), "author": esc(item.get("author", "")), "license": esc(item.get("license", "")), } for item in site.get("image_credits", []) ] return { "brand_name": esc(brand["name"]), "brand_name_en": esc(brand["name_en"]), "tagline": esc(brand["tagline"]), "since": esc(brand["since"]), "footer_note": esc(site.get("footer_note", "")), "contact_email": esc(email) if email else "", "email_href": esc(email_href) if email_href else "", "email_html": email_html, "instagram_link": instagram_link, "credits": credits, "home": home, "asset_prefix": asset_prefix, } def product_loop_items(products: List[Dict[str, Any]]) -> List[Dict[str, Any]]: items: List[Dict[str, Any]] = [] for product in products: image = str(product["image"]) width, height = image_size(image) sold_html = '

    판매 완료

    ' 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 = '" if gallery_figures else "" prev_product = products[index - 1] if index > 0 else None next_product = products[index + 1] if index + 1 < len(products) else None list_fallback = ( '' '목록' '모든 작품' "" ) subtitle = str(product.get("subtitle", "")).strip() material = str(product.get("material", "")).strip() price_note = str(product.get("price_note", "")).strip() price_note_html = ( f'

    {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 . The base needs the full title; # the product template needs only the work's name. template = (TEMPLATES / "product.html").read_text(encoding="utf-8") body_context = dict(context) body_context["title"] = esc(product["title"]) body_context["title_text"] = esc(product["title"]) body = render(template, body_context, f"product {product['slug']}") context["content"] = body return render((TEMPLATES / "base.html").read_text(encoding="utf-8"), context, "base.html") def verify_dist(products: List[Dict[str, Any]]) -> None: pages = [DIST / "index.html", *sorted((DIST / "p").glob("*.html"))] errors: List[str] = [] images = 0 for page in pages: text = page.read_text(encoding="utf-8") images += len(re.findall(r"<img\s", text)) for attr in re.findall(r'(?:href|src)="([^"]+)"', text): attr = html.unescape(attr) if attr.startswith(("http://", "https://", "mailto:", "data:", "tel:", "#")): continue target = attr.split("#", 1)[0] if not target: continue resolved = (page.parent / target).resolve() if not resolved.exists(): errors.append(f"{page.relative_to(DIST)} -> {attr}") if errors: for error in errors: print(f"깨진 경로: {error}", file=sys.stderr) fail(f"깨진 상대경로 {len(errors)}개") index_text = (DIST / "index.html").read_text(encoding="utf-8") work_links = sorted(set(re.findall(r'href="p/[^"]+\.html"', index_text))) if len(work_links) < len(products): fail("첫 페이지의 작품 링크 수가 작품 수보다 적습니다.") print(f"검증: 페이지 {len(pages)}개, 이미지 {images}개, 깨진 상대경로 0개, 작품 링크 {len(work_links)}개") def main() -> None: try: site = json.loads((CONTENT / "site.json").read_text(encoding="utf-8")) except json.JSONDecodeError as error: fail(f"content/site.json 문법 오류: {error}") brand = site["brand"] products_all = load_products() products = sort_products(products_all, str(site.get("product_sort", "newest"))) steps = load_process() shared_index = build_shared(site, home="", asset_prefix="") shared_product = build_shared(site, home="../", asset_prefix="../") index_html = build_index(site, products, steps, shared_index, brand) product_pages = { product["slug"]: build_product_page(product, products, shared_product, brand, position) for position, product in enumerate(products) } if DIST.exists(): shutil.rmtree(DIST) (DIST / "p").mkdir(parents=True) shutil.copytree( ASSETS, DIST / "assets", ignore=shutil.ignore_patterns(".DS_Store", "*.log", "__pycache__"), ) (DIST / "index.html").write_text(index_html, encoding="utf-8") for slug, page in product_pages.items(): (DIST / "p" / f"{slug}.html").write_text(page, encoding="utf-8") verify_dist(products) print("빌드 완료: dist/") print(" dist/index.html") for slug in product_pages: print(f" dist/p/{slug}.html") if __name__ == "__main__": main()