@@ -10526,6 +10526,184 @@ def extract_dmf(path: Path) -> dict:
1052610526 return {"nodes" : nodes , "edges" : edges }
1052710527
1052810528
10529+ # Head tokens in an HCL traversal that are meta/builtins, not references to a
10530+ # block defined in the corpus (count.index, each.key, self.*, path.module, ...).
10531+ _TF_META_HEADS = frozenset ({"count" , "each" , "self" , "path" , "terraform" })
10532+
10533+
10534+ def extract_terraform (path : Path ) -> dict :
10535+ """Extract Terraform/HCL blocks and the references between them via tree-sitter.
10536+
10537+ Nodes: resources, data sources, modules, variables, outputs, providers, and
10538+ locals. Edges: `contains` (file -> block), `references` (block -> the blocks
10539+ it interpolates, e.g. `aws_instance.web` -> `var.region`), and `depends_on`
10540+ (explicit dependency edges).
10541+
10542+ Node IDs are scoped by the parent directory, not the file stem, because
10543+ Terraform resources are module(directory)-scoped: a resource defined in
10544+ main.tf is referenced from other .tf files in the same directory. Directory
10545+ scoping lets those cross-file references resolve when per-file extractions
10546+ are merged (stem scoping would split a definition from its references).
10547+ """
10548+ try :
10549+ import tree_sitter_hcl as tshcl
10550+ from tree_sitter import Language , Parser
10551+ except ImportError :
10552+ return {"nodes" : [], "edges" : [], "error" : "tree_sitter_hcl not installed. Run: pip install tree-sitter-hcl" }
10553+
10554+ try :
10555+ language = Language (tshcl .language ())
10556+ parser = Parser (language )
10557+ source = path .read_bytes ()
10558+ tree = parser .parse (source )
10559+ root = tree .root_node
10560+ except Exception as e :
10561+ return {"nodes" : [], "edges" : [], "error" : str (e )}
10562+
10563+ str_path = str (path )
10564+ file_nid = _make_id (str_path )
10565+ scope = path .parent .name or "tf"
10566+
10567+ nodes : list [dict ] = [{"id" : file_nid , "label" : path .name , "file_type" : "code" ,
10568+ "source_file" : str_path , "source_location" : None }]
10569+ edges : list [dict ] = []
10570+ seen_ids : set [str ] = {file_nid }
10571+ seen_edges : set [tuple [str , str , str ]] = set ()
10572+
10573+ def _read (n ) -> str :
10574+ return source [n .start_byte :n .end_byte ].decode ("utf-8" , errors = "replace" )
10575+
10576+ def _label_text (n ) -> str :
10577+ return _read (n ).strip ().strip ('"' )
10578+
10579+ def _add_node (address : str , label : str , line : int ) -> str :
10580+ nid = _make_id (scope , address )
10581+ if nid not in seen_ids :
10582+ seen_ids .add (nid )
10583+ nodes .append ({"id" : nid , "label" : label , "file_type" : "code" ,
10584+ "source_file" : str_path , "source_location" : f"L{ line } " })
10585+ edges .append ({"source" : file_nid , "target" : nid , "relation" : "contains" ,
10586+ "confidence" : "EXTRACTED" , "source_file" : str_path ,
10587+ "source_location" : f"L{ line } " , "weight" : 1.0 })
10588+ return nid
10589+
10590+ def _add_edge (src : str , address : str , relation : str , line : int ) -> None :
10591+ tgt = _make_id (scope , address )
10592+ if src == tgt :
10593+ return
10594+ key = (src , tgt , relation )
10595+ if key in seen_edges :
10596+ return
10597+ seen_edges .add (key )
10598+ edges .append ({"source" : src , "target" : tgt , "relation" : relation ,
10599+ "confidence" : "EXTRACTED" , "source_file" : str_path ,
10600+ "source_location" : f"L{ line } " , "weight" : 1.0 })
10601+
10602+ def _block_parts (block ) -> tuple :
10603+ btype = None
10604+ labels : list [str ] = []
10605+ for c in block .children :
10606+ if c .type in ("block_start" , "body" , "block_end" ):
10607+ break
10608+ if c .type == "identifier" and btype is None :
10609+ btype = _read (c )
10610+ elif c .type in ("string_lit" , "identifier" ):
10611+ labels .append (_label_text (c ))
10612+ return btype , labels
10613+
10614+ def _ref_address (expr ):
10615+ head = _read (expr )
10616+ parent = expr .parent
10617+ attrs : list [str ] = []
10618+ if parent is not None :
10619+ seen_self = False
10620+ for c in parent .children :
10621+ if c .id == expr .id :
10622+ seen_self = True
10623+ continue
10624+ if seen_self and c .type == "get_attr" :
10625+ name = None
10626+ for gc in c .children :
10627+ if gc .type == "identifier" :
10628+ name = _read (gc )
10629+ break
10630+ if name is None :
10631+ break
10632+ attrs .append (name )
10633+ elif seen_self and c .type not in ("get_attr" ,):
10634+ break
10635+ if head in _TF_META_HEADS or not head :
10636+ return None
10637+ if head == "var" :
10638+ return f"var.{ attrs [0 ]} " if attrs else None
10639+ if head == "local" :
10640+ return f"local.{ attrs [0 ]} " if attrs else None
10641+ if head == "module" :
10642+ return f"module.{ attrs [0 ]} " if attrs else None
10643+ if head == "data" :
10644+ return f"data.{ attrs [0 ]} .{ attrs [1 ]} " if len (attrs ) >= 2 else None
10645+ return f"{ head } .{ attrs [0 ]} " if attrs else None
10646+
10647+ def _collect_refs (node , owner_nid : str , relation : str ) -> None :
10648+ rel = relation
10649+ if node .type == "attribute" :
10650+ key_node = node .child_by_field_name ("key" ) or (
10651+ node .children [0 ] if node .children else None
10652+ )
10653+ if key_node is not None and _read (key_node ) == "depends_on" :
10654+ rel = "depends_on"
10655+ if node .type == "variable_expr" :
10656+ addr = _ref_address (node )
10657+ if addr :
10658+ _add_edge (owner_nid , addr , rel , node .start_point [0 ] + 1 )
10659+ for c in node .children :
10660+ if c .is_named :
10661+ _collect_refs (c , owner_nid , rel )
10662+
10663+ def _body_of (block ):
10664+ for c in block .children :
10665+ if c .type == "body" :
10666+ return c
10667+ return None
10668+
10669+ body = next ((c for c in root .children if c .type == "body" ), root )
10670+ for block in body .children :
10671+ if block .type != "block" :
10672+ continue
10673+ btype , labels = _block_parts (block )
10674+ line = block .start_point [0 ] + 1
10675+ blk_body = _body_of (block )
10676+ if btype == "resource" and len (labels ) >= 2 :
10677+ owner = _add_node (f"{ labels [0 ]} .{ labels [1 ]} " , f"{ labels [0 ]} .{ labels [1 ]} " , line )
10678+ elif btype == "data" and len (labels ) >= 2 :
10679+ owner = _add_node (f"data.{ labels [0 ]} .{ labels [1 ]} " , f"data.{ labels [0 ]} .{ labels [1 ]} " , line )
10680+ elif btype == "module" and labels :
10681+ owner = _add_node (f"module.{ labels [0 ]} " , f"module.{ labels [0 ]} " , line )
10682+ elif btype == "variable" and labels :
10683+ owner = _add_node (f"var.{ labels [0 ]} " , f"var.{ labels [0 ]} " , line )
10684+ elif btype == "output" and labels :
10685+ owner = _add_node (f"output.{ labels [0 ]} " , f"output.{ labels [0 ]} " , line )
10686+ elif btype == "provider" and labels :
10687+ owner = _add_node (f"provider.{ labels [0 ]} " , f"provider.{ labels [0 ]} " , line )
10688+ elif btype == "locals" and blk_body is not None :
10689+ for attr in blk_body .children :
10690+ if attr .type != "attribute" :
10691+ continue
10692+ key_node = attr .children [0 ] if attr .children else None
10693+ if key_node is None :
10694+ continue
10695+ key = _read (key_node )
10696+ lnid = _add_node (f"local.{ key } " , f"local.{ key } " , attr .start_point [0 ] + 1 )
10697+ _collect_refs (attr , lnid , "references" )
10698+ continue
10699+ else :
10700+ continue
10701+ if blk_body is not None :
10702+ _collect_refs (blk_body , owner , "references" )
10703+
10704+ return {"nodes" : nodes , "edges" : edges }
10705+
10706+
1052910707_DISPATCH : dict [str , Any ] = {
1053010708 ".py" : extract_python ,
1053110709 ".js" : extract_js ,
@@ -10594,6 +10772,9 @@ def extract_dmf(path: Path) -> dict:
1059410772 ".sh" : extract_bash ,
1059510773 ".bash" : extract_bash ,
1059610774 ".json" : extract_json ,
10775+ ".tf" : extract_terraform ,
10776+ ".tfvars" : extract_terraform ,
10777+ ".hcl" : extract_terraform ,
1059710778 ".dm" : extract_dm ,
1059810779 ".dme" : extract_dm ,
1059910780 ".dmi" : extract_dmi ,
0 commit comments