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(health): classify Dart codegen, minified and webpack output as generated (#3637)

Swati Ahuja436b157766b7
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 214d1acad..8cb81e362 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -24,7 +24,7 @@ from typing import Any
import structlog
-from ...code_origin import is_build_file
+from ...code_origin import code_origin, is_build_file
from ...entry_candidacy import is_reachability_root
from ...ingestion.decorator_names import decorator_base as _decorator_base
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
@@ -969,7 +969,9 @@ class DeadCodeAnalyzer:
findings: list[DeadCodeFindingData] = []
dynamic_patterns = cfg.get("dynamic_patterns", _DEFAULT_DYNAMIC_PATTERNS)
- whitelist = set(cfg.get("whitelist", []))
+ # Machine output known only by its content (a webpack chunk, a minified
+ # bundle) joins the whitelist, which every pass already honours.
+ whitelist = set(cfg.get("whitelist", [])) | self._content_machine_output()
if cfg.get("detect_unreachable_files", True):
findings.extend(self._detect_unreachable_files(whitelist))
@@ -2245,6 +2247,19 @@ class DeadCodeAnalyzer:
# Helpers
# ------------------------------------------------------------------
+ def _content_machine_output(self) -> set[str]:
+ """Files ``code_origin`` reads as generated or vendored from their bytes.
+
+ The path-only rules are asked per candidate by ``never_flag_path``.
+ ``is_test=False`` skips the test-path check, which cannot change
+ either answer and is half the cost.
+ """
+ return {
+ path
+ for path, data in self._source_map.items()
+ if code_origin(path, data, is_test=False) in ("generated", "vendored")
+ }
+
def _should_never_flag(self, path: str, whitelist: set[str]) -> bool:
"""Return True if path should never be flagged as dead.
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 3f136b40a..1139640bd 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -744,13 +744,9 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
"*OuterClass.java", # protoc generated outer class
"*$WrapperImpl.java",
# ---- Dart / Flutter conventions ---------------------------------------
- # build_runner outputs, linked from their source via ``part``.
- "*.g.dart",
- "*.freezed.dart", # freezed data classes
- "*.gr.dart", # auto_route generated router
- "*.config.dart", # injectable DI config
- "*.mocks.dart", # mockito codegen
- "*.gen.dart", # flutter_gen assets
+ # build_runner outputs are generated by name in ``code_origin``. Injectable's
+ # DI config stays here only: as an origin the name is too often hand-written.
+ "*.config.dart",
# package:test / integration_test runners execute these directly; no
# static importer exists. ``example/`` is pub.dev's showcase convention.
"*_test.dart",
diff --git a/packages/core/src/repowise/core/code_origin.py b/packages/core/src/repowise/core/code_origin.py
index 0ce8b84ca..971b11844 100644
--- a/packages/core/src/repowise/core/code_origin.py
+++ b/packages/core/src/repowise/core/code_origin.py
@@ -90,6 +90,10 @@ _DOCSTRING_OPENER_RE = re.compile(r"""^[rRuUbB]?(?:\"\"\"|''')""")
_GENERATED_DIR_TOKENS = frozenset({"__generated__", "generated-src", "generated-sources"})
_GENERATED_BUILD_DIR = "generated"
_BUILD_OUTPUT_PARENTS = frozenset({"main", "build", "target"})
+# Adjacent directories a generator owns where neither name does alone:
+# CocoaPods writes ``Pods/Target Support Files/``; a bare ``pods/`` is as often
+# a first-party package (Kubernetes pods).
+_GENERATED_DIR_PAIRS = frozenset({("pods", "target support files")})
# Beyond the first two lines, only an explicit sentence in a comment counts:
# Java generators put "This class is generated." in the class Javadoc, after
# the license and the imports. The looser markers ("DO NOT EDIT") stay
@@ -109,6 +113,10 @@ _GENERATED_SENTENCE_RE = re.compile(
r"|GENERATED\b.*(?:\bINSTEAD\b|\bDO NOT (?:HAND[- ])?(?:EDIT|MODIFY)|\bNOT BE (?:EDITED|MODIFIED))"
r")"
)
+# Dart build_runner's banner, written after the license, past the first two
+# lines. Only the whole line counts: "Do not modify by hand without ..." or
+# "Generated code: see docs" in a hand-written file says something else.
+_GENERATED_BANNER_LINE_RE = re.compile(r"^GENERATED CODE - DO NOT MODIFY BY HAND\s*$")
_GENERATED_SENTENCE_LINES = 40
_PREAMBLE_PREFIXES = ("package ", "import ", "from ", "using ")
@@ -174,11 +182,15 @@ def _leading_generated_sentence(header: str) -> bool:
if text is None:
if not line.startswith(_PREAMBLE_PREFIXES):
return False
- elif _GENERATED_SENTENCE_RE.search(text.upper()) and not _above_import(lines, i):
+ elif _says_generated(text.upper()) and not _above_import(lines, i):
return True
return False
+def _says_generated(text: str) -> bool:
+ return bool(_GENERATED_SENTENCE_RE.search(text) or _GENERATED_BANNER_LINE_RE.search(text))
+
+
def _above_import(lines: list[str], i: int) -> bool:
"""A comment right above an import is about that import ("this file is
generated at build time" over the import of a build artifact)."""
@@ -232,6 +244,11 @@ def _deps_suffixes() -> tuple[str, ...]:
# Kept out of the registry's generated suffixes, which ingestion skips: the file
# stays in the graph and only leaves the fix lists.
_BUNDLE_SUFFIXES = (".bundle.js", ".bundle.mjs", ".bundle.cjs")
+# Dart build_runner outputs (json_serializable, freezed, auto_route, mockito,
+# flutter_gen), kept out of the registry for the same reason: a ``part`` file
+# must stay in the graph. ``.config.dart`` is not here: injectable writes one,
+# but the name is as often a hand-written config.
+_CODEGEN_SUFFIXES = (".g.dart", ".freezed.dart", ".gr.dart", ".mocks.dart", ".gen.dart")
def _is_generated_name(name: str) -> bool:
@@ -240,9 +257,31 @@ def _is_generated_name(name: str) -> bool:
".generated." in lowered
or lowered.endswith(_generated_suffixes())
or lowered.endswith(_BUNDLE_SUFFIXES)
+ or lowered.endswith(_CODEGEN_SUFFIXES)
)
+# A bundler's output by its content, for chunks with no telling name: a
+# minified head (a mean line over 1,000 chars across at least 2 KB; hand-written
+# code averages well under 100), or webpack's chunk and runtime shapes, which
+# only webpack writes: ``(self.webpackChunkapp = ...).push(`` and a file
+# opening with the ``/******/`` runtime banner that defines
+# ``__webpack_require__``.
+_MINIFIED_MIN_HEAD = 2048
+_MINIFIED_MEAN_LINE = 1000
+_WEBPACK_CHUNK_RE = re.compile(
+ r"\(\s*(?:self|window|this|globalThis)(?:\.|\[\s*[\"'])webpack(?:Chunk|Jsonp)[\w$]*"
+)
+_WEBPACK_RUNTIME_RE = re.compile(r"\A\s*/\*{6}/.*?__webpack_require__", re.DOTALL)
+
+
+def _is_bundler_output(header: str) -> bool:
+ lines = header.count("\n") + 1
+ if len(header) >= _MINIFIED_MIN_HEAD and len(header) > _MINIFIED_MEAN_LINE * lines:
+ return True
+ return bool(_WEBPACK_CHUNK_RE.search(header) or _WEBPACK_RUNTIME_RE.search(header))
+
+
# --------------------------------------------------------------------------
# Vendored
# --------------------------------------------------------------------------
@@ -648,6 +687,7 @@ def _is_generated_path(name: str, dirs: list[str]) -> bool:
return (
_is_generated_name(name)
or any(d in _GENERATED_DIR_TOKENS for d in dirs)
+ or any(pair in _GENERATED_DIR_PAIRS for pair in pairwise(dirs))
or any(
d == _GENERATED_BUILD_DIR and i and dirs[i - 1] in _BUILD_OUTPUT_PARENTS
for i, d in enumerate(dirs)
@@ -729,9 +769,7 @@ def code_origin(
normalized, name, dirs = split
header = _header_text(text)
- if _is_generated_path(name, dirs) or (
- header and (_declares_generated(name, header) or _is_reference_stub(name, dirs, header))
- ):
+ if _is_generated_path(name, dirs) or (header and _is_generated_content(name, dirs, header)):
return "generated"
if _is_vendored_path(name.lower(), dirs) or (
header
@@ -742,6 +780,14 @@ def code_origin(
return _maintained_origin(normalized, name, dirs, is_test, repo_root)
+def _is_generated_content(name: str, dirs: list[str], header: str) -> bool:
+ return (
+ _declares_generated(name, header)
+ or _is_reference_stub(name, dirs, header)
+ or _is_bundler_output(header)
+ )
+
+
def _maintained_origin(
normalized: str,
name: str,
diff --git a/tests/unit/dead_code/test_convention_never_flag.py b/tests/unit/dead_code/test_convention_never_flag.py
index 603dea241..f783ed188 100644
--- a/tests/unit/dead_code/test_convention_never_flag.py
+++ b/tests/unit/dead_code/test_convention_never_flag.py
@@ -146,3 +146,25 @@ def test_a_build_file_runs_what_it_names():
assert is_runner_file("server/build.gradle")
assert is_runner_file("eng/Versions.props")
assert not is_runner_file("src/main.c")
+
+
+ "path",
+ [
+ # build_runner outputs, generated by name in ``code_origin``.
+ "lib/src/photo.g.dart",
+ "lib/models/user.freezed.dart",
+ "lib/router/app_router.gr.dart",
+ "test/api_test.mocks.dart",
+ "lib/gen/assets.gen.dart",
+ # Injectable's DI config, kept as a dead-code glob only.
+ "lib/di/injection.config.dart",
+ ],
+)
+def test_dart_codegen_outputs_are_never_flagged(path):
+ assert never_flag_path(path)
+ assert not _unreachable(path)
+
+
+def test_hand_written_dart_stays_flaggable():
+ assert not never_flag_path("lib/src/photo.dart")
diff --git a/tests/unit/dead_code/test_whitelist_safety.py b/tests/unit/dead_code/test_whitelist_safety.py
index a8ebbe204..95356e449 100644
--- a/tests/unit/dead_code/test_whitelist_safety.py
+++ b/tests/unit/dead_code/test_whitelist_safety.py
@@ -174,3 +174,29 @@ def test_report_deletable_lines_sum():
# deletable, however stale.
assert safe_findings == []
assert report.deletable_lines == 0
+
+
+def test_machine_output_known_by_content_is_never_flagged():
+ """A webpack chunk or a minified bundle with an ordinary name is not dead code."""
+ node = {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ }
+ paths = ("static/js/main.4f1c2a.js", "public/app.js", "src/legacy.js")
+ g = _build_graph(nodes={path: dict(node) for path in paths})
+ source_map = {
+ "static/js/main.4f1c2a.js": b'(self.webpackChunkapp=self.webpackChunkapp||[]).push([[179],{});\n',
+ "public/app.js": b"!function(t,n){" + b"a=1;" * 1100 + b"}();",
+ "src/legacy.js": b"export function old() {\n return 1;\n}\n",
+ }
+
+ report = DeadCodeAnalyzer(g, git_meta_map={}, source_map=source_map).analyze(
+ {"detect_unused_exports": False, "detect_zombie_packages": False}
+ )
+
+ flagged = {f.file_path for f in report.findings}
+ assert "src/legacy.js" in flagged
+ assert not flagged & {"static/js/main.4f1c2a.js", "public/app.js"}
diff --git a/tests/unit/test_code_origin.py b/tests/unit/test_code_origin.py
index 58a33ae36..442663e0e 100644
--- a/tests/unit/test_code_origin.py
+++ b/tests/unit/test_code_origin.py
@@ -540,3 +540,133 @@ def test_sphinx_and_jekyll_count_under_a_plain_doc_folder(tmp_path) -> None:
(tmp_path / "documentation" / "_layouts").mkdir()
assert code_origin("doc/source/ext/roles.py", repo_root=tmp_path) == "docs_example"
assert code_origin("documentation/plugins/x.rb", repo_root=tmp_path) == "docs_example"
+
+
+_DART_PART = (
+ "// Copyright 2020 The Flutter Authors.\n"
+ "// Use of this source code is governed by a BSD-style license.\n"
+ "\n"
+ "// GENERATED CODE - DO NOT MODIFY BY HAND\n"
+ "\n"
+ "part of 'photo.dart';\n"
+)
+
+
+ "path",
+ [
+ "lib/src/photo.g.dart",
+ "lib/models/user.freezed.dart",
+ "lib/router/app_router.gr.dart",
+ "test/api_test.mocks.dart",
+ "lib/gen/assets.gen.dart",
+ ],
+)
+def test_dart_codegen_outputs_are_generated_by_name(path: str) -> None:
+ assert code_origin(path) == "generated"
+ assert code_origin(path, _DART_PART) == "generated"
+ assert is_vendored_or_generated_path(path)
+
+
+def test_dart_injectable_config_stays_production() -> None:
+ assert code_origin("lib/di/injection.config.dart") == "production"
+
+
+def test_generated_banner_after_a_license() -> None:
+ assert code_origin("lib/src/photo.dart", _DART_PART) == "generated"
+ # Ingestion's skip rule still reads the first two lines only.
+ assert not is_generated_header(_DART_PART)
+
+
+ "line",
+ [
+ "// DO NOT MODIFY BY HAND: run tool/gen.dart",
+ "/// Do not modify by hand; edit schema.yaml",
+ "# Do not modify by hand without reading the runbook",
+ "// Generated code: see docs",
+ "// Generated code. See README",
+ ],
+)
+def test_banner_like_prose_after_a_license_stays_production(line: str) -> None:
+ text = f"// Copyright Acme.\n// Licensed MIT.\n{line}\nlibrary x;\n"
+ assert code_origin("lib/src/x.dart", text) == "production"
+
+
+def test_late_generated_comment_in_hand_written_dart_stays_production() -> None:
+ text = (
+ "// Copyright Acme.\n"
+ "import 'package:flutter/widgets.dart';\n"
+ "\n"
+ "class Photo {\n"
+ " // GENERATED CODE - DO NOT MODIFY BY HAND lives in photo.g.dart\n"
+ "}\n"
+ )
+ assert code_origin("lib/src/photo.dart", text) == "production"
+ # "Generated code" as prose, not as the banner, past the first two lines.
+ prose = (
+ "// Copyright Acme.\n// Licensed MIT.\n"
+ "// Generated code goes to lib/gen; edit the templates.\nlibrary x;\n"
+ )
+ assert code_origin("lib/src/x.dart", prose) == "production"
+
+
+def test_minified_head_is_generated() -> None:
+ blob = "!function(t,n){" + "a=1;" * 1100
+ assert code_origin("chat/src/backendMain/resources/js/chat.js", blob) == "generated"
+ assert code_origin("web/app.js", blob.encode()) == "generated"
+ # A license line first does not hide the bundle.
+ assert code_origin("web/app.js", "/*! lib v1.2 | MIT */\n" + blob) == "generated"
+ # Without content the path alone decides.
+ assert code_origin("chat/src/backendMain/resources/js/chat.js") == "production"
+
+
+def test_long_hand_written_js_stays_production() -> None:
+ body = "export function f(a, b) {\n return a + b;\n}\n" * 200
+ assert code_origin("src/math.js", body) == "production"
+ # A long line or two among ordinary code is not a bundle.
+ long_line = "const TABLE = [" + "1, " * 600 + "];\n"
+ assert code_origin("src/table.js", long_line + body) == "production"
+ # A short one-line file is too little to judge.
+ assert code_origin("src/one.js", "export const x = 1;" * 50) == "production"
+
+
+ "text",
+ [
+ '(self["webpackChunkapp"] = self["webpackChunkapp"] || []).push([[179], {\n',
+ "(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[888],{\n",
+ '(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0], {\n',
+ "/******/ (() => { // webpackBootstrap\n/******/ \tvar __webpack_modules__ = ({});\n"
+ "/******/ \tfunction __webpack_require__(moduleId) {\n",
+ ],
+)
+def test_webpack_chunks_and_runtime_are_generated(text: str) -> None:
+ assert code_origin("static/js/main.4f1c2a.js", text) == "generated"
+
+
+ "text",
+ [
+ "declare const __webpack_require__: (id: string) => unknown;\n",
+ "if (typeof __webpack_require__ === 'function') {\n load();\n}\n",
+ "// Webpack names chunks webpackChunk<name> on self.\nconst key = 'webpackChunk' + name;\n",
+ ],
+)
+def test_code_about_webpack_is_not_a_chunk(text: str) -> None:
+ assert code_origin("src/loader.ts", text) == "production"
+
+
+def test_cocoapods_target_support_files_are_generated() -> None:
+ path = "ios/Pods/Target Support Files/Pods-Runner/Pods-Runner-dummy.m"
+ assert code_origin(path) == "generated"
+ assert is_vendored_or_generated_path(path)
+ # Generated wins over the "Tests" target name the test classifier reads.
+ assert code_origin("Pods/Target Support Files/Pods-AppTests/Pods-AppTests-dummy.m") == (
+ "generated"
+ )
+
+
+def test_a_first_party_pods_package_stays_production() -> None:
+ assert code_origin("internal/k8s/pods/watcher.go") == "production"
+ assert code_origin("pods/support/files.go") == "production"