Coverage for circular_deps/parsers/go.py: 100%

1 from __future__ import annotations

2

3 import tree_sitter_go as tsgo

4 from tree_sitter import Language

5 from tree_sitter import Parser

6

7 from circular_deps.models import ImportInfo

8 from circular_deps.parsers.base import ImportParser

9

10 GO_LANGUAGE = Language(tsgo.language())

11

12

13 def parse(code):

14 parser_obj = Parser(GO_LANGUAGE)

15 tree = parser_obj.parse(code.encode())

16 return tree.root_node

17

18

19 class GoImportParser(ImportParser):

20 def extract_imports(self, source, filepath):

21 root = parse(source)

22 imports = []

23

24 for node in root.children:

25 if node.type == "import_declaration":

26 for child in node.children:

27 if child.type == "import_spec":

28 imports.extend(self._process_import_spec(child))

29 elif child.type == "import_spec_list":

30 for spec in child.children:

31 if spec.type == "import_spec":

32 imports.extend(self._process_import_spec(spec))

33

34 return imports

35

36 def _process_import_spec(self, node):

37 imports = []

38 path = ""

39

40 for child in node.children:

41 if child.type == "interpreted_string_literal":

42 path = child.text.decode().strip('"')

43

44 if path:

45 imports.append(

46 ImportInfo(

47 raw_module=path,

48 resolved_path=None,

49 import_type="absolute",

50 line=node.start_point[0] + 1,

51 is_dynamic=False,

52 node_type="import_spec",

53 )

54 )

55

56 return imports