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): an export its own file uses is export-only, not dead (#3510)

Raghav Chamadiyab551d6653a51
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index d03fbd67a..7af37fb2d 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -352,6 +352,7 @@ def dead_code_command(
"risk_factors": f.risk_factors,
"lines": f.lines,
"primary_owner": f.primary_owner,
+ "export_only": f.export_only,
}
)
click.echo(json.dumps(output, indent=2))
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index ddc91fd83..f2253331b 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -77,6 +77,7 @@ from .name_occurrences import (
clamp_named_types,
clamp_path_mentions,
clamp_unverified_absence,
+ demote_exports_used_in_own_code,
demote_used_in_own_file,
drop_bare_name_uses,
drop_internals_used_in_own_file,
@@ -1013,6 +1014,9 @@ class DeadCodeAnalyzer:
# version of the same question — not "could an unread file explain
# this" but "did we look anywhere except the import graph".
findings = drop_bare_name_uses(findings, self._source_map)
+ # Before the clamp, which would otherwise read a same-file use as
+ # "named elsewhere" and leave the row in the default view.
+ findings = demote_exports_used_in_own_code(findings, self._source_map)
findings = clamp_unverified_absence(findings, self._source_map)
findings = drop_internals_used_in_own_file(findings, self._source_map)
findings = clamp_path_mentions(findings, self._source_map)
diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.py
index 70532f15a..f56d8d618 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/models.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py
@@ -42,6 +42,10 @@ class DeadCodeFindingData:
# only; file/package-kind findings leave both None).
start_line: int | None = None
end_line: int | None = None
+ # An unused export its own file uses: only the ``export`` is unneeded, so
+ # no line of it is deletable. Capped below the stored floor, so only a live
+ # run (the CLI below ``--min-confidence 0.4``) ever shows one.
+ export_only: bool = False
@property
def is_spanned_symbol(self) -> bool:
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 1af8c7fb1..4a276e3cf 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
@@ -52,8 +52,14 @@ from dataclasses import dataclass, field
from enum import Enum
from pathlib import PurePosixPath
+from ...ingestion.extractors.visibility import (
+ _TS_EXPORT_ASSIGN_RE,
+ _TS_EXPORT_DEFAULT_NAME_RE,
+ _TS_EXPORT_LIST_SOURCE_RE,
+)
from ...ingestion.languages.js_config_values import plugin_path_arguments, value_spans
from ...ingestion.languages.registry import REGISTRY
+from ...ingestion.source_mask import can_mask, mask_source
from .constants import (
_BARE_NAME_USE_LANGUAGES,
_NON_CODE_LANGUAGES,
@@ -197,29 +203,84 @@ def _uses_in_own_file(
def demote_used_in_own_file(
findings: list[DeadCodeFindingData], source_map: dict[str, bytes]
) -> None:
- """Cap *findings* whose name their own file writes outside their span.
-
- For an unused export no other file names: a use beside it (a request type
- its endpoint takes, a helper the class below calls) means it is used and
- at most exported wider than it needs to be. Kept below the review floor
- with the line that uses it, rather than dropped, since a same-file use by
- a symbol that is itself dead keeps it alive. Mutates in place.
+ """Mark *findings* whose name their own file writes outside their span export-only.
+
+ For an unused export: a use beside it (a request type its endpoint takes,
+ a constant the function below reads) means it is used and at most
+ exported wider than it needs to be. Kept below the review floor with the
+ line that uses it, never deletion-ready, rather than dropped, since a
+ same-file use by a symbol that is itself dead keeps it alive. Mutates in
+ place.
"""
by_file: dict[str, list[DeadCodeFindingData]] = {}
for finding in findings:
- if finding.symbol_name and finding.file_path in source_map:
+ # Already marked by another reading of the same file: one verdict, one line.
+ if finding.symbol_name and finding.file_path in source_map and not finding.export_only:
by_file.setdefault(finding.file_path, []).append(finding)
for path, pending in by_file.items():
verdicts = _uses_in_own_file(source_map, path, pending)
for finding in pending:
verdict = verdicts[id(finding)]
- if verdict.answer is not _Answer.USED:
- continue
- finding.confidence = min(finding.confidence, UNVERIFIED_INTERNAL_CONFIDENCE)
- finding.safe_to_delete = False
- finding.evidence.append(
- f"Used in its own file at {verdict.used_at}; at most it need not be public"
- )
+ if verdict.answer is _Answer.USED:
+ _mark_export_only(finding, verdict.used_at)
+
+
+def _mark_export_only(finding: DeadCodeFindingData, used_at: str | None) -> None:
+ finding.export_only = True
+ finding.confidence = min(finding.confidence, UNVERIFIED_INTERNAL_CONFIDENCE)
+ finding.safe_to_delete = False
+ finding.reason = f"'{finding.symbol_name}' is used in its own file; only its export is unused"
+ finding.evidence.append(f"Used in its own file at {used_at}; at most it need not be public")
+
+
+def demote_exports_used_in_own_code(
+ findings: list[DeadCodeFindingData], source_map: dict[str, bytes]
+) -> list[DeadCodeFindingData]:
+ """:func:`demote_used_in_own_file` for Python and JS-family unused exports.
+
+ Read with comments and string bodies blanked, so a name listed in
+ ``__all__`` or mentioned in a docstring is not a use, while a template
+ literal's ``${NAME}`` still is. A JS/TS export clause (``export { X }``,
+ ``export default X``) only publishes the name, so it is blanked too.
+ Ceiling: a Python f-string's ``{NAME}`` is blanked as well, so such a use
+ is missed and the finding stays as it was.
+ Other languages are left to :func:`clamp_unverified_absence`. Each file is
+ masked once. Returns the same list.
+ """
+ exports = [
+ f
+ for f in findings
+ if f.kind is DeadCodeKind.UNUSED_EXPORT
+ and f.file_path in source_map
+ and can_mask(PurePosixPath(f.file_path).suffix)
+ ]
+ masked = {path: _own_code(path, source_map[path]) for path in {f.file_path for f in exports}}
+ demote_used_in_own_file(exports, masked)
+ return findings
+
+
+#: Statements that only publish a name the file declares, never use it.
+_EXPORT_CLAUSES = (_TS_EXPORT_LIST_SOURCE_RE, _TS_EXPORT_DEFAULT_NAME_RE, _TS_EXPORT_ASSIGN_RE)
+
+
+def _own_code(path: str, blob: bytes) -> bytes:
+ """*blob*'s code with comments, string bodies and JS/TS export clauses blanked.
+
+ Lines are kept, so a match still reports its real line number.
+ """
+ suffix = PurePosixPath(path).suffix
+ text = mask_source(blob.decode("utf-8", "replace"), suffix, strings=True)
+ if suffix.lower() != ".py":
+ for clause in _EXPORT_CLAUSES:
+ text = clause.sub(_blank, text)
+ return text.encode("utf-8")
+
+
+def _blank(match: re.Match[str]) -> str:
+ return _NOT_NEWLINE.sub(" ", match.group())
+
+
+_NOT_NEWLINE = re.compile(r"[^\n]")
def searchable_token(name: str) -> bytes:
diff --git a/packages/core/src/repowise/core/analysis/decisions/conventions.py b/packages/core/src/repowise/core/analysis/decisions/conventions.py
index 739468bc6..0b88a1e7f 100644
--- a/packages/core/src/repowise/core/analysis/decisions/conventions.py
+++ b/packages/core/src/repowise/core/analysis/decisions/conventions.py
@@ -38,7 +38,8 @@ from repowise.core.analysis.decisions.scope import resolve_module_nodes
from repowise.core.analysis.external_systems.links import declaration_name_candidates
from repowise.core.ingestion.cohesion import UNIT_FANOUT_LANGUAGES
from repowise.core.ingestion.external_systems.io_kind import classify_io_kind
-from repowise.core.workspace.extractors.http.wrappers import mask_source, symbol_body
+from repowise.core.ingestion.source_mask import mask_source
+from repowise.core.workspace.extractors.http.wrappers import symbol_body
if TYPE_CHECKING:
import networkx as nx
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index b02df1da1..c25d10c38 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -315,7 +315,19 @@ def php_visibility(_name: str, modifier_texts: list[str]) -> str:
_TS_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
_TS_EXPORT_DEFAULT_RE = re.compile(r"\bexport\s+default\s+([A-Za-z_$][\w$]*)")
_TS_EXPORT_ASSIGN_RE = re.compile(r"\bexport\s*=\s*([A-Za-z_$][\w$]*)")
-_TS_CJS_EXPORTS_RE = re.compile(r"\bmodule\.exports\b|\bexports\s*[.\[]")
+# CommonJS is a write to ``exports``, never a read: ``ext.exports``,
+# ``const prev = module.exports`` or a local ``exports.enabled`` is ordinary
+# code, and treating it as CommonJS kept every non-exported declaration in the
+# file public. A write assigns ``module.exports`` (or a member of it) or a
+# member of bare ``exports``, or ``Object.assign``/``defineProperty`` onto one.
+_CJS_MODULE_EXPORTS = r"""\bmodule\s*(?:\.\s*exports\b|\[\s*["']exports["']\s*\])"""
+_CJS_MEMBER = r"(?:\.\s*[A-Za-z_$][\w$]*|\[[^\]\n]*\])"
+_CJS_ASSIGN = r"\s*=(?![=>])"
+_TS_CJS_EXPORTS_RE = re.compile(
+ rf"{_CJS_MODULE_EXPORTS}(?:\s*{_CJS_MEMBER})?{_CJS_ASSIGN}"
+ rf"|(?<![.\w$])exports\s*{_CJS_MEMBER}{_CJS_ASSIGN}"
+ rf"|\b(?:defineProperty|assign)\(\s*(?:{_CJS_MODULE_EXPORTS}|exports\b)"
+)
# The same list form, plus whatever follows the closing brace, so a clause with
# a ``from`` source can be told from one without. Only the source-less form
diff --git a/packages/core/src/repowise/core/ingestion/source_mask.py b/packages/core/src/repowise/core/ingestion/source_mask.py
new file mode 100644
index 000000000..e13a26e19
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/source_mask.py
@@ -0,0 +1,159 @@
+"""Blank comments, and optionally string bodies, out of Python and JS-family source.
+
+Offsets are preserved, so a match in the masked text indexes the original.
+Shared by the HTTP client extractors, convention mining and dead-code
+analysis, none of which should read a name written in a comment as code.
+"""
+
+from __future__ import annotations
+
+__all__ = ["can_mask", "mask_source"]
+
+_JS_LIKE = frozenset({".ts", ".tsx", ".js", ".jsx", ".mjs"})
+
+# A ``/`` opens a regex literal (rather than dividing) when the previous
+# significant character cannot end an expression. The standard heuristic, and
+# enough to stop a ``/\\)/`` corrupting a parenthesis scan.
+_REGEX_PRECEDERS = frozenset("(,=:[!&|?{};+-*%~^<>")
+
+
+def _string_prefix(text: str, quote_idx: int) -> str:
+ """The ``rb``/``f``/``u`` prefix letters immediately before a quote, if any."""
+ k = quote_idx
+ while k > 0 and text[k - 1] in "rRbBuUfF":
+ k -= 1
+ # Preceded by more identifier means those letters end a name, not a prefix.
+ if k > 0 and (text[k - 1].isalnum() or text[k - 1] == "_"):
+ return ""
+ return text[k:quote_idx]
+
+
+def can_mask(suffix: str) -> bool:
+ """Whether :func:`mask_source` reads files with *suffix* (else returns them as-is)."""
+ return suffix.lower() == ".py" or suffix.lower() in _JS_LIKE
+
+
+def mask_source(text: str, suffix: str, *, strings: bool = False) -> str:
+ """Blank out comments — and optionally string bodies — preserving offsets.
+
+ Every masked character is replaced by a space and newlines are kept, so the
+ result is the same length as *text* and indexes into it interchangeably.
+ That is what lets the call scanner match against masked text while slicing
+ arguments by the same offsets.
+
+ Two callers, two needs. Sink detection masks strings as well, because a
+ ``fetch(`` inside a comment or a string is not a call — without this, a
+ symbol is confirmed an HTTP wrapper by a line like
+ ``// used to fetch(path) directly``, which is the name-guessing failure
+ reappearing through the back door. The call-site scanner masks comments
+ only, since it still has to read the URL literal it is looking for.
+ """
+ if not can_mask(suffix):
+ return text
+
+ if suffix.lower() == ".py":
+ # Python: ``#`` to end of line, plus string bodies when asked. Both the
+ # triple-quoted delimiter and the ``r`` prefix are read, because getting
+ # either wrong desynchronises the scan for the rest of the file — a
+ # docstring containing a ``"`` would close early and leave real code
+ # masked, and ``r"\"`` would swallow its own closing quote.
+ out = list(text)
+ i, n = 0, len(text)
+ while i < n:
+ ch = text[i]
+ if ch == "#":
+ while i < n and text[i] != "\n":
+ out[i] = " "
+ i += 1
+ continue
+ if ch not in "'\"":
+ i += 1
+ continue
+ delim = text[i : i + 3] if text[i : i + 3] in ("'''", '"""') else ch
+ raw = "r" in _string_prefix(text, i).lower()
+ i += len(delim)
+ while i < n:
+ if text[i] == "\\" and not raw:
+ if strings:
+ out[i] = " "
+ if i + 1 < n and text[i + 1] != "\n":
+ out[i + 1] = " "
+ i += 2
+ continue
+ if text.startswith(delim, i):
+ i += len(delim)
+ break
+ if strings and text[i] != "\n":
+ out[i] = " "
+ i += 1
+ return "".join(out)
+
+ out = list(text)
+ i, n = 0, len(text)
+ # Stack of open template literals, so a nested `` `x` `` inside ``${...}``
+ # is opened rather than read as closing the outer one.
+ tmpl_depth: list[int] = []
+ quote = ""
+ prev_sig = ""
+ while i < n:
+ ch = text[i]
+ if quote:
+ if ch == "\\":
+ if strings:
+ out[i] = " "
+ if i + 1 < n and text[i + 1] != "\n":
+ out[i + 1] = " "
+ i += 2
+ continue
+ if quote == "`" and ch == "$" and i + 1 < n and text[i + 1] == "{":
+ tmpl_depth.append(1)
+ quote = ""
+ i += 2
+ continue
+ if ch == quote:
+ quote = ""
+ elif strings:
+ out[i] = " " if ch != "\n" else "\n"
+ i += 1
+ continue
+ if ch == "/" and i + 1 < n and text[i + 1] == "/":
+ while i < n and text[i] != "\n":
+ out[i] = " "
+ i += 1
+ continue
+ if ch == "/" and i + 1 < n and text[i + 1] == "*":
+ while i < n and not (text[i] == "*" and i + 1 < n and text[i + 1] == "/"):
+ if text[i] != "\n":
+ out[i] = " "
+ i += 1
+ for j in range(i, min(i + 2, n)):
+ out[j] = " "
+ i += 2
+ continue
+ if ch == "/" and prev_sig in _REGEX_PRECEDERS:
+ i += 1
+ while i < n and text[i] != "\n":
+ if text[i] == "\\":
+ out[i] = " "
+ if i + 1 < n:
+ out[i + 1] = " "
+ i += 2
+ continue
+ if text[i] == "/":
+ out[i] = " "
+ i += 1
+ break
+ out[i] = " "
+ i += 1
+ continue
+ if ch in "'\"`":
+ quote = ch
+ elif tmpl_depth and ch == "}":
+ tmpl_depth.pop()
+ quote = "`"
+ elif tmpl_depth and ch == "{":
+ tmpl_depth[-1] += 1
+ if not ch.isspace():
+ prev_sig = ch
+ i += 1
+ return "".join(out)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py b/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py
index c76c46f8a..56ed3c84d 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py
@@ -38,6 +38,8 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING
+from repowise.core.ingestion.source_mask import mask_source
+
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -113,151 +115,6 @@ _SINK_CALL_NAMES_BY_SUFFIX: dict[str, frozenset[str]] = {
}
-_JS_LIKE = frozenset({".ts", ".tsx", ".js", ".jsx", ".mjs"})
-
-# A ``/`` opens a regex literal (rather than dividing) when the previous
-# significant character cannot end an expression. The standard heuristic, and
-# enough to stop a ``/\\)/`` corrupting a parenthesis scan.
-_REGEX_PRECEDERS = frozenset("(,=:[!&|?{};+-*%~^<>")
-
-
-def _string_prefix(text: str, quote_idx: int) -> str:
- """The ``rb``/``f``/``u`` prefix letters immediately before a quote, if any."""
- k = quote_idx
- while k > 0 and text[k - 1] in "rRbBuUfF":
- k -= 1
- # Preceded by more identifier means those letters end a name, not a prefix.
- if k > 0 and (text[k - 1].isalnum() or text[k - 1] == "_"):
- return ""
- return text[k:quote_idx]
-
-
-def mask_source(text: str, suffix: str, *, strings: bool = False) -> str:
- """Blank out comments — and optionally string bodies — preserving offsets.
-
- Every masked character is replaced by a space and newlines are kept, so the
- result is the same length as *text* and indexes into it interchangeably.
- That is what lets the call scanner match against masked text while slicing
- arguments by the same offsets.
-
- Two callers, two needs. Sink detection masks strings as well, because a
- ``fetch(`` inside a comment or a string is not a call — without this, a
- symbol is confirmed an HTTP wrapper by a line like
- ``// used to fetch(path) directly``, which is the name-guessing failure
- reappearing through the back door. The call-site scanner masks comments
- only, since it still has to read the URL literal it is looking for.
- """
- if suffix.lower() != ".py" and suffix.lower() not in _JS_LIKE:
- return text
-
- if suffix.lower() == ".py":
- # Python: ``#`` to end of line, plus string bodies when asked. Both the
- # triple-quoted delimiter and the ``r`` prefix are read, because getting
- # either wrong desynchronises the scan for the rest of the file — a
- # docstring containing a ``"`` would close early and leave real code
- # masked, and ``r"\"`` would swallow its own closing quote.
- out = list(text)
- i, n = 0, len(text)
- while i < n:
- ch = text[i]
- if ch == "#":
- while i < n and text[i] != "\n":
- out[i] = " "
- i += 1
- continue
- if ch not in "'\"":
- i += 1
- continue
- delim = text[i : i + 3] if text[i : i + 3] in ("'''", '"""') else ch
- raw = "r" in _string_prefix(text, i).lower()
- i += len(delim)
- while i < n:
- if text[i] == "\\" and not raw:
- if strings:
- out[i] = " "
- if i + 1 < n and text[i + 1] != "\n":
- out[i + 1] = " "
- i += 2
- continue
- if text.startswith(delim, i):
- i += len(delim)
- break
- if strings and text[i] != "\n":
- out[i] = " "
- i += 1
- return "".join(out)
-
- out = list(text)
- i, n = 0, len(text)
- # Stack of open template literals, so a nested `` `x` `` inside ``${...}``
- # is opened rather than read as closing the outer one.
- tmpl_depth: list[int] = []
- quote = ""
- prev_sig = ""
- while i < n:
- ch = text[i]
- if quote:
- if ch == "\\":
- if strings:
- out[i] = " "
- if i + 1 < n and text[i + 1] != "\n":
- out[i + 1] = " "
- i += 2
- continue
- if quote == "`" and ch == "$" and i + 1 < n and text[i + 1] == "{":
- tmpl_depth.append(1)
- quote = ""
- i += 2
- continue
- if ch == quote:
- quote = ""
- elif strings:
- out[i] = " " if ch != "\n" else "\n"
- i += 1
- continue
- if ch == "/" and i + 1 < n and text[i + 1] == "/":
- while i < n and text[i] != "\n":
- out[i] = " "
- i += 1
- continue
- if ch == "/" and i + 1 < n and text[i + 1] == "*":
- while i < n and not (text[i] == "*" and i + 1 < n and text[i + 1] == "/"):
- if text[i] != "\n":
- out[i] = " "
- i += 1
- for j in range(i, min(i + 2, n)):
- out[j] = " "
- i += 2
- continue
- if ch == "/" and prev_sig in _REGEX_PRECEDERS:
- i += 1
- while i < n and text[i] != "\n":
- if text[i] == "\\":
- out[i] = " "
- if i + 1 < n:
- out[i + 1] = " "
- i += 2
- continue
- if text[i] == "/":
- out[i] = " "
- i += 1
- break
- out[i] = " "
- i += 1
- continue
- if ch in "'\"`":
- quote = ch
- elif tmpl_depth and ch == "}":
- tmpl_depth.pop()
- quote = "`"
- elif tmpl_depth and ch == "{":
- tmpl_depth[-1] += 1
- if not ch.isspace():
- prev_sig = ch
- i += 1
- return "".join(out)
-
-
def sink_patterns(suffix: str) -> tuple[re.Pattern[str], ...]:
"""The sink patterns for *suffix*, or empty when the language has none."""
return _SINKS_BY_SUFFIX.get(suffix.lower(), ())
diff --git a/tests/unit/cli/test_dead_code_stored.py b/tests/unit/cli/test_dead_code_stored.py
index aca478410..18408000c 100644
--- a/tests/unit/cli/test_dead_code_stored.py
+++ b/tests/unit/cli/test_dead_code_stored.py
@@ -144,3 +144,23 @@ def test_uncommitted_changes_are_noted_not_recomputed(indexed_repo, monkeypatch)
assert result.exit_code == 0, result.output
assert "working tree has changes the index does not include" in result.output
assert "stored_symbol" in result.output
+
+
+def test_json_marks_an_export_its_own_file_uses_as_export_only(indexed_repo):
+ (indexed_repo / "links.ts").write_text(
+ "export const SITE_URL = 'https://x.dev';\n"
+ "export function link(m: string) {\n"
+ " return `${SITE_URL}/a#${m}`;\n"
+ "}\n"
+ )
+ _git(indexed_repo, "add", "links.ts")
+ _git(indexed_repo, "commit", "-q", "-m", "links")
+
+ findings = _json(indexed_repo, "--min-confidence", "0.0")
+
+ assert all(isinstance(f["export_only"], bool) for f in findings)
+ (site,) = [f for f in findings if f["symbol_name"] == "SITE_URL"]
+ assert site["export_only"] is True
+ assert site["safe_to_delete"] is False
+ (link,) = [f for f in findings if f["symbol_name"] == "link"]
+ assert link["export_only"] is False
diff --git a/tests/unit/dead_code/test_export_only.py b/tests/unit/dead_code/test_export_only.py
new file mode 100644
index 000000000..ddf349293
--- /dev/null
+++ b/tests/unit/dead_code/test_export_only.py
@@ -0,0 +1,192 @@
+"""An unused export its own file uses is export-only, not dead code.
+
+``export const SITE_URL`` read by the function below it has no importer, but
+deleting it breaks that function: only the ``export`` keyword is unneeded. Such
+a row stays an ``unused_export`` below the default floor, marked
+``export_only``, never deletion-ready and worth no deletable line. A mention
+in a comment, a docstring or a Python ``__all__`` entry is not a use; a
+template literal's ``${NAME}`` is.
+"""
+
+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 (
+ demote_exports_used_in_own_code,
+ demote_used_in_own_file,
+)
+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def _exports_over(path: str, source: str, symbols: list[dict], language: str) -> dict:
+ """Unused-export findings for one file (with one importer) analysed with its source."""
+ g = _build_graph(
+ nodes={
+ path: {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbols": [
+ {"visibility": "public", "decorators": [], "language": language, **s}
+ for s in symbols
+ ],
+ },
+ "src/main.ts": {"is_entry_point": True, "is_test": False},
+ },
+ # An importer naming another symbol, so import absence is evidence (1.0).
+ edges=[("src/main.ts", path, {"edge_type": "imports", "imported_names": ["other"]})],
+ )
+ report = DeadCodeAnalyzer(g, git_meta_map={}, source_map={path: source.encode()}).analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ return {f.symbol_name: f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+
+
+def _const(name: str, line: int) -> dict:
+ return {"name": name, "kind": "variable", "start_line": line, "end_line": line}
+
+
+def test_ts_export_read_in_its_own_file_is_export_only_and_never_deletable():
+ source = (
+ 'export const SITE_URL = "https://x.dev";\n' # 1
+ "export const UNUSED_URL = 1;\n" # 2
+ "export function other(m: string) {\n" # 3
+ " return `${SITE_URL}/a#${m}`;\n" # 4
+ "}\n"
+ )
+ found = _exports_over(
+ "src/links.ts",
+ source,
+ [_const("SITE_URL", 1), _const("UNUSED_URL", 2), {**_const("other", 3), "end_line": 5}],
+ "typescript",
+ )
+ used = found["SITE_URL"]
+ assert used.export_only is True
+ assert used.safe_to_delete is False
+ assert used.confidence < RISK_CAP_CONFIDENCE
+ assert "used in its own file" in used.reason
+ assert "src/links.ts:4" in used.evidence[-1]
+ # The control: a truly unused export is untouched.
+ dead = found["UNUSED_URL"]
+ assert dead.export_only is False
+ assert dead.confidence >= RISK_CAP_CONFIDENCE
+
+
+def test_export_only_rows_add_no_deletable_lines():
+ source = "export const LIMIT = 5;\nexport function other() { return LIMIT; }\n"
+ g_findings = _exports_over(
+ "src/a.ts",
+ source,
+ [_const("LIMIT", 1), {**_const("other", 2), "kind": "function"}],
+ "typescript",
+ )
+ assert g_findings["LIMIT"].export_only
+ assert not any(f.safe_to_delete for f in g_findings.values() if f.export_only)
+
+
+def test_ts_mention_in_a_comment_or_string_is_not_a_use():
+ source = (
+ "export const LIMIT = 5;\n" # 1
+ "// LIMIT is documented here\n" # 2
+ 'export const label = "LIMIT";\n' # 3
+ )
+ found = _exports_over(
+ "src/a.ts", source, [_const("LIMIT", 1), _const("label", 3)], "typescript"
+ )
+ assert found["LIMIT"].export_only is False
+
+
+def test_python_name_listed_only_in_all_is_not_a_use():
+ source = (
+ "def plan_json(plan):\n" # 1
+ ' """plan_json renders the plan."""\n' # 2
+ " return plan\n" # 3
+ "\n"
+ "def fmt(x): return x\n" # 5
+ "def other():\n" # 6
+ " return sorted([], key=fmt)\n" # 7
+ "\n"
+ '__all__ = ["plan_json", "fmt", "other"]\n' # 9
+ )
+ found = _exports_over(
+ "pkg/mod.py",
+ source,
+ [
+ {"name": "plan_json", "kind": "function", "start_line": 1, "end_line": 3},
+ {"name": "fmt", "kind": "function", "start_line": 5, "end_line": 5},
+ {"name": "other", "kind": "function", "start_line": 6, "end_line": 7},
+ ],
+ "python",
+ )
+ assert found["plan_json"].export_only is False
+ # A use the graph missed (a callable passed as a value) is still a use.
+ assert found["fmt"].export_only is True
+ assert found["fmt"].safe_to_delete is False
+
+
+ "clause",
+ [
+ "export { LIMIT };",
+ "export { LIMIT as MAX };",
+ "export {\n LIMIT,\n};",
+ "export default LIMIT;",
+ ],
+)
+def test_an_export_clause_naming_it_is_not_a_use(clause: str):
+ source = f"const LIMIT = 5;\n{clause}\n"
+ found = _exports_over("src/a.ts", source, [_const("LIMIT", 1)], "typescript")
+ assert found["LIMIT"].export_only is False
+ assert found["LIMIT"].confidence >= RISK_CAP_CONFIDENCE
+
+
+def test_a_function_that_only_calls_itself_stays_dead():
+ source = (
+ "export function walk(n: number): number {\n" # 1
+ " return n > 0 ? walk(n - 1) : 0;\n" # 2
+ "}\n" # 3
+ )
+ found = _exports_over(
+ "src/walk.ts",
+ source,
+ [{"name": "walk", "kind": "function", "start_line": 1, "end_line": 3}],
+ "typescript",
+ )
+ assert found["walk"].export_only is False
+ assert found["walk"].confidence >= RISK_CAP_CONFIDENCE
+
+
+def test_a_row_marked_twice_carries_one_evidence_line():
+ path = "src/a.ts"
+ source = {path: b"export const LIMIT = 5;\nexport const two = LIMIT * 2;\n"}
+ finding = DeadCodeFindingData(
+ kind=DeadCodeKind.UNUSED_EXPORT,
+ file_path=path,
+ symbol_name="LIMIT",
+ symbol_kind="variable",
+ confidence=1.0,
+ reason="test",
+ last_commit_at=None,
+ commit_count_90d=0,
+ lines=1,
+ evidence=[],
+ safe_to_delete=True,
+ primary_owner=None,
+ age_days=None,
+ start_line=1,
+ end_line=1,
+ )
+ demote_used_in_own_file([finding], source)
+ demote_exports_used_in_own_code([finding], source)
+ assert finding.export_only is True
+ assert finding.safe_to_delete is False
+ assert len(finding.evidence) == 1
diff --git a/tests/unit/ingestion/test_ts_visibility_refinement.py b/tests/unit/ingestion/test_ts_visibility_refinement.py
index 9c2124a4f..d23e1ff47 100644
--- a/tests/unit/ingestion/test_ts_visibility_refinement.py
+++ b/tests/unit/ingestion/test_ts_visibility_refinement.py
@@ -11,6 +11,8 @@ from __future__ import annotations
from datetime import datetime
+import pytest
+
from repowise.core.ingestion.models import FileInfo
from repowise.core.ingestion.parser import ASTParser
@@ -107,3 +109,74 @@ module.exports = { run };
vis = _symbols(src, path="src/mod.js")
assert vis["run"] == "public"
assert vis["internal"] == "public"
+
+
+def test_commonjs_named_export_assignment_keeps_everything_public() -> None:
+ src = """
+const run = () => {};
+const internal = () => {};
+exports.run = run;
+"""
+ vis = _symbols(src, path="src/mod.js")
+ assert vis["internal"] == "public"
+
+
+def test_reading_an_exports_variable_is_not_commonjs() -> None:
+ # A VS Code extension's activated ``exports`` object read as a value.
+ src = """
+interface GitExtension { readonly enabled: boolean; }
+export async function getApi(ext: { exports: GitExtension }) {
+ const exports = ext.exports;
+ if (!exports.enabled) return null;
+ return exports["enabled"];
+}
+"""
+ vis = _symbols(src)
+ assert vis["GitExtension"] == "private"
+ assert vis["getApi"] == "public"
+
+
+_CJS_WRITES = [
+ "module.exports = { run };",
+ "module.exports.run = run;",
+ 'module.exports["run"] = run;',
+ 'module["exports"] = { run };',
+ "module['exports'] = { run };",
+ "exports.run = run;",
+ 'exports["run"] = run;',
+ "Object.assign(exports, { run });",
+ "Object.assign(module.exports, { run });",
+ 'Object.defineProperty(exports, "run", { value: run });',
+ 'Object.defineProperty(module.exports, "run", { value: run });',
+]
+
+
[email protected]("write", _CJS_WRITES)
+def test_each_commonjs_write_form_keeps_everything_public(write: str) -> None:
+ src = f"const run = () => {{}};\nconst internal = () => {{}};\n{write}\n"
+ assert _symbols(src, path="src/mod.js")["internal"] == "public"
+
+
+ "read",
+ [
+ "const prev = module.exports;",
+ "if (module.exports === prev) {}",
+ "use(module.exports);",
+ "const enabled = ext.exports.enabled;",
+ ],
+)
+def test_reading_module_exports_is_not_commonjs(read: str) -> None:
+ src = f"const internal = () => {{}};\nexport const run = () => {{}};\n{read}\n"
+ vis = _symbols(src, path="src/mod.ts")
+ assert vis["internal"] == "private"
+ assert vis["run"] == "public"
+
+
+def test_export_shape_still_reads_a_commonjs_default() -> None:
+ from repowise.core.analysis.dead_code.entry_shape import export_shape
+
+ blob = b"const run = () => {};\nmodule.exports = run;\n"
+ assert export_shape("src/mod.js", frozenset({"run"}), blob) == frozenset({"default"})
+ read_only = b"export const run = 1;\nconst prev = module.exports;\n"
+ assert export_shape("src/mod.ts", frozenset({"run"}), read_only) == frozenset({"run"})