Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ uml-viewer groups entries by `:namespace` and joins each operation on `:name`. `
| TypeScript | the dotted module path, or `module.Class` | the function or method name |
| Rust | `crate::module`, or `crate::module::Type` | the function or method name |
| Python | the dotted module path, or `module.Class` | the function or method name |
| Dart | the package name plus the path under `lib/` (`gap_core.src.models.user`), or `module.Type` | the function or method name; `size` / `size=` for a getter / setter, `operator +`, a factory's name |
| Swift | the module, or `Module.Type` | the function, method, initializer, subscript, or property |

Rename or move is a new entry. There is no identity matching across runs.
Expand All @@ -70,6 +71,8 @@ Rust counts `if`, loops, each `match` arm, `?`, and `&&` / `||`. `mod tests` is

Python counts `if`, `elif`, `for`, `while`, `except`, each `match` case, a comprehension filter, a conditional expression, and each `and` / `or`. Nested functions stay inside the enclosing function. Coverage is LCOV from `coverage.py`, running pytest when the project uses it and `unittest` otherwise. `coverage` and `pytest` are installed into the project's interpreter when they are missing.

Dart (`.dart`) counts `if`, `for`, `while`, `do`, `catch`, `?:`, each `switch` case and `default`, each `switch` expression arm, each `&&` / `||`, `??`, `?.`, and collection `if` / `for`. Entries are top-level functions, methods of classes, mixins, extensions and enums, getters, setters, operators, and factory constructors (`factory A.fromJson` is `fromJson`, `factory A` is `A`). Generative constructors, abstract and `external` members are not entries; local functions and closures count toward the function that holds them. The namespace comes from the nearest `pubspec.yaml`: its `name` plus the path under `lib/`, or under the package for files outside `lib/` (`demo.bin.tool`). Generated files (`*.g.dart`, `*.freezed.dart`, `*.mocks.dart`, `*.gr.dart`, `*.config.dart`, `*.pb*.dart`), `.dart_tool`, `test/`, `integration_test/`, `test_driver/`, and `*_test.dart` are skipped. Coverage is LCOV. In a workspace with several packages, each package runs its own tests; `flutter test` writes paths relative to the package, and crapper makes them absolute so `lib/a.dart` in two packages stays two files. `--use-existing-coverage` also reads each package's `coverage/lcov.info`, which `flutter test --coverage` writes by default. In a Flutter workspace, `flutter test` re-resolves dependencies and may rewrite the workspace's `pubspec.lock`; check `git status` after a run and restore the file if the change is not wanted. A package outside `--root` is allowed: its report goes under `target/coverage/dart/external__<absolute path>/`. The Dart VM marks only executable lines, so a line like `return 1;` may have no hit count; the function's percentage is over the lines that have one.

Swift counts `if` (each `else if` is another `if`), `guard`, `for`, `while`, `repeat-while`, each `catch`, `?:`, each `switch` case including `default`, `&&`, `||`, `??`, and optional chaining (`a?.b`, `a?[i]`, `a?()`). These are not decisions: `try` / `try?` / `try!`, `as?` / `as!` / `is`, a `where` clause, `#if`, and the `?` on an optional type (`Int?`) or a failable `init?`. One `if` or `guard` is one decision even when it lists several conditions. `case 1, 2` is one case. Operators inside a string or a comment are not decisions; an interpolated expression is. `#if` does not hide the branches the grammar still parses.

Entries are top-level functions, methods on classes, structs, enums, actors, extensions, and protocols, initializers, deinitializers, subscripts, computed properties, and property observers. A requirement or accessor with no statements, such as `{ get set }`, is not an entry. `get`, `set`, `willSet`, and `didSet` stay inside the property. A closure stored directly in a `let` or `var` is an entry. Any other closure stays inside the enclosing function, the same way a nested callback stays inside its function in TypeScript. A type declared inside a function keeps its own methods, and those methods are not also charged to the outer function.
Expand All @@ -88,6 +91,7 @@ By default a run deletes the previous report for each language it is about to me
| TypeScript | `npm run coverage`, or Vitest `--coverage`, or `npx c8 ... npm test` | `coverage/lcov.info` or `target/coverage/typescript/lcov.info` |
| Rust | `cargo llvm-cov` or `cargo tarpaulin`, per Cargo package | `target/coverage/rust/lcov.info` |
| Python | `coverage run` with pytest or unittest, then `coverage lcov` | `target/coverage/python/lcov.info` |
| Dart | `flutter test --coverage --coverage-path ...` when `pubspec.yaml` depends on `sdk: flutter`, else `dart test --coverage-path ...`, per package | `target/coverage/dart/<package>/lcov.info` |
| Swift | `swift test --enable-code-coverage`, then `llvm-cov export` (JSON by default); or `xcodebuild test -enableCodeCoverage YES` and `xcrun xccov view --report --json` | `target/coverage/swift/**/*.json` |

A missing tool or a failed test run scores that language at 0% and still writes the snapshot. Pass `--coverage-command` to replace those defaults with one command of your own. `--no-coverage` is the run that leaves coverage and CRAP as N/A.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[project]
name = "crapper"
version = "0.1.0"
description = "CRAP scores for Clojure, Java, Go, TypeScript, Rust, Python, and Swift, in the snapshot uml-viewer reads."
description = "CRAP scores for Clojure, Java, Go, TypeScript, Rust, Python, Dart, and Swift, in the snapshot uml-viewer reads."
readme = "README.md"
license = { file = "LICENSE" }
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
Expand Down
11 changes: 10 additions & 1 deletion src/crapper/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from crapper.coverage import CoverageBundle, load_bundle
from crapper.discover import (
CLOJURE_TEST_SUFFIXES,
DART_GENERATED_SUFFIXES,
DART_TEST_SUFFIX,
GO_TEST_SUFFIX,
JS_TEST_SUFFIXES,
SKIP_DIRS,
Expand All @@ -24,6 +26,7 @@
from crapper.runners import run_coverage

_SKIPPED_DIRS = ", ".join(sorted(SKIP_DIRS | TEST_DIRS))
_DART_GENERATED = " ".join(f"*{suffix}" for suffix in DART_GENERATED_SUFFIXES)
_TEST_PATTERNS = ", ".join(
[
f"*{GO_TEST_SUFFIX}",
Expand All @@ -32,6 +35,8 @@
"test_*.py",
"*_test.py",
"conftest.py",
f"*{DART_TEST_SUFFIX}",
"Dart files under integration_test/ or test_driver/",
"*Tests.swift",
]
)
Expand All @@ -45,7 +50,7 @@

Languages: Clojure (.clj .cljc .cljs .bb), Java (.java), Go (.go),
TypeScript and JavaScript (.ts .tsx .mts .cts .js .jsx .mjs .cjs),
Rust (.rs), Python (.py), Swift (.swift).
Rust (.rs), Python (.py), Dart (.dart), Swift (.swift).

Options:
-h, --help Print this help and exit.
Expand All @@ -69,6 +74,7 @@

With no paths, source files under the project root are analyzed. Directories
named {_SKIPPED_DIRS} are skipped, as are {_TEST_PATTERNS}.
Generated Dart files ({_DART_GENERATED}) are not sources.

Coverage, when it is produced:
Clojure clj -M:cov --lcov, then Cloverage form counts or LCOV
Expand All @@ -77,6 +83,8 @@
TypeScript npm run coverage, Vitest's own LCOV, or c8 around npm test
Rust cargo llvm-cov, or cargo tarpaulin, in the nearest Cargo.toml
Python coverage.py LCOV, via pytest or unittest, per project
Dart flutter test --coverage for Flutter packages, else
dart test --coverage-path, per pubspec.yaml
Swift swift test --enable-code-coverage, then llvm-cov JSON;
or xcodebuild test and xcrun xccov view --report --json

Expand All @@ -87,6 +95,7 @@
TypeScript dotted module path, or module.Class for methods
Rust crate::module, or crate::module::Type for methods
Python dotted module path, or module.Class for methods
Dart package.path.under.lib, or module.Type for methods
Swift the module, or Module.Type for methods and properties
"""

Expand Down
10 changes: 9 additions & 1 deletion src/crapper/coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pathlib import Path
from urllib.parse import unquote

from crapper.dart_coverage import absolute_sources, package_reports
from crapper.model import Function
from crapper.runners import nearest_marker

Expand Down Expand Up @@ -850,7 +851,14 @@ def _merge_texts(paths: list[Path]) -> list[str]:

def _merge_lcov(root: Path) -> dict[str, dict[int, tuple[int, int]]]:
merged: dict[str, dict[int, tuple[int, int]]] = {}
for text in _merge_texts(_lcov_paths(root)):
dart = package_reports(root)
skipped = {report.resolve() for _, report in dart}
paths = [path for path in _lcov_paths(root) if path.resolve() not in skipped]
# A package's own `flutter test --coverage` report is the fallback; a
# fresh report under target/ wins.
for package, report in dart:
merged.update(parse_lcov(absolute_sources(_read(report) or "", package)))
for text in _merge_texts(paths):
merged.update(parse_lcov(text))
return merged

Expand Down
49 changes: 49 additions & 0 deletions src/crapper/dart_coverage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Dart and Flutter coverage: the test command for a package, and LCOV paths.

`flutter test --coverage` writes `SF:` paths relative to the package
(`lib/a.dart`); `dart test --coverage-path` writes absolute ones. Relative
paths are made absolute, so `lib/a.dart` in two packages stays two files.
"""

import os
import re
from pathlib import Path

from crapper.discover import SKIP_DIRS

_FLUTTER_SDK = re.compile(r"^\s*sdk:\s*['\"]?flutter['\"]?\s*$", re.MULTILINE)
_SOURCE = re.compile(r"^SF:(?!/)(.+)$", re.MULTILINE)


def is_flutter(package: Path) -> bool:
pubspec = package / "pubspec.yaml"
text = pubspec.read_text(encoding="utf-8", errors="replace") if pubspec.is_file() else ""
return _FLUTTER_SDK.search(text) is not None


def dart_command(package: Path, report: Path) -> list[str]:
if is_flutter(package):
return ["flutter", "test", "--coverage", "--coverage-path", str(report)]
return ["dart", "test", "--coverage-path", str(report)]


def absolute_sources(text: str, package: Path) -> str:
return _SOURCE.sub(lambda match: f"SF:{package / match.group(1)}", text)


def rewrite_report(report: Path, package: Path) -> None:
if report.is_file():
text = report.read_text(encoding="utf-8", errors="replace")
report.write_text(absolute_sources(text, package.resolve()), encoding="utf-8")


def package_reports(root: Path) -> list[tuple[Path, Path]]:
"""`(package, <package>/coverage/lcov.info)` for each Dart package under `root`."""

found = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [name for name in dirnames if name not in SKIP_DIRS]
report = Path(dirpath) / "coverage" / "lcov.info"
if "pubspec.yaml" in filenames and report.is_file():
found.append((Path(dirpath).resolve(), report))
return found
27 changes: 26 additions & 1 deletion src/crapper/discover.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
".cljs": "clojure",
".bb": "clojure",
".java": "java",
".dart": "dart",
".go": "go",
".ts": "typescript",
".tsx": "typescript",
Expand Down Expand Up @@ -41,12 +42,14 @@
"testdata",
"__pycache__",
".clj-kondo",
".dart_tool",
".build",
".swiftpm",
"DerivedData",
}

TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__"}
DART_TEST_DIRS = {"integration_test", "test_driver"}

GO_TEST_SUFFIX = "_test.go"
CLOJURE_TEST_SUFFIXES = ("_test.clj", "_test.cljc", "_test.cljs", "_test.bb")
Expand All @@ -70,14 +73,34 @@
)


DART_TEST_SUFFIX = "_test.dart"
DART_GENERATED_SUFFIXES = (
".g.dart",
".freezed.dart",
".mocks.dart",
".gr.dart",
".config.dart",
".pb.dart",
".pbenum.dart",
".pbjson.dart",
".pbserver.dart",
)


def language_of(path: str | Path) -> str | None:
file_path = Path(path)
name = file_path.name
if name.endswith(".d.ts"):
if name.endswith(".d.ts") or name.endswith(DART_GENERATED_SUFFIXES):
return None
return EXTENSIONS.get(file_path.suffix)


def _dart_test(file_path: Path) -> bool:
return file_path.name.endswith(DART_TEST_SUFFIX) or any(
part in DART_TEST_DIRS for part in file_path.parts
)


def _swift_test(file_path: Path) -> bool:
"""XCTest and Swift Testing keep tests in `Tests/` or a `*Tests` target."""

Expand All @@ -93,6 +116,8 @@ def is_test_file(path: str | Path) -> bool:
name = file_path.name
if name.endswith(GO_TEST_SUFFIX):
return True
if file_path.suffix == ".dart" and _dart_test(file_path):
return True
if name.endswith(CLOJURE_TEST_SUFFIXES):
return True
if name.endswith(JS_TEST_SUFFIXES):
Expand Down
2 changes: 2 additions & 0 deletions src/crapper/languages/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Per-language function extraction."""

from crapper.languages.clojure import functions_in_source as clojure_functions
from crapper.languages.dart import functions_in_source as dart_functions
from crapper.languages.golang import functions_in_source as go_functions
from crapper.languages.java import functions_in_source as java_functions
from crapper.languages.python import functions_in_source as python_functions
Expand All @@ -12,6 +13,7 @@
_READERS = {
"clojure": clojure_functions,
"java": java_functions,
"dart": dart_functions,
"go": go_functions,
"typescript": typescript_functions,
"python": python_functions,
Expand Down
Loading