feat(config): declare languages for ambiguous extensions via .graphifyrc (#2961)

An ambiguous extension (`.inc`, `.h`, TS-family, ...) is hard-mapped to one
global default; when that is wrong the file does not error — it parses as the
wrong language and yields a few incidental nodes, so the graph looks populated
while the real symbols are missing. A project can now declare what an extension
means via `language.<ext>=<language|.ext>` lines in `.graphifyrc` (which already
holds `viz_node_limit`). The declaration flows through file classification,
extractor selection, grammar/resolution, imports, watch, and the AST cache
(salt + manifest language field + incremental invalidation), is thread-local
per scan root, and is forwarded to the worker pool. Default detection is
byte-for-byte unchanged when no declaration is present.

Landed from PR #3789 (squashed), which carried @abhay-codes07's original #3075
forward with reviewed follow-ups. Authorship credited to both contributors.

Co-Authored-By: Andre Brait <andrebrait@gmail.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
committed 2026-10-12 12:16:17 +01:00
1 parent 41418864aa
commit 9c66fd30dc
23 files changed
+1866 -125

No files matched your search

+23
View File
@@ -384,6 +384,29 @@ See the [full command reference](#full-command-reference) below.
graphify honors `.gitignore` and supports `--exclude` patterns and a project `.graphifyignore`. Details: **[Configuration](https://docs.graphify.com/reference/configuration)**.
## Project configuration
Create a `.graphifyrc` in the scan root for settings that belong to the project rather than to one run. One `key=value` per line; lines beginning with `#` are comments.
**Ambiguous extensions.** Some extensions mean different languages in different projects: `.inc` is PHP on pfSense, Pascal in a Delphi tree, SQL or assembly elsewhere; `.h` is C or C++; `.m` is Objective-C or MATLAB. graphify has to pick one global default, and when it picks wrong the file does not fail — it parses as the wrong language and yields a handful of incidental nodes, so the graph looks populated while the real symbols are missing. Declare what the extension means in your repo:
```
# .graphifyrc
# A language name:
language.inc=php
# Or an extension graphify already knows:
language.tpl=.ts
# Baked into the git hooks (see Team setup):
viz_node_limit=0
```
The declaration controls file classification, extractor selection and language-specific grammar and resolution, and the AST cache: a file re-parsed under a different language never reuses the old entry. Original source paths and physical format conventions, such as Fortran `.F90` preprocessing and C/C++ header/implementation pairing, are preserved. Optional language backends must still be installed. A typo is reported once on stderr and the scan continues with graphify's defaults.
Adding, changing, or removing a language declaration invalidates affected incremental manifest entries even when the source bytes have not changed. `graphify watch` recognizes declared source extensions and root `.graphifyrc` changes, including atomic replacement; configuration changes schedule an AST rebuild and flag semantic work for the next extraction. The same configuration is read by `graphify extract`, `graphify update`, the hooks, the MCP server, and the `/graphify` skill.
Extensionless local JS/TS imports can also resolve declared suffixes. Native suffixes retain precedence within file and directory-index lookup, and file candidates are tried before directory indexes. Python module and package lookups also support declared Python suffixes, while retaining native `.py` precedence.
---
## Team setup
+20 -3
View File
@@ -1044,11 +1044,19 @@ def cache_dir(root: Path = Path("."), kind: str = "ast",
return d
def _salted_key(h: str, salt: str | None) -> str:
"""Derive the on-disk key from a content hash plus optional salt."""
if not salt:
return h
return hashlib.sha256(f"{h}:{salt}".encode("utf-8")).hexdigest()
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
cache_root: Path | None = None, prompt: "str | Path | None" = None,
prompt_file: "str | Path | None" = None,
allow_legacy: bool = True,
allow_partial: bool = False) -> dict | None:
allow_partial: bool = False,
salt: str | None = None) -> dict | None:
"""Return cached extraction for this file if hash matches, else None.
Cache key: SHA256 of file contents.
@@ -1077,6 +1085,10 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
so :func:`check_semantic_cache` can report N to the user. Callers that must
not mix vintages within one entry (see :func:`save_semantic_cache`'s
``merge_existing``) pass allow_legacy=False.
``salt`` folds extra material into the key for an entry whose validity
depends on more than the file's bytes — a file the project remaps to
another language (#2961) parses to a different graph from the same
content, so it must not hit the entry produced under the old extractor.
Returns None if no cache entry or file has changed.
"""
global _legacy_semantic_hits, _corrupt_cache_entries
@@ -1085,6 +1097,7 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
h = file_hash(path, root, cache_root=cache_root)
except OSError:
return None
h = _salted_key(h, salt)
prompt_fp = _resolve_prompt_fp(prompt, prompt_file)
entry = cache_dir(location, kind, prompt_fp) / f"{h}.json"
legacy_hit = False
@@ -1191,9 +1204,13 @@ def _present_target_files(result: dict, root: Path) -> list[str]:
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast",
cache_root: Path | None = None, prompt: "str | Path | None" = None,
prompt_file: "str | Path | None" = None) -> None:
prompt_file: "str | Path | None" = None,
salt: str | None = None) -> None:
"""Save extraction result for this file.
``salt`` must match what the corresponding :func:`load_cached` passes
(see there); it namespaces the key, not the directory.
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
result should be a dict with 'nodes' and 'edges' lists.
@@ -1244,7 +1261,7 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
# the entry replays portably under any root (#2257). Strictly after the
# source_file pass, which owns that field's bare-relative format.
_relativize_ids_in(on_disk, p, root)
h = file_hash(p, root, cache_root=cache_root)
h = _salted_key(file_hash(p, root, cache_root=cache_root), salt)
location = cache_root if cache_root is not None else root
target_dir = cache_dir(location, kind, _resolve_prompt_fp(prompt, prompt_file))
entry = target_dir / f"{h}.json"
-1
View File
@@ -29,7 +29,6 @@ from graphify.interface_dispatch import ( # noqa: F401 (re-exported for caller
_CSHARP_SUFFIXES = (".cs",)
def resolve_csharp_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
+26 -2
View File
@@ -23,6 +23,7 @@ from graphify.google_workspace import (
google_workspace_enabled,
)
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME, out_path
from graphify.rcfile import activate_language_overrides, cache_salt, effective_suffix
class FileType(str, Enum):
@@ -525,7 +526,9 @@ def classify_file(path: Path) -> FileType | None:
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
ext = path.suffix.lower()
# A project may declare what an ambiguous extension means to it
# (.graphifyrc `language.inc=php`, #2961); classify by the declared one.
ext = effective_suffix(path).lower()
if not ext:
return _shebang_file_type(path)
if ext in CODE_EXTENSIONS:
@@ -1883,6 +1886,9 @@ def _resolves_under_root(path: Path, root: Path) -> bool:
def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace: bool | None = None, extra_excludes: list[str] | None = None, cache_root: Path | None = None, gitignore: bool = True) -> dict:
root = root.resolve()
# The project's extension->language declarations (#2961) shape
# classification for this scan.
activate_language_overrides(root)
configured_out_dir = root / GRAPHIFY_OUT
configured_out_names = {configured_out_dir.name}
try:
@@ -2569,6 +2575,9 @@ def save_manifest(
re-queues the file after the failure is fixed, without deleting
graphify-out/.
"""
# Another root may have activated different overrides in this thread.
if root is not None:
activate_language_overrides(Path(root))
existing = load_manifest(manifest_path, root=root)
# Index both raw and NFC forms so scan/clear membership survives the
@@ -2705,12 +2714,19 @@ def save_manifest(
mtime, h = hashed[f]
key = _nfc(f)
prev = _normalise_entry(existing.get(key, {})) or {}
# Hash workers do not inherit this thread's language overrides.
current_lang = cache_salt(f)
lang_changed = current_lang != prev.get("language")
if kind in ("ast", "both"):
ast_h = h
elif lang_changed:
ast_h = ""
else:
ast_h = prev.get("ast_hash", "")
if kind in ("semantic", "both"):
sem_h = h
elif lang_changed:
sem_h = ""
else:
# Preserve semantic_hash only when content is unchanged
sem_h = prev.get("semantic_hash", "") if h == prev.get("ast_hash", "") else ""
@@ -2723,6 +2739,7 @@ def save_manifest(
and mtime == prev.get("mtime")
and (ast_h == prev.get("ast_hash", "") if kind in ("ast", "both") else True)
and (sem_h == prev.get("semantic_hash", "") if kind in ("semantic", "both") else True)
and not lang_changed
and not _in_clear_ast(f)
and not _in_clear(f)
)
@@ -2732,6 +2749,9 @@ def save_manifest(
"ast_hash": ast_h,
"semantic_hash": sem_h,
}
if current_lang is not None:
# No override keeps legacy rows unchanged.
entry["language"] = current_lang
manifest[key] = entry
if storage_root is not None:
manifest = _collapse_manifest_duplicates(
@@ -2867,7 +2887,11 @@ def detect_incremental(
# the graph drifted from disk (#1859). No stored hash means we
# cannot verify content — any mtime delta forces a re-extract,
# and the next save promotes the entry into the dict schema.
if isinstance(stored, (int, float)):
# A language change invalidates even identical bytes and legacy rows.
stored_lang = stored.get("language") if isinstance(stored, dict) else None
if stored is not None and cache_salt(f) != stored_lang:
changed = True
elif isinstance(stored, (int, float)):
changed = current_mtime != stored
elif isinstance(stored, dict):
# Normalise legacy {mtime, hash} to new schema
+83 -41
View File
@@ -29,6 +29,13 @@ from .pascal_resolution import resolve_pascal_inherited_calls
from .markdown_resolution import MARKDOWN_MENTION_SUFFIXES, resolve_markdown_mentions
# --- migrated to graphify/extractors/ (see graphify/extractors/MIGRATION.md) ---
from graphify.rcfile import (
activate_language_overrides,
cache_salt,
effective_suffix,
get_language_overrides,
set_language_overrides,
)
from graphify.extractors.base import ( # noqa: F401
_LANGUAGE_BUILTIN_GLOBALS,
_file_stem,
@@ -43,6 +50,8 @@ from graphify.extractors.blade import extract_blade # noqa: F401
from graphify.extractors.cobol import extract_cobol # noqa: F401
from graphify.extractors.csharp import (
CsharpNameResolver,
_is_cs_file,
_is_dotnet_source_file,
_resolve_cross_file_csharp_imports,
_resolve_csharp_type_references,
)
@@ -102,6 +111,7 @@ from graphify.extractors.resolution import ( # noqa: E402,F401
_disambiguate_colliding_node_ids,
_find_workspace_root,
_go_import_path_for_file,
_is_python_package_dir,
_is_type_like_definition,
_js_call_identifier,
_js_default_export_name,
@@ -430,7 +440,7 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
the edge dangles and is silently dropped — the graph loses most ``imports``
edges purely because of where the scan started. Build an alias map from the
dotted-module id to the real file-node id by detecting each ``.py`` file's
package root (the contiguous run of ancestor dirs carrying ``__init__.py``)
package root (the contiguous run of ancestor dirs carrying a Python initializer)
and rewrite matching ``imports``/``imports_from`` edge targets. Guards: never
shadow an existing node id, and drop an alias claimed by more than one file
(ambiguous -> leave dangling, as before). Files whose package root IS the
@@ -442,7 +452,7 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
node_ids = {n.get("id") for n in all_nodes if isinstance(n, dict)}
alias_to_files: dict[str, set[str]] = {}
for p in paths:
if p.suffix.lower() not in (".py", ".pyi"):
if effective_suffix(p).lower() not in (".py", ".pyi"):
continue
try:
rel = Path(p).resolve().relative_to(root)
@@ -455,7 +465,7 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
levels = 0
# Bounded by the number of dirs between the file and the scan root, so a
# pathological `/__init__.py` chain can't loop forever.
while levels < len(parts) - 1 and (d / "__init__.py").is_file():
while levels < len(parts) - 1 and _is_python_package_dir(d):
levels += 1
d = d.parent
if levels == 0:
@@ -466,7 +476,11 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
file_node = _file_node_id(rel)
alias = _make_id(str(Path(*mod_parts).with_suffix("")))
alias_to_files.setdefault(alias, set()).add(file_node)
if p.name in ("__init__.py", "__init__.pyi") and len(mod_parts) > 1:
if (
p.stem == "__init__"
and effective_suffix(p) in (".py", ".pyi")
and len(mod_parts) > 1
):
# `import pkg` / `from pkg import x` targets the package-dir id.
pkg_alias = _make_id(str(Path(*mod_parts[:-1])))
alias_to_files.setdefault(pkg_alias, set()).add(file_node)
@@ -485,7 +499,7 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
if (
isinstance(e, dict)
and e.get("relation") in ("imports", "imports_from")
and str(e.get("source_file", "")).lower().endswith((".py", ".pyi"))
and effective_suffix(str(e.get("source_file", ""))).lower() in (".py", ".pyi")
):
tgt = e.get("target")
if tgt in alias_map:
@@ -494,10 +508,10 @@ def _repoint_python_package_imports(paths, all_nodes, all_edges, root) -> None:
def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
"""Repoint Python sibling-import edges to the real file node in directories
without an __init__.py (#3430).
without a Python package initializer (#3430).
When a Python file below the scan root lives in a non-package directory
(no __init__.py in its immediate parent), plain imports of same-directory
(no package initializer in its immediate parent), plain imports of same-directory
modules (e.g. `scripts/main.py: import greeter`) target a bare name (`greeter`),
while the real file node is scan-root-relative (`scripts_greeter`). Because
the directory is not a package, `_repoint_python_package_imports` skips it
@@ -505,7 +519,7 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
(`greeter.greet()`) to be dropped.
This pass is strictly importer-directory-local:
- Only applies when the importing file's parent directory has no __init__.py.
- Only applies when the importing file's parent directory has no package initializer.
- Resolves only to unambiguous same-directory candidate modules in the scanned corpus.
- Never builds a global alias map and never searches outside the importer's directory.
- Preserves local aliases (e.g. `import greeter as g`).
@@ -521,7 +535,7 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
# dir_path -> {module_name_id: set_of_file_node_ids}
dir_siblings: dict[Path, dict[str, set[str]]] = {}
for p in paths:
if p.suffix.lower() not in (".py", ".pyi"):
if effective_suffix(p).lower() not in (".py", ".pyi"):
continue
try:
p_res = Path(p).resolve()
@@ -533,7 +547,7 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
if file_node not in node_ids:
continue
if p_res.name in ("__init__.py", "__init__.pyi"):
if p_res.stem == "__init__" and effective_suffix(p_res) in (".py", ".pyi"):
# Sibling package directory inside parent_dir (parent_dir / subpkg / __init__.py)
pkg_dir = p_res.parent
parent_dir = pkg_dir.parent
@@ -541,7 +555,7 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
# capture a bare `import logging`, which means the stdlib module (#4261).
if pkg_dir.name in _PYTHON_STDLIB_MODULE_NAMES:
continue
if not (parent_dir / "__init__.py").is_file() and not (parent_dir / "__init__.pyi").is_file():
if not _is_python_package_dir(parent_dir, (".py", ".pyi")):
mod_key = _make_id(pkg_dir.name)
dir_siblings.setdefault(parent_dir, {}).setdefault(mod_key, set()).add(file_node)
continue
@@ -549,7 +563,7 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
d = p_res.parent
# PEP 328 guard: if the directory is a package, implicit relative imports
# are forbidden in Python 3. Do not index packages as loose sibling directories.
if (d / "__init__.py").is_file() or (d / "__init__.pyi").is_file():
if _is_python_package_dir(d, (".py", ".pyi")):
continue
# A loose module named like a stdlib module (e.g. `logging.py`) must not
@@ -577,7 +591,7 @@ def _repoint_python_sibling_imports(paths, all_nodes, all_edges, root) -> None:
if not (
isinstance(e, dict)
and e.get("relation") in ("imports", "imports_from")
and str(e.get("source_file", "")).lower().endswith((".py", ".pyi"))
and effective_suffix(str(e.get("source_file", ""))).lower() in (".py", ".pyi")
):
continue
@@ -2148,7 +2162,7 @@ def extract_python(path: Path, *, root: Path | None = None) -> dict:
def extract_js(path: Path) -> dict:
"""Extract classes, functions, arrow functions, and imports from a .js/.ts/.tsx/.mts/.cts file."""
suffix = path.suffix.lower()
suffix = effective_suffix(path).lower()
is_ts = suffix in (".ts", ".tsx", ".mts", ".cts")
if suffix == ".tsx":
config = _TSX_CONFIG
@@ -3390,7 +3404,7 @@ def _lang_is_case_insensitive(source_file: object) -> bool:
"""True when the file's language resolves identifiers case-insensitively (#1581)."""
if not source_file:
return False
return Path(str(source_file)).suffix.lower() in _CASE_INSENSITIVE_EXTS
return effective_suffix(str(source_file)).lower() in _CASE_INSENSITIVE_EXTS
# Language interop families for cross-file call resolution. A call in one language
@@ -3440,7 +3454,7 @@ def _lang_family(source_file: object) -> str | None:
"""Interop family of the file's language, or None when unknown/not code."""
if not source_file:
return None
return _LANG_FAMILY_BY_EXT.get(Path(str(source_file)).suffix.lower())
return _LANG_FAMILY_BY_EXT.get(effective_suffix(str(source_file)).lower())
# A language's own built-in throwable hierarchy, keyed by the interop family of
@@ -3667,7 +3681,7 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
for edge in edges:
is_csharp_scoped_edge = (
str(edge.get("source_file", "")).endswith((".cs", ".razor", ".cshtml"))
_is_dotnet_source_file(str(edge.get("source_file", "")))
and edge.get("relation") in csharp_scoped_relations
)
source = edge.get("source")
@@ -3675,7 +3689,7 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
remapped_source = remap[str(source)]
if not (
is_csharp_scoped_edge
and str(by_id.get(remapped_source, {}).get("source_file", "")).endswith(".cs")
and _is_cs_file(str(by_id.get(remapped_source, {}).get("source_file", "")))
) and not _cross_language_candidate(edge, remapped_source):
edge["source"] = remapped_source
target = edge.get("target")
@@ -3683,7 +3697,7 @@ def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
remapped_target = remap[str(target)]
if not (
is_csharp_scoped_edge
and str(by_id.get(remapped_target, {}).get("source_file", "")).endswith(".cs")
and _is_cs_file(str(by_id.get(remapped_target, {}).get("source_file", "")))
) and not _names_own_builtin_base(
edge, str(target), remapped_target
) and not _cross_language_candidate(edge, remapped_target):
@@ -3866,7 +3880,7 @@ def _merge_csharp_partial_class_nodes(
"""
groups: dict[tuple[str, str], list[dict]] = {}
for n in all_nodes:
if not str(n.get("source_file", "")).endswith(".cs"):
if not _is_cs_file(str(n.get("source_file", ""))):
continue
if n.get("file_type") != "code":
continue
@@ -4926,7 +4940,7 @@ def _resolve_csharp_member_calls(
if e.get("relation") != "inherits":
continue
src_file = e.get("source_file")
if not (isinstance(src_file, str) and src_file.endswith(".cs")):
if not _is_cs_file(src_file):
continue
src, tgt = e.get("source"), e.get("target")
if not (isinstance(src, str) and isinstance(tgt, str)):
@@ -7578,6 +7592,12 @@ def _get_extractor(path: Path) -> Any | None:
# (#1377). apm.yml would otherwise be a .yml document handled by the LLM.
if is_package_manifest_path(path):
return extract_package_manifest
# A project-declared remap (.graphifyrc `language.inc=php`, #2961) wins
# over every sniff below: the user has said what the extension means in
# this repo, so a remapped `.h`/`.m` also skips the C++/ObjC probes.
remapped = effective_suffix(path)
if remapped != path.suffix:
return _DISPATCH.get(remapped) or _DISPATCH.get(remapped.lower())
# `.h` is C/C++/ObjC-ambiguous; route Objective-C headers to extract_objc
# (the suffix map sends `.h` to extract_c, which can't read @interface etc.).
# ObjC sniffing has priority over the C++ sniff: an Objective-C++ header can
@@ -7620,6 +7640,13 @@ def _safe_extract_with_xaml_root(extractor, path: Path, root: Path) -> dict:
_XAML_ACTIVE_EXTRACT_ROOT = previous_root
def _worker_init(language_overrides: dict[str, str]) -> None:
"""Pool initializer. Under ``spawn`` a worker re-imports the package and
starts with no overrides; hand it the parent's so `_get_extractor` and the
cache key agree across processes (#2961)."""
set_language_overrides(language_overrides)
def _extract_single_file(args: tuple) -> tuple[int, dict]:
"""Worker function for parallel extraction. Runs in a subprocess.
@@ -7644,11 +7671,11 @@ def _extract_single_file(args: tuple) -> tuple[int, dict]:
root = Path(root_str)
cache_location = Path(cache_location_str)
_raise_recursion_limit()
bypass_cache = path.suffix in _JS_CACHE_BYPASS_SUFFIXES
bypass_cache = effective_suffix(path) in _JS_CACHE_BYPASS_SUFFIXES
# Check cache first (avoid re-extraction)
if not bypass_cache:
cached = load_cached(path, root, cache_root=cache_location)
cached = load_cached(path, root, cache_root=cache_location, salt=cache_salt(path))
if cached is not None:
return idx, cached
@@ -7665,7 +7692,7 @@ def _extract_single_file(args: tuple) -> tuple[int, dict]:
# An intentional decline or virtual workspace root (result.get("skipped"))
# is cached so repeat runs do not re-extract and re-report it (#3910).
if not bypass_cache and "error" not in result and (result.get("nodes") or result.get("skipped")):
save_cached(path, result, root, cache_root=cache_location)
save_cached(path, result, root, cache_root=cache_location, salt=cache_salt(path))
return idx, result
@@ -7769,7 +7796,11 @@ def _extract_parallel(
failed: list[int] = [] # positions into uncached_work whose future failed
_PROGRESS_INTERVAL = 100
try:
with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as pool:
with concurrent.futures.ProcessPoolExecutor(
max_workers=max_workers,
initializer=_worker_init,
initargs=(get_language_overrides(),),
) as pool:
futures = {
pool.submit(_extract_single_file, item): pos
for pos, item in enumerate(work_items)
@@ -7873,13 +7904,13 @@ def _extract_sequential(
if extractor is None:
per_file[idx] = {"nodes": [], "edges": []}
continue
bypass_cache = path.suffix in _JS_CACHE_BYPASS_SUFFIXES
bypass_cache = effective_suffix(path) in _JS_CACHE_BYPASS_SUFFIXES
# XAML boundary anchors on `root` (the corpus), not the cache location.
result = _safe_extract_with_xaml_root(extractor, path, root)
# See _extract_single_file: don't cache an anomalous zero-node result (#1666),
# but cache intentional declines/virtual manifests carrying `skipped` (#3910).
if not bypass_cache and "error" not in result and (result.get("nodes") or result.get("skipped")):
save_cached(path, result, root, cache_root=cache_location)
save_cached(path, result, root, cache_root=cache_location, salt=cache_salt(path))
per_file[idx] = result
if total_files >= _PROGRESS_INTERVAL:
# Consistent denominator with the intermediate lines (#1693).
@@ -8010,6 +8041,17 @@ def extract(
if len(module_paths) > 1 and module_id not in scan_root_aliases
}
# Project-level extension->language declarations (#2961). detect() has
# usually activated them for this root already; a direct library caller
# (the skill runbook, the MCP server, the issue's own repro) gets them here.
_overrides = activate_language_overrides(root)
if _overrides:
print(
" language overrides (.graphifyrc): "
+ ", ".join(f"{k} -> {v}" for k, v in sorted(_overrides.items())),
flush=True,
)
# #1774: the cache is an OUTPUT, so when no explicit cache_root is given it is
# written under the current working directory — never `root` (the inferred
# common parent of the inputs), which would drop graphify-out/ inside a
@@ -8027,9 +8069,9 @@ def extract(
if _get_extractor(path) is None:
per_file[i] = {"nodes": [], "edges": []}
continue
bypass_cache = path.suffix in _JS_CACHE_BYPASS_SUFFIXES
bypass_cache = effective_suffix(path) in _JS_CACHE_BYPASS_SUFFIXES
if not bypass_cache:
cached = load_cached(path, root, cache_root=cache_location)
cached = load_cached(path, root, cache_root=cache_location, salt=cache_salt(path))
if cached is not None:
per_file[i] = cached
continue
@@ -8139,7 +8181,7 @@ def extract(
from graphify.detect import CODE_EXTENSIONS as _CODE_EXTS
_no_extractor: dict[str, int] = {}
for _p in paths:
_ext = _p.suffix.lower()
_ext = effective_suffix(_p).lower()
if _ext in _CODE_EXTS and _get_extractor(_p) is None:
_no_extractor[_ext] = _no_extractor.get(_ext, 0) + 1
if _no_extractor:
@@ -8166,7 +8208,7 @@ def extract(
for i, _p in enumerate(paths):
_err = (per_file[i] or {}).get("error") or ""
if _DEP_MISSING_MARKER in _err or _DEP_LOAD_FAILED_MARKER in _err:
_ext = _p.suffix.lower()
_ext = effective_suffix(_p).lower()
_missing_dep_count[_ext] = _missing_dep_count.get(_ext, 0) + 1
_missing_dep_error.setdefault(_ext, _err)
for _ext, _n in sorted(_missing_dep_count.items(), key=lambda kv: (-kv[1], kv[0])):
@@ -8772,7 +8814,7 @@ def extract(
_php_exts = {".php", ".phtml", ".php3", ".php4", ".php5", ".php7", ".phps"}
_php_sel = [
(r, p) for r, p in zip(per_file, paths)
if p.suffix.lower() in _php_exts and not p.name.lower().endswith(".blade.php")
if effective_suffix(p).lower() in _php_exts and not p.name.lower().endswith(".blade.php")
]
if _php_sel:
try:
@@ -8788,7 +8830,7 @@ def extract(
# internal class with that simple name, manufacturing a false hub. Parking
# such references on an FQN-labeled stub first prevents the merge, and
# import-exact resolution of internal references (#1318/#1744) still applies.
_java_sel = [(r, p) for r, p in zip(per_file, paths) if p.suffix == ".java"]
_java_sel = [(r, p) for r, p in zip(per_file, paths) if effective_suffix(p) == ".java"]
if _java_sel:
try:
_resolve_java_type_references(
@@ -8799,7 +8841,7 @@ def extract(
logging.getLogger(__name__).warning("Java type-reference resolution failed, skipping: %s", exc)
# Resolve internal Go pkg.Type references exactly and park external ones
# before the generic bare-label stub rewire can manufacture a collision.
_go_sel = [(r, p) for r, p in zip(per_file, paths) if p.suffix == ".go"]
_go_sel = [(r, p) for r, p in zip(per_file, paths) if effective_suffix(p) == ".go"]
if _go_sel:
try:
_resolve_go_type_references(
@@ -8813,9 +8855,9 @@ def extract(
"Go type-reference resolution failed, skipping: %s", exc
)
# Cross-file Python import resolution and type-reference repointing (#3252)
py_paths = [p for p in paths if p.suffix == ".py"]
py_paths = [p for p in paths if effective_suffix(p) == ".py"]
if py_paths:
py_results = [r for r, p in zip(per_file, paths) if p.suffix == ".py"]
py_results = [r for r, p in zip(per_file, paths) if effective_suffix(p) == ".py"]
try:
cross_file_edges = _resolve_cross_file_imports(
py_results, py_paths, all_nodes, all_edges,
@@ -8828,9 +8870,9 @@ def extract(
_rewire_unique_stub_nodes(all_nodes, all_edges)
# Cross-file Java import resolution
java_paths = [p for p in paths if p.suffix == ".java"]
java_paths = [p for p in paths if effective_suffix(p) == ".java"]
if java_paths:
java_results = [r for r, p in zip(per_file, paths) if p.suffix == ".java"]
java_results = [r for r, p in zip(per_file, paths) if effective_suffix(p) == ".java"]
try:
all_edges.extend(_resolve_cross_file_java_imports(java_results, java_paths))
except Exception as exc:
@@ -8841,9 +8883,9 @@ def extract(
# references edges left on shadow stubs, disambiguating same-named types by the
# referencing file's `using` directives + enclosing namespace (mirrors Java #1318).
_DOTNET_TYPE_EXTS = {".cs", ".razor", ".cshtml"}
cs_paths = [p for p in paths if p.suffix.lower() in _DOTNET_TYPE_EXTS]
cs_paths = [p for p in paths if effective_suffix(p).lower() in _DOTNET_TYPE_EXTS]
if cs_paths:
cs_results = [r for r, p in zip(per_file, paths) if p.suffix.lower() in _DOTNET_TYPE_EXTS]
cs_results = [r for r, p in zip(per_file, paths) if effective_suffix(p).lower() in _DOTNET_TYPE_EXTS]
try:
_resolve_csharp_type_references(cs_results, cs_paths, all_nodes, all_edges)
except Exception as exc:
@@ -9288,7 +9330,7 @@ def extract(
# legitimately call across files without an explicit import. Scoped to
# direct calls: the indirect_call path above is already conservative
# (INFERRED, callable-target-gated) and independent of import evidence.
if not has_import_evidence and str(rc.get("source_file", "")).endswith(_JS_TS_CALL_SUFFIXES):
if not has_import_evidence and effective_suffix(str(rc.get("source_file", ""))) in _JS_TS_CALL_SUFFIXES:
continue
if rc.get("via_stub") and not (has_import_evidence or stub_scope_hit):
continue
+5 -8
View File
@@ -14,6 +14,7 @@ import html
from pathlib import Path
from graphify.extractors.base import _make_id
from graphify.rcfile import effective_suffix
def _build_csharp_type_def_index(
@@ -58,11 +59,7 @@ def _build_csharp_type_def_index(
if all_edges is not None and nid in non_type_ids:
continue
source_file = node.get("source_file")
if (
not isinstance(source_file, str)
or not source_file.endswith(".cs")
or node.get("file_type") != "code"
):
if not _is_cs_file(source_file) or node.get("file_type") != "code":
continue
if label.endswith(")") or label.startswith(".") or "." in label:
continue
@@ -179,11 +176,11 @@ _DOTNET_SOURCE_EXTS = (".cs", ".razor", ".cshtml")
def _is_cs_file(value: object) -> bool:
return isinstance(value, str) and value.endswith(".cs")
return isinstance(value, str) and effective_suffix(value) == ".cs"
def _is_dotnet_source_file(value: object) -> bool:
return isinstance(value, str) and value.endswith(_DOTNET_SOURCE_EXTS)
return isinstance(value, str) and effective_suffix(value) in _DOTNET_SOURCE_EXTS
def _metadata(value: object) -> dict:
@@ -230,7 +227,7 @@ class CsharpNameResolver:
if not (
source_node
and isinstance(source_node.get("label"), str)
and source_node.get("label", "").endswith(_DOTNET_SOURCE_EXTS)
and _is_dotnet_source_file(source_node.get("label"))
):
continue
source_file = source_node.get("source_file")
+2 -1
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes, _read_text
from graphify.rcfile import effective_suffix
def extract_ocaml(path: Path) -> dict:
@@ -21,7 +22,7 @@ def extract_ocaml(path: Path) -> dict:
return {"nodes": [], "edges": [], "error": "tree-sitter-ocaml not installed"}
try:
if path.suffix == ".mli":
if effective_suffix(path) == ".mli":
language = Language(tsocaml.language_ocaml_interface())
else:
language = Language(tsocaml.language_ocaml())
+74 -22
View File
@@ -12,6 +12,7 @@ from graphify.extractors.base import ( # noqa: F401
_read_source_text,
_read_text,
)
from graphify.rcfile import effective_suffix, get_language_overrides
import functools
import hashlib
import json
@@ -36,6 +37,18 @@ _JS_RESOLVE_EXTS = (".ts", ".tsx", ".mts", ".cts", ".svelte", ".js", ".jsx", ".m
_JS_INDEX_FILES = ("index.ts", "index.tsx", "index.svelte", "index.js", "index.jsx", "index.mjs")
def _declared_language_suffixes(target_exts: tuple[str, ...]) -> tuple[str, ...]:
"""Return declared literal suffixes for these languages in deterministic order."""
# Mapping keys must be single suffixes, never relative path fragments.
suffixes = [
source_ext
for source_ext, target_ext in get_language_overrides().items()
if target_ext in target_exts
and Path(f"x{source_ext}").suffix == source_ext
]
return tuple(sorted(suffixes))
def _resolve_js_import_path(candidate: Path) -> Path:
"""Resolve a JS/TS/Svelte import target to a local file when it exists."""
candidate = Path(os.path.normpath(candidate))
@@ -48,24 +61,32 @@ def _resolve_js_import_path(candidate: Path) -> Path:
# TS ESM convention: imports often spell .js/.jsx while source is .ts/.tsx.
if candidate.suffix == ".js":
ts_candidate = candidate.with_suffix(".ts")
if ts_candidate.is_file():
if ts_candidate.is_file() and effective_suffix(ts_candidate) in _JS_CACHE_BYPASS_SUFFIXES:
return ts_candidate
elif candidate.suffix == ".jsx":
tsx_candidate = candidate.with_suffix(".tsx")
if tsx_candidate.is_file():
if tsx_candidate.is_file() and effective_suffix(tsx_candidate) in _JS_CACHE_BYPASS_SUFFIXES:
return tsx_candidate
declared_exts = _declared_language_suffixes(_JS_RESOLVE_EXTS)
# Append extensions to the full filename, which covers extensionless imports,
# multi-dot helpers, and Svelte 5 rune files like Foo.svelte.ts.
for ext in _JS_RESOLVE_EXTS:
# Native suffixes retain precedence over declared ones.
for ext in _JS_RESOLVE_EXTS + declared_exts:
with_ext = candidate.parent / f"{candidate.name}{ext}"
if with_ext.is_file():
if with_ext.is_file() and effective_suffix(with_ext) in _JS_CACHE_BYPASS_SUFFIXES:
return with_ext
# Only fall back to directory indexes after file candidates lose.
# Only fall back to directory indexes after file candidates lose, native
# index names before declared ones.
if candidate.is_dir():
for index_name in _JS_INDEX_FILES:
index_candidate = candidate / index_name
if index_candidate.is_file() and effective_suffix(index_candidate) in _JS_CACHE_BYPASS_SUFFIXES:
return index_candidate
for ext in declared_exts:
index_candidate = candidate / f"index{ext}"
if index_candidate.is_file():
return index_candidate
@@ -1692,17 +1713,17 @@ def _parse_js_tree(path: Path):
# .vue embeds the script in non-JS markup; mask it out and parse the
# <script> with TS.
vue_lang: str | None = None
if path.suffix == ".vue":
if effective_suffix(path) == ".vue":
masked, vue_lang = _vue_mask_non_script(
_read_source_text(path, warn=False)
)
source = masked.encode("utf-8")
else:
source = _read_source_bytes(path, warn=False)
use_ts = path.suffix in (".ts", ".mts", ".cts") or (
path.suffix == ".vue" and vue_lang not in ("js", "jsx")
use_ts = effective_suffix(path) in (".ts", ".mts", ".cts") or (
effective_suffix(path) == ".vue" and vue_lang not in ("js", "jsx")
)
if path.suffix == ".tsx":
if effective_suffix(path) == ".tsx":
# .tsx must use the JSX-aware TSX grammar, mirroring the engine's
# _TSX_CONFIG (ts_language_fn="language_tsx"). Parsing .tsx with
# language_typescript misparses JSX, and tree-sitter's error
@@ -2113,7 +2134,7 @@ _JS_FACT_NODE_TYPES = frozenset({
def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolutionFacts) -> None:
js_paths = [
path for path in paths
if path.suffix in _JS_CACHE_BYPASS_SUFFIXES
if effective_suffix(path) in _JS_CACHE_BYPASS_SUFFIXES
]
if not js_paths:
return
@@ -2402,21 +2423,46 @@ def _python_imported_names(node, source: bytes) -> list[tuple[str, str]]:
names.append((name, local))
return names
def _is_python_package_dir(directory: Path, suffixes: tuple[str, ...] = (".py",)) -> bool:
if any(
(directory / f"__init__{suffix}").is_file()
and effective_suffix(directory / f"__init__{suffix}") in suffixes
for suffix in suffixes
):
return True
return any(
(directory / f"__init__{suffix}").is_file()
for suffix in _declared_language_suffixes(suffixes)
if suffix not in suffixes
)
def _probe_declared_python_module_candidate(candidate: Path) -> Path | None:
for suffix in _declared_language_suffixes((".py",)):
init_path = candidate / f"__init__{suffix}"
if init_path.is_file():
return init_path
if candidate.name:
module_path = candidate.with_suffix(suffix)
if module_path.is_file():
return module_path
return None
def _probe_python_module_candidate(candidate: Path) -> Path | None:
"""Resolve one module-path candidate to a .py file (dir+__init__, exact, or
with a .py suffix), or None."""
"""Resolve native Python modules and packages before declared suffixes."""
if candidate.is_dir():
init_path = candidate / "__init__.py"
if init_path.is_file():
if init_path.is_file() and effective_suffix(init_path) == ".py":
return init_path
if candidate.is_file():
return candidate
if not candidate.name:
return None
return _probe_declared_python_module_candidate(candidate)
py_candidate = candidate.with_suffix(".py")
if py_candidate.is_file():
if py_candidate.is_file() and effective_suffix(py_candidate) == ".py":
return py_candidate
return None
return _probe_declared_python_module_candidate(candidate)
# Cache: scan root (resolved str) → dotted namespace prefix or ""
@@ -2575,7 +2621,7 @@ def _resolve_python_module_path(module_name: str, current_path: Path, root: Path
# implicit-relative semantics), fabricating edges to what may be an
# external dependency (#2072 review). A src-layout root (src/, no
# __init__.py) is still probed.
if (anc / "__init__.py").is_file():
if _is_python_package_dir(anc):
continue
cand = _accept(_probe_python_module_candidate(anc / rel))
if cand is not None:
@@ -2594,7 +2640,7 @@ def _resolve_python_namespace_dir(module_name: str, current_path: Path, root: Pa
scan root, then sys.path-root ancestors) and returns only a directory that
exists inside the root."""
def _namespace(candidate: Path) -> "Path | None":
if not candidate.is_dir() or (candidate / "__init__.py").is_file():
if not candidate.is_dir() or _is_python_package_dir(candidate):
return None
try:
_resolve_cached(candidate).relative_to(_resolve_cached(root))
@@ -2631,7 +2677,7 @@ def _resolve_python_namespace_dir(module_name: str, current_path: Path, root: Pa
anc.relative_to(root)
except ValueError:
break # left the scan root; stop walking up
if anc == root or (anc / "__init__.py").is_file():
if anc == root or _is_python_package_dir(anc):
continue # root already probed; a package dir is not a sys.path root (#2072)
hit = _namespace(anc / rel)
if hit is not None:
@@ -2665,7 +2711,7 @@ def _collect_python_symbol_resolution_facts(
ambiguous_python_modules: set[str] | None = None,
) -> None:
ambiguous_python_modules = ambiguous_python_modules or set()
py_paths = [path for path in paths if path.suffix == ".py"]
py_paths = [path for path in paths if effective_suffix(path) == ".py"]
if not py_paths:
return
@@ -2692,7 +2738,11 @@ def _collect_python_symbol_resolution_facts(
# (__init__.py) and an imported name matches a submodule file on
# disk, emit a file-level import edge to that submodule rather
# than only to the package.
pkg_dir = target_path.parent if target_path.name == "__init__.py" else None
pkg_dir = (
target_path.parent
if target_path.stem == "__init__" and effective_suffix(target_path) == ".py"
else None
)
else:
# A PEP 420 namespace package: the module names a directory with
# no __init__.py, so there is no module file to resolve to, but
@@ -2708,6 +2758,8 @@ def _collect_python_symbol_resolution_facts(
sub_py = pkg_dir / f"{imported_name}.py"
sub_pkg = pkg_dir / imported_name / "__init__.py"
submodule = sub_py if sub_py.is_file() else (sub_pkg if sub_pkg.is_file() else None)
if submodule is None:
submodule = _probe_declared_python_module_candidate(pkg_dir / imported_name)
if submodule is not None:
imported_module = (
f"{module_name}.{imported_name}"
@@ -2725,7 +2777,7 @@ def _collect_python_symbol_resolution_facts(
facts.imports.append(
_SymbolImportFact(path, local_name, target_path, imported_name, line)
)
if path.name == "__init__.py":
if path.stem == "__init__":
facts.exports.append(
_SymbolExportFact(
path,
+2 -1
View File
@@ -6,6 +6,7 @@ import re
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id
from graphify.rcfile import effective_suffix
# Robot Framework standard libraries - imports of these are noise (like the
@@ -159,7 +160,7 @@ def extract_robot(path: Path) -> dict:
add_node(file_nid, path.name, 1)
try:
if path.suffix.lower() == ".resource":
if effective_suffix(path).lower() == ".resource":
model = get_resource_model(str_path)
else:
model = get_model(str_path)
+6 -31
View File
@@ -552,39 +552,14 @@ echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY
"""
def _load_graphifyrc(root: Path) -> dict[str, str | int]:
"""Load key/value options from <root>/.graphifyrc if present.
def _load_graphifyrc(root: Path) -> dict:
"""Load ``<root>/.graphifyrc``; the parser lives in :mod:`graphify.rcfile`.
Supported options:
viz_node_limit: integer >= 0 (e.g. viz_node_limit=0)
Kept as the hooks-side name so callers and tests need not move. Returns
``viz_node_limit`` (used here) alongside any other option the file sets.
"""
rc_path = root / ".graphifyrc"
if not rc_path.is_file():
return {}
cfg: dict[str, str | int] = {}
content = rc_path.read_text(encoding="utf-8")
for line_num, raw in enumerate(content.splitlines(), 1):
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
raise ValueError(f"Invalid line {line_num} in {rc_path}: {raw!r} (expected key=value)")
key, val = line.split("=", 1)
key = key.strip()
val = val.strip()
if key == "viz_node_limit":
try:
parsed_val = int(val)
if parsed_val < 0:
raise ValueError("must be a non-negative integer")
cfg["viz_node_limit"] = parsed_val
except ValueError as exc:
raise ValueError(
f"Invalid viz_node_limit in {rc_path} at line {line_num}: {val!r}. "
f"Must be a non-negative integer."
) from exc
return cfg
from graphify.rcfile import load_graphifyrc
return load_graphifyrc(root)
def _git_root(path: Path) -> Path | None:
+8 -4
View File
@@ -31,6 +31,8 @@ protocols, for one) adds a wrapper, not a second copy of the algorithm.
"""
from __future__ import annotations
from graphify.rcfile import effective_suffix
DISPATCH_RELATION = "dispatches_to"
@@ -39,12 +41,14 @@ def declared_in(node: dict | None, suffixes: tuple[str, ...]) -> bool:
Every end of a dispatch pair has to pass this. A sourceless stub minted for
a dangling reference carries no members worth dispatching to, and a
cross-language pair is a name collision rather than an implementation.
cross-language pair is a name collision rather than an implementation. The
suffix is the effective one, so a `.graphifyrc` language declaration counts
(#2961).
"""
if not node:
return False
source_file = node.get("source_file")
return bool(source_file) and str(source_file).endswith(suffixes)
return bool(source_file) and effective_suffix(str(source_file)) in suffixes
def method_label(node: dict) -> str:
@@ -78,11 +82,11 @@ def resolve_interface_dispatch(
in a file with one of these extensions.
"""
if not any(
str(result.get("source_file", "")).endswith(suffixes)
declared_in(result, suffixes)
for result in per_file
if isinstance(result, dict)
) and not any(
str(n.get("source_file", "")).endswith(suffixes) for n in all_nodes
declared_in(n, suffixes) for n in all_nodes
):
return
+252
View File
@@ -0,0 +1,252 @@
"""Project-level configuration: ``<root>/.graphifyrc``.
One ``key=value`` per line, ``#`` comments, blank lines ignored. Keys:
``viz_node_limit=<int>``
Baked into the generated git hooks (see :mod:`graphify.hooks`).
``language.<ext>=<language | .ext>``
Treat files with extension ``<ext>`` as the named language for
classification, extractor dispatch and cross-file resolution (#2961).
``<ext>`` may be written with or without its leading dot; the value is
either a language name from :data:`LANGUAGE_ALIASES` or an explicit
extension graphify already knows (``.php``, ``.pas``, ``.sql``, ...)::
# pfSense: every .inc under this repo is PHP, not Pascal
language.inc=php
# a repo whose templates are plain TypeScript
language.tpl=.ts
An ambiguous extension (``.inc`` is PHP, Pascal, SQL or assembly
depending on the project; ``.m`` is Objective-C or MATLAB; ``.h`` is C or
C++) has no single correct global mapping, so the project declares it.
The parser imports :mod:`graphify.detect` lazily only when it must validate
an explicit extension. This avoids a module-level import cycle while keeping
typos from silently disabling classification.
"""
from __future__ import annotations
import sys
import threading
from pathlib import Path
RC_FILENAME = ".graphifyrc"
# Language name -> the canonical extension graphify dispatches it under.
# Deliberately a short list of names a user is likely to type; any known
# extension can be given directly instead (``language.inc=.php``).
LANGUAGE_ALIASES: dict[str, str] = {
"php": ".php",
"pascal": ".pas", "delphi": ".pas", "freepascal": ".pas",
"sql": ".sql",
"python": ".py",
"javascript": ".js", "js": ".js",
"typescript": ".ts", "ts": ".ts",
"c": ".c",
"cpp": ".cpp", "c++": ".cpp", "cxx": ".cpp",
"objc": ".mm", "objective-c": ".mm", "objectivec": ".mm",
"java": ".java",
"kotlin": ".kt",
"scala": ".scala",
"groovy": ".groovy",
"go": ".go", "golang": ".go",
"rust": ".rs",
"ruby": ".rb",
"csharp": ".cs", "c#": ".cs",
"swift": ".swift",
"lua": ".lua",
"zig": ".zig",
"elixir": ".ex",
"julia": ".jl",
"dart": ".dart",
"r": ".r",
"fortran": ".f90",
"shell": ".sh", "bash": ".sh", "sh": ".sh",
"powershell": ".ps1",
"verilog": ".v", "systemverilog": ".sv",
"terraform": ".tf", "hcl": ".hcl",
"ocaml": ".ml",
"lisp": ".lisp", "commonlisp": ".lisp",
"markdown": ".md",
"json": ".json",
"yaml": ".yaml",
"html": ".html",
}
def _normalise_ext(raw: str) -> str:
ext = raw.strip().lower()
if not ext.startswith("."):
ext = "." + ext
return ext
def parse_language_value(value: str) -> str:
"""Resolve the right-hand side of ``language.<ext>=`` to a canonical suffix.
Accepts a name from :data:`LANGUAGE_ALIASES` (case-insensitive) or an
explicit dotted extension. Raises ``ValueError`` for anything else.
"""
v = value.strip()
if not v:
raise ValueError("empty value")
if v.startswith("."):
ext = _normalise_ext(v)
if len(ext) < 2 or any(ch.isspace() for ch in ext):
raise ValueError(f"{value!r} is not an extension")
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS
if ext not in CODE_EXTENSIONS and ext not in DOC_EXTENSIONS:
raise ValueError(f"unknown extension {value!r}")
return ext
try:
return LANGUAGE_ALIASES[v.lower()]
except KeyError:
known = ", ".join(sorted(LANGUAGE_ALIASES))
raise ValueError(
f"unknown language {value!r} (use one of: {known}; "
f"or an explicit extension such as .php)"
) from None
def load_graphifyrc(root: Path) -> dict:
"""Parse ``<root>/.graphifyrc``. Returns ``{}`` when absent.
Returned keys: ``viz_node_limit`` (int) and ``languages``
(``{".inc": ".php", ...}``) — each present only when the file sets it.
Unknown keys are ignored so a newer graphify's options do not break an
older one. Malformed lines raise ``ValueError`` naming the line.
"""
rc_path = Path(root) / RC_FILENAME
if not rc_path.is_file():
return {}
cfg: dict = {}
languages: dict[str, str] = {}
content = rc_path.read_text(encoding="utf-8")
for line_num, raw in enumerate(content.splitlines(), 1):
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
raise ValueError(f"Invalid line {line_num} in {rc_path}: {raw!r} (expected key=value)")
key, val = line.split("=", 1)
key = key.strip()
val = val.strip()
if key == "viz_node_limit":
try:
parsed_val = int(val)
if parsed_val < 0:
raise ValueError("must be a non-negative integer")
cfg["viz_node_limit"] = parsed_val
except ValueError as exc:
raise ValueError(
f"Invalid viz_node_limit in {rc_path} at line {line_num}: {val!r}. "
f"Must be a non-negative integer."
) from exc
elif key.startswith("language."):
ext_part = key[len("language."):].strip()
if not ext_part or any(ch.isspace() for ch in ext_part):
raise ValueError(
f"Invalid language key in {rc_path} at line {line_num}: {key!r} "
f"(expected language.<ext>=<language>)"
)
try:
target = parse_language_value(val)
except ValueError as exc:
raise ValueError(
f"Invalid {key} in {rc_path} at line {line_num}: {exc}"
) from None
languages[_normalise_ext(ext_part)] = target
if languages:
cfg["languages"] = languages
return cfg
# ---------------------------------------------------------------------------
# Active overrides for this process
# ---------------------------------------------------------------------------
#
# detect()/extract() activate the scan root's overrides for the run; the
# extraction pool forwards them to its workers (they do not inherit module
# state under ``spawn``). Stored lower-cased on both sides.
# Thread-local, not module-global: two extractions can run concurrently in one
# process (an MCP server, a threaded harness) with different roots, and a shared
# dict let one scan's `activate_language_overrides` clobber the other's while
# `effective_suffix`/`classify_file`/`cache_salt` read it — cross-contaminating
# which extractor a `.inc`/`.m`/`.h` file gets (#2961 review). Each thread now
# carries its own overrides. The dominant paths are unaffected: the CLI runs on
# the main thread, and a spawn pool worker sets its own copy in `_worker_init`
# on its main thread, the same thread that then runs `_extract_single_file`.
_local = threading.local()
_warned_roots: set[str] = set() # warning-dedup only; harmless to share
def _active() -> dict[str, str]:
got = getattr(_local, "active", None)
if got is None:
got = {}
_local.active = got
return got
def set_language_overrides(mapping: dict[str, str] | None) -> None:
"""Replace this thread's extension overrides (``{".inc": ".php"}``)."""
active = _active()
active.clear()
if mapping:
for ext, target in mapping.items():
active[_normalise_ext(ext)] = _normalise_ext(target)
def get_language_overrides() -> dict[str, str]:
return dict(_active())
def activate_language_overrides(root: Path) -> dict[str, str]:
"""Load ``<root>/.graphifyrc`` and make its language overrides active.
A malformed file is reported once per root on stderr and treated as
having no overrides — a scan must not die on a config typo, but the
user must hear about it, or their ``.inc`` silently stays Pascal.
Returns the mapping now active.
"""
try:
cfg = load_graphifyrc(Path(root))
except (ValueError, OSError) as exc:
key = str(root)
if key not in _warned_roots:
_warned_roots.add(key)
print(f"[graphify] warning: ignoring {RC_FILENAME}: {exc}", file=sys.stderr)
cfg = {}
set_language_overrides(cfg.get("languages"))
return get_language_overrides()
def effective_suffix(path: Path | str) -> str:
"""The suffix graphify should treat ``path`` as having.
Returns the override target when the file's extension is remapped, else
the real suffix untouched (case preserved, so callers that distinguish
``.F90`` from ``.f90`` keep doing so).
"""
suffix = Path(path).suffix
active = _active()
if not active:
return suffix
return active.get(suffix.lower(), suffix)
def cache_salt(path: Path | str) -> str | None:
"""Extra cache-key material for a remapped file, else ``None``.
An AST cache entry is keyed by content, and the same bytes parse to a
different graph under a different extractor — so a ``.inc`` cached as
Pascal must not be served once the project declares it PHP.
"""
active = _active()
if not active:
return None
target = active.get(Path(path).suffix.lower())
return f"language={target}" if target else None
+4 -1
View File
@@ -75,7 +75,10 @@ def run_language_resolvers(
exercise the driver in isolation.
"""
active = _REGISTRY if resolvers is None else resolvers
suffixes_present = {p.suffix for p in paths}
# Honour project-level remaps (#2961): a `.inc` declared PHP must wake
# the PHP resolvers, not Pascal's.
from graphify.rcfile import effective_suffix
suffixes_present = {effective_suffix(p) for p in paths}
for resolver in active:
if not (resolver.suffixes & suffixes_present):
continue
+3 -2
View File
@@ -14,6 +14,7 @@ from graphify.extractors.base import _read_source_text
from graphify.ids import make_id as _shared_make_id
from graphify.paths import disambiguate_ambiguous_candidates
from graphify.security import sanitize_metadata
from graphify.rcfile import effective_suffix
@@ -262,14 +263,14 @@ def resolve_python_import_guided_calls(
# downstream `.get("raw_calls", [])` lookup never raises
result_by_file: dict[str, dict[str, Any]] = {}
for index, path in enumerate(paths):
if path.suffix != ".py":
if effective_suffix(path) != ".py":
continue
slot: Any = per_file[index] if index < len(per_file) else None
result_by_file[str(path)] = slot if isinstance(slot, dict) else {"nodes": [], "edges": []}
resolved_edges: list[dict[str, Any]] = []
for path in paths:
if path.suffix != ".py":
if effective_suffix(path) != ".py":
continue
source_file = str(path)
aliases = parse_python_import_aliases(path)
+31 -7
View File
@@ -371,6 +371,12 @@ from graphify.detect import (
_load_graphifyignore,
_is_ignored,
)
from graphify.rcfile import (
RC_FILENAME,
activate_language_overrides,
effective_suffix,
set_language_overrides,
)
_WATCHED_EXTENSIONS = CODE_EXTENSIONS | DOC_EXTENSIONS | PAPER_EXTENSIONS | IMAGE_EXTENSIONS
_CODE_EXTENSIONS = CODE_EXTENSIONS
@@ -2565,7 +2571,7 @@ def _notify_only(watch_path: Path) -> None:
def _has_non_code(changed_paths: list[Path]) -> bool:
return any(p.suffix.lower() not in _CODE_EXTENSIONS for p in changed_paths)
return any(effective_suffix(p).lower() not in _CODE_EXTENSIONS for p in changed_paths)
def _batch_triggers_rebuild(batch: list[Path]) -> bool:
@@ -2577,7 +2583,7 @@ def _batch_triggers_rebuild(batch: list[Path]) -> bool:
this, a doc-only deletion batch would sit behind the needs_update flag
until the next code event or a manual `graphify update` (#2580).
"""
has_code = any(p.suffix.lower() in _CODE_EXTENSIONS for p in batch)
has_code = any(effective_suffix(p).lower() in _CODE_EXTENSIONS for p in batch)
has_deletion = any(not p.exists() for p in batch)
return has_code or has_deletion
@@ -2644,12 +2650,26 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
gitignore=_read_build_gitignore(watch_path / _GRAPHIFY_OUT),
)
# Observer and dispatch threads need the same root-specific snapshot.
root_config_path = watch_root_for_ignore / RC_FILENAME
override_snapshot: dict[str, str] = activate_language_overrides(watch_root_for_ignore)
config_changed = False
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
nonlocal last_trigger, pending
nonlocal last_trigger, pending, override_snapshot, config_changed
if event.is_directory or _is_read_only_event(event):
return
path = Path(os.fsdecode(event.src_path))
# Atomic replacement reports the new root config in dest_path.
dest_raw = getattr(event, "dest_path", None)
dest_path = Path(os.fsdecode(dest_raw)) if dest_raw else None
if path == root_config_path or dest_path == root_config_path:
override_snapshot = activate_language_overrides(watch_root_for_ignore)
config_changed = True
last_trigger = time.monotonic()
pending = True
return
# Check .graphifyignore BEFORE the extension/dotfile/out filters so
# the cheapest short-circuit for users with broad ignore patterns
# (node_modules/, .venv/, build/, …) fires first. _is_ignored
@@ -2657,7 +2677,8 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
# relative_to guard, so a stray symlinked event won't raise.
if ignore_patterns and _is_ignored(path, watch_root_for_ignore, ignore_patterns):
return
if path.suffix.lower() not in _WATCHED_EXTENSIONS:
set_language_overrides(override_snapshot)
if effective_suffix(path).lower() not in _WATCHED_EXTENSIONS:
return
try:
filter_parts = path.relative_to(watch_root_for_ignore).parts
@@ -2674,7 +2695,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
handler = Handler()
# Use polling observer on macOS — FSEvents can miss rapid saves in some editors
observer = PollingObserver() if sys.platform == "darwin" else Observer()
observer.schedule(handler, str(watch_path), recursive=True)
observer.schedule(handler, str(watch_root_for_ignore), recursive=True)
observer.start()
print(f"[graphify watch] Watching {watch_path.resolve()} - press Ctrl+C to stop")
@@ -2689,10 +2710,13 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
pending = False
batch = list(changed)
changed.clear()
config_event, config_changed = config_changed, False
print(f"\n[graphify watch] {len(batch)} file(s) changed")
if _batch_triggers_rebuild(batch):
# Reapply the observer's snapshot on the dispatch thread.
set_language_overrides(override_snapshot)
if config_event or _batch_triggers_rebuild(batch):
_rebuild_code(watch_path)
if _batch_needs_llm_flag(batch):
if config_event or _batch_needs_llm_flag(batch):
_notify_only(watch_path)
except KeyboardInterrupt:
print("\n[graphify watch] Stopped.")
+25
View File
@@ -64,3 +64,28 @@ def test_all_extra_is_the_union_of_every_other_extra():
union = {dep for name, deps in extras.items() if name != "all" for dep in deps}
missing = sorted(union - set(extras["all"]))
assert not missing, f"[all] is missing dependencies from other extras: {missing}"
def _leiden_arms(extras: dict) -> dict[str, str]:
"""Map each `leiden` requirement to its interpreter marker."""
return {dep.split(";")[0].strip(): dep.partition(";")[2].strip() for dep in extras["leiden"]}
def test_leiden_extra_installs_a_working_backend_on_every_supported_python():
"""`_partition()` calls graspologic_native.leiden() first and falls back to
NetworkX Louvain when the binding is absent. graspologic's own metadata stops at
3.13, so below that it supplies the binding and from 3.13 the extra must name it
directly -- otherwise `[leiden]` installs nothing on a current interpreter and
clustering silently loses Leiden. The two arms must stay complementary and
exhaustive, or some interpreter is left with no backend."""
arms = _leiden_arms(_extras())
assert arms.get("graspologic") == "python_version < '3.13'", f"below-3.13 arm: {arms}"
native = [pkg for pkg in arms if pkg.startswith("graspologic-native")]
assert len(native) == 1, f"expected exactly one graspologic-native arm, got {arms}"
assert arms[native[0]] == "python_version >= '3.13'", f"3.13+ arm: {arms}"
assert len(arms) == 2, f"a third arm leaves the gate ambiguous: {arms}"
def test_all_extra_gates_leiden_the_same_way():
extras = _extras()
assert set(extras["leiden"]) <= set(extras["all"]), "[all] must carry both leiden arms"
+1 -1
View File
@@ -491,7 +491,7 @@ def test_collect_files_from_dir():
def test_collect_files_skips_hidden():
files = collect_files(FIXTURES)
for f in files:
assert not any(part.startswith(".") for part in f.parts)
assert not any(part.startswith(".") for part in f.relative_to(FIXTURES).parts)
def test_collect_files_follows_symlinked_directory(requires_symlinks, tmp_path):
+178
View File
@@ -0,0 +1,178 @@
"""Declared JS-family suffixes participate in local extensionless imports."""
import pytest
from graphify.extractors.resolution import _resolve_js_module_path
from graphify.rcfile import activate_language_overrides, set_language_overrides
@pytest.fixture(autouse=True)
def reset_overrides():
set_language_overrides(None)
yield
set_language_overrides(None)
@pytest.mark.parametrize("relative", ["dep.tpl", "dep/index.tpl"])
def test_extensionless_import_finds_declared_source_or_directory_index(tmp_path, relative):
(tmp_path / ".graphifyrc").write_text("language.tpl=typescript\n")
source = tmp_path / relative
source.parent.mkdir(parents=True, exist_ok=True)
source.write_text("export function chosen() {}\n")
activate_language_overrides(tmp_path)
assert _resolve_js_module_path("./dep", tmp_path) == source
@pytest.mark.parametrize("directory", [False, True])
def test_native_source_precedence_and_literal_declared_paths_are_preserved(tmp_path, directory):
(tmp_path / ".graphifyrc").write_text("language.tpl=typescript\n")
stem = tmp_path / ("dep/index" if directory else "dep")
stem.parent.mkdir(parents=True, exist_ok=True)
native, declared = stem.with_suffix(".ts"), stem.with_suffix(".tpl")
native.write_text("export function native() {}\n")
declared.write_text("export function declared() {}\n")
activate_language_overrides(tmp_path)
assert _resolve_js_module_path("./dep", tmp_path) == native
assert _resolve_js_module_path(declared) == declared
def test_extensionless_js_lookup_does_not_claim_other_declared_languages(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.tpl=php\n")
(tmp_path / "dep.tpl").write_text("<?php function chosen() {}\n")
activate_language_overrides(tmp_path)
assert _resolve_js_module_path("./dep", tmp_path) == tmp_path / "dep"
def test_import_candidates_ignore_mapping_keys_that_are_not_literal_suffixes(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.tpl/../secret.ts=typescript\n")
(tmp_path / "dep.tpl").mkdir()
(tmp_path / "secret.ts").write_text("export function unrelated() {}\n")
activate_language_overrides(tmp_path)
assert _resolve_js_module_path("./dep", tmp_path) == tmp_path / "dep"
@pytest.mark.parametrize("layout", ["module", "package", "reexport", "submodule", "namespace"])
def test_python_imports_bind_declared_providers_instead_of_same_named_alternatives(tmp_path, layout):
from graphify.extract import extract
(tmp_path / ".graphifyrc").write_text("language.pyx=python\n")
sources = {"other.pyx": "def chosen(): return 2\n"}
statement = "from one import chosen as local\ndef caller(): return local()\n"
if layout == "module":
target = "one.pyx"
elif layout == "package":
target = "one/__init__.pyx"
elif layout == "reexport":
target = "one/body.pyx"
sources["one/__init__.pyx"] = "from .body import chosen\n"
else:
target = "pkg/one.pyx"
statement = "from pkg import one\ndef caller(): return one.chosen()\n"
if layout == "submodule":
sources["pkg/__init__.pyx"] = ""
sources[target] = "def chosen(): return 1\n"
sources["caller.pyx"] = statement
paths = []
for relative, content in sources.items():
path = tmp_path / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
paths.append(path)
result = extract(paths, root=tmp_path, cache_root=tmp_path)
nodes = {node["id"]: node for node in result["nodes"]}
targets = {(nodes[edge["target"]]["label"], nodes[edge["target"]].get("source_file"))
for edge in result["edges"] if edge["relation"] == "calls"
and nodes.get(edge["source"], {}).get("label") == "caller()"}
assert targets == {("chosen()", target)}
def test_python_native_module_and_package_precedence_is_preserved(tmp_path):
from graphify.extractors.resolution import _resolve_python_module_path
(tmp_path / ".graphifyrc").write_text("language.pyx=python\n")
(tmp_path / "one").mkdir()
(tmp_path / "one/__init__.pyx").write_text("def declared(): pass\n")
native = tmp_path / "one.py"
native.write_text("def native(): pass\n")
activate_language_overrides(tmp_path)
caller = tmp_path / "caller.py"
assert _resolve_python_module_path("one", caller, tmp_path, 0) == native
native_package = tmp_path / "one/__init__.py"
native_package.write_text("def package(): pass\n")
assert _resolve_python_module_path("one", caller, tmp_path, 0) == native_package
def test_python_lookup_does_not_claim_another_declared_language(tmp_path):
from graphify.extractors.resolution import _resolve_python_module_path
(tmp_path / ".graphifyrc").write_text("language.tpl=php\n")
(tmp_path / "one.tpl").write_text("<?php function chosen() {}\n")
activate_language_overrides(tmp_path)
assert _resolve_python_module_path("one", tmp_path / "caller.py", tmp_path, 0) is None
def test_declared_native_suffix_can_supply_an_additional_directory_index(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.cjs=typescript\n")
source = tmp_path / "dep/index.cjs"
source.parent.mkdir()
source.write_text("export function chosen() {}\n")
activate_language_overrides(tmp_path)
assert _resolve_js_module_path("./dep", tmp_path) == source
@pytest.mark.parametrize("suffix", [".py", ".pyx"])
@pytest.mark.parametrize("namespace", [False, True])
def test_declared_packages_preserve_absolute_and_explicit_relative_import_scope(tmp_path, suffix, namespace):
from graphify.extract import extract
(tmp_path / ".graphifyrc").write_text("language.pyx=python\n")
package = tmp_path / "src/pkg"
package.mkdir(parents=True)
init = package / f"__init__{suffix}"
init.write_text("")
target = package / (f"utilities/helper{suffix}" if namespace else f"helper{suffix}")
target.parent.mkdir(exist_ok=True)
target.write_text("def chosen(): return 1\n")
caller = package / f"caller{suffix}"
for relative in (True, False):
prefix = "." if relative else ""
statement = (
f"from {prefix}utilities import helper\ndef caller(): return helper.chosen()\n"
if namespace else
f"from {prefix}helper import chosen as local\ndef caller(): return local()\n"
)
caller.write_text(statement)
result = extract([init, target, caller], root=tmp_path, cache_root=tmp_path)
nodes = {node["id"]: node for node in result["nodes"]}
targets = {nodes[edge["target"]].get("source_file") for edge in result["edges"]
if edge["relation"] == "calls" and nodes.get(edge["source"], {}).get("label") == "caller()"}
assert targets == ({target.relative_to(tmp_path).as_posix()} if relative else set())
def test_declared_package_initializer_is_not_a_namespace_package(tmp_path):
from graphify.extractors.resolution import _resolve_python_namespace_dir
(tmp_path / ".graphifyrc").write_text("language.pyx=python\n")
package = tmp_path / "pkg"
package.mkdir()
(package / "__init__.pyx").write_text("def chosen(): return 1\n")
activate_language_overrides(tmp_path)
assert _resolve_python_namespace_dir("pkg", tmp_path / "caller.py", tmp_path, 0) is None
def test_import_of_declared_src_layout_package_targets_its_real_initializer(tmp_path):
from graphify.extract import extract
(tmp_path / ".graphifyrc").write_text("language.pyx=python\n")
package = tmp_path / "src/pkg"
package.mkdir(parents=True)
init = package / "__init__.pyx"
init.write_text("def chosen(): return 1\n")
caller = tmp_path / "src/caller.pyx"
caller.write_text("import pkg\n")
result = extract([init, caller], root=tmp_path, cache_root=tmp_path)
nodes = {node["id"]: node for node in result["nodes"]}
targets = {nodes.get(edge["target"], {}).get("source_file") for edge in result["edges"]
if edge["relation"] in {"imports", "imports_from"}
and nodes.get(edge["source"], {}).get("source_file") == "src/caller.pyx"}
assert targets == {"src/pkg/__init__.pyx"}
+293
View File
@@ -0,0 +1,293 @@
"""Language declarations must invalidate incremental state and reach watch events."""
import hashlib
import json
import threading
from pathlib import Path
import pytest
from graphify import watch as watch_mod
from graphify.detect import detect_incremental, save_manifest
from graphify.rcfile import set_language_overrides
@pytest.fixture(autouse=True)
def reset_overrides():
set_language_overrides(None)
yield
set_language_overrides(None)
def manifest(root):
return root / "graphify-out" / "manifest.json"
def save(root, files, kind="both"):
save_manifest({"code": [str(p) for p in files]}, str(manifest(root)), kind=kind, root=root)
def pending(root, kind="ast"):
result = detect_incremental(root, str(manifest(root)), kind=kind)
return {Path(p).name for p in result["new_files"]["code"]}
def test_language_transitions_requeue_unchanged_bytes_but_not_unrelated_files(tmp_path):
inc, py = tmp_path / "legacy.inc", tmp_path / "other.py"
inc.write_text("<?php function hello() { return 1; }\n")
py.write_text("def other(): return 2\n")
save(tmp_path, [inc, py])
assert pending(tmp_path) == set()
original_stat = inc.stat()
rc = tmp_path / ".graphifyrc"
for language in ("php", "pascal", None):
if language is None:
rc.unlink()
else:
rc.write_text(f"language.inc={language}\n")
assert pending(tmp_path) == {"legacy.inc"}, language
assert inc.stat().st_mtime_ns == original_stat.st_mtime_ns
save(tmp_path, [inc, py])
assert pending(tmp_path) == set(), language
def test_noop_config_edit_and_partial_save_preserve_only_valid_state(tmp_path):
inc, py = tmp_path / "legacy.inc", tmp_path / "other.py"
inc.write_text("<?php function hello() {}\n")
py.write_text("def other(): pass\n")
rc = tmp_path / ".graphifyrc"
rc.write_text("language.inc=php\n")
save(tmp_path, [inc, py])
assert pending(tmp_path) == set()
rc.write_text("# Same declaration, different spelling\nlanguage.inc=.PHP\n")
save(tmp_path, [py])
assert pending(tmp_path) == set()
rc.write_text("language.inc=pascal\n")
save(tmp_path, [py])
assert pending(tmp_path) == {"legacy.inc"}
@pytest.mark.parametrize("kind", ["ast", "semantic", "both"])
def test_saving_one_tier_does_not_validate_the_other_old_language(tmp_path, kind):
inc = tmp_path / "legacy.inc"
inc.write_text("<?php function hello() {}\n")
save(tmp_path, [inc])
assert pending(tmp_path, "ast") == pending(tmp_path, "semantic") == set()
(tmp_path / ".graphifyrc").write_text("language.inc=php\n")
save(tmp_path, [inc], kind)
assert pending(tmp_path, "ast") == ({inc.name} if kind == "semantic" else set())
assert pending(tmp_path, "semantic") == ({inc.name} if kind == "ast" else set())
@pytest.mark.parametrize("shape", ["mtime", "hash", "tiers"])
def test_legacy_manifest_stays_warm_until_a_language_override_applies(tmp_path, shape):
inc = tmp_path / "legacy.inc"
inc.write_text("<?php function hello() {}\n")
stamp = inc.stat().st_mtime
digest = hashlib.md5(inc.read_bytes()).hexdigest()
entry = {
"mtime": stamp,
"hash": {"mtime": stamp, "hash": digest},
"tiers": {"mtime": stamp, "ast_hash": digest, "semantic_hash": digest},
}[shape]
manifest(tmp_path).parent.mkdir()
manifest(tmp_path).write_text(json.dumps({inc.name: entry}))
assert pending(tmp_path) == set()
(tmp_path / ".graphifyrc").write_text("language.inc=php\n")
assert pending(tmp_path) == {inc.name}
def test_save_uses_explicit_root_not_another_roots_active_override(tmp_path):
left, right = tmp_path / "left", tmp_path / "right"
left.mkdir()
right.mkdir()
inc = left / "legacy.inc"
inc.write_text("<?php function hello() {}\n")
(left / ".graphifyrc").write_text("language.inc=php\n")
pending(right)
save(left, [inc])
assert pending(left) == set()
def drive_watch(root, monkeypatch, actions, *, observed_roots=None):
"""Dispatch real watchdog events on a joined observer thread; run real rebuilds."""
observers = pytest.importorskip("watchdog.observers")
polling = pytest.importorskip("watchdog.observers.polling")
handler = None
class Observer:
def schedule(self, value, *args, **kwargs):
nonlocal handler
handler = value
if observed_roots is not None:
observed_roots.append(args[0])
def start(self):
pass
def stop(self):
pass
def join(self):
pass
original_rebuild = watch_mod._rebuild_code
def rebuild(path, **kwargs):
kwargs["no_cluster"] = True
return original_rebuild(path, **kwargs)
steps = iter(actions)
def pump(_seconds):
try:
event = next(steps)()
except StopIteration:
raise KeyboardInterrupt
errors = []
def dispatch():
try:
for notification in event if isinstance(event, list) else [event]:
handler.on_any_event(notification)
except BaseException as error:
errors.append(error)
worker = threading.Thread(target=dispatch)
worker.start()
worker.join(timeout=5)
assert not worker.is_alive(), "STUCK: watcher event handler did not return"
assert not errors, errors
monkeypatch.setattr(observers, "Observer", Observer)
monkeypatch.setattr(polling, "PollingObserver", Observer)
monkeypatch.setattr(watch_mod, "_rebuild_code", rebuild)
monkeypatch.setattr(watch_mod.time, "sleep", pump)
watch_mod.watch(root, debounce=0)
def graph_labels(root):
graph = json.loads((root / "graphify-out" / "graph.json").read_text())
return {node["label"] for node in graph["nodes"]}
def test_watch_declared_code_updates_graph_on_observer_thread(tmp_path, monkeypatch):
events = pytest.importorskip("watchdog.events")
(tmp_path / ".graphifyrc").write_text("language.tpl=php\n")
source = tmp_path / "page.tpl"
def change():
source.write_text("<?php function watched() {}\n")
return events.FileModifiedEvent(str(source))
drive_watch(tmp_path, monkeypatch, [change])
assert "watched()" in graph_labels(tmp_path)
assert not (tmp_path / "graphify-out" / "needs_update").exists()
def test_watch_document_override_marks_semantic_work_instead_of_rebuilding(tmp_path, monkeypatch):
events = pytest.importorskip("watchdog.events")
(tmp_path / ".graphifyrc").write_text("language.tpl=yaml\n")
source = tmp_path / "notes.tpl"
def change():
source.write_text("service: database\n")
return events.FileModifiedEvent(str(source))
drive_watch(tmp_path, monkeypatch, [change])
assert (tmp_path / "graphify-out" / "needs_update").read_text() == "1"
assert not (tmp_path / "graphify-out" / "graph.json").exists()
@pytest.mark.parametrize("operation", ["create", "modify", "replace", "delete"])
def test_watch_root_config_lifecycle_rebuilds_and_refreshes_event_mapping(tmp_path, monkeypatch, operation):
events = pytest.importorskip("watchdog.events")
rc = tmp_path / ".graphifyrc"
source = tmp_path / "page.tpl"
source.write_text("<?php function initial() {}\n")
(tmp_path / "stable.py").write_text("def stable(): pass\n")
if operation != "create":
rc.write_text("language.tpl=pascal\n")
def config_change():
if operation == "delete":
rc.unlink()
return events.FileDeletedEvent(str(rc))
if operation == "replace":
temporary = tmp_path / ".config-new"
temporary.write_text("language.tpl=php\n")
temporary.replace(rc)
return events.FileMovedEvent(str(temporary), str(rc))
rc.write_text("language.tpl=php\n")
return events.FileModifiedEvent(str(rc))
def source_change():
source.write_text("<?php function changed() {}\n")
return events.FileModifiedEvent(str(source))
drive_watch(tmp_path, monkeypatch, [config_change] + ([] if operation == "delete" else [source_change]))
labels = graph_labels(tmp_path)
assert "stable()" in labels
if operation != "delete":
assert "changed()" in labels
assert "initial()" not in labels
@pytest.mark.parametrize("ignored", ["nested-config", "ignored-directory", "output", "read-only"])
def test_watch_keeps_ignored_and_read_only_events_inert(tmp_path, monkeypatch, ignored):
events = pytest.importorskip("watchdog.events")
(tmp_path / ".graphifyrc").write_text("language.tpl=php\n")
(tmp_path / ".graphifyignore").write_text("ignored/\n")
stable = tmp_path / "stable.py"
stable.write_text("def stable(): pass\n")
def ignored_change():
if ignored == "read-only":
return events.FileOpenedEvent(str(stable))
path = tmp_path / {"nested-config": "nested/.graphifyrc", "ignored-directory": "ignored/file.tpl", "output": "graphify-out/cache/file.py"}[ignored]
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("language.tpl=php\n" if ignored == "nested-config" else "def ignored(): pass\n")
return events.FileModifiedEvent(str(path))
drive_watch(tmp_path, monkeypatch, [ignored_change])
assert not (tmp_path / "graphify-out" / "graph.json").exists()
assert not (tmp_path / "graphify-out" / "needs_update").exists()
@pytest.mark.parametrize("with_document_event", [False, True])
def test_watch_config_changes_keep_semantic_work_visible(tmp_path, monkeypatch, with_document_event):
events = pytest.importorskip("watchdog.events")
rc = tmp_path / ".graphifyrc"
document = tmp_path / "notes.md"
(tmp_path / "stable.py").write_text("def stable(): pass\n")
(tmp_path / "data.tpl").write_text("service: database\n")
def change():
rc.write_text("language.tpl=yaml\n")
batch = [events.FileModifiedEvent(str(rc))]
if with_document_event:
document.write_text("# Changed document\n")
batch.append(events.FileModifiedEvent(str(document)))
return batch
drive_watch(tmp_path, monkeypatch, [change])
assert "stable()" in graph_labels(tmp_path)
assert (tmp_path / "graphify-out" / "needs_update").read_text() == "1"
@pytest.mark.parametrize("argument", [".", "src"])
def test_watch_relative_roots_receive_config_events_without_rebasing_source_paths(tmp_path, monkeypatch, argument):
events = pytest.importorskip("watchdog.events")
monkeypatch.chdir(tmp_path)
root = tmp_path / argument
root.mkdir(exist_ok=True)
(root / "page.tpl").write_text("<?php function watched() {}\n")
registered_roots = []
def change():
(root / ".graphifyrc").write_text("language.tpl=php\n")
return events.FileModifiedEvent(str(Path(registered_roots[0]) / ".graphifyrc"))
drive_watch(Path(argument), monkeypatch, [change], observed_roots=registered_roots)
graph = json.loads((root / "graphify-out" / "graph.json").read_text())
paths = {node["source_file"] for node in graph["nodes"] if node["label"] == "watched()"}
assert paths == {str(Path(argument) / "page.tpl")}
+620
View File
@@ -0,0 +1,620 @@
"""A project can declare what an ambiguous extension means to it (#2961).
`.inc` is hard-mapped to the Pascal extractor, but it is "include file" in
whatever language a project uses: PHP on pfSense, Pascal in Delphi, SQL or
assembly elsewhere. A PHP `.inc` parsed as Pascal does not fail — it yields a
handful of incidental nodes, so the graph looks populated while the shipped
runtime is missing from it (7 nodes instead of 471 on the reporter's file).
No global mapping can be right for everyone, so the project says what it
means in `.graphifyrc`::
language.inc=php
The declaration has to reach every place graphify keys a decision on the
suffix — classification, extractor dispatch, the case-folding and interop
rules for cross-file resolution, the language resolvers, and the AST cache
key (same bytes parse to a different graph under a different extractor) —
and it has to survive the trip into the extraction worker processes.
"""
from __future__ import annotations
import concurrent.futures
import io
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
import pytest
from graphify import rcfile
from graphify.detect import FileType, classify_file, detect
from graphify.extract import (
_get_extractor,
_lang_family,
_lang_is_case_insensitive,
extract,
extract_pascal,
extract_php,
)
from graphify.extractors.ocaml import extract_ocaml
from graphify.extractors.robot import extract_robot
try:
from graphify.extract import _worker_init
except ImportError: # pre-fix tree: the pool had no initializer
_worker_init = None
from graphify.rcfile import (
activate_language_overrides,
cache_salt,
effective_suffix,
load_graphifyrc,
parse_language_value,
set_language_overrides,
)
from graphify.resolver_registry import LanguageResolver, run_language_resolvers
PHP_SOURCE = """<?php
namespace PfBlockerNG;
class RuleSet {
public function load(string $path): array { return $this->parse($path); }
private function parse(string $path): array { return []; }
}
function pfb_update_lists(array $cfg): void { $r = new RuleSet(); $r->load('/tmp/x'); }
function pfb_apply_rules(): void { pfb_update_lists([]); }
function pfb_cron(): void { pfb_apply_rules(); }
"""
@pytest.fixture(autouse=True)
def _no_overrides_leak():
"""Overrides are process state; never let one test's config leak into the next."""
set_language_overrides(None)
rcfile._warned_roots.clear()
yield
set_language_overrides(None)
rcfile._warned_roots.clear()
def _quiet_extract(paths, **kw):
with redirect_stdout(io.StringIO()):
return extract(paths, **kw)
# ---------------------------------------------------------------------------
# The .graphifyrc parser
# ---------------------------------------------------------------------------
def test_language_line_maps_an_extension_to_a_canonical_suffix(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.inc=php\n", encoding="utf-8")
assert load_graphifyrc(tmp_path) == {"languages": {".inc": ".php"}}
@pytest.mark.parametrize("key", ["language.inc", "language..inc", "language.INC", "language. inc "])
def test_the_extension_key_is_normalised(tmp_path, key):
(tmp_path / ".graphifyrc").write_text(f"{key}=php\n", encoding="utf-8")
assert load_graphifyrc(tmp_path)["languages"] == {".inc": ".php"}
@pytest.mark.parametrize("value, expected", [
("php", ".php"), ("PHP", ".php"), ("pascal", ".pas"), ("delphi", ".pas"),
("typescript", ".ts"), ("c++", ".cpp"), (".php", ".php"), (".PHP", ".php"),
("markdown", ".md"), (".md", ".md"),
])
def test_values_accept_a_language_name_or_an_explicit_extension(value, expected):
assert parse_language_value(value) == expected
@pytest.mark.parametrize("value", ["", "klingon", ".", ". php", "php script"])
def test_an_unknown_language_is_an_error_naming_the_alternatives(value):
with pytest.raises(ValueError):
parse_language_value(value)
def test_an_unknown_explicit_extension_warns_and_keeps_the_default(tmp_path, capsys):
(tmp_path / ".graphifyrc").write_text(
"language.tpl=.ts\nlanguage.inc=.phhp\n",
encoding="utf-8",
)
assert activate_language_overrides(tmp_path) == {}
assert effective_suffix(Path("a.inc")) == ".inc"
assert "unknown extension '.phhp'" in capsys.readouterr().err
def test_a_bad_language_line_reports_its_line_number(tmp_path):
(tmp_path / ".graphifyrc").write_text("viz_node_limit=5\nlanguage.inc=klingon\n", encoding="utf-8")
with pytest.raises(ValueError, match=r"language\.inc .* line 2.*klingon"):
load_graphifyrc(tmp_path)
def test_a_bad_language_key_is_an_error(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.=php\n", encoding="utf-8")
with pytest.raises(ValueError, match="line 1"):
load_graphifyrc(tmp_path)
def test_the_existing_option_and_unknown_keys_still_behave(tmp_path):
(tmp_path / ".graphifyrc").write_text(
"# comment\nviz_node_limit=0\nfuture_option=whatever\nlanguage.tpl=.ts\n",
encoding="utf-8",
)
cfg = load_graphifyrc(tmp_path)
assert cfg == {"viz_node_limit": 0, "languages": {".tpl": ".ts"}}
def test_hooks_still_reads_the_same_file_through_its_old_name(tmp_path):
from graphify.hooks import _load_graphifyrc
(tmp_path / ".graphifyrc").write_text("viz_node_limit=3\nlanguage.inc=php\n", encoding="utf-8")
assert _load_graphifyrc(tmp_path)["viz_node_limit"] == 3
(tmp_path / ".graphifyrc").write_text("viz_node_limit=-1\n", encoding="utf-8")
with pytest.raises(ValueError, match="Invalid viz_node_limit"):
_load_graphifyrc(tmp_path)
def test_no_file_means_no_overrides(tmp_path):
assert load_graphifyrc(tmp_path) == {}
assert activate_language_overrides(tmp_path) == {}
# ---------------------------------------------------------------------------
# Every suffix-keyed decision sees the declared language
# ---------------------------------------------------------------------------
def test_effective_suffix_is_the_real_one_until_a_project_says_otherwise():
assert effective_suffix(Path("x/a.inc")) == ".inc"
assert effective_suffix(Path("x/a.F90")) == ".F90" # case preserved
set_language_overrides({".inc": ".php"})
assert effective_suffix(Path("x/a.inc")) == ".php"
assert effective_suffix(Path("x/a.INC")) == ".php"
assert effective_suffix(Path("x/a.F90")) == ".F90"
def test_dispatch_goes_to_the_declared_extractor():
assert _get_extractor(Path("a.inc")) is extract_pascal
set_language_overrides({".inc": ".php"})
assert _get_extractor(Path("a.inc")) is extract_php
assert _get_extractor(Path("b.pas")) is extract_pascal # untouched
def test_a_remapped_header_skips_the_content_sniff(tmp_path):
"""`.h` is normally sniffed for C++/ObjC; a declaration makes it definite."""
from graphify.extract import extract_cpp
h = tmp_path / "plain.h"
h.write_text("int add(int a, int b);\n", encoding="utf-8")
set_language_overrides({".h": ".cpp"})
assert _get_extractor(h) is extract_cpp
def test_a_remap_to_an_extension_without_an_extractor_yields_none():
set_language_overrides({".inc": ".nosuchlang"})
assert _get_extractor(Path("a.inc")) is None
def test_classification_follows_the_declaration():
assert classify_file(Path("page.tpl")) is None # unknown extension
set_language_overrides({".tpl": ".php", ".txt": ".md"})
assert classify_file(Path("page.tpl")) is FileType.CODE
assert classify_file(Path("notes.txt")) is FileType.DOCUMENT
def test_case_folding_and_interop_family_follow_the_declaration():
assert not _lang_is_case_insensitive("lib/a.inc")
assert _lang_family("lib/a.inc") is None
set_language_overrides({".inc": ".php"})
assert _lang_is_case_insensitive("lib/a.inc") # PHP identifiers fold case
assert _lang_family("lib/a.inc") == "php"
def test_language_resolvers_wake_for_the_declared_language():
ran: list[str] = []
resolvers = [
LanguageResolver("php", frozenset({".php"}), lambda *a: ran.append("php")),
LanguageResolver("pascal", frozenset({".pas", ".inc"}), lambda *a: ran.append("pascal")),
]
paths = [Path("a.inc")]
run_language_resolvers(paths, [{}], [], [], resolvers=resolvers)
assert ran == ["pascal"]
ran.clear()
set_language_overrides({".inc": ".php"})
run_language_resolvers(paths, [{}], [], [], resolvers=resolvers)
assert ran == ["php"]
# ---------------------------------------------------------------------------
# The reporter's repro: same bytes, two extensions
# ---------------------------------------------------------------------------
@pytest.fixture
def php_pair(tmp_path):
(tmp_path / "a.inc").write_text(PHP_SOURCE, encoding="utf-8")
(tmp_path / "b.php").write_text(PHP_SOURCE, encoding="utf-8")
return tmp_path
def _counts(root, name):
r = _quiet_extract([root / name], cache_root=root, root=root)
return len(r["nodes"]), len(r["edges"])
def test_without_a_declaration_the_inc_file_is_nearly_empty(php_pair):
"""The failure mode: no error, just a graph missing the runtime."""
inc, php = _counts(php_pair, "a.inc"), _counts(php_pair, "b.php")
assert php[0] > 5 and php[1] > 5
assert inc[0] < php[0] and inc[1] < php[1]
def test_with_the_declaration_the_two_files_yield_the_same_graph(php_pair):
(php_pair / ".graphifyrc").write_text("language.inc=php\n", encoding="utf-8")
assert _counts(php_pair, "a.inc") == _counts(php_pair, "b.php")
def test_a_library_caller_needs_no_setup_beyond_the_file(php_pair):
"""extract() finds `<root>/.graphifyrc` itself — the skill runbook and the
MCP server call it directly, never through the CLI."""
(php_pair / ".graphifyrc").write_text("language.inc=php\n", encoding="utf-8")
set_language_overrides(None) # nothing pre-activated
assert _counts(php_pair, "a.inc") == _counts(php_pair, "b.php")
def test_extract_announces_the_active_overrides(php_pair):
(php_pair / ".graphifyrc").write_text("language.inc=php\n", encoding="utf-8")
out = io.StringIO()
with redirect_stdout(out):
extract([php_pair / "a.inc"], cache_root=php_pair, root=php_pair)
assert ".inc -> .php" in out.getvalue()
def test_detect_counts_a_declared_extension_as_code(tmp_path):
(tmp_path / "page.tpl").write_text(PHP_SOURCE, encoding="utf-8")
with redirect_stdout(io.StringIO()):
before = detect(tmp_path)["files"]
(tmp_path / ".graphifyrc").write_text("language.tpl=php\n", encoding="utf-8")
with redirect_stdout(io.StringIO()):
after = detect(tmp_path)["files"]
assert not any(p.endswith("page.tpl") for p in before.get("code", []))
assert any(p.endswith("page.tpl") for p in after.get("code", []))
# ---------------------------------------------------------------------------
# The cache must not replay the other language's parse
# ---------------------------------------------------------------------------
def test_cache_salt_exists_only_for_remapped_files():
assert cache_salt(Path("a.inc")) is None
set_language_overrides({".inc": ".php"})
assert cache_salt(Path("a.inc")) == "language=.php"
assert cache_salt(Path("b.php")) is None
def test_changing_the_declaration_does_not_serve_the_stale_entry(php_pair):
"""Extract as Pascal (cached), declare PHP, extract again: the PHP graph,
not the Pascal entry keyed by the same bytes."""
pascal = _counts(php_pair, "a.inc")
(php_pair / ".graphifyrc").write_text("language.inc=php\n", encoding="utf-8")
php = _counts(php_pair, "a.inc")
assert php == _counts(php_pair, "b.php") != pascal
# and back again: the PHP entry must not be served for the Pascal parse
(php_pair / ".graphifyrc").write_text("language.inc=pascal\n", encoding="utf-8")
assert _counts(php_pair, "a.inc") == pascal
# ---------------------------------------------------------------------------
# Worker processes
# ---------------------------------------------------------------------------
@pytest.mark.skipif(_worker_init is None, reason="pre-fix tree")
def test_worker_init_installs_the_parents_overrides():
_worker_init({".inc": ".php"})
assert _get_extractor(Path("a.inc")) is extract_php
@pytest.mark.skipif(_worker_init is None, reason="pre-fix tree")
def test_the_pool_hands_its_workers_the_overrides(php_pair, monkeypatch):
"""Under `spawn` a worker starts with empty module state; the pool must
forward the mapping through its initializer."""
seen: dict = {}
class RecordingPool(concurrent.futures.ThreadPoolExecutor):
def __init__(self, max_workers=None, initializer=None, initargs=(), **kw):
seen["initializer"] = initializer
seen["initargs"] = initargs
super().__init__(max_workers=max_workers, initializer=initializer, initargs=initargs)
monkeypatch.setattr(concurrent.futures, "ProcessPoolExecutor", RecordingPool)
for i in range(25): # past _PARALLEL_THRESHOLD
(php_pair / f"f{i}.inc").write_text(PHP_SOURCE, encoding="utf-8")
(php_pair / ".graphifyrc").write_text("language.inc=php\n", encoding="utf-8")
files = sorted(php_pair.glob("f*.inc"))
result = _quiet_extract(files, cache_root=php_pair, root=php_pair, parallel=True)
assert seen["initializer"] is _worker_init
assert seen["initargs"] == ({".inc": ".php"},)
# and every file came back as PHP, not Pascal
per_file = {}
for n in result["nodes"]:
per_file.setdefault(n.get("source_file"), 0)
per_file[n.get("source_file")] += 1
assert len(per_file) == 25 and min(per_file.values()) > 5
# ---------------------------------------------------------------------------
# A config typo must be loud, not fatal
# ---------------------------------------------------------------------------
def test_a_malformed_rc_warns_once_and_scans_without_overrides(php_pair):
(php_pair / ".graphifyrc").write_text("language.inc=klingon\n", encoding="utf-8")
err = io.StringIO()
with redirect_stderr(err):
first = _counts(php_pair, "a.inc")
_counts(php_pair, "a.inc")
assert first == _counts(php_pair, "a.inc") # Pascal, as before
assert err.getvalue().count("ignoring .graphifyrc") == 1
assert "klingon" in err.getvalue()
def test_activating_a_root_without_rc_clears_a_previous_roots_overrides(tmp_path):
set_language_overrides({".inc": ".php"})
activate_language_overrides(tmp_path)
assert effective_suffix(Path("a.inc")) == ".inc"
def test_overrides_do_not_leak_across_concurrent_threads():
"""Two extractions in one process, on different threads with different
roots, must not clobber each other's overrides (#2961 review).
Thread A maps `.inc -> .php`, thread B maps `.inc -> .pas`. Each barrier-
synchronizes so both activations are live at once, then each re-reads its
own `effective_suffix('x.inc')`. With the old module-global dict, whichever
thread activated last won for BOTH; with thread-local state each keeps its
own.
"""
import threading
barrier = threading.Barrier(2)
results: dict[str, str] = {}
def worker(name: str, target: str) -> None:
set_language_overrides({".inc": target})
barrier.wait() # both activations now live simultaneously
results[name] = effective_suffix("x.inc")
ta = threading.Thread(target=worker, args=("php", ".php"))
tb = threading.Thread(target=worker, args=("pas", ".pas"))
ta.start(); tb.start()
ta.join(); tb.join()
assert results == {"php": ".php", "pas": ".pas"}, results
def test_setting_overrides_on_one_thread_leaves_another_thread_clean():
"""A thread that never activated overrides sees none, even while another
thread has them active."""
import threading
set_language_overrides(None) # main thread: no overrides
seen: dict[str, str] = {}
started = threading.Event()
def other() -> None:
set_language_overrides({".inc": ".php"})
started.set()
# keep this thread's overrides live while main checks
import time
time.sleep(0.05)
t = threading.Thread(target=other)
t.start()
started.wait()
# main thread must still see the real suffix, not the other thread's map
assert effective_suffix("x.inc") == ".inc"
t.join()
def _edges(result, relation):
return [e for e in result["edges"] if e["relation"] == relation]
def test_a_declared_ts_file_keeps_its_implements_edge(tmp_path):
base_src = "export interface Base {\n id: number;\n}\n"
consumer_src = (
"import { Base } from './base';\n\n"
"class Consumer implements Base {\n id: number = 1;\n}\n"
)
declared = tmp_path / "declared"
declared.mkdir()
(declared / "base.ts").write_text(base_src, encoding="utf-8")
(declared / "consumer.tpl").write_text(consumer_src, encoding="utf-8")
(declared / ".graphifyrc").write_text("language.tpl=.ts\n", encoding="utf-8")
real = tmp_path / "real"
real.mkdir()
(real / "base.ts").write_text(base_src, encoding="utf-8")
(real / "consumer.ts").write_text(consumer_src, encoding="utf-8")
declared_result = _quiet_extract(
[declared / "base.ts", declared / "consumer.tpl"], cache_root=declared, root=declared
)
real_result = _quiet_extract(
[real / "base.ts", real / "consumer.ts"], cache_root=real, root=real
)
assert len(_edges(real_result, "implements")) == 1
assert len(_edges(declared_result, "implements")) == len(_edges(real_result, "implements"))
def test_a_declared_java_file_disambiguates_implements_by_package(tmp_path):
pkg1 = "package com.pkg1;\npublic interface Base {\n void run();\n}\n"
pkg2 = "package com.pkg2;\npublic interface Base {\n void other();\n}\n"
impl_src = (
"package com.app;\nimport com.pkg1.Base;\n\n"
"public class Impl implements Base {\n public void run() {}\n}\n"
)
declared = tmp_path / "declared"
(declared / "pkg1").mkdir(parents=True)
(declared / "pkg2").mkdir()
(declared / "pkg1" / "Base.java").write_text(pkg1, encoding="utf-8")
(declared / "pkg2" / "Base.java").write_text(pkg2, encoding="utf-8")
(declared / "Impl.jav").write_text(impl_src, encoding="utf-8")
(declared / ".graphifyrc").write_text("language.jav=java\n", encoding="utf-8")
result = _quiet_extract(
[declared / "pkg1" / "Base.java", declared / "pkg2" / "Base.java", declared / "Impl.jav"],
cache_root=declared, root=declared,
)
implements = _edges(result, "implements")
assert len(implements) == 1
target = implements[0]["target"]
target_node = next(n for n in result["nodes"] if n["id"] == target)
assert target_node.get("source_file", "").replace("\\", "/").endswith("pkg1/Base.java")
def test_a_declared_python_file_repoints_a_nested_package_import(tmp_path):
mod_src = "def helper():\n pass\n"
caller_src = "import pkg.mod\n\npkg.mod.helper()\n"
declared = tmp_path / "declared"
(declared / "src" / "pkg").mkdir(parents=True)
(declared / "src" / "pkg" / "__init__.py").write_text("", encoding="utf-8")
(declared / "src" / "pkg" / "mod.pyx").write_text(mod_src, encoding="utf-8")
(declared / "src" / "app.py").write_text(caller_src, encoding="utf-8")
(declared / ".graphifyrc").write_text("language.pyx=python\n", encoding="utf-8")
result = _quiet_extract(
[
declared / "src" / "pkg" / "__init__.py",
declared / "src" / "pkg" / "mod.pyx",
declared / "src" / "app.py",
],
cache_root=declared, root=declared,
)
imports = _edges(result, "imports")
mod_node_id = next(n["id"] for n in result["nodes"] if n["source_file"].endswith("mod.pyx"))
assert any(e["target"] == mod_node_id for e in imports)
def test_a_declared_csharp_file_disambiguates_inherits_by_namespace(tmp_path):
ns1 = "namespace App.Pkg1 {\n public interface Shape { }\n}\n"
ns2 = "namespace App.Pkg2 {\n public interface Shape { }\n}\n"
main_src = (
"using App.Pkg1;\n\nnamespace App {\n public class Wrapper : Shape {\n }\n}\n"
)
declared = tmp_path / "declared"
(declared / "Pkg1").mkdir(parents=True)
(declared / "Pkg2").mkdir()
(declared / "Pkg1" / "Shape.cs").write_text(ns1, encoding="utf-8")
(declared / "Pkg2" / "Shape.cs").write_text(ns2, encoding="utf-8")
(declared / "Main.rzr").write_text(main_src, encoding="utf-8")
(declared / ".graphifyrc").write_text("language.rzr=csharp\n", encoding="utf-8")
result = _quiet_extract(
[declared / "Pkg1" / "Shape.cs", declared / "Pkg2" / "Shape.cs", declared / "Main.rzr"],
cache_root=declared, root=declared,
)
inherits = _edges(result, "inherits")
assert len(inherits) == 1
target = inherits[0]["target"]
target_node = next(n for n in result["nodes"] if n["id"] == target)
assert target_node.get("source_file", "").replace("\\", "/").endswith("Pkg1/Shape.cs")
def test_a_declared_unsupported_language_still_warns_no_extractor(tmp_path, capsys):
# .ets (ArkTS) is a recognized CODE_EXTENSIONS member with no registered
# AST extractor (unlike .r, which upstream now implements behind an
# optional dependency and would instead warn "dependency is missing").
(tmp_path / "a.tpl").write_text("class Foo {}\n", encoding="utf-8")
(tmp_path / ".graphifyrc").write_text("language.tpl=.ets\n", encoding="utf-8")
_quiet_extract([tmp_path / "a.tpl"], cache_root=tmp_path, root=tmp_path)
assert "no AST extractor" in capsys.readouterr().err
def test_a_declared_mli_interface_is_parsed_as_an_interface_not_ml(tmp_path):
pytest.importorskip("tree_sitter_ocaml")
root = tmp_path
(root / ".graphifyrc").write_text("language.tpl4=.mli\n", encoding="utf-8")
activate_language_overrides(root)
impl_src = "let helper x =\n x + 1\n\nlet main () =\n helper 41\n"
declared_path = root / "a.tpl4"
declared_path.write_text(impl_src, encoding="utf-8")
real_mli = root / "a.mli"
real_mli.write_text(impl_src, encoding="utf-8")
declared_result = extract_ocaml(declared_path)
set_language_overrides(None)
real_result = extract_ocaml(real_mli)
assert real_result["edges"] == [] # real .mli: not valid interface syntax, nothing extracted
assert declared_result["edges"] == real_result["edges"]
def test_a_declared_resource_file_excludes_test_cases_like_a_real_resource(tmp_path):
pytest.importorskip("robot")
root = tmp_path
(root / ".graphifyrc").write_text("language.tplr=.resource\n", encoding="utf-8")
content = (
"*** Test Cases ***\nMy Test\n Log hello\n\n"
"*** Keywords ***\nDo Something\n Log hi\n"
)
activate_language_overrides(root)
declared_path = root / "a.tplr"
declared_path.write_text(content, encoding="utf-8")
real_resource = root / "a.resource"
real_resource.write_text(content, encoding="utf-8")
declared_result = extract_robot(declared_path)
set_language_overrides(None)
real_result = extract_robot(real_resource)
declared_labels = {n["label"] for n in declared_result["nodes"]}
real_labels = {n["label"] for n in real_result["nodes"]}
assert "My Test" not in real_labels # real .resource: Test Cases section dropped
assert "Do Something" in real_labels
assert declared_labels - {declared_path.name} == real_labels - {real_resource.name}
def test_declared_typescript_preserves_symbols_and_original_source_paths(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.tpl=typescript\n", encoding="utf-8")
source = tmp_path / "declarations.tpl"
source.write_text("""interface Point { x: number; y: number; }
enum Color { Red, Green, Blue }
class Shape<T> {
constructor(private kind: T) {}
describe(): string { return String(this.kind); }
}
""", encoding="utf-8")
result = _quiet_extract([source], root=tmp_path, cache_root=tmp_path)
expected = {"Point", "Color", "Red", "Green", "Blue", "Shape", ".constructor()", ".describe()"}
assert expected <= {node["label"] for node in result["nodes"]}
assert {node["source_file"] for node in result["nodes"] if node["label"] in expected} == {source.name}
def test_declared_typescript_imports_follow_changed_tsconfig_without_source_edit(tmp_path):
import json
(tmp_path / ".graphifyrc").write_text("language.tpl=ts\n", encoding="utf-8")
caller, one, two = (tmp_path / name for name in ("consumer.tpl", "one.ts", "two.ts"))
caller.write_text("import { chosen } from '@target'; export function run() { return chosen(); }\n", encoding="utf-8")
one.write_text("export function chosen() { return 1; }\n", encoding="utf-8")
two.write_text("export function chosen() { return 2; }\n", encoding="utf-8")
config = tmp_path / "tsconfig.json"
for target in ("one.ts", "two.ts"):
config.write_text(json.dumps({"compilerOptions": {"baseUrl": ".", "paths": {"@target": [target]}}}), encoding="utf-8")
result = _quiet_extract([caller, one, two], root=tmp_path, cache_root=tmp_path)
nodes = {node["id"]: node for node in result["nodes"]}
targets = {nodes[edge["target"]].get("source_file") for edge in _edges(result, "imports_from")
if nodes.get(edge["source"], {}).get("source_file") == caller.name}
assert targets == {target}, (target, targets)
def test_declared_go_resolves_qualified_type_among_same_named_packages(tmp_path):
(tmp_path / ".graphifyrc").write_text("language.gox=go\n", encoding="utf-8")
(tmp_path / "go.mod").write_text("module example.com/app\ngo 1.21\n", encoding="utf-8")
paths = []
for package in ("pkg1", "pkg2"):
directory = tmp_path / package
directory.mkdir()
source = directory / "shape.go"
source.write_text(f"package {package}\ntype Shape struct {{ Sides int }}\n", encoding="utf-8")
paths.append(source)
caller = tmp_path / "main.gox"
caller.write_text('package main\nimport "example.com/app/pkg1"\ntype Wrapper struct { S pkg1.Shape }\n', encoding="utf-8")
result = _quiet_extract([caller, *paths], root=tmp_path, cache_root=tmp_path)
nodes = {node["id"]: node for node in result["nodes"]}
targets = {nodes[edge["target"]].get("source_file") for edge in _edges(result, "references")
if nodes.get(edge["source"], {}).get("label") == "Wrapper"}
assert targets == {"pkg1/shape.go"}, targets
+72
View File
@@ -0,0 +1,72 @@
from pathlib import Path
import pytest
from tests.test_csharp_interface_dispatch import _INJECTED
from tests.test_csharp_partial_classes import _HALVES, _find
from tests.test_language_overrides import _no_overrides_leak as _no_overrides_leak
from tests.test_language_overrides import _quiet_extract
def _extract_declared(tmp_path, monkeypatch, files, suffix):
monkeypatch.chdir(tmp_path)
(tmp_path / ".graphifyrc").write_text("language.rzr=csharp\n", encoding="utf-8")
paths = []
for name, source in files.items():
path = tmp_path / Path(name).with_suffix(suffix)
path.write_text(source, encoding="utf-8")
paths.append(path)
return _quiet_extract(paths, root=tmp_path, cache_root=tmp_path / ".cache")
@pytest.mark.parametrize("suffix", [".cs", ".rzr"])
def test_partial_halves_share_one_class_and_both_members(tmp_path, monkeypatch, suffix):
result = _extract_declared(tmp_path, monkeypatch, _HALVES, suffix)
classes = [node for node in result["nodes"] if node["label"] == "Foo"]
assert len(classes) == 1, "partial halves must merge into one Foo declaration"
members = {
edge["target"] for edge in result["edges"]
if edge["relation"] == "method" and edge["source"] == classes[0]["id"]
}
assert members == {
_find(result, ".Alpha()", "foo"),
_find(result, ".Beta()", "foo"),
}
@pytest.mark.parametrize("suffix", [".cs", ".rzr"])
def test_derived_receiver_calls_the_inherited_base_method(tmp_path, monkeypatch, suffix):
result = _extract_declared(tmp_path, monkeypatch, {
"S.cs": (
"public class BaseSvc { public bool Ping() => true; }\n"
"public class Derived : BaseSvc { }\n"
"public class User {\n"
" public bool Use(Derived d) { return d.Ping(); }\n"
"}\n"
),
}, suffix)
calls = {
(edge["source"], edge["target"]) for edge in result["edges"]
if edge["relation"] == "calls"
}
assert (
_find(result, ".Use()", "user"),
_find(result, ".Ping()", "basesvc"),
) in calls
@pytest.mark.parametrize("suffix", [".cs", ".rzr"])
def test_injected_interface_dispatches_to_its_implementation(tmp_path, monkeypatch, suffix):
result = _extract_declared(tmp_path, monkeypatch, _INJECTED, suffix)
interface_method = _find(result, ".Build()", "ireport")
implementation_method = _find(result, ".Build()", "report_report")
calls = {
(edge["source"], edge["target"]) for edge in result["edges"]
if edge["relation"] == "calls"
}
dispatch = {
(edge["source"], edge["target"]) for edge in result["edges"]
if edge["relation"] == "dispatches_to"
}
assert (_find(result, ".Go()", "runner"), interface_method) in calls
assert dispatch == {(interface_method, implementation_method)}
+113
View File
@@ -0,0 +1,113 @@
"""PR10: inferred candidates and call scope honor declared languages."""
import pytest
from graphify.extractors import resolution
from graphify.rcfile import activate_language_overrides, set_language_overrides
from tests.test_language_overrides import _quiet_extract
@pytest.fixture(autouse=True)
def _restore_language_overrides():
set_language_overrides(None)
yield
set_language_overrides(None)
@pytest.mark.parametrize("remap_native", [False, True])
@pytest.mark.parametrize("layout", ["file", "index", "esm"])
def test_js_inferred_candidates_respect_language_and_native_precedence(
tmp_path, layout, remap_native
):
config = "language.tpl=typescript\n"
if remap_native:
config += "language.ts=php\n"
(tmp_path / ".graphifyrc").write_text(config, encoding="utf-8")
activate_language_overrides(tmp_path)
candidate = tmp_path / ("dep.js" if layout == "esm" else "dep")
if layout == "index":
candidate.mkdir()
native, declared = candidate / "index.ts", candidate / "index.tpl"
else:
native, declared = tmp_path / "dep.ts", tmp_path / "dep.tpl"
native.write_text(
"<?php function foreign() {}" if remap_native else "export function native() {}",
encoding="utf-8",
)
declared.write_text("export function declared() {}", encoding="utf-8")
# A missing explicit .js path stays unresolved; it must not substitute PHP.
expected = (candidate if layout == "esm" else declared) if remap_native else native
assert resolution._resolve_js_module_path(candidate) == expected
@pytest.mark.parametrize("remap_native", [False, True])
@pytest.mark.parametrize("layout", ["module", "package"])
def test_python_inferred_candidates_respect_language_and_native_precedence(
tmp_path, layout, remap_native
):
config = "language.pyx=python\n"
if remap_native:
config += "language.py=javascript\n"
(tmp_path / ".graphifyrc").write_text(config, encoding="utf-8")
activate_language_overrides(tmp_path)
if layout == "package":
package = tmp_path / "dep"
package.mkdir()
native, declared = package / "__init__.py", package / "__init__.pyx"
else:
native, declared = tmp_path / "dep.py", tmp_path / "dep.pyx"
native.write_text(
"export function foreign() {}" if remap_native else "def native(): pass\n",
encoding="utf-8",
)
declared.write_text("def declared(): pass\n", encoding="utf-8")
assert resolution._resolve_python_module_path(
"dep", tmp_path / "caller.pyx", tmp_path, 0
) == (declared if remap_native else native)
@pytest.mark.parametrize(
"config, marker, expected",
[
("language.pyx=python\n", "__init__.py", True),
("language.py=javascript\nlanguage.pyx=python\n", "__init__.py", False),
("language.py=javascript\nlanguage.pyx=python\n", "__init__.pyx", True),
],
)
def test_python_package_marker_must_be_python(tmp_path, config, marker, expected):
(tmp_path / ".graphifyrc").write_text(config, encoding="utf-8")
(tmp_path / marker).write_text("", encoding="utf-8")
activate_language_overrides(tmp_path)
assert resolution._is_python_package_dir(tmp_path) is expected
@pytest.mark.parametrize("caller_suffix", [".ts", ".tpl"])
@pytest.mark.parametrize("has_import", [False, True])
def test_js_cross_file_call_requires_an_import(tmp_path, caller_suffix, has_import):
(tmp_path / ".graphifyrc").write_text("language.tpl=typescript\n", encoding="utf-8")
provider = tmp_path / "provider.ts"
caller = tmp_path / f"caller{caller_suffix}"
provider.write_text("export function hidden() {}\n", encoding="utf-8")
caller.write_text(
("import { hidden } from './provider';\n" if has_import else "")
+ "export function caller() { hidden(); }\n",
encoding="utf-8",
)
result = _quiet_extract([provider, caller], root=tmp_path, cache_root=tmp_path)
caller_id = next(
node["id"] for node in result["nodes"]
if node.get("source_file") == caller.name and node["label"] == "caller()"
)
provider_id = next(
node["id"] for node in result["nodes"]
if node.get("source_file") == provider.name and node["label"] == "hidden()"
)
assert any(
edge["source"] == caller_id and edge["target"] == provider_id
and edge["relation"] == "calls"
for edge in result["edges"]
) is has_import
+25
View File
@@ -0,0 +1,25 @@
"""Root configuration controls extraction even when excluded from the corpus."""
import pytest
from tests.test_language_override_lifecycle import drive_watch, graph_labels
@pytest.mark.parametrize("replacement", [False, True])
def test_ignored_root_configuration_still_rebuilds_the_graph(tmp_path, monkeypatch, replacement):
events = pytest.importorskip("watchdog.events")
(tmp_path / ".graphifyignore").write_text(".*\n" if replacement else ".graphifyrc\n")
(tmp_path / "page.tpl").write_text("<?php function configured() {}\n")
config = tmp_path / ".graphifyrc"
def change():
if replacement:
staged = tmp_path / ".replacement"
staged.write_text("language.tpl=php\n")
staged.replace(config)
return events.FileMovedEvent(str(staged), str(config))
config.write_text("language.tpl=php\n")
return events.FileModifiedEvent(str(config))
drive_watch(tmp_path, monkeypatch, [change])
assert "configured()" in graph_labels(tmp_path)
assert (tmp_path / "graphify-out" / "needs_update").read_text() == "1"