forked from CodeGraphContext/CodeGraphContext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcss.py
More file actions
84 lines (74 loc) · 3.19 KB
/
Copy pathcss.py
File metadata and controls
84 lines (74 loc) · 3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# src/codegraphcontext/tools/languages/css.py
from pathlib import Path
from typing import Any, Dict
from codegraphcontext.utils.tree_sitter_manager import execute_query
class CSSTreeSitterParser:
"""A parser for CSS files using tree-sitter."""
def __init__(self, generic_parser_wrapper):
self.generic_parser_wrapper = generic_parser_wrapper
self.language = generic_parser_wrapper.language
self.parser = generic_parser_wrapper.parser
self.language_name = "css"
def _get_node_text(self, node) -> str:
return node.text.decode('utf-8')
def parse(self, path: Path, is_dependency: bool = False, index_source: bool = False) -> Dict[str, Any]:
"""Parses a CSS file and returns its structure."""
with open(path, "r", encoding="utf-8") as f:
source_code = f.read()
tree = self.parser.parse(bytes(source_code, "utf8"))
root_node = tree.root_node
selectors = []
imports = []
variables = []
query_str = """
(class_selector (class_name) @class_name)
(id_selector (id_name) @id_name)
(tag_name) @tag_name
(import_statement (string_value) @import_path)
"""
for node, capture_name in execute_query(self.language, query_str, root_node):
if capture_name == 'class_name':
selectors.append({
"name": "." + self._get_node_text(node),
"type": "class",
"line_number": node.start_point[0] + 1
})
elif capture_name == 'id_name':
selectors.append({
"name": "#" + self._get_node_text(node),
"type": "id",
"line_number": node.start_point[0] + 1
})
elif capture_name == 'tag_name':
selectors.append({
"name": self._get_node_text(node),
"type": "tag",
"line_number": node.start_point[0] + 1
})
elif capture_name == 'import_path':
imports.append({
"name": self._get_node_text(node).strip('\'"'),
"source": self._get_node_text(node).strip('\'"'),
"line_number": node.start_point[0] + 1
})
elif capture_name == 'var_name':
variables.append({
"name": self._get_node_text(node),
"value": None, # Value captured separately
"line_number": node.start_point[0] + 1
})
elif capture_name == 'var_value':
if variables:
variables[-1]["value"] = self._get_node_text(node)
return {
"path": str(path),
"functions": [{"name": s["name"], "line_number": s["line_number"], "type": s["type"]} for s in selectors],
"classes": [],
"variables": variables,
"imports": imports,
"function_calls": [],
"is_dependency": is_dependency,
"lang": self.language_name,
}
def pre_scan_css(files: list[Path], parser_wrapper) -> dict:
return {}