Files
crapper/src/crapper/languages/golang.py
T
Cursor AgentandRobert C. Martin 10c4e43f7b Add Swift function CRAP scores, coverage, and test discovery.
Swift packages and iOS apps had no per-function complexity or coverage join, so crapper could not write a .metrics/crap.edn entry that uml-viewer and mutator can attach to a function. The Swift reader scores top-level functions, methods, initializers, subscripts, computed properties, and closures bound with let or var. Nested closures stay inside the enclosing function. Decision points match the other languages: if, guard, loops, catch, ternary, each switch case, &&, ||, ??, and optional chaining.

Coverage reads llvm-cov JSON from swift test and xccov JSON from xcodebuild, joined on the file suffix and the function's line span. A package runs swift test --enable-code-coverage; an Xcode project runs xcodebuild and xcrun xccov view --report --json.

Proved by tests/test_swift.py against checked-in llvm-cov and xccov fixtures, the existing suite (174 passed), crapper with every function under CRAP 10, dryer with no duplicate at 0.8 or above, and mutator killing every mutant in the Swift reader.

Co-authored-by: Robert C. Martin <[email protected]>
2026-11-25 23:45:32 +00:00

139 lines
4.0 KiB
Python

"""Go functions and cyclomatic complexity, following crap4go.
Decision points are `if`, `for`, `range`, each `switch` / type-switch case,
each `select` clause, and `&&` / `||`. Coverage later uses Go's statement
profile. The namespace is the package import path; methods are namespaced by
their receiver type (`import/path.Widget`) and named `Run`, which is the join
uml-viewer makes between a class and its operations.
"""
from pathlib import Path
from crapper.languages.treesitter import (
absolute_path as _absolute,
binary_logic,
child_of_type,
child_text,
complexity,
descendants,
end_line,
node_text,
parse,
start_line,
)
from crapper.model import Function
_DECISIONS = {
"if_statement",
"for_statement",
"expression_case",
"type_case",
"communication_case",
"default_case",
}
def _is_decision(node) -> bool:
return node.type in _DECISIONS or binary_logic(node)
def _skip(_node) -> bool:
return False
def _package_clause(data: bytes, root) -> str:
for node in descendants(root):
if node.type == "package_identifier":
return node_text(data, node)
return ""
def _type_identifiers(node) -> list[str]:
found = []
for item in descendants(node):
if item.type == "type_identifier":
found.append(item)
return found
def _receiver_type(data: bytes, method) -> str | None:
params = child_of_type(method, "parameter_list")
if params is None:
return None
idents = _type_identifiers(params)
if not idents:
return None
return node_text(data, idents[0])
def _method_name(data: bytes, method) -> str | None:
return child_text(data, method, "field_identifier")
def _function_name(data: bytes, fn) -> str | None:
return child_text(data, fn, "identifier")
def package_namespace(path: str, package_name: str) -> str:
"""Import path of the package, or the package clause when no go.mod exists."""
current = Path(path).resolve().parent
module = None
module_dir = None
while True:
candidate = current / "go.mod"
if candidate.is_file():
for line in candidate.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if stripped.startswith("module "):
module = stripped.split(None, 1)[1].strip()
module_dir = current
break
break
if current.parent == current:
break
current = current.parent
if not module or module_dir is None:
return package_name
relative = Path(path).resolve().parent.relative_to(module_dir).as_posix()
if relative == ".":
return module
return f"{module}/{relative}"
def functions_in_source(
source: str, path: str, project_root: str | None = None
) -> list[Function]:
data, tree = parse(source, "go")
package_name = _package_clause(data, tree.root_node)
package_ns = package_namespace(_absolute(path, project_root), package_name)
found: list[Function] = []
for node in descendants(tree.root_node):
if node.type not in {"function_declaration", "method_declaration"}:
continue
if child_of_type(node, "block") is None:
continue
if node.type == "method_declaration":
name = _method_name(data, node)
receiver = _receiver_type(data, node)
if not name or not receiver:
continue
namespace = f"{package_ns}.{receiver}"
else:
name = _function_name(data, node)
if not name:
continue
namespace = package_ns
found.append(
Function(
name=name,
namespace=namespace,
complexity=complexity(node, _is_decision, _skip),
start_line=start_line(node),
end_line=end_line(node),
path=path,
language="go",
)
)
return found