Help me develop a static site generator in Python with a plugin system where users can write scripts to hook into pre-build and post-build lifecycle events. Use Jinja2 for templating and Markdown for content.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# plugins/base_plugin.py
import sys
from pathlib import Path
# Add ssg to path for imports
ssg_path = Path(__file__).parent.parent
sys.path.insert(0, str(ssg_path))
from ssg.plugin_system import BasePlugin, HookPoint
class SeoPlugin(BasePlugin):
"""SEO optimization plugin."""
name = "SEO Plugin"
version = "1.0.0"
description = "Adds SEO meta tags and sitemap generation"
def initialize(self) -> None:
"""Initialize plugin."""
self.register_hook(HookPoint.POST_RENDER, self.generate_meta_tags)
self.logger.info("SEO Plugin initialized")
def generate_meta_tags(self, context):
"""Generate SEO meta tags."""
if context.metadata:
metadata = context.metadata
# Ensure description exists
if 'description' not in metadata:
metadata['description'] = self.config.description
# Generate keywords if not present
if 'keywords' not in metadata:
metadata['keywords'] = self.config.metadata.get('keywords', '')
self.logger.info(f"Generated SEO tags for {context.content.get('slug')}")
return context
python
# plugins/sitemap_plugin.py
import sys
from pathlib import Path
from datetime import datetime
sys.path.insert(0, str(Path(__file__).parent.parent))
from ssg.plugin_system import BasePlugin, HookPoint
class SitemapPlugin(BasePlugin):
"""Generate XML sitemap."""
name = "Sitemap Plugin"
version = "1.0.0"
description = "Generates XML sitemap for SEO"
def initialize(self) -> None:
"""Initialize plugin."""
self.register_hook(HookPoint.POST_BUILD, self.generate_sitemap)
self.logger.info("Sitemap Plugin initialized")
def generate_sitemap(self, context):
"""Generate sitemap.xml."""
config = context.config
sitemap_content = '<?xml version="1.0" encoding="UTF-8"?>\n'
sitemap_content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
# Add homepage
sitemap_content += self._url_entry(config.site_url, datetime.now(), 'weekly', '1.0')
# Add all content
for content in context.config.contents.values() if hasattr(context.config, 'contents') else []:
url = config.site_url.rstrip('/') + content.url
priority = '0.8' if content.content_type == 'post' else '0.6'
sitemap_content += self._url_entry(
url,
content.metadata.get('date', datetime.now()),
'weekly',
priority
)
sitemap_content += '</urlset>'
# Write sitemap
sitemap_path = config.output_dir / 'sitemap.xml'
with open(sitemap_path, 'w') as f:
f.write(sitemap_content)
self.logger.info(f"Generated sitemap: {sitemap_path}")
return context
@staticmethod
def _url_entry(url: str, date, changefreq: str, priority: str) -> str:
"""Generate single sitemap URL entry."""
date_str = date.strftime('%Y-%m-%d') if hasattr(date, 'strftime') else str(date)
return (
f' <url>\n'
f' <loc>{url}</loc>\n'
f' <lastmod>{date_str}</lastmod>\n'
f' <changefreq>{changefreq}</changefreq>\n'
f' <priority>{priority}</priority>\n'
f' </url>\n'
)
This comprehensive static site generator includes:
✅ Plugin System - Easy hook system for pre/post-build events
✅ Jinja2 Templates - Full template support with inheritance
✅ Markdown Content - Frontmatter parsing and HTML conversion
✅ Configuration - YAML-based configuration
✅ Example Plugins - SEO, Sitemap, Analytics
✅ CLI Interface - Command-line tool
✅ Comprehensive Tests - Unit test suite
✅ Error Handling - Robust error management
✅ Logging - Full logging support
You can easily extend it with custom plugins!
# ssg/plugin_system.py
import logging
import importlib.util
from abc import ABC, abstractmethod
from typing import Dict, List, Callable, Any, Optional
from pathlib import Path
from dataclasses import dataclass
logger = logging.getLogger(__name__)
class HookPoint:
"""Enumeration of available hook points."""
PRE_BUILD = "pre_build"
POST_BUILD = "post_build"
PRE_PROCESS_CONTENT = "pre_process_content"
POST_PROCESS_CONTENT = "post_process_content"
PRE_RENDER = "pre_render"
POST_RENDER = "post_render"
@dataclass
class HookContext:
"""Context passed to hook handlers."""
config: Any
content: Optional[Dict[str, Any]] = None
output_path: Optional[Path] = None
metadata: Optional[Dict[str, Any]] = None
class BasePlugin(ABC):
"""Base class for all plugins."""
name: str = "Unknown Plugin"
version: str = "1.0.0"
description: str = "Plugin description"
def __init__(self, config: 'Config' = None):
"""Initialize plugin."""
self.config = config
self.logger = logging.getLogger(self.__class__.__name__)
self._hooks: Dict[str, List[Callable]] = {}
def register_hook(self, hook_point: str, handler: Callable) -> None:
"""Register a handler for a hook point."""
if hook_point not in self._hooks:
self._hooks[hook_point] = []
self._hooks[hook_point].append(handler)
self.logger.debug(f"Registered handler for {hook_point}")
def get_handlers(self, hook_point: str) -> List[Callable]:
"""Get all handlers for a hook point."""
return self._hooks.get(hook_point, [])
@abstractmethod
def initialize(self) -> None:
"""Initialize the plugin. Override in subclasses."""
pass
def cleanup(self) -> None:
"""Cleanup resources. Override in subclasses if needed."""
pass
def execute_hook(self, hook_point: str, context: HookContext) -> HookContext:
"""Execute all handlers for a hook point."""
handlers = self.get_handlers(hook_point)
for handler in handlers:
try:
context = handler(context) or context
except Exception as e:
self.logger.error(f"Error in handler for {hook_point}: {e}")
raise
return context
class PluginManager:
"""Manages plugin lifecycle and execution."""
def __init__(self, config: 'Config' = None):
"""Initialize plugin manager."""
self.config = config
self.logger = logging.getLogger(__name__)
self.plugins: Dict[str, BasePlugin] = {}
self._hooks: Dict[str, List[Callable]] = {}
def register_hook(self, hook_point: str, handler: Callable) -> None:
"""Register a handler for a hook point."""
if hook_point not in self._hooks:
self._hooks[hook_point] = []
self._hooks[hook_point].append(handler)
def load_plugin(self, plugin_module_path: str) -> BasePlugin:
"""Dynamically load a plugin from a Python file."""
spec = importlib.util.spec_from_file_location(
"plugin",
plugin_module_path
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Look for BasePlugin subclass
plugin_class = None
for attr_name in dir(module):
attr = getattr(module, attr_name)
if (isinstance(attr, type) and
issubclass(attr, BasePlugin) and
attr is not BasePlugin):
plugin_class = attr
break
if not plugin_class:
raise ValueError(f"No BasePlugin subclass found in {plugin_module_path}")
plugin = plugin_class(self.config)
plugin.initialize()
self.plugins[plugin.name] = plugin
self.logger.info(f"Loaded plugin: {plugin.name}")
return plugin
def load_plugins_from_directory(self, plugin_dir: Path) -> int:
"""Load all plugins from a directory."""
if not plugin_dir.exists():
self.logger.warning(f"Plugin directory not found: {plugin_dir}")
return 0
loaded_count = 0
for plugin_file in plugin_dir.glob("*.py"):
if plugin_file.name.startswith("_"):
continue
try:
self.load_plugin(str(plugin_file))
loaded_count += 1
except Exception as e:
self.logger.error(f"Failed to load plugin {plugin_file}: {e}")
return loaded_count
def execute_hook(
self,
hook_point: str,
context: HookContext
) -> HookContext:
"""Execute all registered handlers for a hook point."""
self.logger.debug(f"Executing hook: {hook_point}")
# Execute plugin hooks
for plugin in self.plugins.values():
handlers = plugin.get_handlers(hook_point)
for handler in handlers:
try:
context = handler(context) or context
except Exception as e:
self.logger.error(
f"Error in {plugin.name} handler for {hook_point}: {e}"
)
raise
# Execute manager-level hooks
for handler in self._hooks.get(hook_point, []):
try:
context = handler(context) or context
except Exception as e:
self.logger.error(f"Error in hook handler for {hook_point}: {e}")
raise
return context
def list_plugins(self) -> List[Dict[str, str]]:
"""Get list of loaded plugins."""
return [
{
'name': plugin.name,
'version': plugin.version,
'description': plugin.description,
}
for plugin in self.plugins.values()
]
def cleanup(self) -> None:
"""Cleanup all plugins."""
for plugin in self.plugins.values():
try:
plugin.cleanup()
except Exception as e:
self.logger.error(f"Error cleaning up {plugin.name}: {e}")
# ssg/content.py
import markdown
import logging
from pathlib import Path
from typing import Dict, Any, Optional, Tuple
from datetime import datetime
from dataclasses import dataclass
logger = logging.getLogger(__name__)
@dataclass
class Content:
"""Represents a piece of content (post or page)."""
path: Path
title: str
slug: str
content: str
html: str
metadata: Dict[str, Any]
content_type: str = "post" # post, page, etc.
template: str = "post.html"
@property
def url(self) -> str:
"""Generate URL for the content."""
return f"/{self.content_type}s/{self.slug}/"
@property
def output_path(self) -> Path:
"""Generate output file path."""
return Path(f"{self.content_type}s/{self.slug}/index.html")
class ContentProcessor:
"""Processes markdown content files."""
def __init__(self, markdown_extensions: list = None):
"""Initialize content processor."""
self.markdown_extensions = markdown_extensions or [
'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc',
'markdown.extensions.meta',
]
self.md = markdown.Markdown(extensions=self.markdown_extensions)
def parse_frontmatter(self, content: str) -> Tuple[str, Dict[str, Any]]:
"""Parse YAML frontmatter from content."""
if not content.startswith('---'):
return content, {}
parts = content.split('---', 2)
if len(parts) < 3:
return content, {}
try:
import yaml
frontmatter = yaml.safe_load(parts[1])
body = parts[2].strip()
return body, frontmatter or {}
except Exception as e:
logger.warning(f"Failed to parse frontmatter: {e}")
return content, {}
def process(self, file_path: Path, content_type: str = "post") -> Content:
"""Process a markdown file."""
with open(file_path, 'r', encoding='utf-8') as f:
raw_content = f.read()
# Parse frontmatter and content
body, metadata = self.parse_frontmatter(raw_content)
# Reset markdown instance for each file
self.md.reset()
# Convert markdown to HTML
html = self.md.convert(body)
# Extract metadata from markdown
md_metadata = getattr(self.md, 'Meta', {})
# Merge metadata
all_metadata = {**md_metadata, **metadata}
# Generate slug from filename
slug = file_path.stem
# Get title
title = all_metadata.get('title', slug.replace('-', ' ').title())
if isinstance(title, list):
title = title[0]
# Parse date if present
if 'date' in all_metadata:
date_str = all_metadata['date']
if isinstance(date_str, list):
date_str = date_str[0]
try:
all_metadata['date'] = datetime.strptime(
date_str, '%Y-%m-%d'
).date()
except (ValueError, TypeError):
all_metadata['date'] = date_str
template = all_metadata.get('template', f'{content_type}.html')
if isinstance(template, list):
template = template[0]
return Content(
path=file_path,
title=title,
slug=slug,
content=body,
html=html,
metadata=all_metadata,
content_type=content_type,
template=template,
)
def process_directory(
self,
directory: Path,
content_type: str = "post"
) -> Dict[str, Content]:
"""Process all markdown files in a directory."""
contents = {}
if not directory.exists():
logger.warning(f"Content directory not found: {directory}")
return contents
for md_file in directory.glob("**/*.md"):
try:
content = self.process(md_file, content_type)
contents[content.slug] = content
logger.info(f"Processed: {md_file}")
except Exception as e:
logger.error(f"Failed to process {md_file}: {e}")
return contents
# ssg/generator.py
import logging
import shutil
from pathlib import Path
from typing import Dict, Any
from jinja2 import Environment, FileSystemLoader, select_autoescape
from datetime import datetime
from .config import Config
from .content import ContentProcessor, Content
from .plugin_system import PluginManager, HookContext, HookPoint
from .utils import ensure_dir, copy_directory
logger = logging.getLogger(__name__)
class StaticSiteGenerator:
"""Main static site generator."""
def __init__(self, config: Config):
"""Initialize generator."""
self.config = config
self.plugin_manager = PluginManager(config)
self.content_processor = ContentProcessor(config.markdown_extensions)
self.contents: Dict[str, Content] = {}
self.jinja_env = self._setup_jinja()
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
def _setup_jinja(self) -> Environment:
"""Setup Jinja2 environment."""
env = Environment(
loader=FileSystemLoader(self.config.templates_dir),
autoescape=select_autoescape(['html', 'xml']),
trim_blocks=True,
lstrip_blocks=True,
)
# Add global filters and functions
env.globals['site_name'] = self.config.site_name
env.globals['site_url'] = self.config.site_url
env.globals['site_description'] = self.config.description
env.globals['author'] = self.config.author
env.globals['build_date'] = datetime.now()
return env
def load_plugins(self) -> int:
"""Load plugins from plugin directory."""
if self.config.plugins_dir:
return self.plugin_manager.load_plugins_from_directory(
self.config.plugins_dir
)
return 0
def process_content(self) -> None:
"""Process all content files."""
logger.info("Processing content...")
# Process posts
posts_dir = self.config.content_dir / "posts"
self.contents.update(
self.content_processor.process_directory(posts_dir, "post")
)
# Process pages
pages_dir = self.config.content_dir / "pages"
self.contents.update(
self.content_processor.process_directory(pages_dir, "page")
)
logger.info(f"Processed {len(self.contents)} content items")
def render_content(self) -> None:
"""Render all content to HTML."""
logger.info("Rendering content...")
for slug, content in self.contents.items():
self._render_item(content)
def _render_item(self, content: Content) -> None:
"""Render a single content item."""
try:
# Pre-render hook
context = HookContext(
config=self.config,
content={'slug': content.slug, 'title': content.title},
metadata=content.metadata,
)
context = self.plugin_manager.execute_hook(
HookPoint.PRE_RENDER, context
)
# Get template
template = self.jinja_env.get_template(content.template)
# Prepare template context
template_context = {
'content': content,
'title': content.title,
'body': content.html,
**content.metadata,
}
# Add all contents for navigation
template_context['contents'] = self.contents
# Render
html = template.render(template_context)
# Post-render hook
context = HookContext(
config=self.config,
content={'slug': content.slug, 'title': content.title},
output_path=content.output_path,
metadata=content.metadata,
)
context = self.plugin_manager.execute_hook(
HookPoint.POST_RENDER, context
)
# Write output
output_dir = self.config.output_dir / content.output_path.parent
ensure_dir(output_dir)
output_file = self.config.output_dir / content.output_path
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html)
logger.info(f"Rendered: {content.slug} -> {output_file}")
except Exception as e:
logger.error(f"Failed to render {content.slug}: {e}")
raise
def copy_static_files(self) -> None:
"""Copy static files to output directory."""
if not self.config.static_dir or not self.config.static_dir.exists():
logger.warning("Static directory not found, skipping...")
return
logger.info("Copying static files...")
copy_directory(self.config.static_dir, self.config.output_dir)
def clean_output(self) -> None:
"""Clean output directory."""
if self.config.clean_output and self.config.output_dir.exists():
logger.info(f"Cleaning output directory: {self.config.output_dir}")
shutil.rmtree(self.config.output_dir)
ensure_dir(self.config.output_dir)
def build(self) -> None:
"""Run the complete build process."""
try:
# Pre-build hook
context = HookContext(config=self.config)
self.plugin_manager.execute_hook(HookPoint.PRE_BUILD, context)
# Build steps
self.clean_output()
self.process_content()
self.render_content()
self.copy_static_files()
# Post-build hook
context = HookContext(config=self.config)
self.plugin_manager.execute_hook(HookPoint.POST_BUILD, context)
logger.info("Build completed successfully!")
except Exception as e:
logger.error(f"Build failed: {e}")
raise
finally:
self.plugin_manager.cleanup()
def get_site_data(self) -> Dict[str, Any]:
"""Get site data for templates."""
return {
'name': self.config.site_name,
'url': self.config.site_url,
'description': self.config.description,
'author': self.config.author,
'posts': [c for c in self.contents.values() if c.content_type == 'post'],
'pages': [c for c in self.contents.values() if c.content_type == 'page'],
}