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(dead-code): treat files a tool config or usage line names as entry points (#3508)

Raghav Chamadiya4c0541ad789b
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 0db524073..3f136b40a 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -616,6 +616,9 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*vitest.workspace.*",
"*vitest.shims.*",
"*vitest.root.*",
+ # @vscode/test-cli reads its config by this name from the working directory.
+ *(f".vscode-test{ext}" for ext in _JS_TOOL_EXTS),
+ *(f"*/.vscode-test{ext}" for ext in _JS_TOOL_EXTS),
# Codegen / generated artifacts.
"*.gen.ts",
"*.gen.tsx",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py b/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py
index 4e90a226d..2fe7eb2fe 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/entry_shape.py
@@ -14,9 +14,10 @@ never imported in the first place:
also exports its input type), belongs to the same set.
Each caps the finding to the review tier, except a program: a file whose
-first line is a shebang or that runs under a ``__main__`` guard is an entry
-point, so :func:`drop_program_entries` removes it. The cap also stops
-"no commits in 90 days" lifting such a file to the high tier, since an
+first line is a shebang, that runs under a ``__main__`` guard or that writes
+the ``python <its path>`` command running it is an entry point, so
+:func:`drop_program_entries` removes it. The cap also stops "no commits in
+90 days" lifting such a file to the high tier, since an
untouched loaded file is not an unused one. Shape is not proof of use, so the
file stays listed as a candidate for a person to check.
"""
@@ -91,7 +92,7 @@ def _parse_python(path: str, blob: bytes) -> ast.Module | None:
def _program_reason(path: str, blob: bytes) -> str | None:
- """Why *blob* says it is a program: a shebang or a Python main guard."""
+ """Why *blob* says it is a program: a shebang, a Python main guard or usage line."""
# ``#![`` opens a Rust inner attribute (``#![doc = ...]``), not a shebang.
if blob.startswith(b"#!") and not blob.startswith(b"#!["):
return "Starts with a shebang, so it is run directly rather than imported"
@@ -100,11 +101,33 @@ def _program_reason(path: str, blob: bytes) -> str | None:
isinstance(stmt, ast.If) and _is_main_guard(stmt.test) for stmt in tree.body
):
return 'Has an `if __name__ == "__main__"` block, so it is run as a script'
+ if _runs_itself(path, blob):
+ return "Its own text gives the command that runs it, so it is run as a script"
return None
+def _runs_itself(path: str, blob: bytes) -> bool:
+ """Whether a Python file writes a ``python <its own path>`` usage line.
+
+ Only the file's own path counts, written whole or as a tail of it
+ (``run.py``, ``a/run.py``): a usage line for another script, even one of
+ the same name in another directory, says nothing about this one.
+ """
+ if not path.endswith(".py"):
+ return False
+ name = re.escape(path.rpartition("/")[2].encode())
+ command = rb"\bpython[\d.]*[ \t]+(?:-\S+[ \t]+)*((?:[\w.\\/-]*[\\/])?" + name + rb")(?![\w.])"
+ return any(_names_path(m.group(1), path) for m in re.finditer(command, blob))
+
+
+def _names_path(written: bytes, path: str) -> bool:
+ """Whether *written*, a path as a command line spells it, is *path* or a tail of it."""
+ tail = written.decode("ascii", "ignore").replace("\\", "/").removeprefix("./")
+ return f"/{path}".endswith(f"/{tail}")
+
+
def is_program(path: str, blob: bytes) -> bool:
- """Whether *blob* says it is a program: a shebang, or a Python main guard.
+ """Whether *blob* says it is a program: a shebang, a main guard or a usage line.
Either is the author stating the file is started by a command. Statements
at module level are weaker (an imported module can run code on load), so
diff --git a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py
index 49406d698..1af8c7fb1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/name_occurrences.py
@@ -48,11 +48,11 @@ from __future__ import annotations
import posixpath
import re
from collections.abc import Iterable, Mapping
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from enum import Enum
from pathlib import PurePosixPath
-from ...ingestion.languages.js_config_values import value_spans
+from ...ingestion.languages.js_config_values import plugin_path_arguments, value_spans
from ...ingestion.languages.registry import REGISTRY
from .constants import (
_BARE_NAME_USE_LANGUAGES,
@@ -619,7 +619,8 @@ def clamp_path_mentions(
return findings
named_in = _files_naming({f.file_path for f in in_scope}, source_map)
- run = {id(f) for f in in_scope if _loaded(f, named_in.get(f.file_path, ()), source_map)}
+ loads = _ConfigLoads(source_map)
+ run = {id(f) for f in in_scope if _loaded(f, named_in.get(f.file_path, ()), loads)}
kept = [f for f in findings if id(f) not in run]
for finding in kept:
if finding.kind is DeadCodeKind.UNREACHABLE_FILE:
@@ -627,30 +628,47 @@ def clamp_path_mentions(
return kept
-def _loaded(
- finding: DeadCodeFindingData, namers: Iterable[str], source_map: dict[str, bytes]
-) -> bool:
+def _loaded(finding: DeadCodeFindingData, namers: Iterable[str], loads: _ConfigLoads) -> bool:
"""Whether *namers* load the file of *finding* in the way the finding denies.
- A tool config is read only through its load keys, even when it is also a
+ A tool config is read only through its load keys and plugin path
+ arguments, even when it is also a
runner by name (a bundler config is a build file): a path it mentions in a
comment or an ignore list is not loaded.
"""
path = finding.file_path
configs = [n for n in namers if is_tool_config(n)]
- loaders = [n for n in configs if _config_loads(n, path, source_map)]
+ loaders = [n for n in configs if loads.loads(n, path)]
if finding.kind is DeadCodeKind.UNREACHABLE_FILE:
others = (n for n in namers if n not in configs)
return bool(loaders) or any(map(is_runner_file, others))
- return bool(loaders) and "default" in export_shape(path, frozenset(), source_map.get(path))
-
-
-def _config_loads(config: str, target: str, source_map: dict[str, bytes]) -> bool:
- """Whether *config* names *target* under one of its load keys."""
- values = b"\n".join(value_spans(source_map.get(config, b""), _TOOL_CONFIG_LOAD_KEYS))
- wanted = {key: {target} for key in _path_keys(target)}
- tails = {key.rpartition("/")[2] for key in wanted}
- return target in _targets_in(values, wanted, tails, config.rpartition("/")[0])
+ source = loads.source_map.get(path)
+ return bool(loaders) and "default" in export_shape(path, frozenset(), source)
+
+
+@dataclass
+class _ConfigLoads:
+ """What each tool config loads, read once per config for the whole pass."""
+
+ source_map: dict[str, bytes]
+ _values: dict[str, bytes] = field(default_factory=dict)
+
+ def loads(self, config: str, target: str) -> bool:
+ """Whether *config* names *target* under a load key or as a plugin's path."""
+ wanted = {key: {target} for key in _path_keys(target)}
+ tails = {key.rpartition("/")[2] for key in wanted}
+ base = config.rpartition("/")[0]
+ return target in _targets_in(self._load_values(config), wanted, tails, base)
+
+ def _load_values(self, config: str) -> bytes:
+ if config not in self._values:
+ text = self.source_map.get(config, b"")
+ # Re-quoted so _targets_in reads each as the one path token it is;
+ # a bare word argument is a name, not a file, so it needs a "/".
+ paths = [f'"{s}"'.encode() for s in plugin_path_arguments(text) if "/" in s]
+ spans = value_spans(text, _TOOL_CONFIG_LOAD_KEYS)
+ self._values[config] = b"\n".join([*spans, *paths])
+ return self._values[config]
def _cap_named_by_path(finding: DeadCodeFindingData, namers: list[str] | None) -> None:
diff --git a/packages/core/src/repowise/core/ingestion/languages/js_config_values.py b/packages/core/src/repowise/core/ingestion/languages/js_config_values.py
index 1bbe395b2..80f93b7a9 100644
--- a/packages/core/src/repowise/core/ingestion/languages/js_config_values.py
+++ b/packages/core/src/repowise/core/ingestion/languages/js_config_values.py
@@ -61,6 +61,46 @@ def string_literals(span: bytes) -> list[str]:
return out
+# A plugin factory call: the last name segment ends in ``Plugin``
+# (``createNextIntlPlugin(``, ``x.somePlugin(``). Ceiling: the one shape seen
+# taking a loaded file; a ``with*`` wrapper taking a path is not read until a
+# config shows one.
+_PLUGIN_CALL_RE = re.compile(rb"(?<![\w$])(?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*Plugin\s*\(")
+
+
+def plugin_path_arguments(text: bytes) -> list[str]:
+ """The string literal each plugin factory call in a config takes first.
+
+ ``createNextIntlPlugin("./src/i18n/request.ts")`` hands next-intl a file to
+ load. Any other call's literal (``resolve(...)``, ``glob.sync(...)``) is a
+ path the config computes with, not one a tool loads.
+ """
+ text = strip_comments(text)
+ out: list[str] = []
+ for call in _code_matches(text, _PLUGIN_CALL_RE):
+ arg = text[call.end() : _value_end(text, call.end())].strip()
+ if arg[:1] in _QUOTES and _string_end(arg, 0) == len(arg) - 1:
+ out.extend(string_literals(arg))
+ return out
+
+
+def _code_matches(text: bytes, pattern: re.Pattern[bytes]) -> list[re.Match[bytes]]:
+ """Where *pattern* matches *text* outside any string or template literal.
+
+ A plugin call written inside a literal (``"somePlugin('./x')"``) is text,
+ not a call. Ceiling: a call inside a template literal's ``${...}`` hole is
+ skipped too.
+ """
+ out: list[re.Match[bytes]] = []
+ i = 0
+ for match in pattern.finditer(text):
+ while i < match.start():
+ i = _string_end(text, i) + 1 if text[i] in _QUOTES else i + 1
+ if i == match.start():
+ out.append(match)
+ return out
+
+
def _value_end(text: bytes, start: int) -> int:
"""Where the value expression starting at *start* ends.
diff --git a/tests/unit/analysis/test_ts_never_flag.py b/tests/unit/analysis/test_ts_never_flag.py
index cdfc12a60..392d2fe6e 100644
--- a/tests/unit/analysis/test_ts_never_flag.py
+++ b/tests/unit/analysis/test_ts_never_flag.py
@@ -56,6 +56,12 @@ class TestStoriesAndBench:
assert not _matches("packages/ui/src/manager.js")
assert not _matches("preview.tsx")
+ def test_vscode_test_cli_config(self):
+ # @vscode/test-cli loads .vscode-test.{js,mjs,cjs} by name.
+ assert _matches(".vscode-test.mjs")
+ assert _matches("packages/vscode/.vscode-test.js")
+ assert not _matches("src/vscode-test.mjs")
+
def test_bench_files(self):
assert _matches("packages/zod/bench/arr.bench.ts")
assert _matches("bench/parse.bench.js")
diff --git a/tests/unit/dead_code/test_path_mentions.py b/tests/unit/dead_code/test_path_mentions.py
index 18e10da37..c302b07ac 100644
--- a/tests/unit/dead_code/test_path_mentions.py
+++ b/tests/unit/dead_code/test_path_mentions.py
@@ -9,6 +9,8 @@ keeps its confidence.
from __future__ import annotations
+import pytest
+
from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
from repowise.core.analysis.dead_code.models import DeadCodeFindingData
from repowise.core.analysis.dead_code.name_occurrences import clamp_path_mentions
@@ -213,3 +215,61 @@ def test_a_bundler_config_that_is_also_a_runner_still_needs_a_load_key(monkeypat
config = "// removed ./src/gone.ts last release\nexport default { entry: ['src/index.ts'] }\n"
assert not _dropped("src/gone.ts", {"tsup.config.ts": config})
assert _dropped("src/index.ts", {"tsup.config.ts": config})
+
+
+def test_a_config_passing_a_file_path_to_a_plugin_loads_it():
+ # repowise: packages/web/next.config.ts hands next-intl its request config.
+ config = 'const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");\n'
+ assert _dropped("packages/web/src/i18n/request.ts", {"packages/web/next.config.ts": config})
+
+
+def test_a_plugin_path_argument_needs_a_path_not_a_bare_word():
+ config = 'const plugin = makePlugin("request.ts");\n'
+ assert not _dropped("request.ts", {"next.config.ts": config})
+
+
+ "config",
+ [
+ # A path computed into a variable the ignore list then uses.
+ 'const legacy = path.resolve(__dirname, "src/old.ts");\n'
+ "export default [{ ignores: [legacy] }];\n",
+ 'const files = glob.sync("src/old.ts");\n',
+ 'const text = fs.readFileSync("src/old.ts", "utf8");\n',
+ 'console.log("src/old.ts");\n',
+ 'export default [globalIgnores(["src/old.ts"]), globalIgnores("src/old.ts")];\n',
+ # Nested: only the outer call is a config factory, neither is a plugin.
+ 'export default defineConfig(resolve("src/old.ts"));\n',
+ "export default defineConfig({ ignores: [resolve('./src/old.ts')] });\n",
+ # A plugin's second argument, or a path it computes with, is not its file.
+ 'export default somePlugin({}, "src/old.ts");\n',
+ 'export default somePlugin(resolve("src/old.ts"));\n',
+ # Imported by require: an import edge answers that, not this rule.
+ 'const old = require("./src/old.ts");\n',
+ ],
+)
+def test_a_path_a_config_only_computes_with_is_not_loaded(config):
+ for name in ("eslint.config.js", "next.config.ts"):
+ assert not _dropped("src/old.ts", {name: config})
+ finding = _export("src/old.ts", "default")
+ source = {name: config, "src/old.ts": "export default 1;\n"}
+ assert clamp_path_mentions([finding], {p: s.encode() for p, s in source.items()})
+
+
+def test_a_plugin_in_a_plugins_array_loads_its_path():
+ config = 'export default { plugins: [mdxPlugin("./src/mdx-components.tsx")] };\n'
+ assert _dropped("src/mdx-components.tsx", {"vite.config.ts": config})
+
+
+ "config",
+ [
+ "const note = \"somePlugin('./src/old.ts')\";\n",
+ "const note = 'somePlugin(\"./src/old.ts\")';\n",
+ "const note = `somePlugin('./src/old.ts')`;\n",
+ ],
+)
+def test_plugin_call_text_inside_a_string_is_not_a_load(config):
+ assert not _dropped("src/old.ts", {"next.config.ts": config})
+ # A real call after the literal still loads its file.
+ assert _dropped("src/old.ts", {"next.config.ts": config + 'somePlugin("./src/old.ts");\n'})
diff --git a/tests/unit/dead_code/test_script_entry_points.py b/tests/unit/dead_code/test_script_entry_points.py
index 73e2c6cdc..53d53265e 100644
--- a/tests/unit/dead_code/test_script_entry_points.py
+++ b/tests/unit/dead_code/test_script_entry_points.py
@@ -37,6 +37,27 @@ def test_a_python_main_guard_is_not_unreachable():
assert files == set()
+def test_a_script_whose_docstring_runs_it_is_not_unreachable():
+ # repowise: scripts/gen_readme_hero.py, run by hand per its usage line.
+ body = b'"""Draw the hero.\n\n python scripts/hero.py light\n"""\nimport sys\nprint(sys.argv)\n'
+ files = _unreachable({"scripts/hero.py": {"symbols": []}}, {"scripts/hero.py": body})
+ assert files == set()
+
+
+def test_a_usage_line_for_another_script_is_not_a_program():
+ body = b'"""Helpers for python scripts/run_hero.py."""\nX = 1\n'
+ files = _unreachable({"scripts/hero.py": {"symbols": []}}, {"scripts/hero.py": body})
+ assert files == {"scripts/hero.py"}
+
+
+def test_a_usage_line_for_a_same_named_script_elsewhere_is_not_a_program():
+ body = b'"""Wraps it.\n\n python pkg/b/run.py\n"""\nX = 1\n'
+ files = _unreachable({"pkg/a/run.py": {"symbols": []}}, {"pkg/a/run.py": body})
+ assert files == {"pkg/a/run.py"}
+ own = b'"""Usage: python ./pkg/a/run.py or python a/run.py"""\nX = 1\n'
+ assert _unreachable({"pkg/a/run.py": {"symbols": []}}, {"pkg/a/run.py": own}) == set()
+
+
def test_a_script_a_ci_workflow_runs_is_not_unreachable():
workflow = b"jobs:\n check:\n steps:\n - run: python scripts/emit_sample_dsl.py\n"
files = _unreachable(