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
fix: resolve duplicate Apex coverage by package priority (#4736)
raj bhardwaj9fdab5d5948a
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.pyindex bb1f6f6b1..46ae8b967 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py@@ -23,6 +23,7 @@ Two jobs that make ingested coverage *actually line up* with the repo:from __future__ import annotations+import jsonimport timefrom collections import Counter, defaultdictfrom collections.abc import Iterable, Iterator, Mapping, Sequence@@ -764,12 +765,22 @@ def _apex_names(norm_path: str) -> tuple[str, ...]:return tuple(name + ext for ext in _APEX_EXTS)+def _match_apex_package(hits: Sequence[str], package_dirs: Sequence[str]) -> tuple[str | None, bool]:+ """Select a unique Apex hit from the first package directory with matches."""+ for package_dir in package_dirs:+ in_package = [key for key in hits if key.startswith(package_dir.rstrip("/") + "/")]+ if in_package:+ return (in_package[0], False) if len(in_package) == 1 else (None, True)+ return (hits[0], False) if len(hits) == 1 else (None, bool(hits))++def _match_key(norm_path: str,repo_keys: set[str],suffix_index: dict[str, list[str]],*,prefer_dir: str | None = None,+ apex_package_dirs: Sequence[str] = (),) -> tuple[str | None, bool]:"""Resolve a normalized report path to a canonical key.@@ -789,10 +800,11 @@ def _match_key(if norm_path in repo_keys:return norm_path, False- # An Apex name is unique in an org, so two files of that name are copies: refuse.+ # Apex basenames can be duplicated across Salesforce packages. The project+ # manifest can disambiguate them by package directory priority.hits = [k for name in _apex_names(norm_path) for k in suffix_index.get(name, ())]if hits:- return (hits[0], False) if len(hits) == 1 else (None, True)+ return _match_apex_package(hits, apex_package_dirs)base = norm_path.rsplit("/", 1)[-1]candidates = suffix_index.get(_index_name(base))@@ -872,6 +884,7 @@ def _resolve_path(origin_dir: str | None = None,source_roots: Sequence[str] = (),go_modules: Sequence[tuple[str, str]] = (),+ apex_package_dirs: Sequence[str] = (),) -> tuple[str | None, bool, bool]:"""``(key, ambiguous, exact)`` for one report path, aggregate or per-test.@@ -899,13 +912,23 @@ def _resolve_path(norm = normalize_report_path(raw, strip_prefix=strip_prefix, path_prefix=path_prefix)origin = origin_dirrelative = not _is_absolute(raw)++ def match_path(path: str) -> tuple[str | None, bool]:+ return _match_key(+ path,+ repo_keys,+ suffix_index,+ prefer_dir=origin,+ apex_package_dirs=apex_package_dirs,+ )+if relative and source_roots:found: dict[str, bool] = {} # key -> matched a path exactlyfor root in source_roots:joined = normalize_report_path(f"{root.rstrip('/')}/{raw}", strip_prefix=strip_prefix, path_prefix=path_prefix)- key, _ = _match_key(joined, repo_keys, suffix_index, prefer_dir=origin)+ key, _ = match_path(joined)if key is not None:found[key] = found.get(key, False) or key in (joined, norm)if found:@@ -914,7 +937,7 @@ def _resolve_path(key = _under_origin(norm, origin, repo_keys)if key is not None:return key, False, True- key, ambiguous = _match_key(norm, repo_keys, suffix_index, prefer_dir=origin)+ key, ambiguous = match_path(norm)return key, ambiguous, key is not None and norm == key@@ -1058,6 +1081,7 @@ def resolve_reports(path_prefix: str | None = None,ignore: Sequence[str] = (),go_modules: Sequence[tuple[str, str]] = (),+ apex_package_dirs: Sequence[str] = (),) -> ResolvedCoverage:"""Resolve one or more parsed reports against the indexed tree.@@ -1094,6 +1118,7 @@ def resolve_reports(origin_dir=report.origin_dir,source_roots=report.source_roots,go_modules=modules,+ apex_package_dirs=apex_package_dirs,)# An entry that resolves is ignored by its key; one that does not,# by the path the report wrote.@@ -1374,6 +1399,7 @@ def build_coverage_map(strip_prefix=strip_prefix,path_prefix=path_prefix,ignore=ignore,+ apex_package_dirs=_salesforce_package_dirs(repo_root),# The walk only when a coverprofile needs it.go_modules=(_go_modules(repo_root)@@ -1394,6 +1420,30 @@ def build_coverage_map(return resolved, errors+def _salesforce_package_dirs(repo_root: Path) -> tuple[str, ...]:+ """Package directory priority from ``sfdx-project.json``, if usable."""+ try:+ manifest = json.loads((repo_root / "sfdx-project.json").read_text(encoding="utf-8"))+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):+ return ()+ directories = manifest.get("packageDirectories") if isinstance(manifest, dict) else None+ if not isinstance(directories, list):+ return ()+ prepared: list[tuple[str, bool]] = []+ for entry in directories:+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):+ continue+ path = entry["path"].strip().strip("/")+ if path:+ prepared.append((path, entry.get("default") is True))+ defaults = tuple(path for path, default in prepared if default)+ default_paths = set(defaults)+ remaining = tuple(+ path for path, default in prepared if not default and path not in default_paths+ )+ return defaults + remaining++def oldest_report_time(paths: Iterable[Path]) -> datetime | None:"""The oldest mtime among *paths*, as an aware UTC datetime.diff --git a/tests/unit/health/test_coverage_apex.py b/tests/unit/health/test_coverage_apex.pyindex 4a34eb672..d75e58608 100644--- a/tests/unit/health/test_coverage_apex.py+++ b/tests/unit/health/test_coverage_apex.py@@ -17,7 +17,13 @@ from repowise.core.analysis.health.coverage import (resolve_reports,resolve_test_reports,)-from repowise.core.analysis.health.coverage.discovery import _merge_into+from repowise.core.analysis.health.coverage.discovery import (+ _build_suffix_index,+ _match_key,+ _merge_into,+ _resolve_path,+ _salesforce_package_dirs,+)from repowise.core.analysis.health.coverage.model import (CoverageReport,FileCoverage,@@ -218,6 +224,212 @@ def test_resolution_refuses(raw: str, ambiguous: bool) -> None:assert (res.ambiguous if ambiguous else res.unmatched) == [raw]+def test_match_key_prefers_first_matching_apex_package() -> None:+ repo_keys = {"preferred/classes/Dup.cls", "other/classes/Dup.cls"}+ assert _match_key(+ "Dup.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ apex_package_dirs=("preferred", "other"),+ ) == ("preferred/classes/Dup.cls", False)+++def test_match_key_keeps_ambiguity_in_first_matching_apex_package() -> None:+ repo_keys = {"preferred/classes/Dup.cls", "preferred/extra/Dup.cls", "later/classes/Dup.cls"}+ assert _match_key(+ "Dup.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ apex_package_dirs=("preferred", "later"),+ ) == (None, True)+++def test_match_key_uses_later_apex_package_when_earlier_packages_have_no_hit() -> None:+ repo_keys = {"later/classes/Dup.cls", "other/classes/Dup.cls"}+ assert _match_key(+ "Dup.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ apex_package_dirs=("earlier", "later", "other"),+ ) == ("later/classes/Dup.cls", False)+++def test_match_key_without_apex_package_dirs_keeps_duplicate_ambiguity() -> None:+ repo_keys = {"preferred/classes/Dup.cls", "other/classes/Dup.cls"}+ assert _match_key("Dup.cls", repo_keys, _build_suffix_index(repo_keys)) == (None, True)+++def test_resolve_path_source_roots_apply_apex_package_priority() -> None:+ first = "pkg-one/classes/Dup.cls"+ second = "pkg-two/classes/Dup.cls"+ repo_keys = {first, second}+ # Keep the index order fixed: without package priority, the source-root+ # match would select `first` before the second root is considered.+ suffix_index = {"dup.cls": [first, second]}++ assert _resolve_path(+ "Dup.cls",+ repo_keys,+ suffix_index,+ strip_prefix=None,+ path_prefix=None,+ source_roots=("missing", "/"),+ apex_package_dirs=("pkg-two", "pkg-one"),+ ) == (second, False, False)+++def test_resolve_path_falls_back_when_no_source_root_matches() -> None:+ repo_keys = {"src/Foo.cls"}+ assert _resolve_path(+ "Foo.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ strip_prefix=None,+ path_prefix=None,+ source_roots=("missing/package",),+ ) == ("src/Foo.cls", False, False)+++def test_resolve_path_fallback_uses_apex_package_priority_without_source_root_match() -> None:+ first = "pkg-one/classes/Dup.cls"+ preferred = "pkg-two/classes/Dup.cls"+ repo_keys = {first, preferred}++ # The joined path has too little directory overlap to match either file;+ # only the final bare-name fallback can apply the package preference.+ assert _resolve_path(+ "Dup.cls",+ repo_keys,+ {"dup.cls": [first, preferred]},+ strip_prefix=None,+ path_prefix=None,+ source_roots=("missing/package/deeper",),+ apex_package_dirs=("pkg-two", "pkg-one"),+ ) == ("pkg-two/classes/Dup.cls", False, False)+++def test_resolve_path_uses_matching_file_under_origin_dir() -> None:+ repo_keys = {"packages/app/classes/Dup.cls", "packages/other/classes/Dup.cls"}+ assert _resolve_path(+ "Dup.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ strip_prefix=None,+ path_prefix=None,+ origin_dir="packages/app/classes",+ ) == ("packages/app/classes/Dup.cls", False, True)+++def test_resolve_path_keeps_multiple_source_root_matches_ambiguous() -> None:+ repo_keys = {"pkg-one/classes/Dup.cls", "pkg-two/classes/Dup.cls"}+ assert _resolve_path(+ "Dup.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ strip_prefix=None,+ path_prefix=None,+ source_roots=("pkg-one/classes", "pkg-two/classes"),+ apex_package_dirs=("pkg-two", "pkg-one"),+ ) == (None, True, False)+++def test_match_key_respects_package_directory_boundaries() -> None:+ repo_keys = {"force-app/classes/Dup.cls", "force-app-extra/classes/Dup.cls"}+ assert _match_key(+ "Dup.cls",+ repo_keys,+ _build_suffix_index(repo_keys),+ apex_package_dirs=("force-app", "force-app-extra"),+ ) == ("force-app/classes/Dup.cls", False)+++def test_salesforce_package_dirs_preserves_order_and_filters_duplicate_defaults(+ tmp_path: Path,+) -> None:+ (tmp_path / "sfdx-project.json").write_text(+ '{"packageDirectories":[ '+ '{"path":" /default/ ","default":true},'+ '{"path":"/default/"},'+ '{"path":"later"},'+ '{"path":"later"},'+ '{"path":" /later/ "},'+ '{"path":"default-two","default":true},'+ 'null,{"default":true},{"path":12},{"path":" / "}'+ ']}',+ encoding="utf-8",+ )+ assert _salesforce_package_dirs(tmp_path) == (+ "default",+ "default-two",+ "later",+ "later",+ "later",+ )+++def _build_duplicate(tmp_path: Path, manifest: str | None, keys: set[str]):+ if manifest is not None:+ (tmp_path / "sfdx-project.json").write_text(manifest, encoding="utf-8")+ report_path = tmp_path / "apex.json"+ report_path.write_text(+ '[{"id":"01p000000000001AAA","name":"Dup","totalLines":1,'+ '"lines":{"1":1},"totalCovered":1,"coveredPercent":100}]',+ encoding="utf-8",+ )+ return build_coverage_map(tmp_path, [report_path], keys, allow_partial=True)+++def test_build_coverage_map_prefers_default_salesforce_package(tmp_path: Path) -> None:+ keys = {"first/classes/Dup.cls", "default/classes/Dup.cls"}+ manifest = '{"packageDirectories":[{"path":"first"},{"path":"default","default":true}]}'+ resolved, errors = _build_duplicate(tmp_path, manifest, keys)+ assert errors == []+ assert list(resolved.coverage_map) == ["default/classes/Dup.cls"]+++def test_build_coverage_map_uses_package_declaration_order_without_default(tmp_path: Path) -> None:+ keys = {"second/classes/Dup.cls", "first/classes/Dup.cls"}+ manifest = '{"packageDirectories":[{"path":"first"},{"path":"second"}]}'+ resolved, errors = _build_duplicate(tmp_path, manifest, keys)+ assert errors == []+ assert list(resolved.coverage_map) == ["first/classes/Dup.cls"]++[email protected]("manifest", [None, "not json", "{}"])+def test_build_coverage_map_keeps_duplicates_ambiguous_without_usable_manifest(+ tmp_path: Path, manifest: str | None+) -> None:+ resolved, errors = _build_duplicate(+ tmp_path, manifest, {"first/classes/Dup.cls", "second/classes/Dup.cls"}+ )+ assert errors == []+ assert resolved.coverage_map == {}+ assert resolved.ambiguous == ["Dup.cls"]+++def test_build_coverage_map_keeps_same_package_duplicates_ambiguous(tmp_path: Path) -> None:+ keys = {"preferred/classes/Dup.cls", "preferred/other/Dup.cls", "later/classes/Dup.cls"}+ manifest = '{"packageDirectories":[{"path":"preferred","default":true},{"path":"later"}]}'+ resolved, errors = _build_duplicate(tmp_path, manifest, keys)+ assert errors == []+ assert resolved.coverage_map == {}+ assert resolved.ambiguous == ["Dup.cls"]+++def test_package_preference_preserves_unique_and_non_apex_matching(tmp_path: Path) -> None:+ keys = {"preferred/classes/Only.cls", "other/Makefile"}+ manifest = '{"packageDirectories":[{"path":"preferred","default":true}]}'+ (tmp_path / "sfdx-project.json").write_text(manifest, encoding="utf-8")+ report_path = tmp_path / "coverage.info"+ report_path.write_text(+ "SF:Only.cls\nDA:1,1\nend_of_record\nSF:Makefile\nDA:1,1\nend_of_record\n",+ encoding="utf-8",+ )+ resolved, errors = build_coverage_map(tmp_path, [report_path], keys, allow_partial=True)+ assert errors == []+ assert set(resolved.coverage_map) == keys++def test_per_test_records_resolve_source_and_test_file() -> None:res = resolve_test_reports(parse_apex_contexts(_read("sample.apex.json")), KEYS)test_file = "force-app/main/default/classes/Trigger Recipes/AccountTriggerHandler_Tests.cls"@@ -297,4 +509,4 @@ def test_two_deploy_reports_for_one_class_keep_their_percentage() -> None:text = _read("sample.apex-deploy.json")res = resolve_reports([parse_apex(text), parse_apex(text)], keys)entry = res.coverage_map["force-app/main/default/classes/AccountService.cls"]- assert entry["line_coverage_pct"] == pytest.approx(78.57)\ No newline at end of file+ assert entry["line_coverage_pct"] == pytest.approx(78.57)