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.

feat(impacted-tests): select a manifest change's namer tests instead of every test (#3379)

Raghav Chamadiya53922b452ba0
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 500fb405f..970721e6b 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -253,7 +253,7 @@ a per-test coverage map (`repowise coverage add`) makes it more precise.
- It exits `0` for a subset or for everything, and `2` only when it cannot read the change or the `tests.*` config.
- Branch on the run-all flag, never on `:all`: jest and vitest read it as a pattern and run nothing.
- It runs everything for: an empty change; a Cargo, Make, CMake, Docker or CI file; tool and runtime config (dotfiles, `.tool-versions`, root-level `*.toml`, `*.yaml` and `*.json`, shell scripts); `.repowise/config.yaml`.
-- A lockfile, manifest or test runner config runs its own ecosystem's tests: for a nested `package.json`, lockfile or `go.mod`, the tests under its directory and those reaching code there; at the root, and for Python, Ruby, PHP and Gradle or Maven files (pip requirements included), `tsconfig` and jest or vitest configs, the whole ecosystem. Tests whose code names the file from outside that scope run too (a Python test reading `package.json`); a mention written with a directory names only the files its path can mean (`packages/web/package.json` does not name `packages/ui/package.json`), a bare name, `../package.json` or a path built from parts names every file of that name. If more than 50 non-test files outside the scope name it, everything runs.
+- A lockfile, manifest or test runner config runs its own ecosystem's tests: for a nested `package.json`, lockfile or `go.mod`, the tests under its directory and those reaching code there; at the root, and for Python, Ruby, PHP and Gradle or Maven files (pip requirements included), `tsconfig` and jest or vitest configs, the whole ecosystem. Tests whose code names the file from outside that scope run too (a Python test reading `package.json`); a mention written with a directory names only the files its path can mean (`packages/web/package.json` does not name `packages/ui/package.json`), a bare name, `../package.json` or a path built from parts names every file of that name. A file under a fixture tree (`tests/fixtures/<name>/`) stands for the test code that names that tree or the fixtures directory; when none does, or code outside the test trees names the tree's path, everything runs. If more than 200 non-test files outside the scope name it, everything runs.
- A production package's `__init__.py` selects the tests reaching any module under it.
- A doc, template, query, stylesheet, image or nested data file selects the tests reaching the code that names it. When no code names it, a doc, template, stylesheet or image selects its package's tests, and a query or data file runs everything. Ceiling: a test that globs docs or templates in another package is not seen.
- It also runs everything for: non-code files in a test tree; a changed file with no known test or only a filename guess; a route through a test helper no test imports, unless every known test is selected anyway (the reasons then say so); any Python test helper while a conftest or pytest config loads plugins by name.
diff --git a/packages/core/src/repowise/core/analysis/fixture_readers.py b/packages/core/src/repowise/core/analysis/fixture_readers.py
new file mode 100644
index 000000000..06288b714
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/fixture_readers.py
@@ -0,0 +1,139 @@
+"""Tests read a fixture tree through its directory, not through its files.
+
+A file under ``tests/fixtures/ts_sample/`` is data: a test points an indexer or
+parser at the ``ts_sample`` directory and never imports or names the file. As
+a namer of a changed file (fixture code mentioning ``package.json``) it is a
+test helper no test imports, which runs everything.
+
+Such a namer stands instead for the test code that may read its tree: every
+file in a test tree (a test, a helper, a conftest) whose text names the tree
+(``"ts_sample"``) or the fixtures directory itself (``FIXTURES / name``, a
+listing of it) in its code, comments and docstrings aside, case-insensitively. Those readers then route to their tests as
+any namer does: a helper through the tests importing it, a conftest through
+the tests under it, and a helper no test imports runs everything. The file
+stays the namer, and so keeps the full run, when no test code names its tree
+or code outside test trees names the tree's path.
+"""
+
+from __future__ import annotations
+
+import io
+import re
+import tokenize
+from collections.abc import Callable, Collection, Mapping
+from pathlib import PurePosixPath
+
+# Directories holding test data, as named in ``test_paths``' support tokens.
+FIXTURE_DIRS = frozenset({"fixtures", "__fixtures__", "testdata"})
+
+
+def fixture_root(path: str) -> str | None:
+ """The fixture tree *path* sits in (``tests/fixtures/ts_sample``), ``None`` outside one.
+
+ The outermost fixtures directory decides; a file directly in it has no tree.
+ """
+ parts = PurePosixPath(path).parts
+ for i, part in enumerate(parts[:-2]):
+ if part.lower() in FIXTURE_DIRS:
+ return "/".join(parts[: i + 2])
+ return None
+
+
+def with_fixture_readers(
+ namers: Mapping[str, list[str]],
+ test_code: Collection[str],
+ other_code: Collection[str],
+ read: Callable[[str], str | None],
+ holding: Callable[[Collection[str]], Collection[str] | None] | None = None,
+) -> dict[str, list[str]]:
+ """*namers* with each fixture-tree namer replaced by the test code reading its tree.
+
+ *test_code* are the checkout's code files in test trees, *other_code* the
+ rest; *read* returns a file's text and *holding* (optional) narrows which
+ files to read to those holding a name.
+ """
+ roots = {r for found in namers.values() for n in found if (r := fixture_root(n))}
+ if not roots:
+ return {f: list(n) for f, n in namers.items()}
+ readers = _root_readers(roots, test_code, other_code, read, holding)
+ out: dict[str, list[str]] = {}
+ for f, found in namers.items():
+ kept: dict[str, None] = {}
+ for n in found:
+ kept.update(dict.fromkeys(r for r in _stand_ins(n, readers) if r != f))
+ out[f] = list(kept)
+ return out
+
+
+def _stand_ins(namer: str, readers: Mapping[str, list[str]]) -> list[str]:
+ root = fixture_root(namer)
+ return readers.get(root, [namer]) if root else [namer]
+
+
+def _root_readers(
+ roots: Collection[str],
+ test_code: Collection[str],
+ other_code: Collection[str],
+ read: Callable[[str], str | None],
+ holding: Callable[[Collection[str]], Collection[str] | None] | None,
+) -> dict[str, list[str]]:
+ """``{fixture root: test code reading it}``; a root that must keep its full run is absent."""
+ names = {n for r in roots for n in _dir_names(r)}
+ held = holding(names) if holding else None
+ texts = {
+ p: _code_text(p, read(p) or "").lower()
+ for p in sorted({*test_code, *other_code})
+ if held is None or p in held
+ }
+ out: dict[str, list[str]] = {}
+ for root in roots:
+ leaf, parent = _dir_names(root)
+ if any(root.lower() in texts[p] for p in other_code if p in texts):
+ continue # code outside the test trees names the tree: not only tests read it
+ found = [
+ p
+ for p in test_code
+ if p in texts and fixture_root(p) is None and _names_either(texts[p], leaf, parent)
+ ]
+ if found:
+ out[root] = found
+ return out
+
+
+def _dir_names(root: str) -> tuple[str, str]:
+ """The tree's directory name and the fixtures directory's, as written."""
+ path = PurePosixPath(root)
+ return path.name, path.parent.name
+
+
+def _names_either(text: str, *names: str) -> bool:
+ return any(
+ re.search(rf"(?<![\w\-]){re.escape(n.lower())}(?![\w\-])", text) is not None
+ for n in names
+ )
+
+
+def _code_text(path: str, text: str) -> str:
+ """*text* without comments, and for Python without docstrings: what can name a path.
+
+ Python that does not tokenize is kept whole.
+ """
+ from ..ingestion.languages.js_config_values import strip_comments
+ from ..ingestion.languages.python_strings import _is_statement
+
+ if not path.endswith(".py"):
+ # Ceiling: not string-aware, so a "/*" inside a string can hide code up to a "*/".
+ return strip_comments(text.encode("utf-8")).decode("utf-8", errors="replace")
+ try:
+ tokens = [
+ t
+ for t in tokenize.tokenize(io.BytesIO(text.encode("utf-8")).readline)
+ if t.type not in (tokenize.NL, tokenize.COMMENT)
+ ]
+ except (tokenize.TokenError, SyntaxError, ValueError):
+ return text
+ return " ".join(
+ t.string
+ for i, t in enumerate(tokens)
+ if i and not (t.type == tokenize.STRING and _is_statement(tokens, i))
+ )
diff --git a/packages/core/src/repowise/core/analysis/namer_paths.py b/packages/core/src/repowise/core/analysis/namer_paths.py
index ddd389d5f..cd961299a 100644
--- a/packages/core/src/repowise/core/analysis/namer_paths.py
+++ b/packages/core/src/repowise/core/analysis/namer_paths.py
@@ -5,7 +5,7 @@ text, and every workspace has many files of that name. A mention written with
its directory says which one it means. Each mention is reduced to its written
path, with leading ``/``, ``./`` and ``../`` steps and inner ``a/../`` folded
away (a relative path depends on the working directory, which the text does
-not give), and compared to the file's path, case-insensitively:
+not give), and compared to the file's path, case-insensitively (the name too):
- a written path names every file whose path ends in it
(``ui/package.json`` names ``packages/ui/package.json``), and every file
@@ -48,7 +48,7 @@ def mentions(text: str, name: str) -> list[str | None]:
A mention that is only part of a longer name is left out.
"""
out: list[str | None] = []
- for match in re.finditer(re.escape(name), text):
+ for match in re.finditer(re.escape(name), text, re.IGNORECASE):
if _continues(text, match.end()):
continue
prefix = _directory_part(text, match.start())
@@ -61,11 +61,11 @@ def mentions(text: str, name: str) -> list[str | None]:
def any_may_mean(written: Iterable[str | None], target: str) -> bool:
"""Whether any mention reduced by :func:`mentions` can mean *target*."""
- path = target.casefold()
+ path = target.lower()
for mention in written:
if mention is None:
return True
- tail = mention.casefold()
+ tail = mention.lower()
if tail == path or path.endswith(f"/{tail}") or tail.endswith(f"/{path}"):
return True
return False
diff --git a/packages/core/src/repowise/core/analysis/selection_scopes.py b/packages/core/src/repowise/core/analysis/selection_scopes.py
index abb8a1780..246ecc49f 100644
--- a/packages/core/src/repowise/core/analysis/selection_scopes.py
+++ b/packages/core/src/repowise/core/analysis/selection_scopes.py
@@ -23,8 +23,7 @@ A scope also runs the tests reaching each file that names the changed one, so
a test reading ``package.json`` as data is kept. An ecosystem scope already
holds its own ecosystem's code under its root, so only the namers outside it
are traced; more than :data:`MAX_NAMERS` of those that are not tests
-themselves (or of an asset's) run everything, since tracing that many costs
-what a full run saves. Package
+themselves (or of an asset's) run everything, a bound on the walk's cost. Package
roots are read from the tracked paths the caller already holds, which list
every manifest (the indexed file list misses some; see
:mod:`~repowise.core.ingestion.package_roots`). Ceilings: code that globs a
@@ -55,8 +54,12 @@ from .test_selection import (
is_runnable_test,
)
-# Namers past this many make a full run cheaper to decide than to trace.
-MAX_NAMERS = 50
+# Non-test namers past this many run everything. Set from the walk's cost, not
+# from how useful the subset is: 170 namers (630 routes) walk in about 6 s on a
+# 20k-file repository, inside the agent tools' 30 s budget. Ceiling: past it a
+# full run is the answer; bounding the walk by a time budget instead of a count
+# is the upgrade.
+MAX_NAMERS = 200
_JVM = (".java", ".kt", ".kts", ".scala", ".groovy")
# (ecosystem, test suffixes, scoped to the file's directory, gitwildmatch
diff --git a/packages/core/src/repowise/core/analysis/test_collection.py b/packages/core/src/repowise/core/analysis/test_collection.py
index 8527c7368..b624ae0e2 100644
--- a/packages/core/src/repowise/core/analysis/test_collection.py
+++ b/packages/core/src/repowise/core/analysis/test_collection.py
@@ -91,7 +91,7 @@ _GREP_TIMEOUT_SECONDS = 30
def _git_holding(root: Path, needles: Collection[str]) -> set[str] | None:
- """Tracked files whose working-tree bytes hold any of *needles*: one ``git grep``.
+ """Tracked files whose bytes hold any of *needles*, ignoring case: one ``git grep``.
The names go in on stdin (``-f -``), so no argument list grows with them.
``None`` when git cannot answer in time, or for a needle that is not plain
@@ -105,7 +105,7 @@ def _git_holding(root: Path, needles: Collection[str]) -> set[str] | None:
return None
patterns = "".join(f"{n}\n" for n in needles).encode("utf-8")
ran = git_run(
- root, "grep", "-l", "-z", "-F", "--no-color", "-f", "-", "--",
+ root, "grep", "-l", "-z", "-F", "-i", "--no-color", "-f", "-", "--",
stdin=patterns, timeout=_GREP_TIMEOUT_SECONDS,
) # fmt: skip
# Exit 1 is "no file holds any".
@@ -144,13 +144,15 @@ def plan_scopes(
*cancelled* is polled between file reads, so an abandoned selection stops
reading the checkout.
"""
+ from ..test_paths import is_test_related_path
+ from .fixture_readers import with_fixture_readers
from .selection_scopes import (
is_manifest,
keeps_full_run,
needs_namers,
trigger_scopes,
)
- from .test_selection import file_namers
+ from .test_selection import file_namers, is_code_file
paths = [*change.files, *change.deleted]
# A file that runs everything anyway makes every namer search moot.
@@ -159,6 +161,10 @@ def plan_scopes(
namers: dict[str, list[str]] = {}
if asked:
namers = file_namers(asked, _scan_texts(checkout, asked, cancelled), is_manifest)
+ code = [p for p in checkout.tracked if is_code_file(p)]
+ test_code = [p for p in code if is_test_related_path(p)]
+ other = [p for p in code if not is_test_related_path(p)]
+ namers = with_fixture_readers(namers, test_code, other, checkout.read, checkout.holding)
scopes = trigger_scopes(paths, checkout.tracked, namers, config)
routes = sorted({r for scope in scopes.values() for r in scope.routes} - set(paths))
return Plan(namers, scopes, routes)
diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.py
index f0fcb793a..e7e6210e7 100644
--- a/packages/core/src/repowise/core/analysis/test_selection.py
+++ b/packages/core/src/repowise/core/analysis/test_selection.py
@@ -342,8 +342,8 @@ def file_namers(
Code that reads a file names it (``ROOT / "README.md"``), and a
``--doctest-glob`` turns every doc into a test, so the config declaring
- one names each doc (first). One substring test per distinct file name and
- source. A file *exact* accepts is named only by a mention whose written
+ one names each doc (first). One case-insensitive substring test per
+ distinct file name and source. A file *exact* accepts is named only by a mention whose written
path can mean it (:mod:`~.namer_paths`); any other is
named by its name alone, since another asset may include it (a stylesheet
``@import``) where no code names its directory. Every namer is listed: a
@@ -382,8 +382,9 @@ def _named_in(
from .namer_paths import any_may_mean, mentions
out: list[str] = []
+ folded = text.lower()
for name, same in by_name.items():
- if name not in text:
+ if name.lower() not in folded:
continue
written = mentions(text, name) if exact and any(exact(f) for f in same) else None
out += [
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
index 5158936a5..47f252d46 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
@@ -3,7 +3,8 @@
Detects convention-based relationships (Django, FastAPI, Flask, ASP.NET, Rails,
Laravel, Spring, Express/Nest, Angular, Gin/Echo/Chi, Axum/Actix/Rocket, TYPO3, Godot
``class_name`` globals, pytest ``conftest.py``, JS/TS test-runner setup files,
-helpers a test names by path, and AWS Lambda handlers) and adds
+helpers a test names by path, Alembic migrations a command loads, the
+extension a VS Code extension test runs, and AWS Lambda handlers) and adds
``edge_type="framework"`` edges that no static import graph captures.
Previously a single ``framework_edges.py`` module; split (PR 3.5) into one
@@ -19,6 +20,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from . import (
+ alembic_runner,
android_manifest,
angular,
aspnet,
@@ -48,6 +50,7 @@ from . import (
test_runner_setup,
trpc,
typo3,
+ vscode_extension,
)
from .base import DetectionContext, FrameworkHandler, _add_edge_if_new, read_text
@@ -63,6 +66,8 @@ _HANDLERS: list[FrameworkHandler] = [
*pytest_edges.HANDLERS, # always runs
*test_runner_setup.HANDLERS,
*test_path_strings.HANDLERS,
+ *alembic_runner.HANDLERS,
+ *vscode_extension.HANDLERS,
*django.HANDLERS,
*fastapi.HANDLERS,
*flask.HANDLERS,
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/alembic_runner.py b/packages/core/src/repowise/core/ingestion/framework_edges/alembic_runner.py
new file mode 100644
index 000000000..51db7965e
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/alembic_runner.py
@@ -0,0 +1,128 @@
+"""Code that runs Alembic loads every migration script by path.
+
+``alembic.command.upgrade(config, "head")``, ``alembic.config.main(...)`` and
+an ``alembic upgrade`` subprocess all import ``env.py`` and each file in the
+script directory's ``versions/`` from the filesystem, so the code running them
+has no import edge to any of them, and a test that migrates a database
+reaches none of the migrations it runs.
+
+Any code file (Python, JavaScript, TypeScript) whose code names ``alembic`` (an import, an attribute, a command
+line in a string; comments and docstrings aside) gets an edge to every file
+of every script directory: a directory holding ``env.py`` beside a
+``versions/`` directory. A helper that runs the command passes it on to the
+tests importing the helper through their ordinary import edges. Over-claiming
+on a file that names Alembic without running it costs only a larger
+selection.
+
+Ceilings: ``version_locations`` outside ``<script dir>/versions`` and nested
+version directories are not followed, so a migration there has no edge and a
+change to it keeps its full run; every script directory in the repository is
+linked to every runner.
+"""
+
+from __future__ import annotations
+
+import io
+import posixpath
+import re
+import tokenize
+from typing import TYPE_CHECKING, Any
+
+from ..languages.python_strings import live_text
+from ..resolvers import ResolverContext
+from ..source_text import source_bytes
+from .base import DetectionContext, FrameworkHandler, _add_edge_if_new
+from .test_path_strings import _CODE_EXTS
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+# Stamped on the edge so consumers that mean "imports" can tell it apart.
+ALEMBIC_RUNNER_HINT = "alembic_runner"
+
+_WORD = re.compile(rb"(?<![\w.-])alembic(?![\w-])", re.IGNORECASE)
+# Python 3.12+ tokenizes an f-string's literal text as its own token type.
+_FSTRING_MIDDLE = getattr(tokenize, "FSTRING_MIDDLE", None)
+
+
+def script_files(path_set: set[str]) -> list[str]:
+ """``env.py`` and the migrations of every Alembic script directory in *path_set*."""
+ parents = {
+ posixpath.dirname(posixpath.dirname(p))
+ for p in path_set
+ if p.endswith(".py") and posixpath.basename(posixpath.dirname(p)) == "versions"
+ }
+ scripts = {d for d in parents if posixpath.join(d, "env.py") in path_set}
+ return sorted(p for p in path_set if _in_script_dir(p, scripts))
+
+
+def _in_script_dir(path: str, scripts: set[str]) -> bool:
+ """A migration in ``<script dir>/versions/``, or the script directory's ``env.py``."""
+ folder = posixpath.dirname(path)
+ if posixpath.basename(path) == "env.py":
+ return folder in scripts
+ return (
+ path.endswith(".py")
+ and posixpath.basename(folder) == "versions"
+ and posixpath.dirname(folder) in scripts
+ )
+
+
+def names_alembic(path: str, blob: bytes) -> bool:
+ """Whether *blob*'s code (not its comments or docstrings) names Alembic.
+
+ Python is read by token: a name ``alembic``, the word in an f-string's
+ text, or in a string that is not a docstring. Python that does not
+ tokenize counts when the word is anywhere in it.
+ """
+ if not _WORD.search(blob):
+ return False
+ if not path.endswith(".py"):
+ return bool(_WORD.search(live_text(path, blob)))
+ try:
+ for tok in tokenize.tokenize(io.BytesIO(blob).readline):
+ if tok.type == tokenize.NAME and tok.string == "alembic":
+ return True
+ # Since 3.12 an f-string is split into parts no string check sees.
+ if tok.type == _FSTRING_MIDDLE and _WORD.search(tok.string.encode("utf-8")):
+ return True
+ except (tokenize.TokenError, SyntaxError, ValueError):
+ return True
+ return bool(_WORD.search(live_text(path, blob)))
+
+
+def _add_runner_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext, path_set: set[str]
+) -> int:
+ scripts = script_files(path_set)
+ if not scripts:
+ return 0
+ count = 0
+ for path in sorted(p for p in path_set - set(scripts) if p.endswith(_CODE_EXTS)):
+ text = source_bytes(path, parsed_files[path].file_info.abs_path, ctx.source_map)
+ if not names_alembic(path, text):
+ continue
+ for target in scripts:
+ if _add_edge_if_new(graph, path, target):
+ graph[path][target]["hint_source"] = ALEMBIC_RUNNER_HINT
+ count += 1
+ return count
+
+
+class _AlembicRunnerHandler:
+ """Code running Alembic loads every migration script."""
+
+ def detect(self, dctx: DetectionContext) -> bool:
+ return True
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_runner_edges(graph, parsed_files, ctx, path_set)
+
+
+HANDLERS: list[FrameworkHandler] = [_AlembicRunnerHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/vscode_extension.py b/packages/core/src/repowise/core/ingestion/framework_edges/vscode_extension.py
new file mode 100644
index 000000000..09905e9a1
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/vscode_extension.py
@@ -0,0 +1,91 @@
+"""A VS Code extension test runs the extension its package declares.
+
+An extension test imports the ``vscode`` module and runs inside an editor
+host, which loads the package's ``main`` entry (``dist/extension.js``, built
+from ``src/extension.ts``) and activates it. The test has no import edge to
+that entry, so a change anywhere in the extension reaches no test. In a
+package whose ``package.json`` declares ``engines.vscode``, each test file
+importing ``vscode`` gets an edge to the files the manifest declares as its
+start (:func:`~..resolvers.ts_workspace.manifest_entry_paths`).
+
+Ceilings: a test run against another package's extension is not linked to
+it, and a launcher that starts the host without importing ``vscode``
+(``runTest.ts``) gets no edge. A ``main`` built from a source the index cannot
+map gives no entry, so no edge either, and a change to the extension keeps its
+full run.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING, Any
+
+from ..resolvers import ResolverContext
+from ..resolvers.ts_workspace import (
+ _parsed_package_jsons,
+ get_checked_in_builds,
+ manifest_entry_paths,
+)
+from ..source_text import source_bytes
+from .base import DetectionContext, FrameworkHandler, _add_edge_if_new
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+# Stamped on the edge so consumers that mean "imports" can tell it apart.
+VSCODE_HOST_HINT = "vscode_extension_host"
+
+_JS_EXTS = (".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts")
+_IMPORTS_VSCODE = re.compile(rb"""(?:from\s+|import\s+|require\(\s*|import\s*\(\s*)["']vscode["']""")
+
+
+def _extensions(ctx: ResolverContext, path_set: set[str]) -> dict[str, set[str]]:
+ """``{package dir: its entry files}`` for every package that is a VS Code extension."""
+ checked_in = get_checked_in_builds(ctx)
+ out: dict[str, set[str]] = {}
+ for pkg_dir, data in _parsed_package_jsons(ctx):
+ engines = data.get("engines")
+ if isinstance(engines, dict) and "vscode" in engines:
+ entries = manifest_entry_paths(pkg_dir, data, path_set, checked_in)
+ if entries:
+ out[pkg_dir] = entries
+ return out
+
+
+def _add_host_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext, path_set: set[str]
+) -> int:
+ extensions = _extensions(ctx, path_set)
+ count = 0
+ for pkg_dir, entries in sorted(extensions.items()):
+ prefix = "" if pkg_dir in ("", ".") else f"{pkg_dir}/"
+ for path in sorted(p for p in path_set if p.startswith(prefix) and p.endswith(_JS_EXTS)):
+ if not parsed_files[path].file_info.is_test:
+ continue
+ text = source_bytes(path, parsed_files[path].file_info.abs_path, ctx.source_map)
+ if not _IMPORTS_VSCODE.search(text):
+ continue
+ for entry in sorted(entries):
+ if _add_edge_if_new(graph, path, entry):
+ graph[path][entry]["hint_source"] = VSCODE_HOST_HINT
+ count += 1
+ return count
+
+
+class _VscodeHostHandler:
+ """Extension tests run the extension their package declares."""
+
+ def detect(self, dctx: DetectionContext) -> bool:
+ return True
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_host_edges(graph, parsed_files, ctx, path_set)
+
+
+HANDLERS: list[FrameworkHandler] = [_VscodeHostHandler()]
diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.py
index 0906ea5ab..85c09ea00 100644
--- a/packages/core/src/repowise/core/upgrade/version.py
+++ b/packages/core/src/repowise/core/upgrade/version.py
@@ -70,7 +70,11 @@ STORE_FORMAT_VERSION: int = 2
#: ``notNull#2``) and a C# generic type beside a same-named one gets its arity
#: (``IFoo`1``); the first update re-keys symbols and graph nodes repo-wide. A
#: C++ template function is one ``function`` symbol, no longer also a ``class``.
-PARSER_SCHEMA_VERSION: int = 6
+#:
+#: v7: code naming Alembic gets a framework edge to every migration it can
+#: load, and a VS Code extension test to the entry its package declares; the
+#: first update writes those edges for unchanged files too.
+PARSER_SCHEMA_VERSION: int = 7
#: state.json key holding the store format version that wrote the store.
STORE_FORMAT_VERSION_KEY = "store_format_version"
diff --git a/tests/unit/analysis/test_fixture_readers.py b/tests/unit/analysis/test_fixture_readers.py
new file mode 100644
index 000000000..206bec13c
--- /dev/null
+++ b/tests/unit/analysis/test_fixture_readers.py
@@ -0,0 +1,83 @@
+"""A fixture-tree namer stands for the test code that may read its fixture tree."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.fixture_readers import fixture_root, with_fixture_readers
+
+
+def test_a_fixture_root_is_the_directory_under_the_outermost_fixtures_directory() -> None:
+ assert fixture_root("tests/fixtures/ts_sample/packages/lib/src/orphan.ts") == (
+ "tests/fixtures/ts_sample"
+ )
+ assert fixture_root("pkg/__fixtures__/app/a.ts") == "pkg/__fixtures__/app"
+ assert fixture_root("tests/fixtures/repo/fixtures/inner/a.py") == "tests/fixtures/repo"
+ assert fixture_root("tests/Fixtures/repo/a.py") == "tests/Fixtures/repo"
+ assert fixture_root("tests/fixtures/data.json") is None
+ assert fixture_root("src/app.ts") is None
+
+
+_TEXTS = {
+ "tests/test_ts.py": 'ROOT = FIXTURES / "ts_sample"\n',
+ "tests/test_dynamic.py": 'ROOT = HERE / "fixtures" / f"{lang}_sample"\n',
+ "tests/test_fstring.py": 'ROOT = HERE / f"ts_sample/{part}"\n',
+ "tests/helpers.py": "def trees():\n return list((HERE / 'FIXTURES').iterdir())\n",
+ "tests/test_uses_helper.py": "from tests.helpers import trees\n",
+ "tests/conftest.py": "import pytest\n",
+ "tests/test_other.py": 'ROOT = "ts_sample_extra"\n',
+ "tests/fixtures/ts_sample/b.ts": "// ts_sample fixture\n",
+ "tests/web/fixtures/data.ts": "/** Synthetic fixtures. */\nexport const page = 1;\n",
+ "tests/test_doc.py": '"""Reads fixtures."""\nx = 1 # fixtures\n',
+ "src/app.py": "FIXTURE_WORDS = ('fixtures',)\n",
+}
+_TEST_CODE = [p for p in _TEXTS if p.startswith("tests/")]
+_OTHER = [p for p in _TEXTS if not p.startswith("tests/")]
+
+
+def _read(path: str) -> str | None:
+ return _TEXTS.get(path)
+
+
+def test_a_fixture_namer_becomes_every_piece_of_test_code_naming_its_tree() -> None:
+ namers = {"package.json": ["src/cli.py", "tests/fixtures/ts_sample/a.ts"]}
+ out = with_fixture_readers(namers, _TEST_CODE, _OTHER, _read)
+ # A helper and a dynamically built tree name are readers too; the helper
+ # routes to its importers like any namer. Fixture files are not readers,
+ # nor is a mention in a comment or a docstring.
+ assert out == {
+ "package.json": [
+ "src/cli.py",
+ "tests/test_ts.py",
+ "tests/test_dynamic.py",
+ "tests/test_fstring.py",
+ "tests/helpers.py",
+ ]
+ }
+
+
+def test_trees_sharing_a_name_share_their_readers() -> None:
+ namers = {"package.json": ["a/fixtures/ts_sample/x.ts", "b/fixtures/ts_sample/y.ts"]}
+ out = with_fixture_readers(namers, _TEST_CODE, _OTHER, _read)["package.json"]
+ assert "tests/test_ts.py" in out
+ assert not any("fixtures/ts_sample" in p for p in out)
+
+
+def test_a_tree_no_test_code_names_keeps_its_file_as_the_namer() -> None:
+ namers = {"package.json": ["tests/fixtures/go_sample/main.go"]}
+ assert with_fixture_readers(namers, ["tests/test_other.py"], [], _read) == namers
+
+
+def test_a_tree_named_by_code_outside_the_test_trees_keeps_its_full_run() -> None:
+ texts = {**_TEXTS, "src/indexer.py": 'SAMPLE = "tests/fixtures/ts_sample"\n'}
+ namers = {"package.json": ["tests/fixtures/ts_sample/a.ts"]}
+ out = with_fixture_readers(namers, _TEST_CODE, [*_OTHER, "src/indexer.py"], texts.get)
+ assert out == namers
+
+
+def test_grep_narrowing_gives_the_same_readers() -> None:
+ namers = {"package.json": ["tests/fixtures/ts_sample/a.ts"]}
+
+ def holding(names):
+ return {p for p, t in _TEXTS.items() if any(n.lower() in t.lower() for n in names)}
+
+ narrowed = with_fixture_readers(namers, _TEST_CODE, _OTHER, _read, holding)
+ assert narrowed == with_fixture_readers(namers, _TEST_CODE, _OTHER, _read)
diff --git a/tests/unit/analysis/test_namer_paths.py b/tests/unit/analysis/test_namer_paths.py
index 32eba8eac..551ee06fa 100644
--- a/tests/unit/analysis/test_namer_paths.py
+++ b/tests/unit/analysis/test_namer_paths.py
@@ -22,6 +22,8 @@ _UI = "packages/ui/package.json"
('"myrepo/packages/ui/package.json"', True),
('"file:///abs/repo/packages/ui/package.json"', True),
('"PACKAGES/UI/package.json"', True),
+ ('"PACKAGES/UI/PACKAGE.JSON"', True),
+ ('"PACKAGE.JSON"', True),
('ROOT / "packages/web/package.json"', False),
('"tests/fixtures/package.json"', False),
('"/app/packages/web/package.json"', False),
diff --git a/tests/unit/analysis/test_selection_scopes.py b/tests/unit/analysis/test_selection_scopes.py
index c80f01dad..70f2f0e6d 100644
--- a/tests/unit/analysis/test_selection_scopes.py
+++ b/tests/unit/analysis/test_selection_scopes.py
@@ -316,6 +316,7 @@ def _namer_checkout(tmp_path):
"web/src/app.test.ts": "readFileSync('package.json')\n",
"tools/build.py": "print('web/package.json', 'README.md')\n",
"tools/data.py": "open('docs/data.md')\n",
+ "tools/upper.py": "open('WEB/PACKAGE.JSON')\n",
"docs/a.md": "# a\n",
"docs/data.md": "# data\n",
"src/mod.py": "x = 1\n",
@@ -348,8 +349,10 @@ def test_plan_scopes_names_the_same_files_from_git_grep_as_from_reading_them(tmp
assert checkout.holding is not None
grepped = plan_scopes(change, _NONE, checkout)
assert grepped == plan_scopes(change, _NONE, replace(checkout, holding=None))
+ # The name is matched ignoring case, in the grep and in the read alike.
assert grepped.namers["web/package.json"] == [
"tools/build.py",
+ "tools/upper.py",
"web/src/app.test.ts",
"web/src/app.ts",
]
diff --git a/tests/unit/ingestion/test_loader_edges.py b/tests/unit/ingestion/test_loader_edges.py
new file mode 100644
index 000000000..c5711da20
--- /dev/null
+++ b/tests/unit/ingestion/test_loader_edges.py
@@ -0,0 +1,130 @@
+"""Files a runtime loads by path for a test: Alembic migrations and a VS Code extension's entry."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import networkx as nx
+import pytest
+
+from repowise.core.ingestion.framework_edges.alembic_runner import (
+ ALEMBIC_RUNNER_HINT,
+ _add_runner_edges,
+)
+from repowise.core.ingestion.framework_edges.vscode_extension import (
+ VSCODE_HOST_HINT,
+ _add_host_edges,
+)
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.test_paths import is_test_related_path
+
+
+def _ctx(sources: dict[str, str], repo_path=None) -> tuple[nx.DiGraph, dict, ResolverContext]:
+ graph = nx.DiGraph()
+ graph.add_nodes_from(sources)
+ parsed = {
+ p: SimpleNamespace(file_info=SimpleNamespace(is_test=is_test_related_path(p), abs_path=p))
+ for p in sources
+ }
+ ctx = ResolverContext(
+ path_set=set(sources),
+ stem_map={},
+ graph=graph,
+ repo_path=repo_path,
+ source_map={p: s.encode() for p, s in sources.items()},
+ )
+ return graph, parsed, ctx
+
+
+def _edges(graph: nx.DiGraph, hint: str) -> set[tuple[str, str]]:
+ return {(s, t) for s, t, d in graph.edges(data=True) if d.get("hint_source") == hint}
+
+
+_SCRIPTS = {
+ "db/alembic/env.py": "from alembic import context\n",
+ "db/alembic/versions/0001_init.py": "from alembic import op\ndef upgrade(): ...\n",
+ "db/alembic/versions/0002_more.py": "def upgrade(): ...\n",
+ # A versions directory with no env.py beside it is not a script directory.
+ "app/versions/v1.py": "x = 1\n",
+}
+_LINKED = {
+ "db/alembic/env.py",
+ "db/alembic/versions/0001_init.py",
+ "db/alembic/versions/0002_more.py",
+}
+
+
+ ("runner", "linked"),
+ [
+ ("from alembic import command\ncommand.upgrade(cfg, 'head')\n", True),
+ ("from alembic import (\n command,\n)\n", True),
+ ("import alembic.config\nalembic.config.main(argv=['upgrade', 'head'])\n", True),
+ ("import alembic\nalembic.command.upgrade(cfg, 'head')\n", True),
+ ("subprocess.run(['alembic', 'upgrade', 'head'])\n", True),
+ ("os.system('alembic upgrade head')\n", True),
+ ('subprocess.run(f"alembic upgrade {rev}", shell=True)\n', True),
+ ('subprocess.run(f"{tool} upgrade {rev}")\n', False),
+ ("from tests.db import migrate # alembic underneath\n", False),
+ ('"""Runs alembic in CI."""\nx = 1\n', False),
+ ("import alembic_utils\n", False),
+ ],
+)
+def test_code_naming_alembic_reaches_every_migration(runner: str, linked: bool) -> None:
+ graph, parsed, ctx = _ctx({**_SCRIPTS, "tests/test_migrate.py": runner})
+ _add_runner_edges(graph, parsed, ctx, ctx.path_set)
+ expected = {("tests/test_migrate.py", s) for s in _LINKED} if linked else set()
+ assert _edges(graph, ALEMBIC_RUNNER_HINT) == expected
+
+
+def test_a_helper_running_alembic_passes_it_on_through_its_importers() -> None:
+ sources = {**_SCRIPTS, "tests/db.py": "from alembic import command\n", "tests/t.py": "x\n"}
+ graph, parsed, ctx = _ctx(sources)
+ _add_runner_edges(graph, parsed, ctx, ctx.path_set)
+ assert {s for s, _ in _edges(graph, ALEMBIC_RUNNER_HINT)} == {"tests/db.py"}
+
+
+def test_a_migration_outside_a_script_directory_gets_no_edge() -> None:
+ graph, parsed, ctx = _ctx({**_SCRIPTS, "tests/test_m.py": "import alembic\n"})
+ _add_runner_edges(graph, parsed, ctx, ctx.path_set)
+ assert {t for _, t in _edges(graph, ALEMBIC_RUNNER_HINT)} == _LINKED
+
+
+def test_an_extension_test_reaches_the_entry_its_package_declares(tmp_path) -> None:
+ manifest = {"name": "ext", "main": "./dist/extension.js", "engines": {"vscode": "^1.90.0"}}
+ (tmp_path / "ext").mkdir()
+ (tmp_path / "ext" / "package.json").write_text(json.dumps(manifest), encoding="utf-8")
+ (tmp_path / "lib").mkdir()
+ (tmp_path / "lib" / "package.json").write_text('{"main": "index.js"}', encoding="utf-8")
+ graph, parsed, ctx = _ctx(
+ {
+ "ext/src/extension.ts": "export function activate() {}\n",
+ "ext/src/test/extension.test.ts": 'import * as vscode from "vscode";\n',
+ "ext/webview/src/app.test.ts": 'import { render } from "./app";\n',
+ "lib/index.js": "module.exports = {}\n",
+ "lib/index.test.js": 'const vscode = require("vscode");\n',
+ "ext/src/test/bare.test.ts": 'import "vscode";\n',
+ },
+ repo_path=tmp_path,
+ )
+ assert _add_host_edges(graph, parsed, ctx, ctx.path_set) == 2
+ assert _edges(graph, VSCODE_HOST_HINT) == {
+ ("ext/src/test/extension.test.ts", "ext/src/extension.ts"),
+ ("ext/src/test/bare.test.ts", "ext/src/extension.ts"),
+ }
+
+
+def test_an_entry_built_from_no_known_source_gives_no_edge(tmp_path) -> None:
+ manifest = {"main": "./out/bundle.js", "engines": {"vscode": "^1.90.0"}}
+ (tmp_path / "ext").mkdir()
+ (tmp_path / "ext" / "package.json").write_text(json.dumps(manifest), encoding="utf-8")
+ graph, parsed, ctx = _ctx(
+ {
+ "ext/lib/activate.ts": "export function activate() {}\n",
+ "ext/src/test/extension.test.ts": 'import * as vscode from "vscode";\n',
+ },
+ repo_path=tmp_path,
+ )
+ # No edge, so a change to the extension's code keeps its full run.
+ assert _add_host_edges(graph, parsed, ctx, ctx.path_set) == 0