Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(selection): see every string an edge resolves when the index lags (#3325)

Raghav Chamadiyaff0a2952ac47
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index 864bf2502..29f0576e6 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -402,7 +402,8 @@ def _cat_file_batch(repo_path: str, sha: str, paths: list[str]) -> dict[str, byt
def read_blobs(repo_path: str, specs: list[tuple[str, str]]) -> dict[tuple[str, str], bytes] | None:
"""``{(rev, path): bytes}`` over one ``git cat-file --batch``; ``None`` if git failed.
- An object missing at its revision is omitted rather than raising.
+ An object missing at its revision, or one that is not a file (a submodule),
+ is omitted instead of raising.
"""
request = "\n".join(f"{rev}:{path}" for rev, path in specs) + "\n"
proc = subprocess.run(
@@ -422,14 +423,16 @@ def read_blobs(repo_path: str, specs: list[tuple[str, str]]) -> dict[tuple[str,
header = data[cursor:newline]
# A missing object echoes the whole spec back: "<sha>:<path> missing".
# Match the suffix, not the field count, because a path may hold spaces.
- if header.endswith(b" missing"):
+ # A submodule whose commit this repository lacks: "<sha> submodule", no body.
+ fields = header.decode("utf-8", "replace").split()
+ if header.endswith(b" missing") or fields[1:] == ["submodule"]:
cursor = newline + 1
continue
- fields = header.decode("utf-8", "replace").split()
if len(fields) < 3 or not fields[2].isdigit():
break # unparseable header: stop rather than misread the stream
size = int(fields[2])
start = newline + 1
- out[spec] = data[start : start + size]
+ if fields[1] == "blob": # a submodule whose commit is here reads as that commit
+ out[spec] = data[start : start + size]
cursor = start + size + 1 # trailing newline
return out
diff --git a/packages/core/src/repowise/core/analysis/import_drift.py b/packages/core/src/repowise/core/analysis/import_drift.py
index b1e39435c..5cf6427c5 100644
--- a/packages/core/src/repowise/core/analysis/import_drift.py
+++ b/packages/core/src/repowise/core/analysis/import_drift.py
@@ -5,8 +5,9 @@ not move since. In Python and JavaScript / TypeScript a file reaches another
only through an import the parser reads (``import``, ``from``, ``require``,
``import()``, a re-export) or through a string a loader resolves (a dotted
module name in a plugin table, a mocked or spawned path). Two versions with the
-same imports and the same module- or path-shaped string literals therefore
-have the same edges, whatever else changed in them.
+same imports and the same strings every string-reading edge producer reads
+(each producer's own extractor, so a shape one resolves is never missed)
+therefore have the same edges, whatever else changed in them.
Cheapest check first: the strings are a regex away, and when no line that
differs can be part of an import statement (one naming an import keyword, or
@@ -29,6 +30,9 @@ from collections import Counter
from datetime import UTC, datetime
from pathlib import PurePosixPath
+from ..ingestion.dynamic_hints import django as django_hints
+from ..ingestion.dynamic_hints.python_imports import string_inputs
+from ..ingestion.framework_edges.test_path_strings import path_literals
from ..ingestion.models import EXTENSION_TO_LANGUAGE, FileInfo
# Data and prose: they import nothing, so they cannot carry a route.
@@ -74,7 +78,7 @@ def edges_may_differ(path: str, before: bytes | None, after: bytes | None) -> bo
language = _language(path)
if language not in _IMPORT_WORD:
return _WHITESPACE.sub(b" ", before).strip() != _WHITESPACE.sub(b" ", after).strip()
- if _names(before) != _names(after):
+ if _names(path, language, before) != _names(path, language, after):
return True
if not _touches_imports(language, before, after):
return False
@@ -82,10 +86,14 @@ def edges_may_differ(path: str, before: bytes | None, after: bytes | None) -> bo
return old is None or old != _imports(path, language, after)
-def _names(source: bytes) -> list[bytes]:
- """The module- or path-shaped string literals of one version."""
+def _names(path: str, language: str, source: bytes) -> tuple:
+ """The strings of one version that a loader or an edge producer may resolve."""
found = {m.group(2) for m in _NAME_LITERAL.finditer(source)}
- return sorted(n for n in found if b"." in n or b"/" in n)
+ names = sorted(n for n in found if b"." in n or b"/" in n)
+ paths = sorted(set(path_literals(source)))
+ if language != "python":
+ return names, paths
+ return names, paths, string_inputs(path, source), django_hints.edge_strings(path, source)
def _touches_imports(language: str, before: bytes, after: bytes) -> bool:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py
index 8ad74d093..8b2683fd0 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py
@@ -170,6 +170,50 @@ def _extract_string_value(node: ast.expr) -> str | None:
return None
+_SETTINGS_NAMES = ("INSTALLED_APPS", "ROOT_URLCONF", "MIDDLEWARE")
+_INCLUDE_RE = re.compile(r"""include\(\s*['\"]([\w\.]+)['\"]""")
+
+
+def settings_entries(tree: ast.Module) -> list[tuple[str, list[str]]]:
+ """``(setting, strings)`` per assignment of a setting that names code, in order."""
+ found: list[tuple[str, list[str]]] = []
+ for node in ast.walk(tree):
+ # ``INSTALLED_APPS += [...]`` extends the setting in place.
+ if isinstance(node, (ast.Assign, ast.AugAssign)):
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+ found += [
+ (t.id, _setting_strings(t.id, node.value))
+ for t in targets
+ if isinstance(t, ast.Name) and t.id in _SETTINGS_NAMES
+ ]
+ return found
+
+
+def _setting_strings(name: str, value: ast.expr) -> list[str]:
+ if name != "ROOT_URLCONF":
+ return _extract_string_list(value)
+ module = _extract_string_value(value)
+ return [module] if module else []
+
+
+def edge_strings(path: str, blob: bytes) -> list | None:
+ """What this extractor reads from *blob*, for comparing two versions of *path*.
+
+ The code-naming settings of a settings file (as :meth:`_scan_settings`
+ finds them), the ``include()`` targets of a ``urls.py``; ``None`` for a
+ settings file that does not parse, which gets no edges.
+ """
+ p = PurePosixPath(path)
+ if p.name == "urls.py":
+ return sorted({m.group(1) for m in _INCLUDE_RE.finditer(blob.decode("utf-8", "ignore"))})
+ if p.name != "settings.py" and not (p.parent.name == "settings" and p.suffix == ".py"):
+ return []
+ try:
+ return settings_entries(ast.parse(blob.decode("utf-8", "ignore")))
+ except Exception: # as in _scan_settings, which skips any file that will not parse
+ return None
+
+
class DjangoDynamicHints(DynamicHintExtractor):
name = "django_settings"
@@ -209,48 +253,25 @@ class DjangoDynamicHints(DynamicHintExtractor):
except ValueError:
continue
- for node in ast.walk(tree):
- # ``INSTALLED_APPS += [...]`` extends the setting in place.
- if not isinstance(node, (ast.Assign, ast.AugAssign)):
+ for name, values in settings_entries(tree):
+ if name == "INSTALLED_APPS":
+ for app in values:
+ edges.extend(
+ self._installed_app_edges(rel_settings, app, repo_root, app_modules)
+ )
continue
- targets = node.targets if isinstance(node, ast.Assign) else [node.target]
- for target in targets:
- if not (isinstance(target, ast.Name)):
- continue
- name = target.id
-
- if name == "INSTALLED_APPS":
- for app in _extract_string_list(node.value):
- edges.extend(
- self._installed_app_edges(rel_settings, app, repo_root, app_modules)
+ # ROOT_URLCONF and MIDDLEWARE name modules.
+ for module in values:
+ resolved = _module_to_path(module, repo_root)
+ if resolved:
+ edges.append(
+ DynamicEdge(
+ source=rel_settings,
+ target=resolved,
+ edge_type="dynamic_imports",
+ hint_source=self.name,
)
-
- elif name == "ROOT_URLCONF":
- module = _extract_string_value(node.value)
- if module:
- resolved = _module_to_path(module, repo_root)
- if resolved:
- edges.append(
- DynamicEdge(
- source=rel_settings,
- target=resolved,
- edge_type="dynamic_imports",
- hint_source=self.name,
- )
- )
-
- elif name == "MIDDLEWARE":
- for middleware in _extract_string_list(node.value):
- resolved = _module_to_path(middleware, repo_root)
- if resolved:
- edges.append(
- DynamicEdge(
- source=rel_settings,
- target=resolved,
- edge_type="dynamic_imports",
- hint_source=self.name,
- )
- )
+ )
return edges
@@ -303,7 +324,6 @@ class DjangoDynamicHints(DynamicHintExtractor):
def _scan_urls(self, repo_root: Path) -> list[DynamicEdge]:
edges: list[DynamicEdge] = []
- include_re = re.compile(r"""include\(\s*['\"]([\w\.]+)['\"]""")
for urls_file in self._rglob(repo_root, "urls.py"):
try:
@@ -312,7 +332,7 @@ class DjangoDynamicHints(DynamicHintExtractor):
except Exception:
continue
- for match in include_re.finditer(source):
+ for match in _INCLUDE_RE.finditer(source):
module = match.group(1)
resolved = _module_to_path(module, repo_root)
if resolved:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py
index 9187bf026..e36212308 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py
@@ -237,6 +237,31 @@ def python_dynamic_refs(rel: str, blob: bytes, resolver: ModuleStringResolver) -
return refs
+def string_inputs(rel: str, blob: bytes) -> tuple:
+ """What :func:`python_dynamic_refs` reads from *blob*, for comparing two versions.
+
+ The markers that gate it, and every string or templated load it may
+ resolve with whether it may sit in a comment or docstring; where one may,
+ the strings in code too, read the way the extractor reads them. Two
+ versions alike here get the same refs from the same modules. Ceiling: a
+ ``module:attr`` reference also depends on the target defining *attr*,
+ which only the target's text says.
+ """
+ gates = tuple(m for m in _DYNAMIC_IMPORT_MARKERS if m in blob)
+ triples = [m.start() for m in _TRIPLE_QUOTE_RE.finditer(blob)]
+ found = {
+ (m.group(0), _maybe_not_code(blob, triples, m.start()))
+ for r in (_DOTTED_STRING_RE, _ATTR_STRING_RE, _TEMPLATE_LOAD_RE)
+ for m in r.finditer(blob)
+ }
+ # Tokenizing costs far more than the scan, so only where the extractor tokenizes.
+ live: set[bytes] = set()
+ if any(maybe_not_code for _, maybe_not_code in found):
+ code = live_text(rel, blob)
+ live = {m.group(0) for r in (_DOTTED_STRING_RE, _ATTR_STRING_RE) for m in r.finditer(code)}
+ return gates, sorted(found), sorted(live)
+
+
class PythonDynamicHints(DynamicHintExtractor):
name = "python_dynamic_import"
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.py b/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.py
index d88ffdb2c..cc14db727 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/test_path_strings.py
@@ -51,12 +51,17 @@ def _is_helper(target: str) -> bool:
return name not in _DIR_SCOPED and not is_test_path(name)
+def path_literals(text: bytes) -> list[bytes]:
+ """The code-file paths *text* spells as string literals, in order."""
+ return [m.group(1) for m in _PATH_LITERAL_RE.finditer(text)]
+
+
def path_string_targets(path: str, text: bytes, path_set: set[str]) -> list[str]:
"""Indexed code files *text*, the source of *path*, names relative to its directory."""
base = posixpath.dirname(path)
found: dict[str, None] = {}
- for match in _PATH_LITERAL_RE.finditer(text):
- spec = match.group(1).decode("ascii", errors="ignore")
+ for literal in path_literals(text):
+ spec = literal.decode("ascii", errors="ignore")
target = posixpath.normpath(posixpath.join(base, spec))
if target in path_set and _is_helper(target) and target != path:
found[target] = None
diff --git a/tests/unit/analysis/test_import_drift.py b/tests/unit/analysis/test_import_drift.py
index 622f1c9e9..de61f2b79 100644
--- a/tests/unit/analysis/test_import_drift.py
+++ b/tests/unit/analysis/test_import_drift.py
@@ -50,6 +50,66 @@ def test_an_import_or_a_module_name_moves_the_edges(path, before, after) -> None
assert edges_may_differ(path, before, after) is True
+_SETTINGS = b'INSTALLED_APPS = [\n "django.contrib.admin",\n "polls",\n]\n'
+
+
+ ("path", "before", "after"),
+ [
+ # A lazy registry's module:attr string.
+ (
+ "pkg/cli/__init__.py",
+ b'CMDS = {"run": "pkg.cli.run:main"}\n',
+ b'CMDS = {"run": "pkg.cli.other:main"}\n',
+ ),
+ # The same string moving out of a comment into code.
+ (
+ "pkg/cli/__init__.py",
+ b'CMDS = {\n # "run": "pkg.cli.run:main",\n}\n',
+ b'CMDS = {\n "run": "pkg.cli.run:main",\n}\n',
+ ),
+ # A dotted string starts to count once the file loads modules by name.
+ (
+ "pkg/loader.py",
+ b'NAME = "pkg.plugins.a"\n',
+ b'NAME = "pkg.plugins.a"\nload = lazy_subcommands\n',
+ ),
+ # A templated load.
+ (
+ "pkg/loader.py",
+ b'importlib.import_module(f"pkg.plugins.{name}")\n',
+ b'importlib.import_module(f"pkg.handlers.{name}")\n',
+ ),
+ # A test naming a helper it runs by a path relative to itself.
+ (
+ "tests/test_server.py",
+ b'H = Path(__file__).parent / "1_server.py"\n',
+ b'H = Path(__file__).parent / "2_server.py"\n',
+ ),
+ ("tests/cli.test.ts", b'spawn("~/run.ts");\n', b'spawn("~/serve.ts");\n'),
+ # Django settings and URLconfs name apps and modules by bare name.
+ ("mysite/settings.py", _SETTINGS, _SETTINGS.replace(b'"polls"', b'"blog"')),
+ ("mysite/settings/base.py", _SETTINGS, _SETTINGS.replace(b' "polls",\n', b"")),
+ ("mysite/settings.py", b'ROOT_URLCONF = "urls"\n', b'ROOT_URLCONF = "routes"\n'),
+ ("mysite/settings.py", b'MIDDLEWARE = ["audit"]\n', b'MIDDLEWARE = ["audit", "trace"]\n'),
+ # Parsed at the indexed revision, unparseable now: its edges are gone.
+ ("mysite/settings.py", _SETTINGS, _SETTINGS.replace(b"]\n", b"\n")),
+ (
+ "mysite/urls.py",
+ b'urlpatterns = [path("", include("polls"))]\n',
+ b'urlpatterns = [path("", include("blog"))]\n',
+ ),
+ ],
+)
+def test_a_string_an_edge_producer_resolves_moves_the_edges(path, before, after) -> None:
+ assert edges_may_differ(path, before, after) is True
+
+
+def test_a_bare_name_outside_django_wiring_is_not_compared() -> None:
+ before = b'MODES = ["polls"]\n'
+ assert edges_may_differ("mysite/views.py", before, before.replace(b"polls", b"blog")) is False
+
+
def test_a_file_on_one_side_only_moves_no_route() -> None:
assert edges_may_differ("m.py", None, _PY) is False
assert edges_may_differ("m.py", _PY, None) is False
diff --git a/tests/unit/change_health/test_regressions.py b/tests/unit/change_health/test_regressions.py
index fa975bf06..11b7f8a99 100644
--- a/tests/unit/change_health/test_regressions.py
+++ b/tests/unit/change_health/test_regressions.py
@@ -15,11 +15,11 @@ from repowise.core.analysis.change_health.service import (
DeltaRequest,
_suggestion,
)
-from repowise.core.analysis.change_health.sources import GitRevisionSource
+from repowise.core.analysis.change_health.sources import GitRevisionSource, read_blobs
from repowise.core.analysis.health import HealthFindingData, Severity
from repowise.core.analysis.health.scoring import score_file
-from .conftest import python_complex
+from .conftest import git, python_complex
def finding(marker="long_method", *, line, severity=Severity.MEDIUM, symbol=None, impact=1.0):
@@ -110,6 +110,25 @@ def test_a_path_with_a_space_missing_at_a_revision_does_not_derail_the_batch(mak
assert blobs["keep.py"] == b"x = 1\n"
+def test_a_submodule_entry_does_not_derail_the_batch(make_repo):
+ """A gitlink reads as no file, and the specs after it still read.
+
+ Git answers ``<sha> submodule`` with no body when the submodule's commit is
+ not in this repository, and the commit object itself when it is.
+ """
+ repo = make_repo()
+ head = repo.commit("seed", {"after.py": "z = 3\n"})
+ absent = "1234567890" * 4
+ for path, sha in (("vendor/lib", absent), ("vendor/own", head)):
+ git(repo.path, "update-index", "--add", "--cacheinfo", f"160000,{sha},{path}")
+ git(repo.path, "commit", "-q", "-m", "add submodules")
+
+ specs = [("HEAD", "vendor/lib"), ("HEAD", "vendor/own"), ("HEAD", "after.py")]
+ blobs = read_blobs(str(repo.path), specs)
+
+ assert blobs == {("HEAD", "after.py"): b"z = 3\n"}
+
+
def test_a_change_touching_a_path_with_a_space_still_compares(make_repo):
repo = make_repo()
repo.commit("seed", {"keep.py": "x = 1\n"})