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.

feat(health): store each file's code origin and per-function dispatch and deprecation facts (#2820)

Raghav Chamadiya0acdf164c0d0
diff --git a/packages/core/alembic/versions/0092_health_code_origin.py b/packages/core/alembic/versions/0092_health_code_origin.py
new file mode 100644
index 000000000..6615fee6d
--- /dev/null
+++ b/packages/core/alembic/versions/0092_health_code_origin.py
@@ -0,0 +1,37 @@
+"""health_file_metrics: record where each scored file's code comes from.
+
+``code_origin`` is one of production, test, vendored, docs_example, generated
+or tooling, decided at score time with the file's head in hand. Nullable with
+no backfill: the analyzer stamp that ships with it re-scores every file.
+
+Local SQLite stores get the column from ``init_db``'s additive reconciler; this
+migration covers managed Postgres.
+
+Revision ID: 0092
+Revises: 0091
+Create Date: 2026-10-01
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0092"
+down_revision: str | None = "0091"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "health_file_metrics",
+ sa.Column("code_origin", sa.String(16), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("health_file_metrics", "code_origin")
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
index 9d799c4d1..27ee44166 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
@@ -86,6 +86,7 @@ class BrainMethodDetector:
"max_nesting": fn.max_nesting,
"dependents_count": ctx.dependents_count,
"centrality_floor": floor,
+ "dispatch_share": fn.dispatch_share,
},
reason=(
f"Brain Method: {fn.name} is {fn.nloc} lines, CCN {fn.ccn}, "
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
index 1c92c8226..6c9c4ecb0 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
@@ -54,6 +54,7 @@ class ComplexConditionalDetector:
details={
"operator_count": cond.operator_count,
"enclosing_construct": cond.enclosing_construct,
+ "dispatch_share": fc.dispatch_share,
},
reason=(
f"{cond.enclosing_construct} condition combines "
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py
index b0cd64f3c..2f764cb2d 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py
@@ -40,6 +40,7 @@ class ComplexMethodDetector:
"ccn": fn.ccn,
"cognitive": fn.cognitive,
"nloc": fn.nloc,
+ "dispatch_share": fn.dispatch_share,
},
reason=f"{fn.name} has cyclomatic complexity {fn.ccn}",
)
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py
index 6bcc2dda7..9f85ccf02 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py
@@ -64,6 +64,7 @@ class LargeMethodDetector:
details={
"nloc": fn.nloc,
"ccn": fn.ccn,
+ "dispatch_share": fn.dispatch_share,
},
reason=f"{fn.name} is {fn.nloc} lines long",
)
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py
index c37b1a000..87be6a23a 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py
@@ -39,6 +39,7 @@ class NestedComplexityDetector:
"max_nesting": fn.max_nesting,
"ccn": fn.ccn,
"cognitive": fn.cognitive,
+ "dispatch_share": fn.dispatch_share,
},
reason=f"{fn.name} nests {fn.max_nesting} levels deep",
)
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/deprecation.py b/packages/core/src/repowise/core/analysis/health/complexity/deprecation.py
new file mode 100644
index 000000000..a4bec3eeb
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/complexity/deprecation.py
@@ -0,0 +1,161 @@
+"""Whether a function is marked deprecated.
+
+A deprecated function is on its way out, so a finding on it is rarely the
+first thing to fix. This reads the two ways code says so:
+
+- a marker on the declaration: Python ``@deprecated``, Java / Kotlin
+ ``@Deprecated``, C# ``[Obsolete]``, Rust ``#[deprecated]``, a JSDoc
+ ``@deprecated`` tag, or Go's ``// Deprecated:`` doc paragraph;
+- a top-level statement of the body that issues a deprecation warning
+ (``warnings.warn(..., DeprecationWarning)``, ``console.warn("... deprecated")``,
+ a ``warn_deprecated(...)`` helper).
+
+Only an unconditional warning at the top of the body counts (the first two
+statements after a docstring). One inside a branch, or one whose message
+names a parameter (``"old_opt is deprecated"``), deprecates an option or a
+code path, not the function. A function whose own name says it warns
+(``warn_deprecated`` itself) is a helper for other deprecations and is not
+read as deprecated by its body.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from .languages import LanguageNodeMap
+
+_MARKER_RE = re.compile(
+ r"@(?:[\w.]+\.)?deprecated\b"
+ r"|\[\s*(?:System\.)?Obsolete(?:Attribute)?\b"
+ r"|#\[\s*deprecated\b"
+ r"|^\s*(?://+|/?\*+|#)?\s*Deprecated:",
+ re.IGNORECASE | re.MULTILINE,
+)
+_DEPRECATION_WORD_RE = re.compile(r"deprecat|Removed\w*Warning", re.IGNORECASE)
+_WARN_CALLEE_RE = re.compile(r"warn", re.IGNORECASE)
+_HELPER_NAME_RE = re.compile(r"deprecat|warn", re.IGNORECASE)
+
+# ``annotat`` covers Kotlin's top-level ``annotated_expression``: the grammar
+# reads a file-level ``@Deprecated(...)`` as an expression beside the ``fun``.
+_PRECEDING_KINDS = ("comment", "attribute", "annotat", "decorator")
+_WRAPPER_KINDS = frozenset({"export_statement", "decorated_definition"})
+_STATEMENT_LISTS = frozenset({"statement_list", "body_statement"})
+
+
+def _text(node: Node | None) -> str:
+ return (node.text or b"").decode("utf-8", errors="replace") if node is not None else ""
+
+
+def _preceding_text(anchor: Node) -> list[str]:
+ """Comments and attributes directly above *anchor*, nearest first."""
+ out: list[str] = []
+ sib = anchor.prev_sibling
+ while sib is not None and any(k in sib.type for k in _PRECEDING_KINDS):
+ out.append(_text(sib))
+ sib = sib.prev_sibling
+ return out
+
+
+def _declaration_text(fn_node: Node, body: Node, source: bytes) -> list[str]:
+ texts: list[str] = []
+ # The head: modifiers, annotations and attributes the grammar keeps inside
+ # the declaration (Java, Kotlin, C#). It stops at the parameters, whose
+ # inline types can carry a JSDoc ``@deprecated`` for one option.
+ head_end = next(
+ (c.start_byte for c in fn_node.children if "parameter" in c.type or "body" in c.type),
+ body.start_byte if body is not fn_node else fn_node.start_byte,
+ )
+ if head_end > fn_node.start_byte:
+ texts.append(source[fn_node.start_byte : head_end].decode("utf-8", errors="replace"))
+ anchor = fn_node
+ while anchor.parent is not None and anchor.parent.type in _WRAPPER_KINDS:
+ anchor = anchor.parent
+ # Python decorators sit on the wrapper, beside the definition.
+ texts.extend(_text(c) for c in anchor.children if "decorator" in c.type)
+ texts.extend(_preceding_text(anchor))
+ return texts
+
+
+_TOP_STATEMENTS = 2
+_IGNORED_PARAMETERS = frozenset({"self", "cls", "this"})
+_WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+
+
+def _top_level_statements(body: Node) -> list[Node]:
+ """The first statements of the body, after a leading docstring."""
+ named = [c for c in body.named_children if "comment" not in c.type]
+ if len(named) == 1 and named[0].type in _STATEMENT_LISTS:
+ named = [c for c in named[0].named_children if "comment" not in c.type]
+ if named and named[0].type == "expression_statement" and named[0].named_children and (
+ named[0].named_children[0].type == "string"
+ ):
+ named = named[1:]
+ return named[:_TOP_STATEMENTS]
+
+
+def _parameter_names(fn_node: Node) -> set[str]:
+ params = fn_node.child_by_field_name("parameters") or next(
+ (c for c in fn_node.children if "parameter" in c.type), None
+ )
+ names: set[str] = set()
+ for param in params.named_children if params is not None else ():
+ name = (
+ param
+ if param.type == "identifier"
+ else param.child_by_field_name("name")
+ or param.child_by_field_name("pattern")
+ or next((c for c in param.named_children if c.type == "identifier"), None)
+ )
+ if name is not None and name.text:
+ names.add(name.text.decode("utf-8", errors="replace"))
+ return names - _IGNORED_PARAMETERS
+
+
+def _call_in(statement: Node, lmap: LanguageNodeMap) -> Node | None:
+ """The call a statement consists of. ``return f()`` is a value, not a warning."""
+ if statement.type in lmap.call_kinds:
+ return statement
+ named = statement.named_children
+ if (
+ statement.type.endswith("expression_statement")
+ and len(named) == 1
+ and named[0].type in lmap.call_kinds
+ ):
+ return named[0]
+ return None
+
+
+def _warns_deprecation(call: Node, source: bytes) -> bool:
+ args = call.child_by_field_name("arguments")
+ end = args.start_byte if args is not None else call.end_byte
+ callee = source[call.start_byte : end].decode("utf-8", errors="replace").strip()
+ if not _WARN_CALLEE_RE.search(callee):
+ return False
+ # ``warn_deprecated(...)`` / ``deprecated.warn(...)`` say it in the name;
+ # ``warnings.warn(...)`` / ``console.warn(...)`` say it in the arguments.
+ return bool(
+ _DEPRECATION_WORD_RE.search(callee)
+ or (args is not None and _DEPRECATION_WORD_RE.search(_text(args)))
+ )
+
+
+def is_deprecated(
+ fn_node: Node, body: Node, name: str, lmap: LanguageNodeMap, source: bytes
+) -> bool:
+ """Whether the function at *fn_node* declares or announces its deprecation."""
+ if any(_MARKER_RE.search(t) for t in _declaration_text(fn_node, body, source)):
+ return True
+ if _HELPER_NAME_RE.search(name) or body is fn_node:
+ return False
+ parameters = _parameter_names(fn_node)
+ for statement in _top_level_statements(body):
+ call = _call_in(statement, lmap)
+ if call is None or not _warns_deprecation(call, source):
+ continue
+ message = set(_WORD_RE.findall(_text(call.child_by_field_name("arguments"))))
+ return not (message & parameters)
+ return False
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py b/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
new file mode 100644
index 000000000..806ba1d62
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
@@ -0,0 +1,245 @@
+"""How much of a function's decision logic lives in one dispatch on one value.
+
+A ``match`` / ``switch`` / ``when`` over one subject, an ``if`` / ``elif``
+chain whose every condition tests the same name, or a run of sibling ``if``
+guards that each test it (``if kind == "a": return ...``), is long by
+construction: a per-node-type handler adds one arm per case, and the arms are
+independent of each other. ``dispatch_share`` lets a reader tell that shape
+apart from a function that is complex all over.
+
+The share is the decision points inside that one branch, arms and everything
+nested in them, over the function's decision points (CCN minus the entry
+path). It counts the same nodes :mod:`.cyclomatic` charged, so a flat switch
+that CCN charges one point is one point here too. It is a fact read beside
+CCN; it changes no CCN, threshold or score.
+
+"Top level" means not nested inside another branch, case or catch. Loops,
+``try`` / ``with`` blocks and closures are walked through, since a visitor's
+dispatch usually sits inside the loop that reads the next token, and a
+middleware factory's inside the closure it returns.
+
+The 0.6 cut a consumer reads it against was fitted on labelled dev repos (see
+the tests); it is not a property of the fact.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from typing import TYPE_CHECKING, NamedTuple
+
+from .cyclomatic import (
+ _ELSE_IF_NODE_KINDS,
+ _collect_case_children,
+ _is_boolean_operator,
+ _is_elif_continuation,
+ _walk_function_body,
+)
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from .languages import LanguageNodeMap
+
+# An ``if`` with one ``elif`` is a decision, not a dispatch; the same holds for
+# a run of guards.
+_MIN_ARMS = 3
+
+_WRAPPER_KINDS = frozenset({"parenthesized_expression", "condition_clause"})
+_COMPARISON_KINDS = frozenset(
+ {
+ "comparison_operator",
+ "binary_expression",
+ "binary",
+ "instanceof_expression",
+ "is_expression",
+ "is_pattern_expression",
+ "check_expression",
+ "equality_expression",
+ }
+)
+# Calls that test their first argument's type or value.
+_TYPE_TEST_FUNCTIONS = frozenset({"isinstance", "issubclass", "type", "hasattr"})
+# Methods that test their receiver.
+_RECEIVER_TESTS = frozenset(
+ {"equals", "equalsignorecase", "is_a?", "kind_of?", "instance_of?", "startswith"}
+)
+_LITERAL_MARKERS = ("string", "integer", "number", "float", "true", "false", "null", "nil", "char")
+_MAX_SUBJECT_CHARS = 80
+_SPACE_RE = re.compile(r"\s+")
+
+
+def _unwrap(node: Node | None) -> Node | None:
+ while node is not None and node.type in _WRAPPER_KINDS:
+ named = node.named_children
+ if len(named) != 1:
+ return node
+ node = named[0]
+ return node
+
+
+def _name(node: Node | None) -> str | None:
+ """The subject text of an operand, ``None`` for a literal or a sprawl."""
+ node = _unwrap(node)
+ if node is None or node.text is None:
+ return None
+ if node.type == "unary_expression" and node.child_by_field_name("argument") is not None:
+ # ``typeof x`` tests ``x``.
+ return _name(node.child_by_field_name("argument"))
+ kind = node.type.lower()
+ if kind in ("none", "true", "false") or any(m in kind for m in _LITERAL_MARKERS):
+ return None
+ text = node.text.decode("utf-8", errors="replace")
+ if "\n" in text or len(text) > _MAX_SUBJECT_CHARS:
+ return None
+ return _SPACE_RE.sub("", text)
+
+
+def _call_parts(node: Node) -> tuple[str, Node | None, list[Node]]:
+ """``(method name, receiver, arguments)`` for a call node, best effort."""
+ receiver = node.child_by_field_name("object") or node.child_by_field_name("receiver")
+ callee = node.child_by_field_name("function") or node.child_by_field_name("method")
+ name_node = node.child_by_field_name("name") or callee
+ if callee is not None and callee.type in ("attribute", "member_expression"):
+ receiver = callee.child_by_field_name("object")
+ name_node = callee.child_by_field_name("attribute") or callee.child_by_field_name(
+ "property"
+ )
+ name = (name_node.text or b"").decode("utf-8", errors="replace") if name_node else ""
+ args_node = node.child_by_field_name("arguments")
+ args = list(args_node.named_children) if args_node is not None else []
+ return name.rsplit(".", 1)[-1].lower(), receiver, args
+
+
+def _subject(node: Node | None, lmap: LanguageNodeMap) -> str | None:
+ """The one name a condition tests, ``None`` when it tests no single one."""
+ node = _unwrap(node)
+ if node is None:
+ return None
+ if _is_boolean_operator(node, lmap):
+ # ``kind == "call" and lang == "ruby"`` dispatches on ``kind``: the
+ # first side that tests a name is the one the arm is keyed on.
+ return _subject(node.child_by_field_name("left"), lmap) or _subject(
+ node.child_by_field_name("right"), lmap
+ )
+ if node.type in _COMPARISON_KINDS:
+ named = node.named_children
+ left = node.child_by_field_name("left") or (named[0] if named else None)
+ right = node.child_by_field_name("right") or (named[-1] if named else None)
+ return _name(left) or _name(right)
+ if node.type in lmap.call_kinds:
+ name, receiver, args = _call_parts(node)
+ if name in _TYPE_TEST_FUNCTIONS and receiver is None and args:
+ return _name(args[0])
+ if name in _RECEIVER_TESTS:
+ return _name(receiver) or (_name(args[0]) if args else None)
+ return None
+
+
+def _chain_arms(node: Node) -> list[Node]:
+ """The ``if`` and every ``elif`` / ``else if`` arm that continues it."""
+ arms = [node]
+ current = node
+ while True:
+ continuations: list[Node] = []
+ for child in current.children:
+ candidates = child.named_children if child.type == "else_clause" else [child]
+ continuations.extend(c for c in candidates if _is_elif_continuation(c))
+ if not continuations:
+ return arms
+ arms.extend(continuations)
+ current = continuations[-1]
+
+
+def _one_subject(arms: list[Node], lmap: LanguageNodeMap) -> bool:
+ """Whether every arm's condition tests the same single name."""
+ if len(arms) < _MIN_ARMS:
+ return False
+ subjects = Counter(_subject(arm.child_by_field_name("condition"), lmap) for arm in arms)
+ return len(subjects) == 1 and None not in subjects
+
+
+def _is_lone_if(node: Node) -> bool:
+ """An ``if`` that neither continues nor is continued by an ``elif``."""
+ return (
+ node.type in _ELSE_IF_NODE_KINDS
+ and not _is_elif_continuation(node)
+ and len(_chain_arms(node)) == 1
+ )
+
+
+def _has_subject(node: Node) -> bool:
+ """A subjectless ``switch {}`` / ``when {}`` / ``case`` is an ``if`` chain."""
+ if node.type == "expression_switch_statement":
+ return node.child_by_field_name("value") is not None
+ if node.type == "when_expression":
+ return any(c.type == "when_subject" for c in node.children)
+ if node.type == "case" and any(c.type == "when" for c in node.children):
+ return node.child_by_field_name("value") is not None
+ return True
+
+
+class _Siblings(NamedTuple):
+ """A stand-in body holding just the nodes of one dispatch, for the walker."""
+
+ children: list[Node]
+
+
+def _points(nodes: list[Node], lmap: LanguageNodeMap) -> int:
+ """Decision points the CCN walk charges inside *nodes*."""
+ return _walk_function_body(_Siblings(nodes), lmap)[0] - 1 # type: ignore[arg-type]
+
+
+def _guard_runs(children: list[Node], lmap: LanguageNodeMap) -> list[list[Node]]:
+ """Runs of three or more consecutive sibling ``if`` guards on one subject."""
+ runs: list[list[Node]] = []
+ run: list[Node] = []
+ subject: str | None = None
+ for child in [*children, None]:
+ this = (
+ _subject(child.child_by_field_name("condition"), lmap)
+ if child is not None and _is_lone_if(child)
+ else None
+ )
+ if this is not None and this == subject:
+ run.append(child) # type: ignore[arg-type]
+ continue
+ if len(run) >= _MIN_ARMS:
+ runs.append(run)
+ run, subject = ([child] if this is not None else []), this # type: ignore[list-item]
+ return runs
+
+
+def dispatch_points(body: Node, lmap: LanguageNodeMap) -> int:
+ """Decision points inside the largest top-level dispatch on one subject."""
+ stop_kinds = lmap.case_kinds | lmap.catch_kinds | lmap.function_kinds
+ best = 0
+ stack: list[Node] = [body]
+ while stack:
+ parent = stack.pop()
+ children = [c for c in parent.children if c.is_named]
+ for run in _guard_runs(children, lmap):
+ best = max(best, _points(run, lmap))
+ for node in children:
+ if node.type in lmap.switch_kinds:
+ if _has_subject(node) and any(
+ c.is_named for c in _collect_case_children(node, lmap)
+ ):
+ best = max(best, _points([node], lmap))
+ continue
+ if node.type in lmap.branch_kinds:
+ if (
+ node.type in _ELSE_IF_NODE_KINDS
+ and not _is_elif_continuation(node)
+ and _one_subject(_chain_arms(node), lmap)
+ ):
+ best = max(best, _points([node], lmap))
+ continue
+ if node.type not in stop_kinds:
+ stack.append(node)
+ return best
+
+
+def dispatch_share(points: int, ccn: int) -> float:
+ """*points* as a fraction of the function's decision points, to two decimals."""
+ return round(points / (ccn - 1), 2) if ccn > 1 and points > 0 else 0.0
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index db67aca44..42a10e4b5 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -100,6 +100,14 @@ class FunctionComplexity:
# a suppression path, and means a registered-but-never-invoked callback
# contributes. In the direction that lane already errs.
bare_called_names: frozenset[str] = frozenset()
+ # CCN points of the largest top-level ``switch`` / ``match`` / same-subject
+ # ``if`` chain, over ``ccn``, to two decimals. Near 1.0 the function is
+ # one dispatch on one value. Read beside CCN, never in place of it.
+ # ``complexity/dispatch.py``.
+ dispatch_share: float = 0.0
+ # True when the declaration is marked deprecated or the body's top level
+ # issues a deprecation warning. ``complexity/deprecation.py``.
+ deprecated: bool = False
def __post_init__(self) -> None:
if self.complex_conditions is None:
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index b260ee5d3..79e1f139a 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -27,6 +27,8 @@ drives the individual passes, each of which lives in its own sibling module:
- ``cyclomatic``: the CCN / cognitive / nesting engine
- ``assertions``: assertion blocks + per-function assertion totals
- ``test_case``: whether a walked function is a test case
+- ``dispatch``: how much of the CCN is one dispatch on one value
+- ``deprecation``: whether a function is marked deprecated
- ``mock_walk``: per-function mock-setup counting (test-quality)
- ``error_handling``: error-handling anti-patterns
- ``perf_walk``: the performance-risk pass
@@ -49,6 +51,8 @@ from .ast_utils import (
)
from .class_analysis import _collect_classes
from .cyclomatic import _walk_function_body
+from .deprecation import is_deprecated
+from .dispatch import dispatch_points, dispatch_share
from .error_handling import _collect_error_handling, _eh_rust_attr_is_test
from .languages import get_language_map
from .mock_walk import _count_mock_setup, file_may_contain_mocks
@@ -189,6 +193,8 @@ def walk_file(
is_test_case=is_test_case(fn_node, name, language),
called_names=called,
bare_called_names=bare_called,
+ dispatch_share=dispatch_share(dispatch_points(body, lmap), ccn),
+ deprecated=is_deprecated(fn_node, body, name, lmap, source),
)
functions.append(fc)
fc_by_node_id[fn_node.id] = fc
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 77a534a6b..b69360d30 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -20,10 +20,13 @@ from __future__ import annotations
import asyncio
import os
from datetime import UTC, datetime
+from pathlib import Path
from typing import Any
import structlog
+from ...code_origin import CodeOrigin, code_origin
+from ...git_refs import remote_name
from ...ingestion.git_indexer.enrich import count_active_contributors
from ...ingestion.git_indexer.function_blame import (
BlameIndex,
@@ -116,6 +119,11 @@ log = structlog.get_logger(__name__)
# moves, a span must clear a minimum-worth floor, ``slice_nloc`` counts code
# lines only, and JSX prop plumbing earns no Extract Method. Stored plans and
# opportunities change, and ``REFACTORING_MODEL_VERSION`` moved with this.
+# v37 (also): the walker records ``dispatch_share`` and ``deprecated`` per
+# function, which a cached v36 walk does not carry, and each file metric gains
+# ``code_origin``. Complexity findings copy ``dispatch_share`` into their
+# details and findings on a deprecated function gain ``deprecated: true``. No
+# CCN, threshold, weight or score moves.
#
# v36 (also): which files are tests changed (``repowise.core.test_paths``).
# Compound directories headed by a test word (``e2e-tests/``, ``pkg_tests/``,
@@ -349,6 +357,26 @@ log = structlog.get_logger(__name__)
HEALTH_ANALYZER_VERSION = 37
+def _mark_deprecated(
+ findings: list[HealthFindingData], functions: list[FunctionComplexity]
+) -> None:
+ """Stamp ``deprecated: true`` on each function-level finding inside a
+ deprecated function. Absent, not false, everywhere else, so the details of
+ every other finding are byte-for-byte what they were."""
+ spans = [(fc.name, fc.start_line, fc.end_line) for fc in functions if fc.deprecated]
+ if not spans:
+ return
+ for finding in findings:
+ if finding.function_name is None:
+ continue
+ line = finding.line_start
+ if any(
+ name == finding.function_name and (line is None or start <= line <= end)
+ for name, start, end in spans
+ ):
+ finding.details["deprecated"] = True
+
+
def walked_functions(
fc_list: list[FunctionComplexity], language: str
) -> tuple[FunctionComplexity, ...]:
@@ -594,6 +622,11 @@ class HealthAnalyzer:
# falls back to inferring them from the analyzed file list, which sees
# only the manifests the traverser emitted.
self.repo_root = repo_root
+ # Origins are decided in ``_walk``, which holds the bytes, and kept by
+ # path: the walk cache keys on content alone, so a path-dependent
+ # answer cannot live on the cached walk.
+ self._project_name: str | None = None
+ self._origins: dict[str, CodeOrigin] = {}
# Every source read in the pass. Defaults to the working tree; a
# revision comparison supplies bytes instead.
self.read_source: SourceReader = source_reader or disk_source_reader
@@ -1247,6 +1280,7 @@ class HealthAnalyzer:
source = self.read_source(path)
if source is None:
return FileComplexity(functions=[], classes=[])
+ self._origins[pf.file_info.path] = self._origin(pf, source)
key = None
if self._walk_cache is not None:
from repowise.core.ingestion import compute_content_hash
@@ -1272,6 +1306,24 @@ class HealthAnalyzer:
self._walk_cache.put(key, fcx)
return fcx
+ def _project(self) -> str | None:
+ """The repository's name, so its own release banner is never read as a
+ vendored library's. The ``origin`` remote names it even in a worktree;
+ the checkout folder is the fallback. One git call per pass, on first use.
+ """
+ if self._project_name is None and self.repo_root is not None:
+ root = str(self.repo_root)
+ self._project_name = remote_name(root) or Path(root).name
+ return self._project_name
+
+ def _origin(self, pf: Any, source: bytes | None = None) -> CodeOrigin:
+ return code_origin(
+ pf.file_info.path,
+ source,
+ is_test=bool(pf.file_info.is_test),
+ project=self._project(),
+ )
+
def _save_walk_cache(self) -> None:
"""Persist the walk entries this pass used or produced, if any."""
if self._walk_cache is not None:
@@ -1432,6 +1484,7 @@ class HealthAnalyzer:
findings = attach_impacts(biomarker_results, deductions)
for f in findings:
f.file_path = file_path
+ _mark_deprecated(findings, fc_list)
# The overall surfaced score stays == the defect dimension (no blend
# yet); the per-dimension scores ride alongside it, additively.
@@ -1464,6 +1517,7 @@ class HealthAnalyzer:
structure_deduction=structure_deduction,
history_deduction=history_deduction,
is_test=bool(pf.file_info.is_test),
+ code_origin=self._origins.get(file_path) or self._origin(pf),
)
# Refactoring layer: reuse the data just computed (class cohesion
diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.py
index c0c61ab54..a70f91faa 100644
--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py
+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py
@@ -7,9 +7,10 @@ column, and safe to hand to an agent.
The kernel holds structural coordinates and detector evidence. It deliberately
excludes prose and derived values: ``reason`` is generated text that a wording
-change would churn, and two ``details`` keys are outputs of later passes rather
-than facts about the location, so leaving them in would make the id of a
-finding move whenever an unrelated model changed its mind.
+change would churn, and a few ``details`` keys are outputs of later passes or
+annotations of the enclosing function, not evidence for the finding, so
+leaving them in would make the id of a finding move whenever an unrelated
+model changed its mind.
"""
from __future__ import annotations
@@ -33,13 +34,17 @@ value, and an id minted by an older kernel stops matching.
_PREFIX = "finding"
-_DERIVED_DETAIL_KEYS = frozenset({"opportunity_id", "reliable_entry_reachability"})
+_DERIVED_DETAIL_KEYS = frozenset(
+ {"opportunity_id", "reliable_entry_reachability", "dispatch_share", "deprecated"}
+)
"""Detail keys written by later passes, not by the detector that found the row.
``opportunity_id`` is stamped by causal grouping, so leaving it in would make
every finding id churn whenever the performance model version moved.
``reliable_entry_reachability`` is a repository-wide graph answer that flips
-when unrelated code changes.
+when unrelated code changes. ``dispatch_share`` and ``deprecated`` describe the
+function a finding sits in, not the finding, and joined after ids were already
+stored: counting them would have renamed every complexity finding at once.
"""
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index 5b5c1a594..63ded3253 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -161,6 +161,10 @@ class HealthFileMetricData:
# path classifier and carried here so every surface that narrows to
# production reads a column instead of re-deriving the answer.
is_test: bool = False
+ # Where the file's code comes from: ``production``, ``test``, ``vendored``,
+ # ``docs_example``, ``generated`` or ``tooling``
+ # (:func:`repowise.core.code_origin.code_origin`). ``None`` when unknown.
+ code_origin: str | None = None
@dataclass
diff --git a/packages/core/src/repowise/core/code_origin.py b/packages/core/src/repowise/core/code_origin.py
new file mode 100644
index 000000000..d84f85780
--- /dev/null
+++ b/packages/core/src/repowise/core/code_origin.py
@@ -0,0 +1,316 @@
+"""Where a file's code comes from, and so whether it ships.
+
+Sibling of :mod:`repowise.core.test_paths` and :mod:`repowise.core.support_paths`.
+Those answer one question each; this one picks the single origin a ranked
+surface needs before it can put a file at the top of a fix list. A tutorial
+under ``docs_src/`` or a vendored ``typeahead.jquery.js`` can carry a perfectly
+real finding that nobody should be asked to fix first.
+
+The answer is one of :data:`CODE_ORIGINS`, decided in precedence order, so a
+file has exactly one: ``generated`` beats ``vendored`` beats ``test`` beats
+``docs_example`` beats ``tooling``, and everything else is ``production``.
+
+The generated-file banner rule is the one ingestion already applies before it
+indexes a file (:func:`is_generated_header`, moved here from the traverser so
+both read one rule). Ingestion also drops ``vendor/``, ``node_modules/`` and
+``*.min.js`` before analysis ever sees them; they are classified here anyway so
+a caller holding a bare path gets the same answer.
+"""
+
+from __future__ import annotations
+
+import re
+from functools import lru_cache
+from pathlib import PurePosixPath
+from typing import Literal
+
+from .support_paths import EXAMPLE_DIR_TOKENS
+from .test_paths import is_test_related_path
+
+__all__ = [
+ "CODE_ORIGINS",
+ "CodeOrigin",
+ "code_origin",
+ "is_generated_header",
+]
+
+CodeOrigin = Literal["production", "test", "vendored", "docs_example", "generated", "tooling"]
+
+CODE_ORIGINS: tuple[CodeOrigin, ...] = (
+ "production",
+ "test",
+ "vendored",
+ "docs_example",
+ "generated",
+ "tooling",
+)
+
+# --------------------------------------------------------------------------
+# Generated
+# --------------------------------------------------------------------------
+
+# Generated-file banners, read only from comment lines and docstring openers
+# in the first two lines. These two count anywhere in the comment text:
+_GENERATED_ANYWHERE_MARKERS: tuple[str, ...] = ("DO NOT EDIT", "@GENERATED")
+# ...these only where the comment text starts ("<auto-generated>" included):
+_GENERATED_LEADING_MARKERS: tuple[str, ...] = (
+ "CODE GENERATED",
+ "THIS FILE WAS AUTOMATICALLY GENERATED",
+ "GENERATED CODE",
+ "AUTO-GENERATED",
+)
+# ...plus the sentence that says it anywhere in the comment.
+_THIS_FILE_GENERATED_RE = re.compile(
+ r"\bTHIS FILE (?:IS|WAS) (?:AUTO-?|AUTOMATICALLY )?GENERATED\b"
+)
+# Longest first, so "/*" is stripped whole rather than as "/".
+_COMMENT_PREFIXES: tuple[str, ...] = ("<!--", "//", "/*", "--", "#", "*", ";")
+_DOCSTRING_OPENER_RE = re.compile(r"""^[rRuUbB]?(?:\"\"\"|''')""")
+
+_GENERATED_DIR_TOKENS = frozenset({"__generated__"})
+
+
+def _comment_text(line: str, in_docstring: bool) -> str | None:
+ """The text of a comment line or docstring opener, None for anything else."""
+ if in_docstring:
+ return line
+ if opener := _DOCSTRING_OPENER_RE.match(line):
+ return line[opener.end() :].strip()
+ for prefix in _COMMENT_PREFIXES:
+ if line.startswith(prefix):
+ return line[len(prefix) :].strip()
+ return None
+
+
+def _is_banner(text: str) -> bool:
+ """Whether upper-cased comment *text* declares its file generated."""
+ if any(marker in text for marker in _GENERATED_ANYWHERE_MARKERS):
+ return True
+ if _THIS_FILE_GENERATED_RE.search(text):
+ return True
+ # Leading punctuation is decoration ("<auto-generated>", "*** GENERATED").
+ lead = text.lstrip("<!*-=#/; \t")
+ return lead.startswith(_GENERATED_LEADING_MARKERS)
+
+
+def is_generated_header(header: str) -> bool:
+ """Whether the first two lines of *header* carry a generated-file banner.
+
+ A banner sits in a comment or a module docstring. Code and prose that
+ merely mention codegen (a string literal "Auto-generated by ...", a
+ docstring about "the auto-generated client") are not banners.
+ """
+ in_docstring = False
+ for line in header.splitlines()[:2]:
+ text = _comment_text(line.strip(), in_docstring)
+ if text is None:
+ continue
+ # A bare opener ('"""' alone) puts the docstring text on the next line.
+ in_docstring = not text and bool(_DOCSTRING_OPENER_RE.match(line.strip()))
+ if _is_banner(text.upper()):
+ return True
+ return False
+
+
+@lru_cache(maxsize=1)
+def _generated_suffixes() -> tuple[str, ...]:
+ # Deferred: the ingestion package imports the traverser, which imports
+ # this module for the banner rule above.
+ from .ingestion.languages.registry import REGISTRY
+
+ return tuple(sorted(REGISTRY.generated_suffixes()))
+
+
+def _is_generated_name(name: str) -> bool:
+ return ".generated." in name or name.endswith(_generated_suffixes())
+
+
+# --------------------------------------------------------------------------
+# Vendored
+# --------------------------------------------------------------------------
+
+_VENDORED_DIR_TOKENS = frozenset(
+ {
+ "vendor",
+ "vendors",
+ "third_party",
+ "thirdparty",
+ "third-party",
+ "node_modules",
+ "bower_components",
+ "site-packages",
+ }
+)
+# Matched only as the first segment: ``pkg/external/`` is as often a package
+# that talks to external services as it is a copy of someone else's code.
+_VENDORED_ROOT_TOKENS = frozenset({"external", "externals"})
+_MINIFIED_SUFFIXES = (".min.js", ".min.css", ".min.mjs")
+
+# A copied library is recognisable by its header only in the directories a
+# site serves assets from. Anywhere else a license header is far more often
+# the repository's own.
+_ASSET_DIR_TOKENS = frozenset({"docs", "doc", "static", "assets", "public", "_static"})
+_HEADER_LINES = 20
+_LICENSE_RE = re.compile(
+ r"copyright|\(c\)|©|@license|licen[cs]ed\s+under|released\s+under|\bMIT\b",
+ re.IGNORECASE,
+)
+# What says the header names a project and its release, rather than an owner:
+# a preserved banner, a license tag, or "<name> v1.2" / "<name>.js 0.10.5".
+_BANNER_RE = re.compile(
+ r"/\*!|@license|@preserve|\b[A-Za-z][\w.\-]*\s+v?\d+\.\d+(?:\.\d+)?\b"
+)
+
+
+def _comment_lines(header: str) -> list[str]:
+ lines: list[str] = []
+ for raw in header.splitlines()[:_HEADER_LINES]:
+ text = _comment_text(raw.strip(), False)
+ if text is not None:
+ lines.append(text)
+ return lines
+
+
+def _squash(text: str) -> str:
+ """Lowercase alphanumerics only, so ``my-lib`` and ``MyLib`` compare equal."""
+ return re.sub(r"[^0-9a-z]", "", text.lower())
+
+
+def _third_party_header(header: str, project: str | None) -> bool:
+ """Whether the leading comments carry another project's license banner.
+
+ Conservative on purpose: it needs a license or copyright line **and** a
+ versioned or preserved banner, both in comments, and the banner must not
+ name *project* when the caller knows it. A repository's own
+ ``Copyright (c) 2024 Acme`` header has no release banner, so it stays.
+ """
+ comments = "\n".join(_comment_lines(header))
+ if not comments or not _LICENSE_RE.search(comments) or not _BANNER_RE.search(comments):
+ return False
+ return not (project and _squash(project) in _squash(comments))
+
+
+# --------------------------------------------------------------------------
+# Docs, examples, tooling
+# --------------------------------------------------------------------------
+
+# Docs roots count at any depth. Docs are the plural and FastAPI's ``docs_src``
+# only: a singular ``doc/`` is as often a shipped package (cobra's ``doc``
+# generates man pages) as a documentation tree.
+_DOCS_ROOT_TOKENS = frozenset({"docs", "docs_src"})
+# Examples as ``support_paths`` reads them, less the benchmark harnesses, which
+# run the system (tooling below). Unlike ``support_paths`` these count only as
+# the first segment or directly under a docs root: ``src/pkg/examples/`` is
+# as often shipped code (an example registry, a runner) as a sample.
+_EXAMPLE_TOKENS = EXAMPLE_DIR_TOKENS - {"bench", "benches", "benchmarks"}
+_TUTORIAL_PREFIX = "tutorial"
+
+
+def _is_example_dir(segment: str) -> bool:
+ return segment in _EXAMPLE_TOKENS or segment.startswith(_TUTORIAL_PREFIX)
+
+
+def _is_docs_example(dirs: list[str]) -> bool:
+ # Anything under a docs root already counts, examples beneath it included.
+ return any(d in _DOCS_ROOT_TOKENS for d in dirs) or bool(dirs and _is_example_dir(dirs[0]))
+
+
+# Close to ``perf/causal.py``'s tooling parts, with two differences: the
+# benchmark spellings ``bench`` / ``benches`` join ``benchmarks``, and there is
+# no ``/cli/`` rule, since a CLI's source ships and its findings are real work.
+# Migrations join too: they run once at deploy time and are append-only.
+_TOOLING_DIR_TOKENS = frozenset(
+ {
+ ".github",
+ "bench",
+ "benches",
+ "benchmarks",
+ "build",
+ "devtools",
+ "scripts",
+ "tooling",
+ "tools",
+ "migrations",
+ }
+)
+_TOOLING_ROOT_NAMES = frozenset(
+ {"setup.py", "noxfile.py", "fabfile.py", "Rakefile", "Gruntfile.js"}
+)
+_TOOLING_NAME_RE = re.compile(
+ r"^(?:gulpfile|webpack\.config|vite\.config|rollup\.config|eslint\.config|"
+ r"jest\.config|vitest\.config|babel\.config|karma\.conf)\.[cm]?[jt]s$"
+)
+
+
+def _header_text(text: str | bytes | None) -> str:
+ if text is None:
+ return ""
+ if isinstance(text, bytes):
+ # Twenty lines of a hand-written file fit in 4 KB; a minified bundle
+ # has no newlines, and its first 4 KB says as much as the rest.
+ return text[:4096].decode("utf-8", errors="ignore")
+ return text[:4096]
+
+
+def code_origin(
+ path: str,
+ text: str | bytes | None = None,
+ *,
+ is_test: bool | None = None,
+ project: str | None = None,
+) -> CodeOrigin:
+ """The one origin of the file at repo-relative *path*.
+
+ *text* is the file's content, or just its head; only the first 20 lines
+ are read. Without it the content rules (generated banner, third-party
+ license header) cannot fire and the answer rests on the path.
+
+ *is_test* is the flag ingestion stored, when the caller has it. ``None``
+ derives it from the path with the shared test classifier.
+
+ *project* is the repository's name, so its own release banner is not
+ taken for someone else's.
+ """
+ normalized = path.replace("\\", "/")
+ parts = PurePosixPath(normalized).parts
+ if not parts:
+ return "production"
+ name = parts[-1]
+ dirs = [p.lower() for p in parts[:-1]]
+ header = _header_text(text)
+
+ if (
+ _is_generated_name(name)
+ or any(d in _GENERATED_DIR_TOKENS for d in dirs)
+ or (header and is_generated_header(header))
+ ):
+ return "generated"
+
+ lowered_name = name.lower()
+ if (
+ any(d in _VENDORED_DIR_TOKENS for d in dirs)
+ or (dirs and dirs[0] in _VENDORED_ROOT_TOKENS)
+ or lowered_name.endswith(_MINIFIED_SUFFIXES)
+ or (
+ header
+ and any(d in _ASSET_DIR_TOKENS for d in dirs)
+ and _third_party_header(header, project)
+ )
+ ):
+ return "vendored"
+
+ if is_test if is_test is not None else is_test_related_path(normalized):
+ return "test"
+
+ if _is_docs_example(dirs):
+ return "docs_example"
+
+ if (
+ any(d in _TOOLING_DIR_TOKENS for d in dirs)
+ or "/alembic/versions/" in f"/{normalized.lower()}"
+ or (not dirs and name in _TOOLING_ROOT_NAMES)
+ or _TOOLING_NAME_RE.match(lowered_name)
+ ):
+ return "tooling"
+
+ return "production"
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index bab1a04b9..40ed79ab4 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -72,6 +72,17 @@ def toplevel(repo_path: str) -> str:
return _read(repo_path, ["rev-parse", "--show-toplevel"])
+def remote_name(repo_path: str) -> str:
+ """The repository's name on its ``origin`` remote, ``""`` when it has none.
+
+ The checkout folder is not the name in a worktree or a renamed clone; the
+ remote URL's last segment is, for every host's URL shape.
+ """
+ url = _read(repo_path, ["config", "--get", "remote.origin.url"]).rstrip("/")
+ name = url.replace("\\", "/").replace(":", "/").rsplit("/", 1)[-1]
+ return name[: -len(".git")] if name.endswith(".git") else name
+
+
def tracked_paths(repo_path: str) -> frozenset[str]:
"""Every path git tracks, repo-relative POSIX, or empty when git cannot answer."""
return frozenset(p for p in _read(repo_path, ["ls-files", "-z"]).split("\0") if p)
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index 5427527a5..c996eef1e 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -29,6 +29,7 @@ import pathspec
import structlog
from pathspec.patterns.gitwildmatch import GitWildMatchPattern, GitWildMatchPatternError
+from ..code_origin import is_generated_header
from ..entry_candidacy import conventional_entry_stems, not_an_execution_start
from ..test_paths import is_test_related_path
from .languages.registry import REGISTRY as _LANG_REGISTRY
@@ -275,24 +276,6 @@ _BLOCKED_FILENAME_SPEC: pathspec.PathSpec = pathspec.PathSpec.from_lines(
"gitwildmatch", _BLOCKED_FILENAME_PATTERNS
)
-# Generated-file banners, read only from comment lines and docstring openers
-# in the first two lines. These two count anywhere in the comment text:
-_GENERATED_ANYWHERE_MARKERS: tuple[str, ...] = ("DO NOT EDIT", "@GENERATED")
-# ...these only where the comment text starts ("<auto-generated>" included):
-_GENERATED_LEADING_MARKERS: tuple[str, ...] = (
- "CODE GENERATED",
- "THIS FILE WAS AUTOMATICALLY GENERATED",
- "GENERATED CODE",
- "AUTO-GENERATED",
-)
-# ...plus the sentence that says it anywhere in the comment.
-_THIS_FILE_GENERATED_RE = re.compile(
- r"\bTHIS FILE (?:IS|WAS) (?:AUTO-?|AUTOMATICALLY )?GENERATED\b"
-)
-# Longest first, so "/*" is stripped whole rather than as "/".
-_COMMENT_PREFIXES: tuple[str, ...] = ("<!--", "//", "/*", "--", "#", "*", ";")
-_DOCSTRING_OPENER_RE = re.compile(r"""^[rRuUbB]?(?:\"\"\"|''')""")
-
_GENERATED_SUFFIXES: tuple[str, ...] = tuple(_LANG_REGISTRY.generated_suffixes())
# Package-root manifests for monorepo detection, from the language registry.
@@ -1060,8 +1043,8 @@ def _is_generated(abs_path: Path) -> bool:
A generated-file banner sits on the first line or two, in a comment or a
module docstring. Code and prose that merely mention codegen (a string
literal "Auto-generated by …", a docstring about "the auto-generated
- client") are not banners, so a marker counts only as :func:`_is_banner`
- reads it.
+ client") are not banners; :func:`repowise.core.code_origin.is_generated_header`
+ holds the rule.
"""
name = abs_path.name
if any(name.endswith(sfx) for sfx in _GENERATED_SUFFIXES):
@@ -1071,39 +1054,7 @@ def _is_generated(abs_path: Path) -> bool:
header = f.read(512)
except OSError:
return False
- in_docstring = False
- for line in header.splitlines()[:2]:
- text = _comment_text(line.strip(), in_docstring)
- if text is None:
- continue
- # A bare opener ('"""' alone) puts the docstring text on the next line.
- in_docstring = not text and bool(_DOCSTRING_OPENER_RE.match(line.strip()))
- if _is_banner(text.upper()):
- return True
- return False
-
-
-def _comment_text(line: str, in_docstring: bool) -> str | None:
- """The text of a comment line or docstring opener, None for anything else."""
- if in_docstring:
- return line
- if opener := _DOCSTRING_OPENER_RE.match(line):
- return line[opener.end() :].strip()
- for prefix in _COMMENT_PREFIXES:
- if line.startswith(prefix):
- return line[len(prefix) :].strip()
- return None
-
-
-def _is_banner(text: str) -> bool:
- """Whether upper-cased comment *text* declares its file generated."""
- if any(marker in text for marker in _GENERATED_ANYWHERE_MARKERS):
- return True
- if _THIS_FILE_GENERATED_RE.search(text):
- return True
- # Leading punctuation is decoration ("<auto-generated>", "*** GENERATED").
- lead = text.lstrip("<!*-=#/; \t")
- return lead.startswith(_GENERATED_LEADING_MARKERS)
+ return is_generated_header(header)
def _is_config_file(language: LanguageTag) -> bool:
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 0cd9a1db5..40be087c9 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -177,6 +177,7 @@ def _health_metric_row_data(metric: Any) -> dict:
"structure_deduction": getattr(metric, "structure_deduction", None),
"history_deduction": getattr(metric, "history_deduction", None),
"is_test": bool(getattr(metric, "is_test", False)),
+ "code_origin": getattr(metric, "code_origin", None),
}
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 3cf00fc7b..93e61fe12 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2151,6 +2151,12 @@ class HealthFileMetric(Base):
# before the column existed; derived from the path, so ``backfill_is_test``
# fills those in without re-scoring anything.
is_test: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
+ # Where the file's code comes from (``production`` / ``test`` /
+ # ``vendored`` / ``docs_example`` / ``generated`` / ``tooling``), decided
+ # by ``repowise.core.code_origin`` with the file's head in hand, so a
+ # reader ranking what to fix never re-reads or re-parses the file. NULL on
+ # rows written before the column existed.
+ code_origin: Mapped[str | None] = mapped_column(String(16), nullable=True)
# Commit this row was scored against. Health is a separate pass from indexing
# and can lag it, so ``Repository.head_commit`` does not answer "how old is
# this score". Per-row rather than per-repo because the incremental path
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 05f5059e9..b89ac4496 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1248,6 +1248,7 @@ def _refreshed_metric(refreshed: Any, stored: Any) -> dict:
"structure_deduction": refreshed.structure_deduction,
"history_deduction": refreshed.history_deduction,
"is_test": stored.is_test,
+ "code_origin": getattr(stored, "code_origin", None),
}
diff --git a/tests/unit/health/test_dispatch_and_deprecation.py b/tests/unit/health/test_dispatch_and_deprecation.py
new file mode 100644
index 000000000..b17583455
--- /dev/null
+++ b/tests/unit/health/test_dispatch_and_deprecation.py
@@ -0,0 +1,455 @@
+"""Two per-function walker facts: ``dispatch_share`` and ``deprecated``.
+
+``dispatch_share`` is the share of a function's decision points that sit
+inside its largest top-level dispatch on one subject, arms and what they nest. ``deprecated`` is a declaration marker or a
+top-level deprecation warning. Neither moves a CCN, threshold or score.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.duplication import DuplicationReport
+from repowise.core.analysis.health.engine import HealthAnalyzer
+from repowise.core.analysis.health.finding_identity import finding_public_id
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+
+_EXT = {
+ "python": "py",
+ "typescript": "ts",
+ "javascript": "js",
+ "go": "go",
+ "java": "java",
+ "csharp": "cs",
+ "rust": "rs",
+ "kotlin": "kt",
+ "ruby": "rb",
+}
+
+
+def _functions(language: str, source: str) -> dict:
+ fcx = walk_file(f"/tmp/sample.{_EXT[language]}", language, source.encode())
+ if not fcx.functions:
+ pytest.skip(f"{language} grammar unavailable")
+ return {fc.name: fc for fc in fcx.functions}
+
+
+# --------------------------------------------------------------------------
+# dispatch_share
+# --------------------------------------------------------------------------
+
+_PY = """
+def visit(node):
+ if isinstance(node, A):
+ return 1
+ elif isinstance(node, B) or isinstance(node, C):
+ return 2
+ elif isinstance(node, D):
+ return 3
+ else:
+ return 4
+
+def matcher(tokens, flag):
+ for t in tokens:
+ match t.kind:
+ case "a":
+ x()
+ case "b":
+ y()
+ case _:
+ z()
+ if flag:
+ w()
+
+def guards(node, flag):
+ if flag:
+ prepare()
+ if node.type == "call" and strict:
+ return call(node)
+ if node.type == "name":
+ if node.text:
+ return node.text
+ return ""
+ if node.type in ("int", "float"):
+ return number(node)
+ return None
+
+def mixed(x, y):
+ if x == 1:
+ return 1
+ elif y == 2:
+ return 2
+ elif x == 3:
+ return 3
+
+def short_chain(x):
+ if x == 1:
+ return 1
+ elif x == 2:
+ return 2
+
+def nested(x, ready):
+ if ready:
+ match x:
+ case 1:
+ a()
+ case 2:
+ b()
+"""
+
+
+def test_python_if_chain_on_one_subject() -> None:
+ # Every decision point (three arms plus one ``or``) is the dispatch.
+ fns = _functions("python", _PY)
+ assert fns["visit"].ccn == 5
+ assert fns["visit"].dispatch_share == 1.0
+
+
+def test_python_match_inside_a_loop_counts() -> None:
+ # Five decision points (for, three cases, if); the match holds three.
+ fns = _functions("python", _PY)
+ assert fns["matcher"].ccn == 6
+ assert fns["matcher"].dispatch_share == 0.6
+
+
+def test_python_guard_run_counts_what_its_arms_nest() -> None:
+ # Six decision points: the unrelated ``if flag``, then three guards on
+ # ``node.type`` holding one ``and`` and one nested ``if``: 5 of 6.
+ fns = _functions("python", _PY)
+ assert fns["guards"].ccn == 7
+ assert fns["guards"].dispatch_share == 0.83
+
+
[email protected]("name", ["mixed", "short_chain", "nested"])
+def test_python_negatives(name: str) -> None:
+ # Two subjects, a two-arm chain, and a match nested under a branch.
+ assert _functions("python", _PY)[name].dispatch_share == 0.0
+
+
+def test_typescript_switch_chain_and_closure() -> None:
+ fns = _functions(
+ "typescript",
+ """
+function sw(x: Node) {
+ if (ready) { go() }
+ switch (x.kind) {
+ case 1: if (a) { b(); } break;
+ case 2: c(); break;
+ case 3: d(); break;
+ }
+}
+function chain(x) {
+ for (const k of ks) { use(k) }
+ if (x.k === 1) {} else if (x.k === 2) {} else if (x.k === 3 || x.k === 4) {}
+}
+function two(x, y) {
+ if (x.k === 1) {} else if (y.k === 2) {} else if (x.k === 3) {}
+}
+const mw = (target) => {
+ return async (c) => {
+ if (ready) { log() }
+ switch (target) { case "json": if (a) { b() } break; case "form": f(); break }
+ }
+}
+""",
+ )
+ # Three arms and the if nested in one, of five decision points.
+ assert fns["sw"].dispatch_share == 0.8
+ assert fns["chain"].dispatch_share == 0.8
+ assert fns["two"].dispatch_share == 0.0
+ # A middleware factory's dispatch sits in the closure it returns.
+ assert fns["mw"].dispatch_share == 0.75
+
+
+def test_go_switch_needs_a_subject() -> None:
+ fns = _functions(
+ "go",
+ """package m
+func F(x int) int {
+ if ready { go() }
+ switch x {
+ case 1:
+ if a { return 1 }
+ case 2:
+ return 2
+ case 3:
+ return 3
+ }
+ return 0
+}
+func H(x int) int {
+ if ready { go() }
+ switch {
+ case x > 1:
+ if a { return 1 }
+ case x < 0:
+ return 2
+ }
+ return 0
+}
+""",
+ )
+ assert fns["F"].dispatch_share == 0.8
+ assert fns["H"].dispatch_share == 0.0
+
+
+def test_java_switch_and_equals_chain() -> None:
+ fns = _functions(
+ "java",
+ """class A {
+ int f(int x) { if (r) go(); switch (x) { case 1: if (a) return 1; case 2: return 2; } return 0; }
+ int g(String cmd) {
+ if ("a".equals(cmd)) {} else if ("b".equals(cmd)) {} else if ("c".equals(cmd)) {}
+ return 0;
+ }
+}""",
+ )
+ assert fns["f"].dispatch_share == 0.75
+ assert fns["g"].dispatch_share == 1.0
+
+
+def test_csharp_flat_switch_expression_is_one_point() -> None:
+ fns = _functions(
+ "csharp",
+ "class A { int F(int x) { if (r) Go(); return x switch { 1 => 1, 2 => 2, _ => 3 }; } }",
+ )
+ # A flat switch charges one point, so it is one point of the share too.
+ assert fns["F"].ccn == 3
+ assert fns["F"].dispatch_share == 0.5
+
+
+def test_rust_match() -> None:
+ fns = _functions(
+ "rust",
+ "fn f(x: E) -> i32 { if r { go(); } "
+ "match x { E::A => { if a { 1 } else { 2 } } E::B => 2, E::C => 3 } }",
+ )
+ assert fns["f"].dispatch_share == 0.8
+
+
+def test_kotlin_when_needs_a_subject() -> None:
+ fns = _functions(
+ "kotlin",
+ """fun f(x: Int): Int { if (a) {}; return when (x) { 1 -> { if (b) 1 else 2 } 2 -> 3 else -> 4 } }
+fun g(x: Int): Int { return when { x > 1 -> { if (b) 1 else 2 } x < 0 -> 3 else -> 4 } }""",
+ )
+ assert fns["f"].dispatch_share == 0.8
+ assert fns["g"].dispatch_share == 0.0
+
+
+def test_ruby_case_needs_a_subject() -> None:
+ fns = _functions(
+ "ruby",
+ """def f(x)
+ go if ready
+ case x
+ when 1 then if a then 1 end
+ when 2 then 2
+ end
+end
+def g(x)
+ go if ready
+ case
+ when x > 1 then if a then 1 end
+ when x < 0 then 2
+ end
+end
+""",
+ )
+ assert fns["f"].dispatch_share == 0.75
+ assert fns["g"].dispatch_share == 0.0
+
+
+# --------------------------------------------------------------------------
+# deprecated
+# --------------------------------------------------------------------------
+
+_PY_DEPRECATED = '''
+import warnings
+
+def old():
+ """Doc."""
+ warnings.warn("old is deprecated", DeprecationWarning, stacklevel=2)
+ return 1
+
+@typing_extensions.deprecated("use new")
+def decorated():
+ pass
+
+@deprecated
+def bare_decorated():
+ pass
+
+def param(x=None):
+ if x:
+ warnings.warn("x is deprecated", DeprecationWarning)
+
+def warn_deprecated(msg):
+ warnings.warn(msg, DeprecationWarning)
+
+def plain():
+ warnings.warn("slow path", RuntimeWarning)
+
+def finder(c):
+ return find_deprecated_settings(c)
+
+def opt(x, old_opt=None):
+ warnings.warn("old_opt is deprecated, use new_opt", DeprecationWarning)
+ return x
+
+def late(x):
+ prepare(x)
+ check(x)
+ warnings.warn("late is deprecated", DeprecationWarning)
+
+def generic():
+ """Old."""
+ # Kept for one release.
+ warnings.warn("deprecated", DeprecationWarning)
+'''
+
+
[email protected]("name", ["old", "decorated", "bare_decorated", "generic"])
+def test_python_deprecated(name: str) -> None:
+ assert _functions("python", _PY_DEPRECATED)[name].deprecated is True
+
+
+ "name", ["param", "warn_deprecated", "plain", "finder", "opt", "late"]
+)
+def test_python_not_deprecated(name: str) -> None:
+ # A warning in a branch deprecates a parameter, a helper that warns for
+ # others is not itself deprecated, another warning category is not one, and
+ # returning a value from a deprecation helper is not a warning. A message
+ # naming a parameter deprecates the option, and a warning below the top of
+ # the body is not the function announcing itself.
+ assert _functions("python", _PY_DEPRECATED)[name].deprecated is False
+
+
+ ("language", "source"),
+ [
+ ("java", "class A { @Deprecated int f() { return 1; } int g() { return 1; } }"),
+ ("kotlin", '@Deprecated("x")\nfun f(): Int { return 1 }\nfun g(): Int { return 1 }'),
+ ("csharp", 'class A { [Obsolete("x")] int f() { return 1; } int g() { return 1; } }'),
+ ("rust", '#[deprecated(since = "1.0")]\nfn f() -> i32 { 1 }\nfn g() -> i32 { 1 }'),
+ (
+ "typescript",
+ "/** Old.\n * @deprecated use g */\nexport function f() { return 1 }\n"
+ "/** Current. */\nexport function g() { return 1 }",
+ ),
+ (
+ "go",
+ "package m\n// F is old.\n//\n// Deprecated: use G.\nfunc F() int { return 1 }\n"
+ "// G is current.\nfunc G() int { return 1 }",
+ ),
+ ("javascript", 'function f() { console.warn("f is deprecated"); }\nfunction g() { return 1 }'),
+ ("ruby", 'def f\n warn "f is deprecated"\nend\ndef g\n 1\nend\n'),
+ ],
+)
+def test_deprecated_marker_per_language(language: str, source: str) -> None:
+ fns = _functions(language, source)
+ first, second = ("F", "G") if language == "go" else ("f", "g")
+ assert fns[first].deprecated is True
+ assert fns[second].deprecated is False
+
+
+def test_a_deprecated_option_in_an_inline_type_is_not_the_function() -> None:
+ fns = _functions(
+ "typescript",
+ """/** Serve files. */
+export const serveStatic = (options: {
+ /** @deprecated use root */
+ path?: string
+}) => { return options }
+""",
+ )
+ assert fns["serveStatic"].deprecated is False
+
+
+# --------------------------------------------------------------------------
+# Engine: details, metric origin, stable ids
+# --------------------------------------------------------------------------
+
+_TANGLED = b"""
+import warnings
+
+def tangled(x):
+ warnings.warn("tangled is deprecated", DeprecationWarning)
+ total = 0
+ if x == 1:
+ total += 1
+ elif x == 2:
+ total += 2
+ elif x == 3:
+ total += 3
+ elif x == 4:
+ total += 4
+ elif x == 5:
+ total += 5
+ elif x == 6:
+ total += 6
+ elif x == 7:
+ total += 7
+ elif x == 8:
+ total += 8
+ elif x == 9:
+ total += 9
+ return total
+
+def fine():
+ return 1
+"""
+
+
+def _evaluate(path: str):
+ fcx = walk_file("/tmp/tangled.py", "python", _TANGLED)
+ if not fcx.functions:
+ pytest.skip("python grammar unavailable")
+ pf = SimpleNamespace(
+ file_info=SimpleNamespace(
+ path=path, language="python", abs_path="/tmp/tangled.py", is_test=False
+ ),
+ symbols=[],
+ )
+ return HealthAnalyzer(graph=None)._evaluate_file(
+ pf,
+ fcx,
+ paired_tests=set(),
+ package_roots=set(),
+ disabled=[],
+ dup_report=DuplicationReport(),
+ )
+
+
+def test_complexity_findings_carry_dispatch_share_and_deprecated() -> None:
+ _, findings, _ = _evaluate("src/tangled.py")
+ complex_method = next(f for f in findings if f.biomarker_type == "complex_method")
+ # The chain holds all nine decision points.
+ assert complex_method.details["dispatch_share"] == 1.0
+ assert complex_method.details["deprecated"] is True
+
+
+def test_metric_carries_code_origin() -> None:
+ assert _evaluate("src/tangled.py")[0].code_origin == "production"
+ assert _evaluate("docs_src/tutorial/tangled.py")[0].code_origin == "docs_example"
+
+
+def test_new_detail_keys_leave_the_finding_id_unchanged() -> None:
+ base = HealthFindingData(
+ biomarker_type="complex_method",
+ severity=Severity.HIGH,
+ file_path="src/a.py",
+ function_name="f",
+ line_start=1,
+ line_end=30,
+ details={"ccn": 12, "cognitive": 20, "nloc": 30},
+ health_impact=1.0,
+ )
+ annotated = HealthFindingData(
+ **{**base.__dict__, "details": {**base.details, "dispatch_share": 0.8, "deprecated": True}}
+ )
+ assert finding_public_id(annotated) == finding_public_id(base)
diff --git a/tests/unit/health/test_walk_cache.py b/tests/unit/health/test_walk_cache.py
index ac25891c3..653ce20b4 100644
--- a/tests/unit/health/test_walk_cache.py
+++ b/tests/unit/health/test_walk_cache.py
@@ -155,11 +155,18 @@ def test_the_walk_itself_does_not_serve_a_ts_file_to_a_tsx_file(tmp_path: Path)
# revert to keying on the language tag fails here rather than passing.
src = b'const C = () => <div>{label}</div>;\nit("t", () => { render(<C />); });\n'
cache = HealthWalkCache(tmp_path, HEALTH_ANALYZER_VERSION)
- analyzer = SimpleNamespace(read_source=lambda _p: src, _walk_cache=cache)
+ analyzer = SimpleNamespace(
+ read_source=lambda _p: src,
+ _walk_cache=cache,
+ _origins={},
+ _origin=lambda _pf, _source=None: "production",
+ )
def parsed(name: str):
return SimpleNamespace(
- file_info=SimpleNamespace(abs_path=str(tmp_path / name), language="typescript")
+ file_info=SimpleNamespace(
+ path=name, abs_path=str(tmp_path / name), language="typescript"
+ )
)
vocab = AssertVocabulary()
diff --git a/tests/unit/persistence/test_health_dimensions_crud.py b/tests/unit/persistence/test_health_dimensions_crud.py
index 77ff721b1..469bc3b81 100644
--- a/tests/unit/persistence/test_health_dimensions_crud.py
+++ b/tests/unit/persistence/test_health_dimensions_crud.py
@@ -7,6 +7,8 @@ so a future edit to one writer that forgets the new fields is caught.
from __future__ import annotations
+import json
+
import pytest
from repowise.core.analysis.health.models import (
@@ -86,6 +88,50 @@ async def test_upsert_health_metrics_persists_dimension_scores(async_session):
assert row.performance_score is None
+async def test_both_metric_writers_persist_code_origin(async_session):
+ """``code_origin`` is read off the row, so both writers must store it."""
+ repo = await insert_repo(async_session)
+ await save_health_metrics(
+ async_session,
+ repo.id,
+ [_metric("docs_src/app.py", code_origin="docs_example"), _metric("legacy.py")],
+ )
+ await async_session.commit()
+ rows = {r.file_path: r for r in await get_health_metrics(async_session, repo.id)}
+ assert rows["docs_src/app.py"].code_origin == "docs_example"
+ assert rows["legacy.py"].code_origin is None
+
+ await upsert_health_metrics(
+ async_session, repo.id, [_metric("legacy.py", code_origin="vendored")]
+ )
+ await async_session.commit()
+ rows = {r.file_path: r for r in await get_health_metrics(async_session, repo.id)}
+ assert rows["legacy.py"].code_origin == "vendored"
+
+
+async def test_finding_details_round_trip_dispatch_share_and_deprecated(async_session):
+ repo = await insert_repo(async_session)
+ finding = HealthFindingData(
+ biomarker_type="complex_method",
+ severity=Severity.HIGH,
+ file_path="a.py",
+ function_name="visit",
+ line_start=1,
+ line_end=40,
+ details={"ccn": 20, "dispatch_share": 0.85, "deprecated": True},
+ health_impact=1.0,
+ )
+ await save_health_findings(async_session, repo.id, [finding])
+ await async_session.commit()
+
+ row = (await get_health_findings(async_session, repo.id))[0]
+ details = json.loads(row.details_json)
+ assert details["dispatch_share"] == 0.85
+ assert details["deprecated"] is True
+
+
@pytest.mark.asyncio
async def test_save_health_findings_persists_dimension(async_session):
repo = await insert_repo(async_session)
diff --git a/tests/unit/test_code_origin.py b/tests/unit/test_code_origin.py
new file mode 100644
index 000000000..7d68aa9e0
--- /dev/null
+++ b/tests/unit/test_code_origin.py
@@ -0,0 +1,157 @@
+"""One origin per file: production, test, vendored, docs_example, generated, tooling."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.code_origin import CODE_ORIGINS, code_origin, is_generated_header
+
+_JQUERY = (
+ "/*!\n"
+ " * jQuery JavaScript Library v3.6.0\n"
+ " * https://jquery.com/\n"
+ " * Copyright OpenJS Foundation and other contributors\n"
+ " * Released under the MIT license\n"
+ " */\n"
+ "(function (global, factory) {\n"
+)
+_TYPEAHEAD = (
+ "/*!\n"
+ " * typeahead.js 0.10.5\n"
+ " * https://github.com/twitter/typeahead.js\n"
+ " * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT\n"
+ " */\n"
+)
+_OWN_HEADER = (
+ "// Copyright (c) 2024 Acme Corp. All rights reserved.\n"
+ "// Licensed under the MIT License.\n"
+ "export function boot() {}\n"
+)
+
+
+ ("path", "expected"),
+ [
+ ("src/flask/app.py", "production"),
+ ("app.py", "production"),
+ ("src/examples.py", "production"), # a file named for examples is code
+ ("pkg/external_api/client.go", "production"),
+ ("pkg/external/client.go", "production"), # external/ only at the root
+ ("tests/test_app.py", "test"),
+ ("src/app.test.ts", "test"),
+ ("vendor/github.com/x/y.go", "vendored"),
+ ("web/node_modules/lodash/index.js", "vendored"),
+ ("static/bower_components/jquery/jquery.js", "vendored"),
+ ("third_party/zlib/inflate.c", "vendored"),
+ ("src/thirdparty/docopt.py", "vendored"),
+ ("external/abseil/str.cc", "vendored"),
+ ("static/js/app.min.js", "vendored"),
+ ("assets/site.min.css", "vendored"),
+ ("docs_src/tutorial/first_steps.py", "docs_example"),
+ ("docs/conf.py", "docs_example"),
+ ("doc/man_docs.go", "production"), # cobra's doc/ is a shipped package
+ ("src/x/examples/a.py", "production"), # a nested examples/ can ship
+ ("pkg/samples/registry.go", "production"),
+ ("src/tutorials/steps.py", "production"),
+ ("examples/a.py", "docs_example"),
+ ("docs/examples/a.py", "docs_example"),
+ ("examples/tutorial/app.py", "docs_example"),
+ ("example/main.go", "docs_example"),
+ ("samples/hello/Program.cs", "docs_example"),
+ ("tutorials/part1/app.js", "docs_example"),
+ ("tutorial_01/app.py", "docs_example"),
+ ("scripts/release.py", "tooling"),
+ (".github/scripts/label.js", "tooling"),
+ ("tools/gen.go", "tooling"),
+ ("benchmarks/bench_app.py", "tooling"),
+ ("app/migrations/0001_initial.py", "tooling"),
+ ("db/alembic/versions/abc_add.py", "tooling"),
+ ("setup.py", "tooling"),
+ ("vite.config.ts", "tooling"),
+ ("src/__generated__/schema.ts", "generated"),
+ ("api/user_pb2.py", "generated"),
+ ("api/user_grpc.pb.go", "generated"),
+ ("Forms/Main.Designer.cs", "generated"),
+ ("src/client.generated.ts", "generated"),
+ ],
+)
+def test_path_rules(path: str, expected: str) -> None:
+ assert code_origin(path) == expected
+
+
+def test_every_answer_is_one_of_the_six() -> None:
+ assert set(CODE_ORIGINS) == {
+ "production",
+ "test",
+ "vendored",
+ "docs_example",
+ "generated",
+ "tooling",
+ }
+
+
+def test_precedence_is_generated_vendored_test_docs_tooling() -> None:
+ assert code_origin("vendor/foo_test.go") == "vendored"
+ assert code_origin("docs/tests/test_x.py") == "test"
+ assert code_origin("examples/scripts/run.py") == "docs_example"
+ assert code_origin("vendor/x.go", "// Code generated by protoc. DO NOT EDIT.\n") == "generated"
+
+
+def test_stored_test_flag_wins_over_the_path() -> None:
+ assert code_origin("src/checks.py", is_test=True) == "test"
+ assert code_origin("tests/test_app.py", is_test=False) == "production"
+
+
+def test_generated_banner_in_the_header() -> None:
+ assert code_origin("pkg/x.go", b"// Code generated by stringer. DO NOT EDIT.\n") == "generated"
+ assert code_origin("pkg/x.py", '"""Auto-generated by the build."""\n') == "generated"
+
+
+def test_generated_banner_negatives() -> None:
+ # A string literal mentioning codegen is not a banner.
+ assert code_origin("pkg/x.py", 'MSG = "auto-generated client"\n') == "production"
+ # A banner below the second line is not a header.
+ assert not is_generated_header("a = 1\nb = 2\n# DO NOT EDIT\n")
+
+
[email protected]("header", [_JQUERY, _TYPEAHEAD])
[email protected]("folder", ["docs/_static", "static/js", "assets", "public/lib"])
+def test_third_party_header_under_asset_dirs_is_vendored(header: str, folder: str) -> None:
+ assert code_origin(f"{folder}/lib.js", header) == "vendored"
+
+
+def test_third_party_header_outside_asset_dirs_stays() -> None:
+ assert code_origin("src/lib.js", _JQUERY) == "production"
+
+
+def test_own_license_header_is_not_vendored() -> None:
+ assert code_origin("static/js/boot.js", _OWN_HEADER) == "production"
+ assert code_origin("docs/_static/boot.js", _OWN_HEADER) == "docs_example"
+
+
+def test_own_release_banner_is_not_vendored() -> None:
+ banner = "/*! acme v1.2.0 | (c) Acme | MIT License */\n"
+ assert code_origin("static/acme.js", banner, project="acme") == "production"
+ assert code_origin("static/acme.js", banner, project="other") == "vendored"
+
+
+def test_own_banner_matches_the_project_name_loosely() -> None:
+ banner = "/*! MyLib v2.0.1 | (c) Someone | MIT License */\n"
+ assert code_origin("static/mylib.js", banner, project="my-lib") == "production"
+ assert code_origin("static/mylib.js", banner, project="my_lib") == "production"
+
+
+def test_header_banner_must_sit_in_a_comment() -> None:
+ # A version string in code with a copyright assignment is not a banner.
+ text = 'copyright = "2010 Pallets"\nrelease = "Flask 3.0.1"\n'
+ assert code_origin("docs/conf.py", text) == "docs_example"
+ assert code_origin("static/conf.py", text) == "production"
+
+
+def test_header_is_read_from_the_first_twenty_lines_only() -> None:
+ text = "\n" * 25 + _JQUERY
+ assert code_origin("static/js/lib.js", text) == "production"
+
+
+def test_windows_separators() -> None:
+ assert code_origin("docs_src\\tutorial\\app.py") == "docs_example"
diff --git a/tests/unit/test_git_refs.py b/tests/unit/test_git_refs.py
index 30e739ffe..f65c9342b 100644
--- a/tests/unit/test_git_refs.py
+++ b/tests/unit/test_git_refs.py
@@ -15,6 +15,7 @@ from repowise.core.git_refs import (
current_branch,
default_base,
list_branches,
+ remote_name,
resolve,
)
@@ -193,3 +194,24 @@ class TestCommitFileSets:
def test_a_non_repository_yields_nothing(self, tmp_path: Path) -> None:
assert commit_file_sets(str(tmp_path / "nowhere_at_all"), "main..feat") == []
+
+
+ "url",
+ [
+ "https://github.com/pallets/flask.git",
+ "[email protected]:pallets/flask.git",
+ "https://gitlab.example.com/group/sub/flask/",
+ ],
+)
+def test_remote_name_is_the_last_url_segment(tmp_path: Path, url: str) -> None:
+ root = tmp_path / "checkout-folder"
+ root.mkdir()
+ _run(root, "init", "-b", "main")
+ _run(root, "remote", "add", "origin", url)
+ assert remote_name(str(root)) == "flask"
+
+
+def test_remote_name_is_empty_without_a_remote(tmp_path: Path) -> None:
+ _run(tmp_path, "init", "-b", "main")
+ assert remote_name(str(tmp_path)) == ""