Initial commit: CodeMap v0.1.0 - CLI tool for code analysis and diagram generation
This commit is contained in:
62
codemap/parsers/javascript_parser.py
Normal file
62
codemap/parsers/javascript_parser.py
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List
|
||||||
|
from codemap.parsers.base import BaseParser, Dependency, ParsedFile
|
||||||
|
|
||||||
|
|
||||||
|
class JavaScriptParser(BaseParser):
|
||||||
|
supported_extensions = [".js", ".jsx", ".ts", ".tsx", ".mjs"]
|
||||||
|
|
||||||
|
IMPORT_PATTERNS = [
|
||||||
|
re.compile(r'^import\s+(?:\{[^}]*\}|\* as \w+|\w+)\s+from\s+["\']([^"\']+)["\']'),
|
||||||
|
re.compile(r'^import\s+["\']([^"\'])["\']'),
|
||||||
|
re.compile(r'require\s*\(\s*["\']([^"\']+)["\']\s*\)'),
|
||||||
|
re.compile(r'import\s*\(\s*["\']([^"\']+)["\']\s*\)'),
|
||||||
|
]
|
||||||
|
|
||||||
|
ES6_FROM_PATTERN = re.compile(r'from\s+["\']([^"\'])["\']')
|
||||||
|
REQUIRE_PATTERN = re.compile(r'require\s*\(\s*["\']([^"\']+)["\']\s*\)')
|
||||||
|
|
||||||
|
def parse(self, file_path: Path) -> ParsedFile:
|
||||||
|
module_name = self.extract_module_name(file_path)
|
||||||
|
dependencies: List[Dependency] = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(file_path, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
except (UnicodeDecodeError, OSError) as e:
|
||||||
|
return ParsedFile(
|
||||||
|
file_path=file_path,
|
||||||
|
module_name=module_name,
|
||||||
|
dependencies=[],
|
||||||
|
file_type="javascript"
|
||||||
|
)
|
||||||
|
|
||||||
|
lines = content.split('\n')
|
||||||
|
for line_num, line in enumerate(lines, 1):
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith('//'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
for pattern in self.IMPORT_PATTERNS:
|
||||||
|
match = pattern.match(line)
|
||||||
|
if match:
|
||||||
|
import_path = match.group(1)
|
||||||
|
if not import_path.startswith('.') and not import_path.startswith('/'):
|
||||||
|
dep = Dependency(
|
||||||
|
module_name=import_path,
|
||||||
|
file_path=file_path,
|
||||||
|
line_number=line_num
|
||||||
|
)
|
||||||
|
dependencies.append(dep)
|
||||||
|
break
|
||||||
|
|
||||||
|
return ParsedFile(
|
||||||
|
file_path=file_path,
|
||||||
|
module_name=module_name,
|
||||||
|
dependencies=dependencies,
|
||||||
|
file_type="javascript"
|
||||||
|
)
|
||||||
|
|
||||||
|
def extract_module_name(self, file_path: Path) -> str:
|
||||||
|
return file_path.stem
|
||||||
Reference in New Issue
Block a user