-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbash.py
More file actions
67 lines (54 loc) · 1.99 KB
/
Copy pathbash.py
File metadata and controls
67 lines (54 loc) · 1.99 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
from __future__ import annotations
import tree_sitter_bash
from tree_sitter import Language, Node, Parser
from server.parser.base import CodeSymbol, _node_text
BASH_LANGUAGE = Language(tree_sitter_bash.language())
def _docstring(node: Node, source: bytes) -> str | None:
prev = node.prev_sibling
lines: list[str] = []
while prev is not None:
if prev.type == "comment":
lines.insert(0, _node_text(prev, source))
prev = prev.prev_sibling
continue
if prev.type in ("\n", " "):
prev = prev.prev_sibling
continue
break
return "\n".join(lines) if lines else None
def _parse_function(node: Node, source: bytes, file_path: str) -> CodeSymbol | None:
name_node = node.child_by_field_name("name")
if name_node is None:
for child in node.children:
if child.type == "word":
name_node = child
break
if name_node is None:
return None
return CodeSymbol(
name=_node_text(name_node, source),
symbol_type="function",
language="bash",
source=_node_text(node, source),
file_path=file_path,
start_line=node.start_point[0] + 1,
end_line=node.end_point[0] + 1,
signature=_node_text(node, source).split("{", 1)[0].strip(),
docstring=_docstring(node, source),
)
class BashParser:
def __init__(self) -> None:
self._parser = Parser(BASH_LANGUAGE)
def supported_extensions(self) -> list[str]:
return [".sh", ".bash"]
def language(self) -> str:
return "bash"
def parse_file(self, source: bytes, file_path: str) -> list[CodeSymbol]:
tree = self._parser.parse(source)
symbols: list[CodeSymbol] = []
for child in tree.root_node.children:
if child.type == "function_definition":
sym = _parse_function(child, source, file_path)
if sym:
symbols.append(sym)
return symbols