Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(dead-code): read export aliases from the parser, not a second scan (#1683)
Raghav Chamadiya8848c456c2d2
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 82f6683b2..f5bf7675a 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -604,41 +604,25 @@ def _posix_normpath(config_dir: Path, raw: str) -> str:return posixpath.normpath(posixpath.join(config_dir.as_posix(), raw))-_TS_EXPORT_ALIAS_RE = re.compile(r"\bexport\s*\{([^}]*)\}(?!\s*from)")---def _find_ts_export_aliases(- parsed_files: dict,- source_map: dict[str, bytes] | None = None,-) -> dict[str, dict[str, str]]:+def _find_ts_export_aliases(parsed_files: dict) -> dict[str, dict[str, str]]:"""Per-file ``{local_name: exported_alias}`` maps for TS/JS alias exports.``export { ConversationHistoryWrapper as ConversationHistory }`` publishesthe symbol under the alias, so importers pull ``ConversationHistory`` andthe local name never appears in any ``imported_names`` edge. The unused-export pass consults this map to match the alias as well.++ Inverted from what the parser already recorded, rather than scanned again.+ This pass used to own a second regex over the same clause and a second read+ of every TS/JS file; the parser now reads the clause once, with comments+ stripped, and the two answers can no longer disagree."""aliases: dict[str, dict[str, str]] = {}for path, pf in parsed_files.items():- if not path.endswith((".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs")):- continue- try:- file_info = getattr(pf, "file_info", None)- if file_info is None:- continue- source = read_source_text(path, file_info.abs_path, source_map)- except Exception:+ published = getattr(pf, "export_aliases", None)+ if not published:continue- file_map: dict[str, str] = {}- for match in _TS_EXPORT_ALIAS_RE.finditer(source):- for part in match.group(1).split(","):- if " as " in part:- local, _, alias = part.strip().partition(" as ")- local, alias = local.strip(), alias.strip()- if local and alias:- file_map[local] = alias- if file_map:- aliases[path] = file_map+ aliases[path] = {local: exported for exported, local in published.items()}return aliases@@ -688,12 +672,15 @@ class DeadCodeAnalyzer:# subset. Empty when a caller has no source access, which is what makes# that check skip rather than guess.self._source_map: dict[str, bytes] = source_map or {}- # Four prepasses below each scan every indexed file for text markers.+ # Three prepasses below each scan every indexed file for text markers.# ``source_map`` is ingestion's ``{repo_relative_path: raw bytes}`` for- # the same file set, so passing it turns four full-repo disk passes+ # the same file set, so passing it turns three full-repo disk passes# into dict lookups. Callers that don't have it (a resume view, the# standalone ``dead-code`` command on a graph built elsewhere) pass# None and each prepass reads from disk exactly as before.+ #+ # The export-alias map was a fourth and is no longer a pass at all:+ # the parser records the clause, so it is a dict inversion.self._dynamic_import_files = find_dynamic_import_files(parsed_files or {}, source_map) | find_dynamic_edge_files(graph)@@ -725,7 +712,7 @@ class DeadCodeAnalyzer:# ``export { local as alias }`` maps so importer edges carrying the# alias still count for the local symbol.self._ts_export_aliases: dict[str, dict[str, str]] = _find_ts_export_aliases(- parsed_files or {}, source_map+ parsed_files or {})# Lazily-built package-directory maps for Go / JVM / C-C++, the one# piece of the rescue state that costs a graph scan. Built on first usediff --git a/tests/unit/dead_code/test_fp_rescues.py b/tests/unit/dead_code/test_fp_rescues.pyindex f8ea5ae89..375d27f13 100644--- a/tests/unit/dead_code/test_fp_rescues.py+++ b/tests/unit/dead_code/test_fp_rescues.py@@ -44,10 +44,20 @@ def _file_node(symbols: list[dict], language: str = "typescript") -> dict:def _parsed_stub(tmp_path: Path, rel: str, source: str) -> SimpleNamespace:+ """A parsed-file stub carrying the export aliases the parser would record.++ Read through the parser's own extractor rather than restated, so a stub+ cannot claim an alias the real pipeline would decline.+ """+ from repowise.core.ingestion.extractors.visibility import ts_export_aliases+abs_path = tmp_path / relabs_path.parent.mkdir(parents=True, exist_ok=True)abs_path.write_text(source, encoding="utf-8")- return SimpleNamespace(file_info=SimpleNamespace(abs_path=str(abs_path)))+ return SimpleNamespace(+ file_info=SimpleNamespace(abs_path=str(abs_path)),+ export_aliases=ts_export_aliases(source),+ )def _unused_export_names(analyzer: DeadCodeAnalyzer) -> set[str]:diff --git a/tests/unit/dead_code/test_prepass_source_map.py b/tests/unit/dead_code/test_prepass_source_map.pyindex d9239c029..0ad1ed094 100644--- a/tests/unit/dead_code/test_prepass_source_map.py+++ b/tests/unit/dead_code/test_prepass_source_map.py@@ -1,10 +1,13 @@-"""The four marker prepasses read ingestion's bytes, and fall back cleanly.+"""The marker prepasses read ingestion's bytes, and fall back cleanly.-``DeadCodeAnalyzer.__init__`` runs four scans over the whole indexed file-set: dynamic-import markers, ``namespace JSX`` declarations, bundler-``resolve.alias`` targets, and ``export { local as alias }`` maps. Each used-to open every file itself, so a TS/JS repo paid four full-repo read passes-before detection started. They now take ingestion's ``source_map``.+``DeadCodeAnalyzer.__init__`` runs three scans over the whole indexed file+set: dynamic-import markers, ``namespace JSX`` declarations and bundler+``resolve.alias`` targets. Each used to open every file itself, so a TS/JS+repo paid a full-repo read pass each before detection started. They now take+ingestion's ``source_map``.++A fourth, the ``export { local as alias }`` map, is no longer a pass at all:+the parser records the clause on the parsed file, so this reads it back.These tests pin the three states that matter (map hit, map miss, no map atall) plus the decoding contract, since a prepass that decoded the handed-in@@ -130,25 +133,34 @@ def test_bundler_alias_targets_fall_back_to_disk(tmp_path):# ---------------------------------------------------------------------------def test_export_aliases_read_the_source_map(tmp_path):- parsed = {"src/history.ts": _parsed(tmp_path, "src/history.ts", "export {};\n")}- source_map = {"src/history.ts": b"export { HistoryWrapper as History };\n"}+def test_export_aliases_come_from_the_parsed_file(tmp_path):+ """The map is the parser's, inverted — neither disk nor the source map.++ Both of those carry a *different* alias here, so a pass that still read+ either one would say so. What the analyzer reports is what the parser+ recorded, which is the whole point of folding the two readers into one.+ """+ parsed = {+ "src/history.ts": _parsed(tmp_path, "src/history.ts", "export { OnDisk as History };\n")+ }+ parsed["src/history.ts"].export_aliases = {"History": "HistoryWrapper"}+ source_map = {"src/history.ts": b"export { InTheMap as History };\n"}assert _analyzer(parsed, source_map)._ts_export_aliases == {"src/history.ts": {"HistoryWrapper": "History"}}-def test_export_aliases_fall_back_to_disk(tmp_path):+def test_a_file_the_parser_recorded_no_alias_for_is_absent(tmp_path):+ """Including one whose text holds a clause the parser declined to record."""parsed = {"src/history.ts": _parsed(tmp_path, "src/history.ts", "export { HistoryWrapper as History };\n")}+ parsed["src/history.ts"].export_aliases = {}- assert _analyzer(parsed, {})._ts_export_aliases == {- "src/history.ts": {"HistoryWrapper": "History"}- }+ assert _analyzer(parsed, {})._ts_export_aliases == {}# --------------------------------------------------------------------------