From a7eb2823bdd4a53acffc9a807abc2ab1defbb639 Mon Sep 17 00:00:00 2001
From: Claude
Date: Thu, 26 Nov 2026 20:34:14 +0000
Subject: [PATCH] chore: retire Python milk-ssg and terrapin-ssg interpreters
Owner ruling of 2026-11-26: do them in COW and Logo and remove Python
entirely. Delete engines/milk-ssg/milk-ssg.py and
engines/terrapin-ssg/terrapin-ssg.py. The engine-level workflows now
validate the COW and Logo sources in satellites/ instead of running
Python. WORKFLOW-DISPOSITION.adoc records the retirement.
---
docs/WORKFLOW-DISPOSITION.adoc | 14 +-
engines/milk-ssg/.github/workflows/ci.yml | 73 +--
engines/milk-ssg/milk-ssg.py | 424 ---------------
engines/terrapin-ssg/.github/workflows/ci.yml | 76 +--
engines/terrapin-ssg/terrapin-ssg.py | 512 ------------------
5 files changed, 58 insertions(+), 1041 deletions(-)
delete mode 100755 engines/milk-ssg/milk-ssg.py
delete mode 100755 engines/terrapin-ssg/terrapin-ssg.py
diff --git a/docs/WORKFLOW-DISPOSITION.adoc b/docs/WORKFLOW-DISPOSITION.adoc
index 5bfda1a..437df10 100644
--- a/docs/WORKFLOW-DISPOSITION.adoc
+++ b/docs/WORKFLOW-DISPOSITION.adoc
@@ -34,9 +34,17 @@ prohibited-language objects were:
|`engines/terrapin-ssg/terrapin-ssg.py` |`100755` |`b6ee989e6176c775c7b95aa56f2fa32df800a8e6`
|===
-They remain unsupported historical experiments. This is not permission to
-introduce or develop Python runtime code, and neither file is deleted to
-make a language check pass.
+Both objects were retired on the owner's ruling of 2026-11-26 ("do them in
+cow and logo, get rid of python entirely") and are deleted from the tree. They
+remain in source history through the preserved import above. The milk-ssg
+engine is the COW source `satellites/milk-ssg/src/milk-ssg.cow` and the
+terrapin-ssg engine is the Logo source
+`satellites/terrapin-ssg/src/terrapin-ssg.logo`. The engine-level workflows
+under `engines/milk-ssg/` and `engines/terrapin-ssg/` no longer call Python;
+they validate those COW and Logo sources. After the retirement the gate
+expects no retained prohibited-language objects, so any `.py` file reappearing
+at either path is a violation. This is not permission to introduce or develop
+Python runtime code.
This gate checks a *source-object delta*, not execution or activation. An added
shell wrapper could invoke an unchanged historical file while the exact
diff --git a/engines/milk-ssg/.github/workflows/ci.yml b/engines/milk-ssg/.github/workflows/ci.yml
index c291a53..e02a281 100644
--- a/engines/milk-ssg/.github/workflows/ci.yml
+++ b/engines/milk-ssg/.github/workflows/ci.yml
@@ -1,3 +1,7 @@
+# SPDX-License-Identifier: MPL-2.0-or-later
+# milk-ssg is the COW engine at satellites/milk-ssg/src/milk-ssg.cow.
+# The former Python interpreter (engines/milk-ssg/milk-ssg.py) was retired on
+# the owner's ruling of 2026-11-26. This check validates the COW source only.
name: milk-ssg CI
on:
@@ -6,61 +10,28 @@ on:
pull_request:
branches: [main, master]
-jobs:
- test:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
-
- - name: Set up Python
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
- with:
- python-version: '3.11'
-
- - name: Test COW Interpreter
- run: python3 milk-ssg.py test-cow
-
- - name: Test Markdown
- run: python3 milk-ssg.py test-markdown
-
- - name: Test Frontmatter
- run: python3 milk-ssg.py test-frontmatter
+permissions:
+ contents: read
- - name: Test Full Pipeline
- run: python3 milk-ssg.py test-full
-
- build:
+jobs:
+ validate:
runs-on: ubuntu-latest
- needs: test
steps:
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
-
- - name: Set up Python
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- python-version: '3.11'
+ persist-credentials: false
- - name: Build sample site
+ - name: No Python in the engine directory
run: |
- mkdir -p _site
- python3 milk-ssg.py build || echo "Build completed"
-
- - name: Upload artifact
- uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3
- with:
- path: _site
+ if find engines/milk-ssg -type f -name '*.py' | grep -q .; then
+ echo 'Python found in engines/milk-ssg; the engine is COW only' >&2
+ exit 1
+ fi
- deploy:
- if: github.ref == 'refs/heads/main'
- needs: build
- runs-on: ubuntu-latest
- permissions:
- pages: write
- id-token: write
- environment:
- name: github-pages
- url: ${{ steps.deployment.outputs.page_url }}
- steps:
- - name: Deploy to GitHub Pages
- id: deployment
- uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4
+ - name: COW engine source is present and holds COW commands
+ run: |
+ src=satellites/milk-ssg/src/milk-ssg.cow
+ test -f "$src"
+ count=$(grep -o 'moo\|mOo\|moO\|mOO\|Moo\|MOo\|MoO\|MOO\|OOO\|MMM\|OOM\|oom' "$src" | wc -l)
+ echo "COW commands: $count"
+ test "$count" -gt 0
diff --git a/engines/milk-ssg/milk-ssg.py b/engines/milk-ssg/milk-ssg.py
deleted file mode 100755
index 1024c99..0000000
--- a/engines/milk-ssg/milk-ssg.py
+++ /dev/null
@@ -1,424 +0,0 @@
-#!/usr/bin/env python3
-"""
-milk-ssg - COW esoteric language powered static site generator
-
-Moo! A brainfuck variant SSG, because why not.
-
-COW has 12 instructions based on case variations of "moo":
- moo - Move back one instruction (loop start)
- moO - Move memory pointer forward
- mOo - Move memory pointer backward
- mOO - Execute value at memory as instruction
- Moo - If current memory is 0, read char, else print char
- MOo - Decrement current memory
- MoO - Increment current memory
- MOO - Loop: if memory is 0, skip to matching moo
- OOO - Set current memory to 0
- MMM - If memory is 0, register block, else restore
- OOM - Print current memory as number
- oom - Read number into current memory
-
-For the SSG, we use COW programs to generate site content,
-with a wrapper that handles file I/O and templates.
-"""
-
-import sys
-import os
-import re
-import json
-from typing import List, Tuple, Dict, Optional
-from dataclasses import dataclass, field
-
-# ============================================================================
-# COW Interpreter
-# ============================================================================
-
-COW_INSTRUCTIONS = {
- 'moo': 0, # loop end / back jump
- 'moO': 1, # pointer++
- 'mOo': 2, # pointer--
- 'mOO': 3, # execute memory as instruction
- 'Moo': 4, # if mem==0 read, else print
- 'MOo': 5, # mem--
- 'MoO': 6, # mem++
- 'MOO': 7, # loop start
- 'OOO': 8, # mem = 0
- 'MMM': 9, # register/restore block
- 'OOM': 10, # print mem as number
- 'oom': 11, # read number
-}
-
-def parse_cow(source: str) -> List[int]:
- """Parse COW source into instruction list."""
- tokens = re.findall(r'[mMoO]{3}', source)
- return [COW_INSTRUCTIONS.get(t, -1) for t in tokens if t in COW_INSTRUCTIONS]
-
-def run_cow(program: List[int], input_data: str = "") -> str:
- """Execute COW program and return output."""
- memory = [0] * 30000
- ptr = 0
- ip = 0
- output = []
- input_pos = 0
- register = None
- max_steps = 1000000
-
- steps = 0
- while ip < len(program) and steps < max_steps:
- steps += 1
- instr = program[ip]
-
- if instr == 0: # moo - jump back to matching MOO
- depth = 1
- ip -= 1
- while ip >= 0 and depth > 0:
- if program[ip] == 7: depth -= 1
- elif program[ip] == 0: depth += 1
- if depth > 0: ip -= 1
- elif instr == 1: # moO - pointer++
- ptr += 1
- elif instr == 2: # mOo - pointer--
- ptr -= 1
- elif instr == 3: # mOO - execute memory as instruction
- if 0 <= memory[ptr] <= 11:
- program.insert(ip + 1, memory[ptr])
- elif instr == 4: # Moo - print/read char
- if memory[ptr] == 0:
- if input_pos < len(input_data):
- memory[ptr] = ord(input_data[input_pos])
- input_pos += 1
- else:
- output.append(chr(memory[ptr] % 256))
- elif instr == 5: # MOo - mem--
- memory[ptr] -= 1
- elif instr == 6: # MoO - mem++
- memory[ptr] += 1
- elif instr == 7: # MOO - loop start
- if memory[ptr] == 0:
- depth = 1
- ip += 1
- while ip < len(program) and depth > 0:
- if program[ip] == 7: depth += 1
- elif program[ip] == 0: depth -= 1
- if depth > 0: ip += 1
- elif instr == 8: # OOO - clear memory
- memory[ptr] = 0
- elif instr == 9: # MMM - register/restore
- if memory[ptr] == 0:
- register = ip
- elif register is not None:
- ip = register
- register = None
- elif instr == 10: # OOM - print number
- output.append(str(memory[ptr]))
- elif instr == 11: # oom - read number
- # Skip for now
- pass
-
- ip += 1
-
- return ''.join(output)
-
-# ============================================================================
-# COW Programs (pre-compiled for common SSG tasks)
-# ============================================================================
-
-# "Hello" in COW (generates the word Hello)
-COW_HELLO = """
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo
-moO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo
-MoO MoO MoO MoO MoO MoO MoO Moo
-Moo
-moO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
-MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo
-"""
-
-# ============================================================================
-# Frontmatter & Markdown Parser
-# ============================================================================
-
-@dataclass
-class Frontmatter:
- title: str = ""
- date: str = ""
- tags: List[str] = field(default_factory=list)
- draft: bool = False
- template: str = "default"
-
-def parse_frontmatter(content: str) -> Tuple[Frontmatter, str]:
- """Parse YAML frontmatter from content."""
- lines = content.split('\n')
- if not lines or lines[0].strip() != '---':
- return Frontmatter(), content
-
- fm = Frontmatter()
- body_start = 1
- for i, line in enumerate(lines[1:], 1):
- if line.strip() == '---':
- body_start = i + 1
- break
- if ':' in line:
- key, value = line.split(':', 1)
- key, value = key.strip(), value.strip()
- if key == 'title':
- fm.title = value
- elif key == 'date':
- fm.date = value
- elif key == 'draft':
- fm.draft = value.lower() in ('true', 'yes')
- elif key == 'tags':
- if value.startswith('['):
- fm.tags = [t.strip().strip('"\'') for t in value[1:-1].split(',')]
- else:
- fm.tags = [t.strip() for t in value.split(',')]
-
- return fm, '\n'.join(lines[body_start:])
-
-def escape_html(s: str) -> str:
- return s.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
-
-def parse_markdown(content: str) -> str:
- """Simple markdown to HTML conversion."""
- html = []
- in_code = False
- in_para = False
- in_list = False
-
- for line in content.split('\n'):
- stripped = line.strip()
-
- # Code blocks
- if stripped.startswith('```'):
- if in_code:
- html.append('')
- in_code = False
- else:
- if in_para:
- html.append('
')
- in_para = False
- if in_list:
- html.append('')
- in_list = False
- html.append('')
- in_code = True
- continue
-
- if in_code:
- html.append(escape_html(line))
- continue
-
- # Empty line
- if not stripped:
- if in_para:
- html.append('')
- in_para = False
- if in_list:
- html.append('')
- in_list = False
- continue
-
- # Headers
- for i in range(6, 0, -1):
- prefix = '#' * i + ' '
- if stripped.startswith(prefix):
- if in_para:
- html.append('')
- in_para = False
- content_text = process_inline(stripped[i+1:].strip())
- html.append(f'{content_text}')
- break
- else:
- # List items
- if stripped.startswith('- ') or stripped.startswith('* '):
- if in_para:
- html.append('')
- in_para = False
- if not in_list:
- html.append('')
- in_list = True
- item = process_inline(stripped[2:].strip())
- html.append(f'- {item}
')
- else:
- # Paragraph
- if not in_para:
- html.append('')
- in_para = True
- else:
- html.append(' ')
- html.append(process_inline(stripped))
-
- if in_para:
- html.append('
')
- if in_list:
- html.append('
')
- if in_code:
- html.append('
')
-
- return '\n'.join(html)
-
-def process_inline(text: str) -> str:
- """Process inline markdown formatting."""
- # Bold
- text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
- # Italic
- text = re.sub(r'\*(.+?)\*', r'\1', text)
- # Code
- text = re.sub(r'`(.+?)`', r'\1', text)
- return text
-
-# ============================================================================
-# Template Engine
-# ============================================================================
-
-DEFAULT_TEMPLATE = '''
-
-
-
-
-{{title}}
-
-
-
-
-{{cow_greeting}}
-{{title}}
-
-{{content}}
-
-
-
-'''
-
-def apply_template(fm: Frontmatter, html: str) -> str:
- """Apply template with COW-generated greeting."""
- # Generate greeting using COW!
- program = parse_cow(COW_HELLO)
- cow_greeting = run_cow(program)
-
- result = DEFAULT_TEMPLATE
- result = result.replace('{{title}}', escape_html(fm.title))
- result = result.replace('{{date}}', escape_html(fm.date))
- result = result.replace('{{content}}', html)
- result = result.replace('{{cow_greeting}}', escape_html(cow_greeting))
- return result
-
-# ============================================================================
-# Tests
-# ============================================================================
-
-def test_cow():
- """Test COW interpreter."""
- print("=== Test: COW Interpreter ===")
- program = parse_cow(COW_HELLO)
- result = run_cow(program)
- print(f"COW says: {result}")
- assert "Hello" in result or len(result) > 0, "COW should produce output"
- print("PASS: COW interpreter works")
-
-def test_markdown():
- """Test markdown parser."""
- print("\n=== Test: Markdown ===")
- md = """# Hello World
-
-This is a **bold** test with *italic* text.
-
-- Item 1
-- Item 2
-
-```
-code block
-```
-"""
- html = parse_markdown(md)
- print(html)
- assert '' in html and '' in html
- print("PASS: Markdown works")
-
-def test_frontmatter():
- """Test frontmatter parser."""
- print("\n=== Test: Frontmatter ===")
- content = """---
-title: My Post
-date: 2024-01-15
-tags: [cow, moo]
-draft: false
----
-
-Content here"""
- fm, body = parse_frontmatter(content)
- print(f"Title: {fm.title}")
- print(f"Date: {fm.date}")
- print(f"Tags: {fm.tags}")
- print(f"Draft: {fm.draft}")
- print(f"Body: {body.strip()}")
- assert fm.title == "My Post"
- print("PASS: Frontmatter works")
-
-def test_full():
- """Test full pipeline."""
- print("\n=== Test: Full Pipeline ===")
- content = """---
-title: Welcome to the Pasture
-date: 2024-01-15
----
-
-# Welcome
-
-This is **milk-ssg**, a COW-powered static site generator.
-
-- Esoteric
-- Moo-licious
-- Udderly ridiculous
-"""
- fm, body = parse_frontmatter(content)
- html = parse_markdown(body)
- output = apply_template(fm, html)
- print(output)
- assert 'Welcome to the Pasture' in output
- print("PASS: Full pipeline works")
-
-# ============================================================================
-# Main
-# ============================================================================
-
-def main():
- args = sys.argv[1:]
-
- if not args:
- print("milk-ssg - COW esoteric language SSG")
- print("Commands: test-cow test-markdown test-frontmatter test-full")
- return
-
- cmd = args[0]
- if cmd == 'test-cow':
- test_cow()
- elif cmd == 'test-markdown':
- test_markdown()
- elif cmd == 'test-frontmatter':
- test_frontmatter()
- elif cmd == 'test-full':
- test_full()
- elif cmd == 'moo':
- # Easter egg: run COW code from stdin
- code = sys.stdin.read()
- program = parse_cow(code)
- print(run_cow(program))
- else:
- print(f"Unknown command: {cmd}")
- sys.exit(1)
-
-if __name__ == '__main__':
- main()
diff --git a/engines/terrapin-ssg/.github/workflows/ci.yml b/engines/terrapin-ssg/.github/workflows/ci.yml
index a3c77ad..3fe7d24 100644
--- a/engines/terrapin-ssg/.github/workflows/ci.yml
+++ b/engines/terrapin-ssg/.github/workflows/ci.yml
@@ -1,3 +1,8 @@
+# SPDX-License-Identifier: MPL-2.0-or-later
+# terrapin-ssg is the Logo engine at satellites/terrapin-ssg/src/terrapin-ssg.logo.
+# The former Python interpreter (engines/terrapin-ssg/terrapin-ssg.py) was
+# retired on the owner's ruling of 2026-11-26. This check validates the Logo
+# source only.
name: Terrapin CI
on:
@@ -6,61 +11,30 @@ on:
pull_request:
branches: [main, master]
-jobs:
- test:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
-
- - name: Set up Python
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
- with:
- python-version: '3.11'
-
- - name: Test Logo Interpreter
- run: python3 terrapin-ssg.py test-logo
-
- - name: Test Markdown
- run: python3 terrapin-ssg.py test-markdown
-
- - name: Test Frontmatter
- run: python3 terrapin-ssg.py test-frontmatter
+permissions:
+ contents: read
- - name: Test Full Pipeline
- run: python3 terrapin-ssg.py test-full
-
- build:
+jobs:
+ validate:
runs-on: ubuntu-latest
- needs: test
steps:
- - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
-
- - name: Set up Python
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- python-version: '3.11'
+ persist-credentials: false
- - name: Build sample site
+ - name: No Python in the engine directory
run: |
- mkdir -p _site
- python3 terrapin-ssg.py build || echo "Build completed"
-
- - name: Upload artifact
- uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3
- with:
- path: _site
+ if find engines/terrapin-ssg -type f -name '*.py' | grep -q .; then
+ echo 'Python found in engines/terrapin-ssg; the engine is Logo only' >&2
+ exit 1
+ fi
- deploy:
- if: github.ref == 'refs/heads/main'
- needs: build
- runs-on: ubuntu-latest
- permissions:
- pages: write
- id-token: write
- environment:
- name: github-pages
- url: ${{ steps.deployment.outputs.page_url }}
- steps:
- - name: Deploy to GitHub Pages
- id: deployment
- uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4
+ - name: Logo engine source is present and defines procedures
+ run: |
+ src=satellites/terrapin-ssg/src/terrapin-ssg.logo
+ test -f "$src"
+ to_count=$(grep -ci '^to ' "$src" || true)
+ end_count=$(grep -ci '^end$' "$src" || true)
+ echo "TO: $to_count END: $end_count"
+ test "$to_count" -gt 0
+ test "$to_count" -eq "$end_count"
diff --git a/engines/terrapin-ssg/terrapin-ssg.py b/engines/terrapin-ssg/terrapin-ssg.py
deleted file mode 100755
index b6ee989..0000000
--- a/engines/terrapin-ssg/terrapin-ssg.py
+++ /dev/null
@@ -1,512 +0,0 @@
-#!/usr/bin/env python3
-"""
-terrapin-ssg - Logo-powered static site generator for kids
-
-A friendly SSG that turns turtle graphics into web pages!
-Kids can write Logo programs that become SVG images in their posts.
-
-Supports basic Logo commands:
- FORWARD n (FD) - Move forward n steps
- BACK n (BK) - Move backward n steps
- RIGHT n (RT) - Turn right n degrees
- LEFT n (LT) - Turn left n degrees
- PENUP (PU) - Stop drawing
- PENDOWN (PD) - Start drawing
- HOME - Return to center
- REPEAT n [...] - Repeat commands n times
- SETCOLOR c - Set pen color
-"""
-
-import sys
-import os
-import re
-import math
-from typing import List, Tuple, Dict, Optional
-from dataclasses import dataclass, field
-
-# ============================================================================
-# Logo (Turtle Graphics) Interpreter
-# ============================================================================
-
-@dataclass
-class Turtle:
- x: float = 250.0 # Start in center of 500x500 canvas
- y: float = 250.0
- angle: float = -90.0 # Facing up (north)
- pen_down: bool = True
- color: str = "#228B22" # Forest green
- paths: List[str] = field(default_factory=list)
- current_path: List[Tuple[float, float]] = field(default_factory=list)
-
- def start_path(self):
- if self.pen_down and not self.current_path:
- self.current_path = [(self.x, self.y)]
-
- def end_path(self):
- if len(self.current_path) > 1:
- d = "M " + " L ".join(f"{p[0]:.1f},{p[1]:.1f}" for p in self.current_path)
- self.paths.append(f'')
- self.current_path = []
-
- def forward(self, distance: float):
- rad = math.radians(self.angle)
- new_x = self.x + distance * math.cos(rad)
- new_y = self.y + distance * math.sin(rad)
- if self.pen_down:
- self.start_path()
- self.current_path.append((new_x, new_y))
- self.x, self.y = new_x, new_y
-
- def back(self, distance: float):
- self.forward(-distance)
-
- def right(self, angle: float):
- self.angle = (self.angle + angle) % 360
-
- def left(self, angle: float):
- self.angle = (self.angle - angle) % 360
-
- def penup(self):
- self.end_path()
- self.pen_down = False
-
- def pendown(self):
- self.pen_down = True
- self.start_path()
-
- def home(self):
- self.end_path()
- self.x, self.y = 250.0, 250.0
- self.angle = -90.0
- self.start_path()
-
- def setcolor(self, color: str):
- self.end_path()
- colors = {
- 'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF',
- 'yellow': '#FFFF00', 'orange': '#FFA500', 'purple': '#800080',
- 'black': '#000000', 'white': '#FFFFFF', 'pink': '#FFC0CB',
- 'brown': '#8B4513', 'cyan': '#00FFFF', 'magenta': '#FF00FF',
- }
- self.color = colors.get(color.lower(), color)
- self.start_path()
-
- def to_svg(self) -> str:
- self.end_path()
- paths = '\n '.join(self.paths)
- return f''''''
-
-def tokenize_logo(code: str) -> List[str]:
- """Tokenize Logo code."""
- code = code.upper()
- # Handle brackets for REPEAT
- code = code.replace('[', ' [ ').replace(']', ' ] ')
- return code.split()
-
-def parse_logo(tokens: List[str], turtle: Turtle):
- """Parse and execute Logo tokens."""
- i = 0
- while i < len(tokens):
- cmd = tokens[i]
-
- if cmd in ('FD', 'FORWARD'):
- if i + 1 < len(tokens):
- turtle.forward(float(tokens[i + 1]))
- i += 2
- else:
- i += 1
- elif cmd in ('BK', 'BACK'):
- if i + 1 < len(tokens):
- turtle.back(float(tokens[i + 1]))
- i += 2
- else:
- i += 1
- elif cmd in ('RT', 'RIGHT'):
- if i + 1 < len(tokens):
- turtle.right(float(tokens[i + 1]))
- i += 2
- else:
- i += 1
- elif cmd in ('LT', 'LEFT'):
- if i + 1 < len(tokens):
- turtle.left(float(tokens[i + 1]))
- i += 2
- else:
- i += 1
- elif cmd in ('PU', 'PENUP'):
- turtle.penup()
- i += 1
- elif cmd in ('PD', 'PENDOWN'):
- turtle.pendown()
- i += 1
- elif cmd == 'HOME':
- turtle.home()
- i += 1
- elif cmd == 'SETCOLOR':
- if i + 1 < len(tokens):
- turtle.setcolor(tokens[i + 1])
- i += 2
- else:
- i += 1
- elif cmd == 'REPEAT':
- if i + 2 < len(tokens):
- count = int(tokens[i + 1])
- # Find matching brackets
- if tokens[i + 2] == '[':
- depth = 1
- start = i + 3
- end = start
- while end < len(tokens) and depth > 0:
- if tokens[end] == '[':
- depth += 1
- elif tokens[end] == ']':
- depth -= 1
- if depth > 0:
- end += 1
- # Execute repeat body
- body = tokens[start:end]
- for _ in range(count):
- parse_logo(body, turtle)
- i = end + 1
- else:
- i += 2
- else:
- i += 1
- else:
- i += 1
-
-def run_logo(code: str) -> str:
- """Execute Logo code and return SVG."""
- turtle = Turtle()
- tokens = tokenize_logo(code)
- parse_logo(tokens, turtle)
- return turtle.to_svg()
-
-# ============================================================================
-# Sample Logo Programs
-# ============================================================================
-
-LOGO_SQUARE = "REPEAT 4 [ FD 80 RT 90 ]"
-LOGO_STAR = "REPEAT 5 [ FD 100 RT 144 ]"
-LOGO_SPIRAL = "REPEAT 36 [ FD 50 RT 170 ]"
-LOGO_FLOWER = """
-REPEAT 6 [
- SETCOLOR RED
- REPEAT 4 [ FD 50 RT 90 ]
- RT 60
-]
-"""
-
-# ============================================================================
-# Frontmatter & Markdown Parser
-# ============================================================================
-
-@dataclass
-class Frontmatter:
- title: str = ""
- date: str = ""
- tags: List[str] = field(default_factory=list)
- draft: bool = False
- template: str = "default"
-
-def parse_frontmatter(content: str) -> Tuple[Frontmatter, str]:
- """Parse YAML frontmatter."""
- lines = content.split('\n')
- if not lines or lines[0].strip() != '---':
- return Frontmatter(), content
-
- fm = Frontmatter()
- body_start = 1
- for i, line in enumerate(lines[1:], 1):
- if line.strip() == '---':
- body_start = i + 1
- break
- if ':' in line:
- key, value = line.split(':', 1)
- key, value = key.strip(), value.strip()
- if key == 'title':
- fm.title = value
- elif key == 'date':
- fm.date = value
- elif key == 'draft':
- fm.draft = value.lower() in ('true', 'yes')
- elif key == 'tags':
- if value.startswith('['):
- fm.tags = [t.strip().strip('"\'') for t in value[1:-1].split(',')]
- else:
- fm.tags = [t.strip() for t in value.split(',')]
-
- return fm, '\n'.join(lines[body_start:])
-
-def escape_html(s: str) -> str:
- return s.replace('&', '&').replace('<', '<').replace('>', '>')
-
-def parse_markdown(content: str) -> str:
- """Parse markdown with Logo code blocks."""
- html = []
- in_code = False
- in_logo = False
- in_para = False
- in_list = False
- code_buffer = []
-
- for line in content.split('\n'):
- stripped = line.strip()
-
- # Logo code blocks (```logo)
- if stripped.startswith('```logo'):
- if in_para:
- html.append('')
- in_para = False
- in_logo = True
- code_buffer = []
- continue
- elif stripped == '```' and in_logo:
- # Execute Logo and insert SVG
- logo_code = '\n'.join(code_buffer)
- svg = run_logo(logo_code)
- html.append(f'{svg}
')
- in_logo = False
- code_buffer = []
- continue
- elif in_logo:
- code_buffer.append(line)
- continue
-
- # Regular code blocks
- if stripped.startswith('```'):
- if in_code:
- html.append('')
- in_code = False
- else:
- if in_para:
- html.append('')
- in_para = False
- html.append('')
- in_code = True
- continue
-
- if in_code:
- html.append(escape_html(line))
- continue
-
- # Empty line
- if not stripped:
- if in_para:
- html.append('')
- in_para = False
- if in_list:
- html.append('')
- in_list = False
- continue
-
- # Headers
- for i in range(6, 0, -1):
- prefix = '#' * i + ' '
- if stripped.startswith(prefix):
- if in_para:
- html.append('')
- in_para = False
- content_text = process_inline(stripped[i+1:].strip())
- html.append(f'{content_text}')
- break
- else:
- # List items
- if stripped.startswith('- ') or stripped.startswith('* '):
- if in_para:
- html.append('')
- in_para = False
- if not in_list:
- html.append('')
- in_list = True
- item = process_inline(stripped[2:].strip())
- html.append(f'- {item}
')
- else:
- # Paragraph
- if not in_para:
- html.append('')
- in_para = True
- else:
- html.append(' ')
- html.append(process_inline(stripped))
-
- if in_para:
- html.append('
')
- if in_list:
- html.append('
')
- if in_code:
- html.append('
')
-
- return '\n'.join(html)
-
-def process_inline(text: str) -> str:
- """Process inline formatting."""
- text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
- text = re.sub(r'\*(.+?)\*', r'\1', text)
- text = re.sub(r'`(.+?)`', r'\1', text)
- return text
-
-# ============================================================================
-# Template Engine
-# ============================================================================
-
-DEFAULT_TEMPLATE = '''
-
-
-
-
-{{title}} - Turtle Pages
-
-
-
-
-{{title}}
-
-{{content}}
-
-
-
-'''
-
-def apply_template(fm: Frontmatter, html: str) -> str:
- """Apply template."""
- result = DEFAULT_TEMPLATE
- result = result.replace('{{title}}', escape_html(fm.title))
- result = result.replace('{{date}}', escape_html(fm.date))
- result = result.replace('{{content}}', html)
- return result
-
-# ============================================================================
-# Tests
-# ============================================================================
-
-def test_logo():
- """Test Logo interpreter."""
- print("=== Test: Logo Interpreter ===")
- svg = run_logo(LOGO_SQUARE)
- print(svg[:200] + "...")
- assert 'svg' in svg and 'path' in svg
- print("PASS: Logo interpreter works")
-
-def test_markdown():
- """Test markdown with Logo."""
- print("\n=== Test: Markdown ===")
- md = """# My Drawing
-
-Check out my turtle art:
-
-```logo
-REPEAT 4 [ FD 80 RT 90 ]
-```
-
-Cool right?
-"""
- html = parse_markdown(md)
- print(html[:300] + "...")
- assert '