fix(detect/extract): structurally extract .yaml/.yml config files (#2214)

YAML files were classified as documents, so code-only / AST-only runs
(graphify update) produced zero nodes from them. Move .yaml/.yml into the
code path like .json: add a PyYAML-based structural extractor (extract_yaml)
registered in _DISPATCH, add the suffixes to CODE_EXTENSIONS, drop them from
DOC_EXTENSIONS and the splittable-text set.

Deterministic ids derived from the file path; top-level and nested keys become
nodes with contains edges, capped at 500 pairs / depth 6 to avoid exploding on
data-heavy YAML.

(cherry picked from commit 2e5565a684)
This commit is contained in:
nothariharan authored and safishamsi committed 2026-10-23 15:51:09 +01:00
1 parent d4f3cf7f51
commit 6a21696caa
5 files changed
+113 -5

No files matched your search

+2 -2
View File
@@ -45,8 +45,8 @@ _MANIFEST_PATH = str(out_path("manifest.json"))
_MTIME_COARSE_S = 2.0
_MTIME_SUBSECOND_S = 0.05
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.ejs', '.ets', '.go', '.rs', '.vb', '.cbl', '.cob', '.cobol', '.cpy', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.ml', '.mli', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.vh', '.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', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger', '.lisp', '.cl', '.lsp', '.asd', '.robot', '.resource', '.sol', '.erl', '.hrl', '.escript'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.skill', '.txt', '.rst', '.html', '.yaml', '.yml', '.j2', '.jinja', '.jinja2'}
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.ejs', '.ets', '.go', '.rs', '.vb', '.cbl', '.cob', '.cobol', '.cpy', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.ml', '.mli', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.vh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.yaml', '.yml', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger', '.lisp', '.cl', '.lsp', '.asd', '.robot', '.resource', '.sol', '.erl', '.hrl', '.escript'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.skill', '.txt', '.rst', '.html', '.j2', '.jinja', '.jinja2'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
+3
View File
@@ -66,6 +66,7 @@ from graphify.extractors.erlang import extract_erlang, resolve_erlang_remote_cal
from graphify.extractors.fortran import _cpp_preprocess, extract_fortran # noqa: F401
from graphify.extractors.go import _GO_PREDECLARED_FUNCS, extract_go # noqa: F401
from graphify.extractors.json_config import extract_json # noqa: F401
from graphify.extractors.yaml_config import extract_yaml # noqa: F401
from graphify.extractors.commonlisp import extract_commonlisp # noqa: F401
from graphify.extractors.markdown import extract_markdown, _MD_LINK_INDEX_CACHE # noqa: F401
from graphify.extractors.ocaml import extract_ocaml # noqa: F401
@@ -8713,6 +8714,8 @@ _DISPATCH: dict[str, Any] = {
".sh": extract_bash,
".bash": extract_bash,
".json": extract_json,
".yaml": extract_yaml,
".yml": extract_yaml,
".tf": extract_terraform,
".tfvars": extract_terraform,
".hcl": extract_terraform,
+105
View File
@@ -0,0 +1,105 @@
"""YAML structural extractor.
Deterministic, PyYAML-based extraction for ``.yaml``/``.yml`` files so that
config-heavy repositories (Helm charts, Kubernetes manifests, CI pipelines)
contribute nodes to code-only / AST-only runs (``graphify update``) instead of
being skipped entirely (#2214).
Mirrors ``extract_json`` in shape: a file node plus ``contains`` edges to
top-level (and nested) keys, with a pair/depth cap to keep data-heavy YAML from
exploding into orphan nodes.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from graphify.extractors.base import _file_stem, _make_id
from graphify.ids import normalize_id
def extract_yaml(path: Path) -> dict:
"""Extract structural nodes/edges from a ``.yaml``/``.yml`` file.
Uses PyYAML (``yaml.safe_load``) when available; returns an error payload
otherwise so callers degrade gracefully instead of crashing.
"""
try:
import yaml # type: ignore
except ImportError:
return {"nodes": [], "edges": [], "error": "pyyaml not installed"}
_YAML_MAX_BYTES = 1_048_576 # 1 MiB
try:
with path.open("rb") as _f:
raw = _f.read(_YAML_MAX_BYTES + 1)
if len(raw) > _YAML_MAX_BYTES:
return {"nodes": [], "edges": [], "error": "yaml file too large to index"}
text = raw.decode("utf-8", errors="ignore")
data = yaml.safe_load(text)
except Exception as exc: # noqa: BLE001 - surface any parse failure to caller
return {"nodes": [], "edges": [], "error": str(exc)}
if not isinstance(data, (dict, list)):
# A scalar document carries no structure worth graphing.
return {"nodes": [], "edges": [], "skipped": "scalar yaml"}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
def add_node(nid: str, label: str, line: int = 1, file_type: str = "code") -> None:
if nid and nid not in seen_ids:
seen_ids.add(nid)
nodes.append(
{"id": nid, "label": str(label), "file_type": file_type,
"source_file": str_path, "source_location": f"L{line}"}
)
def add_edge(src: str, tgt: str, relation: str, line: int = 1,
context: str | None = None) -> None:
if not src or not tgt or src == tgt:
return
edge = {"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0}
if context:
edge["context"] = context
edges.append(edge)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
pair_count = [0]
def walk(obj: Any, parent_nid: str, parent_key: str | None, depth: int) -> None:
if depth > 6:
return
if isinstance(obj, dict):
for key, val in obj.items():
if pair_count[0] >= 500:
return
pair_count[0] += 1
key_str = str(key)
if not normalize_id(key_str):
continue
key_nid = _make_id(stem, *(([parent_key] if parent_key else []) + [key_str]))
if not key_nid:
continue
add_node(key_nid, key_str)
add_edge(parent_nid, key_nid, "contains")
if isinstance(val, (dict, list)):
walk(val, key_nid, key_str, depth + 1)
elif isinstance(obj, list):
# Lists of scalars carry no key structure; only recurse into
# structured items without minting index nodes (avoids explosion).
for item in obj:
if isinstance(item, (dict, list)):
walk(item, parent_nid, parent_key, depth + 1)
walk(data, file_nid, None, 0)
return {"nodes": nodes, "edges": edges}
+1 -1
View File
@@ -39,7 +39,7 @@ from graphify.extractors.base import _read_source_text
# addition to DOC_EXTENSIONS fails loudly instead of quietly losing content.
_SPLITTABLE_TEXT_SUFFIXES = frozenset({
".md", ".mdx", ".markdown", ".txt", ".rst",
".qmd", ".skill", ".html", ".yaml", ".yml",
".qmd", ".skill", ".html",
".j2", ".jinja", ".jinja2",
})
+2 -2
View File
@@ -24,8 +24,8 @@ def test_manifests_classify_as_code_not_document(tmp_path):
p = _write(tmp_path / name, "x")
assert is_package_manifest_path(p)
assert classify_file(p) is FileType.CODE, name
# a generic yaml stays a document
assert classify_file(_write(tmp_path / "config.yaml", "a: 1")) is FileType.DOCUMENT
# yaml is now structurally extracted like json (code path) (#2214)
assert classify_file(_write(tmp_path / "config.yaml", "a: 1")) is FileType.CODE
# ── per-format parsing ───────────────────────────────────────────────────────