Initial commit: CodeMap v0.1.0 - CLI tool for code analysis and diagram generation
This commit is contained in:
55
codemap/parsers/python_parser.py
Normal file
55
codemap/parsers/python_parser.py
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import ast
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Set
|
||||||
|
from codemap.parsers.base import BaseParser, Dependency, ParsedFile
|
||||||
|
|
||||||
|
|
||||||
|
class PythonParser(BaseParser):
|
||||||
|
supported_extensions = [".py", ".pyi"]
|
||||||
|
|
||||||
|
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()
|
||||||
|
tree = ast.parse(content, filename=str(file_path))
|
||||||
|
except (SyntaxError, UnicodeDecodeError) as e:
|
||||||
|
return ParsedFile(
|
||||||
|
file_path=file_path,
|
||||||
|
module_name=module_name,
|
||||||
|
dependencies=[],
|
||||||
|
file_type="python"
|
||||||
|
)
|
||||||
|
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if isinstance(node, ast.Import):
|
||||||
|
for alias in node.names:
|
||||||
|
dep = Dependency(
|
||||||
|
module_name=alias.name,
|
||||||
|
file_path=file_path,
|
||||||
|
line_number=node.lineno,
|
||||||
|
alias=alias.asname
|
||||||
|
)
|
||||||
|
dependencies.append(dep)
|
||||||
|
elif isinstance(node, ast.ImportFrom):
|
||||||
|
if node.module:
|
||||||
|
for alias in node.names:
|
||||||
|
dep = Dependency(
|
||||||
|
module_name=node.module,
|
||||||
|
file_path=file_path,
|
||||||
|
line_number=node.lineno,
|
||||||
|
alias=alias.asname
|
||||||
|
)
|
||||||
|
dependencies.append(dep)
|
||||||
|
|
||||||
|
return ParsedFile(
|
||||||
|
file_path=file_path,
|
||||||
|
module_name=module_name,
|
||||||
|
dependencies=dependencies,
|
||||||
|
file_type="python"
|
||||||
|
)
|
||||||
|
|
||||||
|
def extract_module_name(self, file_path: Path) -> str:
|
||||||
|
return file_path.stem
|
||||||
Reference in New Issue
Block a user