Skip to content

Commit 200edec

Browse files
safishamsiclaude
andcommitted
feat(extract): add Terraform/HCL AST extraction via tree-sitter-hcl (#1129)
Adds extract_terraform() for .tf/.tfvars/.hcl files. Nodes: resources, data sources, modules, variables, outputs, providers, locals. Edges: contains, references (interpolation), depends_on. Node IDs are directory-scoped for cross-file resolution. tree-sitter-hcl added as optional extra (graphify[terraform]) matching sql/dm precedent. 8 tests including .tfvars documented no-op behaviour. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
1 parent fff1c98 commit 200edec

4 files changed

Lines changed: 343 additions & 2 deletions

File tree

‎graphify/detect.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class FileType(str, Enum):
2525

2626
_MANIFEST_PATH = "graphify-out/manifest.json"
2727

28-
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml'}
28+
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml'}
2929
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
3030
PAPER_EXTENSIONS = {'.pdf'}
3131
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}

‎graphify/extract.py‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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,

‎pyproject.toml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ sql = ["tree-sitter-sql"]
6969
# must compile from source (needs a C toolchain + python3-dev). Keeping it optional
7070
# avoids breaking the default `uv tool install graphifyy` for everyone (#1104).
7171
dm = ["tree-sitter-dm"]
72-
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper; python_version >= '3.11'", "yt-dlp", "matplotlib", "openai", "tiktoken", "boto3", "anthropic", "tree-sitter-sql", "jieba", "tree-sitter-dm"]
72+
terraform = ["tree-sitter-hcl"]
73+
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper; python_version >= '3.11'", "yt-dlp", "matplotlib", "openai", "tiktoken", "boto3", "anthropic", "tree-sitter-sql", "jieba", "tree-sitter-dm", "tree-sitter-hcl"]
7374

7475
[project.scripts]
7576
graphify = "graphify.__main__:main"
@@ -91,6 +92,7 @@ dev = [
9192
"setuptools>=82.0.1",
9293
"wheel>=0.47.0",
9394
"tomli>=2.0 ; python_version < '3.11'",
95+
"tree-sitter-hcl>=1.2.0",
9496
]
9597

9698
[tool.uv]

‎tests/test_terraform.py‎

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
"""Tests for the Terraform/HCL extractor (graphify/extract.py, issue #187)."""
2+
from __future__ import annotations
3+
4+
from pathlib import Path
5+
6+
from graphify.build import build_from_json
7+
from graphify.extract import extract_terraform
8+
9+
10+
def _write(tmp_path: Path, name: str, body: str) -> Path:
11+
p = tmp_path / name
12+
p.write_text(body, encoding="utf-8")
13+
return p
14+
15+
16+
def _labels(r) -> list[str]:
17+
return [n["label"] for n in r["nodes"]]
18+
19+
20+
def _rel_pairs(r, relation: str) -> set[tuple[str, str]]:
21+
lab = {n["id"]: n["label"] for n in r["nodes"]}
22+
return {
23+
(lab.get(e["source"], e["source"]), lab.get(e["target"], e["target"]))
24+
for e in r["edges"]
25+
if e["relation"] == relation
26+
}
27+
28+
29+
SAMPLE = """\
30+
# leading comment so the body is not children[0]
31+
terraform {
32+
required_providers { azurerm = { source = "hashicorp/azurerm" } }
33+
}
34+
35+
variable "region" { default = "us-east-1" }
36+
37+
provider "aws" { region = var.region }
38+
39+
data "aws_ami" "ubuntu" { most_recent = true }
40+
41+
resource "aws_instance" "web" {
42+
ami = data.aws_ami.ubuntu.id
43+
subnet_id = var.region
44+
depends_on = [aws_security_group.sg]
45+
}
46+
47+
resource "aws_security_group" "sg" { name = "sg" }
48+
49+
module "vpc" {
50+
source = "./modules/vpc"
51+
cidr = local.cidr
52+
}
53+
54+
locals { cidr = "10.0.0.0/16" }
55+
56+
output "ip" { value = aws_instance.web.private_ip }
57+
"""
58+
59+
60+
def test_no_error_and_all_block_types_become_nodes(tmp_path):
61+
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
62+
assert r.get("error") is None
63+
labels = set(_labels(r))
64+
# one node per block type (the terraform{} settings block is intentionally skipped)
65+
for expected in (
66+
"var.region",
67+
"provider.aws",
68+
"data.aws_ami.ubuntu",
69+
"aws_instance.web",
70+
"aws_security_group.sg",
71+
"module.vpc",
72+
"local.cidr",
73+
"output.ip",
74+
):
75+
assert expected in labels, f"missing node {expected!r}"
76+
77+
78+
def test_reference_edges(tmp_path):
79+
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
80+
refs = _rel_pairs(r, "references")
81+
assert ("provider.aws", "var.region") in refs
82+
assert ("aws_instance.web", "data.aws_ami.ubuntu") in refs
83+
assert ("aws_instance.web", "var.region") in refs
84+
assert ("module.vpc", "local.cidr") in refs
85+
assert ("output.ip", "aws_instance.web") in refs
86+
87+
88+
def test_depends_on_edge(tmp_path):
89+
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
90+
assert ("aws_instance.web", "aws_security_group.sg") in _rel_pairs(r, "depends_on")
91+
92+
93+
def test_file_contains_blocks(tmp_path):
94+
r = extract_terraform(_write(tmp_path, "main.tf", SAMPLE))
95+
contains = _rel_pairs(r, "contains")
96+
assert ("main.tf", "aws_instance.web") in contains
97+
assert ("main.tf", "var.region") in contains
98+
99+
100+
def test_meta_heads_not_emitted(tmp_path):
101+
# count.index / each.key / self.* / path.module are builtins, not references.
102+
body = """\
103+
resource "aws_instance" "web" {
104+
count = 2
105+
name = "web-${count.index}"
106+
tags = each.value
107+
dir = path.module
108+
}
109+
"""
110+
r = extract_terraform(_write(tmp_path, "main.tf", body))
111+
targets = {t for _, t in _rel_pairs(r, "references")}
112+
assert not any(t.startswith(("count", "each", "path")) for t in targets)
113+
114+
115+
def test_cross_file_references_resolve_after_merge(tmp_path):
116+
# A resource defined in one file is referenced from another in the same
117+
# directory; directory-scoped IDs must let the edge resolve at build time.
118+
defn = """\
119+
resource "azurerm_resource_group" "main" { name = "rg" }
120+
"""
121+
user = """\
122+
resource "azurerm_network_interface" "nic" {
123+
resource_group_name = azurerm_resource_group.main.name
124+
}
125+
"""
126+
r_defn = extract_terraform(_write(tmp_path, "main.tf", defn))
127+
r_user = extract_terraform(_write(tmp_path, "nic.tf", user))
128+
129+
# The cross-file edge target id equals the definition's node id.
130+
rg_id = next(n["id"] for n in r_defn["nodes"] if n["label"] == "azurerm_resource_group.main")
131+
nic_ref_targets = {e["target"] for e in r_user["edges"] if e["relation"] == "references"}
132+
assert rg_id in nic_ref_targets
133+
134+
# And it survives a real merge: the edge is present (not dropped as dangling).
135+
G = build_from_json(
136+
{
137+
"nodes": r_defn["nodes"] + r_user["nodes"],
138+
"edges": r_defn["edges"] + r_user["edges"],
139+
}
140+
)
141+
nic_id = next(n["id"] for n in r_user["nodes"] if n["label"] == "azurerm_network_interface.nic")
142+
assert G.has_edge(nic_id, rg_id)
143+
144+
145+
def test_empty_and_commentonly_files_are_safe(tmp_path):
146+
assert extract_terraform(_write(tmp_path, "a.tf", "")).get("error") is None
147+
r = extract_terraform(_write(tmp_path, "b.tf", "# just a comment\n"))
148+
# only the file node, no crash
149+
assert len(r["nodes"]) == 1
150+
151+
152+
def test_tfvars_key_value_is_safe(tmp_path):
153+
# .tfvars files contain only key=value assignments (no block structure),
154+
# so extract_terraform produces zero block nodes — only the file node.
155+
# This is the documented intended behaviour for .tfvars.
156+
r = extract_terraform(_write(tmp_path, "terraform.tfvars", 'region = "us-east-1"\nenv = "prod"\n'))
157+
assert r.get("error") is None
158+
assert len(r["nodes"]) == 1 # only the file node, no variable nodes

0 commit comments

Comments
 (0)