Navegador

navegador / navegador / ingestion / python.py
Source Blame History 282 lines
5e4b8e4… anonymous 1 """
5e4b8e4… anonymous 2 Python AST parser — extracts classes, functions, imports, calls, and
5e4b8e4… anonymous 3 their relationships from .py files using tree-sitter.
5e4b8e4… anonymous 4 """
5e4b8e4… anonymous 5
5e4b8e4… anonymous 6 import logging
5e4b8e4… anonymous 7 from pathlib import Path
5e4b8e4… anonymous 8
5e4b8e4… anonymous 9 from navegador.graph.schema import EdgeType, NodeLabel
5e4b8e4… anonymous 10 from navegador.graph.store import GraphStore
5e4b8e4… anonymous 11 from navegador.ingestion.parser import LanguageParser
5e4b8e4… anonymous 12
5e4b8e4… anonymous 13 logger = logging.getLogger(__name__)
5e4b8e4… anonymous 14
5e4b8e4… anonymous 15
5e4b8e4… anonymous 16 def _get_python_language():
5e4b8e4… anonymous 17 try:
5e4b8e4… anonymous 18 import tree_sitter_python as tspython # type: ignore[import]
5e4b8e4… anonymous 19 from tree_sitter import Language
758c6b7… lmata 20
5e4b8e4… anonymous 21 return Language(tspython.language())
5e4b8e4… anonymous 22 except ImportError as e:
758c6b7… lmata 23 raise ImportError("Install tree-sitter-python: pip install tree-sitter-python") from e
5e4b8e4… anonymous 24
5e4b8e4… anonymous 25
5e4b8e4… anonymous 26 def _get_parser():
5e4b8e4… anonymous 27 from tree_sitter import Parser # type: ignore[import]
758c6b7… lmata 28
5e4b8e4… anonymous 29 parser = Parser(_get_python_language())
5e4b8e4… anonymous 30 return parser
5e4b8e4… anonymous 31
5e4b8e4… anonymous 32
5e4b8e4… anonymous 33 def _node_text(node, source: bytes) -> str:
758c6b7… lmata 34 return source[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
5e4b8e4… anonymous 35
5e4b8e4… anonymous 36
5e4b8e4… anonymous 37 def _get_docstring(node, source: bytes) -> str | None:
5e4b8e4… anonymous 38 """Extract the first string literal from a function/class body as docstring."""
5e4b8e4… anonymous 39 body = next((c for c in node.children if c.type == "block"), None)
5e4b8e4… anonymous 40 if not body:
5e4b8e4… anonymous 41 return None
5e4b8e4… anonymous 42 first_stmt = next((c for c in body.children if c.type == "expression_statement"), None)
5e4b8e4… anonymous 43 if not first_stmt:
5e4b8e4… anonymous 44 return None
3c74e66… lmata 45 string_node = next(
3c74e66… lmata 46 (c for c in first_stmt.children if c.type in ("string", "string_content")), None
3c74e66… lmata 47 )
5e4b8e4… anonymous 48 if string_node:
5e4b8e4… anonymous 49 raw = _node_text(string_node, source)
5e4b8e4… anonymous 50 return raw.strip('"""').strip("'''").strip('"').strip("'").strip()
5e4b8e4… anonymous 51 return None
5e4b8e4… anonymous 52
5e4b8e4… anonymous 53
5e4b8e4… anonymous 54 class PythonParser(LanguageParser):
5e4b8e4… anonymous 55 def __init__(self) -> None:
5e4b8e4… anonymous 56 self._parser = _get_parser()
5e4b8e4… anonymous 57
5e4b8e4… anonymous 58 def parse_file(self, path: Path, repo_root: Path, store: GraphStore) -> dict[str, int]:
5e4b8e4… anonymous 59 source = path.read_bytes()
5e4b8e4… anonymous 60 tree = self._parser.parse(source)
5e4b8e4… anonymous 61 rel_path = str(path.relative_to(repo_root))
5e4b8e4… anonymous 62
5e4b8e4… anonymous 63 stats = {"functions": 0, "classes": 0, "edges": 0}
5e4b8e4… anonymous 64
5e4b8e4… anonymous 65 # File node
758c6b7… lmata 66 store.create_node(
758c6b7… lmata 67 NodeLabel.File,
758c6b7… lmata 68 {
758c6b7… lmata 69 "name": path.name,
758c6b7… lmata 70 "path": rel_path,
758c6b7… lmata 71 "language": "python",
758c6b7… lmata 72 "line_count": source.count(b"\n"),
758c6b7… lmata 73 },
758c6b7… lmata 74 )
5e4b8e4… anonymous 75
5e4b8e4… anonymous 76 self._walk(tree.root_node, source, rel_path, store, stats, class_name=None)
5e4b8e4… anonymous 77 return stats
5e4b8e4… anonymous 78
758c6b7… lmata 79 def _walk(
758c6b7… lmata 80 self,
758c6b7… lmata 81 node,
758c6b7… lmata 82 source: bytes,
758c6b7… lmata 83 file_path: str,
758c6b7… lmata 84 store: GraphStore,
758c6b7… lmata 85 stats: dict,
758c6b7… lmata 86 class_name: str | None,
758c6b7… lmata 87 ) -> None:
5e4b8e4… anonymous 88 if node.type == "import_statement":
5e4b8e4… anonymous 89 self._handle_import(node, source, file_path, store, stats)
5e4b8e4… anonymous 90
5e4b8e4… anonymous 91 elif node.type == "import_from_statement":
5e4b8e4… anonymous 92 self._handle_import_from(node, source, file_path, store, stats)
5e4b8e4… anonymous 93
5e4b8e4… anonymous 94 elif node.type == "class_definition":
5e4b8e4… anonymous 95 self._handle_class(node, source, file_path, store, stats)
5e4b8e4… anonymous 96 return # class walker handles children
5e4b8e4… anonymous 97
5e4b8e4… anonymous 98 elif node.type == "function_definition":
5e4b8e4… anonymous 99 self._handle_function(node, source, file_path, store, stats, class_name)
5e4b8e4… anonymous 100 return # function walker handles children
5e4b8e4… anonymous 101
5e4b8e4… anonymous 102 for child in node.children:
5e4b8e4… anonymous 103 self._walk(child, source, file_path, store, stats, class_name)
5e4b8e4… anonymous 104
758c6b7… lmata 105 def _handle_import(
758c6b7… lmata 106 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 107 ) -> None:
5e4b8e4… anonymous 108 for child in node.children:
5e4b8e4… anonymous 109 if child.type == "dotted_name":
5e4b8e4… anonymous 110 name = _node_text(child, source)
758c6b7… lmata 111 store.create_node(
758c6b7… lmata 112 NodeLabel.Import,
758c6b7… lmata 113 {
758c6b7… lmata 114 "name": name,
758c6b7… lmata 115 "file_path": file_path,
758c6b7… lmata 116 "line_start": node.start_point[0] + 1,
758c6b7… lmata 117 "module": name,
758c6b7… lmata 118 },
758c6b7… lmata 119 )
5e4b8e4… anonymous 120 store.create_edge(
758c6b7… lmata 121 NodeLabel.File,
758c6b7… lmata 122 {"path": file_path},
5e4b8e4… anonymous 123 EdgeType.IMPORTS,
758c6b7… lmata 124 NodeLabel.Import,
758c6b7… lmata 125 {"name": name, "file_path": file_path},
5e4b8e4… anonymous 126 )
5e4b8e4… anonymous 127 stats["edges"] += 1
5e4b8e4… anonymous 128
758c6b7… lmata 129 def _handle_import_from(
758c6b7… lmata 130 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 131 ) -> None:
5e4b8e4… anonymous 132 module = ""
5e4b8e4… anonymous 133 for child in node.children:
5e4b8e4… anonymous 134 if child.type in ("dotted_name", "relative_import"):
5e4b8e4… anonymous 135 module = _node_text(child, source)
5e4b8e4… anonymous 136 break
5e4b8e4… anonymous 137 for child in node.children:
5e4b8e4… anonymous 138 if child.type == "import_from_member":
5e4b8e4… anonymous 139 name = _node_text(child, source)
758c6b7… lmata 140 store.create_node(
758c6b7… lmata 141 NodeLabel.Import,
758c6b7… lmata 142 {
758c6b7… lmata 143 "name": name,
758c6b7… lmata 144 "file_path": file_path,
758c6b7… lmata 145 "line_start": node.start_point[0] + 1,
758c6b7… lmata 146 "module": module,
758c6b7… lmata 147 },
758c6b7… lmata 148 )
5e4b8e4… anonymous 149 store.create_edge(
758c6b7… lmata 150 NodeLabel.File,
758c6b7… lmata 151 {"path": file_path},
5e4b8e4… anonymous 152 EdgeType.IMPORTS,
758c6b7… lmata 153 NodeLabel.Import,
758c6b7… lmata 154 {"name": name, "file_path": file_path},
5e4b8e4… anonymous 155 )
5e4b8e4… anonymous 156 stats["edges"] += 1
5e4b8e4… anonymous 157
758c6b7… lmata 158 def _handle_class(
758c6b7… lmata 159 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 160 ) -> None:
5e4b8e4… anonymous 161 name_node = next((c for c in node.children if c.type == "identifier"), None)
5e4b8e4… anonymous 162 if not name_node:
5e4b8e4… anonymous 163 return
5e4b8e4… anonymous 164 name = _node_text(name_node, source)
5e4b8e4… anonymous 165 docstring = _get_docstring(node, source)
5e4b8e4… anonymous 166
758c6b7… lmata 167 store.create_node(
758c6b7… lmata 168 NodeLabel.Class,
758c6b7… lmata 169 {
758c6b7… lmata 170 "name": name,
758c6b7… lmata 171 "file_path": file_path,
758c6b7… lmata 172 "line_start": node.start_point[0] + 1,
758c6b7… lmata 173 "line_end": node.end_point[0] + 1,
758c6b7… lmata 174 "docstring": docstring or "",
758c6b7… lmata 175 },
758c6b7… lmata 176 )
5e4b8e4… anonymous 177 store.create_edge(
758c6b7… lmata 178 NodeLabel.File,
758c6b7… lmata 179 {"path": file_path},
5e4b8e4… anonymous 180 EdgeType.CONTAINS,
758c6b7… lmata 181 NodeLabel.Class,
758c6b7… lmata 182 {"name": name, "file_path": file_path},
5e4b8e4… anonymous 183 )
5e4b8e4… anonymous 184 stats["classes"] += 1
5e4b8e4… anonymous 185 stats["edges"] += 1
5e4b8e4… anonymous 186
5e4b8e4… anonymous 187 # Inheritance
5e4b8e4… anonymous 188 for child in node.children:
5e4b8e4… anonymous 189 if child.type == "argument_list":
5e4b8e4… anonymous 190 for arg in child.children:
5e4b8e4… anonymous 191 if arg.type == "identifier":
5e4b8e4… anonymous 192 parent_name = _node_text(arg, source)
5e4b8e4… anonymous 193 store.create_edge(
758c6b7… lmata 194 NodeLabel.Class,
758c6b7… lmata 195 {"name": name, "file_path": file_path},
5e4b8e4… anonymous 196 EdgeType.INHERITS,
758c6b7… lmata 197 NodeLabel.Class,
758c6b7… lmata 198 {"name": parent_name, "file_path": file_path},
5e4b8e4… anonymous 199 )
5e4b8e4… anonymous 200 stats["edges"] += 1
5e4b8e4… anonymous 201
5e4b8e4… anonymous 202 # Walk class body for methods
5e4b8e4… anonymous 203 body = next((c for c in node.children if c.type == "block"), None)
5e4b8e4… anonymous 204 if body:
5e4b8e4… anonymous 205 for child in body.children:
5e4b8e4… anonymous 206 if child.type == "function_definition":
5e4b8e4… anonymous 207 self._handle_function(child, source, file_path, store, stats, class_name=name)
5e4b8e4… anonymous 208
758c6b7… lmata 209 def _handle_function(
758c6b7… lmata 210 self,
758c6b7… lmata 211 node,
758c6b7… lmata 212 source: bytes,
758c6b7… lmata 213 file_path: str,
758c6b7… lmata 214 store: GraphStore,
758c6b7… lmata 215 stats: dict,
758c6b7… lmata 216 class_name: str | None,
758c6b7… lmata 217 ) -> None:
5e4b8e4… anonymous 218 name_node = next((c for c in node.children if c.type == "identifier"), None)
5e4b8e4… anonymous 219 if not name_node:
5e4b8e4… anonymous 220 return
5e4b8e4… anonymous 221 name = _node_text(name_node, source)
5e4b8e4… anonymous 222 docstring = _get_docstring(node, source)
5e4b8e4… anonymous 223
5e4b8e4… anonymous 224 label = NodeLabel.Method if class_name else NodeLabel.Function
5e4b8e4… anonymous 225 props = {
5e4b8e4… anonymous 226 "name": name,
5e4b8e4… anonymous 227 "file_path": file_path,
5e4b8e4… anonymous 228 "line_start": node.start_point[0] + 1,
5e4b8e4… anonymous 229 "line_end": node.end_point[0] + 1,
5e4b8e4… anonymous 230 "docstring": docstring or "",
5e4b8e4… anonymous 231 "class_name": class_name or "",
5e4b8e4… anonymous 232 }
5e4b8e4… anonymous 233 store.create_node(label, props)
5e4b8e4… anonymous 234
5e4b8e4… anonymous 235 container_label = NodeLabel.Class if class_name else NodeLabel.File
5e4b8e4… anonymous 236 container_key = (
758c6b7… lmata 237 {"name": class_name, "file_path": file_path} if class_name else {"path": file_path}
5e4b8e4… anonymous 238 )
3c74e66… lmata 239 store.create_edge(
758c6b7… lmata 240 container_label,
758c6b7… lmata 241 container_key,
758c6b7… lmata 242 EdgeType.CONTAINS,
758c6b7… lmata 243 label,
3c74e66… lmata 244 {"name": name, "file_path": file_path},
3c74e66… lmata 245 )
5e4b8e4… anonymous 246 stats["functions"] += 1
5e4b8e4… anonymous 247 stats["edges"] += 1
5e4b8e4… anonymous 248
5e4b8e4… anonymous 249 # Call edges — find all call expressions in the body
5e4b8e4… anonymous 250 self._extract_calls(node, source, file_path, name, label, store, stats)
5e4b8e4… anonymous 251
758c6b7… lmata 252 def _extract_calls(
758c6b7… lmata 253 self,
758c6b7… lmata 254 fn_node,
758c6b7… lmata 255 source: bytes,
758c6b7… lmata 256 file_path: str,
758c6b7… lmata 257 fn_name: str,
758c6b7… lmata 258 fn_label: str,
758c6b7… lmata 259 store: GraphStore,
758c6b7… lmata 260 stats: dict,
758c6b7… lmata 261 ) -> None:
5e4b8e4… anonymous 262 def walk_calls(node):
5e4b8e4… anonymous 263 if node.type == "call":
3c74e66… lmata 264 func = next(
3c74e66… lmata 265 (c for c in node.children if c.type in ("identifier", "attribute")), None
3c74e66… lmata 266 )
5e4b8e4… anonymous 267 if func:
5e4b8e4… anonymous 268 callee_name = _node_text(func, source).split(".")[-1]
5e4b8e4… anonymous 269 store.create_edge(
758c6b7… lmata 270 fn_label,
758c6b7… lmata 271 {"name": fn_name, "file_path": file_path},
5e4b8e4… anonymous 272 EdgeType.CALLS,
758c6b7… lmata 273 NodeLabel.Function,
758c6b7… lmata 274 {"name": callee_name, "file_path": file_path},
5e4b8e4… anonymous 275 )
5e4b8e4… anonymous 276 stats["edges"] += 1
5e4b8e4… anonymous 277 for child in node.children:
5e4b8e4… anonymous 278 walk_calls(child)
5e4b8e4… anonymous 279
5e4b8e4… anonymous 280 body = next((c for c in fn_node.children if c.type == "block"), None)
5e4b8e4… anonymous 281 if body:
5e4b8e4… anonymous 282 walk_calls(body)

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button