"""Base generator with shared logic for all documentation generators."""
from pathlib import Path
from typing import Optional
class BaseGenerator:
"""Base class providing common functionality for documentation generators."""
def __init__(self, templates_dir: Path):
"""
Initialize base generator.
Args:
templates_dir: Path to templates directory
"""
self.templates_dir = templates_dir
def read_template(self, template_name: str) -> str:
"""
Read a template file from templates/power/ directory.
Args:
template_name: Name of template (e.g., 'readme', 'architecture')
Returns:
Template content as string
Raises:
FileNotFoundError: If template file doesn't exist
IOError: If template file cannot be read
"""
template_file = self.templates_dir / f"{template_name}.txt"
if not template_file.exists():
raise FileNotFoundError(
f"Template '{template_name}' not found at {template_file}"
)
try:
with open(template_file, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
raise IOError(f"Error reading template '{template_name}': {str(e)}")
def validate_project_path(self, project_path: str) -> Path:
"""
Validate that project path exists and is a directory.
Args:
project_path: Path to project directory
Returns:
Validated Path object
Raises:
ValueError: If path doesn't exist or isn't a directory
"""
path = Path(project_path)
if not path.exists():
raise ValueError(f"Project path does not exist: {project_path}")
if not path.is_dir():
raise ValueError(f"Project path is not a directory: {project_path}")
return path
def create_output_directory(self, project_path: Path, subdir: str = "coderef/foundation-docs") -> Path:
"""
Create output directory for generated documentation.
Args:
project_path: Project root directory
subdir: Subdirectory name for docs (default: "coderef/foundation-docs")
Returns:
Path to created/existing output directory
"""
output_dir = project_path / subdir
output_dir.mkdir(parents=True, exist_ok=True)
return output_dir
def get_template_info(self, template_name: str) -> dict:
"""
Parse template to extract metadata.
Args:
template_name: Name of template
Returns:
Dictionary with template metadata (framework, purpose, save_as, etc.)
"""
content = self.read_template(template_name)
metadata = {}
for line in content.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip()
if key in ['framework', 'purpose', 'save_as', 'store_as']:
metadata[key] = value
return metadata
def save_document(self, content: str, output_dir: Path, filename: str) -> str:
"""
Save generated document to output directory.
Args:
content: Document content to save
output_dir: Directory to save document in
filename: Name of file to save
Returns:
Absolute path to saved file as string
Raises:
IOError: If file cannot be written
"""
file_path = output_dir / filename
try:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
return str(file_path)
except Exception as e:
raise IOError(f"Error saving document to {file_path}: {str(e)}")