Coverage for patterns/common.py: 100%

1"""Pattern detection utilities for code quality."""

2

3 from __future__ import annotations

4

5 from typing import TYPE_CHECKING

6

7 if TYPE_CHECKING:

8 from tree_sitter import Language, Node

9

10

11 def create_query(language: Language, source: str):

12 """Create a tree-sitter Query with error handling."""

13 from tree_sitter import Query

14

15 try:

16 return Query(language, source)

17 except Exception as e:

18 raise ValueError(f"Invalid query: {e}") from e

19

20

21 def run_captures(query, root: Node) -> list[tuple[Node, str]]:

22 """Query captures for a root node and return flat list of (node, capture_name)."""

23 from tree_sitter import QueryCursor

24

25 if root.child_count == 0:

26 return []

27 cursor = QueryCursor(query)

28 result = []

29 for capture_name, node in cursor.captures(root).items():

30 for n in node:

31 result.append((n, capture_name))

32 return result