Files
code-doc-cli/.code_doc_cli/parsers/registry.py
7000pctAUTO 3191bd2f9a
Some checks failed
CI / test (push) Has been cancelled
Add generators and parsers modules
2026-01-29 16:51:53 +00:00

76 lines
2.5 KiB
Python

"""Parser registry for language detection and selection."""
from typing import Dict, Type, Optional
from .base import Parser
from .python_parser import PythonParser
from .typescript_parser import TypeScriptParser
from .go_parser import GoParser
class ParserRegistry:
"""Registry for parser instances by language."""
_parsers: Dict[str, Type[Parser]] = {
"python": PythonParser,
"py": PythonParser,
"typescript": TypeScriptParser,
"ts": TypeScriptParser,
"tsx": TypeScriptParser,
"go": GoParser,
}
_extensions: Dict[str, str] = {
".py": "python",
".pyw": "python",
".ts": "typescript",
".tsx": "typescript",
".go": "go",
}
@classmethod
def register(cls, language: str, parser_class: Type[Parser]) -> None:
"""Register a new parser for a language."""
cls._parsers[language] = parser_class
cls._extensions[language] = language
@classmethod
def get_parser_class(cls, language: str) -> Optional[Type[Parser]]:
"""Get parser class by language name."""
return cls._parsers.get(language.lower())
@classmethod
def get_language_from_extension(cls, file_path: str) -> Optional[str]:
"""Detect language from file extension."""
import os
ext = os.path.splitext(file_path)[1].lower()
return cls._extensions.get(ext)
@classmethod
def get_parser(cls, file_path: str, language: Optional[str] = None) -> Parser:
"""Get a parser instance for a file."""
if language:
parser_class = cls.get_parser_class(language)
if not parser_class:
raise ValueError(f"Unsupported language: {language}")
return parser_class(file_path)
detected_lang = cls.get_language_from_extension(file_path)
if not detected_lang:
raise ValueError(f"Cannot detect language for file: {file_path}")
parser_class = cls.get_parser_class(detected_lang)
if not parser_class:
raise ValueError(f"No parser available for language: {detected_lang}")
return parser_class(file_path)
@classmethod
def get_supported_languages(cls) -> list[str]:
"""Get list of supported language names."""
return list(set(cls._parsers.keys()))
@classmethod
def get_supported_extensions(cls) -> list[str]:
"""Get list of supported file extensions."""
return list(cls._extensions.keys())