diff --git a/README.md b/README.md index 56acc6d..a015d4b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # crapper -CRAP scores for Clojure, Java, Go, TypeScript, Rust, and Python. One run detects the language of each source file, applies that language's complexity and coverage rules, and writes the snapshot [uml-viewer](https://github.com/unclebob/uml-viewer) already reads. +CRAP scores for Clojure, Java, Go, TypeScript, Rust, Python, and Swift. One run detects the language of each source file, applies that language's complexity and coverage rules, and writes the snapshot [uml-viewer](https://github.com/unclebob/uml-viewer) already reads. The formula is the one from [crap4clj](https://github.com/unclebob/crap4clj), [crap4java](https://github.com/unclebob/crap4java), and [crap4go](https://github.com/unclebob/crap4go): @@ -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 | +| 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. @@ -69,6 +70,12 @@ 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. +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. + +The namespace is the module, or `Module.Type` for a member (`Module.Outer.Inner` for a nested type, `Module.Array` for an extension). The module is the SwiftPM target whose path contains the file, otherwise the directory under `Sources/`, otherwise the nearest `.xcworkspace`, or an `.xcodeproj` when that directory has no workspace, otherwise the dotted directory path with `src/` removed. uml-viewer groups on that namespace and joins `:name`. mutator uses the same function list, including each entry's byte span, so a nested closure's mutations belong to the enclosing function. + ## Coverage commands By default a run deletes the previous report for each language it is about to measure and regenerates it: @@ -81,9 +88,38 @@ 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` | +| Swift | `swift test --enable-code-coverage`, then `llvm-cov export -format=json`; 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. +Swift coverage is region coverage. llvm-cov code regions count; branch, gap, skipped, and expansion regions do not. A report with no function regions uses segments that carry a count. An xccov report joins a function on `lineNumber` and uses `coveredLines` / `executableLines`. A path in the report may be absolute; the file is matched by suffix, as the other languages are. + +## Swift coverage on a Mac + +iOS coverage is produced by Xcode on a Mac. crapper runs the commands below when `swift` or `xcodebuild` is on the path. To score a report that was produced on another machine, put the JSON under `target/coverage/swift/` and pass `--use-existing-coverage`. + +Swift package: + +```bash +swift test --enable-code-coverage +bin="$(dirname "$(command -v swift)")/llvm-cov" +profdata="$(find .build -path '*/codecov/default.profdata' -print -quit)" +binary="$(find .build -type f \( -name '*PackageTests' -o -name '*PackageTests.xctest' \) ! -path '*.dSYM/*' -print -quit)" +mkdir -p target/coverage/swift +"$bin" export -format=json -instr-profile="$profdata" "$binary" \ + > target/coverage/swift/llvm-cov.json +``` + +Xcode, including an iOS app. The scheme has to be shared (`xcshareddata/xcschemes`). Use `-workspace App.xcworkspace` when the app has a workspace. + +```bash +xcodebuild test -project App.xcodeproj -scheme App \ + -enableCodeCoverage YES \ + -resultBundlePath target/coverage/swift/Test.xcresult +xcrun xccov view --report --json target/coverage/swift/Test.xcresult \ + > target/coverage/swift/xccov.json +``` + ## Development ```bash diff --git a/pyproject.toml b/pyproject.toml index 435e115..7ba408c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "crapper" version = "0.1.0" -description = "CRAP scores for Clojure, Java, Go, TypeScript, Rust, and Python, in the snapshot uml-viewer reads." +description = "CRAP scores for Clojure, Java, Go, TypeScript, Rust, Python, and Swift, in the snapshot uml-viewer reads." readme = "README.md" license = { file = "LICENSE" } classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"] diff --git a/src/crapper/cli.py b/src/crapper/cli.py index 88b9b23..8348d29 100644 --- a/src/crapper/cli.py +++ b/src/crapper/cli.py @@ -32,6 +32,7 @@ _TEST_PATTERNS = ", ".join( "test_*.py", "*_test.py", "conftest.py", + "*Tests.swift", ] ) @@ -44,7 +45,7 @@ and prints a report sorted worst first. 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). +Rust (.rs), Python (.py), Swift (.swift). Options: -h, --help Print this help and exit. @@ -76,6 +77,8 @@ Coverage, when it is produced: 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 + Swift swift test --enable-code-coverage, then llvm-cov JSON; + or xcodebuild test and xcrun xccov view --report --json uml-viewer joins .metrics/crap.edn on :namespace and :name. Clojure the ns, and the defn name @@ -84,6 +87,7 @@ uml-viewer joins .metrics/crap.edn on :namespace and :name. 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 + Swift the module, or Module.Type for methods and properties """ @@ -108,59 +112,82 @@ def _take(args: list[str], index: int, option: str) -> str: return args[index + 1] -def parse_args(argv: list[str] | None = None) -> Options: - args = list(sys.argv[1:] if argv is None else argv) - if any(arg in {"-h", "--help"} for arg in args): - return Options(action="help", message=HELP, exit_code=0) +def _append_source(options: Options, value: str) -> None: + options.source_roots.append(value) + + +def _set_root(options: Options, value: str) -> None: + options.project_root = Path(value) + + +def _set_coverage_command(options: Options, value: str) -> None: + options.coverage_command = value + + +def _set_threshold(options: Options, value: str) -> None: + try: + options.threshold = float(value) + except ValueError as exc: + raise ValueError("--threshold requires a number") from exc + + +_VALUED = { + "-s": _append_source, + "--source-root": _append_source, + "--root": _set_root, + "--coverage-command": _set_coverage_command, + "--threshold": _set_threshold, +} +_FLAGS = { + "--no-coverage": "no_coverage", + "--use-existing-coverage": "use_existing_coverage", + "--changed": "changed", +} + + +def _apply_arg(options: Options, args: list[str], index: int) -> int: + arg = args[index] + if arg in _VALUED: + _VALUED[arg](options, _take(args, index, arg)) + return index + 2 + if arg in _FLAGS: + setattr(options, _FLAGS[arg], True) + return index + 1 + if arg.startswith("-"): + raise ValueError(f"Unknown option: {arg}") + options.positionals.append(arg) + return index + 1 + + +def _parse_options(args: list[str]) -> Options: options = Options(action="analyze") index = 0 - try: - while index < len(args): - arg = args[index] - if arg in {"-s", "--source-root"}: - options.source_roots.append(_take(args, index, arg)) - index += 2 - continue - if arg == "--root": - options.project_root = Path(_take(args, index, arg)) - index += 2 - continue - if arg == "--coverage-command": - options.coverage_command = _take(args, index, arg) - index += 2 - continue - if arg == "--threshold": - raw = _take(args, index, arg) - try: - options.threshold = float(raw) - except ValueError as exc: - raise ValueError("--threshold requires a number") from exc - index += 2 - continue - if arg == "--no-coverage": - options.no_coverage = True - index += 1 - continue - if arg == "--use-existing-coverage": - options.use_existing_coverage = True - index += 1 - continue - if arg == "--changed": - options.changed = True - index += 1 - continue - if arg.startswith("-"): - raise ValueError(f"Unknown option: {arg}") - options.positionals.append(arg) - index += 1 - except ValueError as exc: - return Options(action="help", message=f"{exc}\n\n{HELP}", exit_code=1) + while index < len(args): + index = _apply_arg(options, args, index) + return options + + +def _coverage_conflict(options: Options) -> Options | None: if options.no_coverage and options.coverage_command: return Options( action="help", message=f"--no-coverage cannot be combined with --coverage-command\n\n{HELP}", exit_code=1, ) + return None + + +def parse_args(argv: list[str] | None = None) -> Options: + args = list(sys.argv[1:] if argv is None else argv) + if any(arg in {"-h", "--help"} for arg in args): + return Options(action="help", message=HELP, exit_code=0) + try: + options = _parse_options(args) + except ValueError as exc: + return Options(action="help", message=f"{exc}\n\n{HELP}", exit_code=1) + conflict = _coverage_conflict(options) + if conflict is not None: + return conflict return options diff --git a/src/crapper/coverage.py b/src/crapper/coverage.py index 293b71d..49d84b1 100644 --- a/src/crapper/coverage.py +++ b/src/crapper/coverage.py @@ -1,4 +1,4 @@ -"""Load Cloverage, LCOV, JaCoCo, and Go coverage profiles. +"""Load Cloverage, LCOV, JaCoCo, Go, and Swift coverage profiles. Clojure prefers Cloverage's per-line form counts, then LCOV. Java uses JaCoCo instruction counters. Go uses statement profiles. LCOV scores a function by @@ -8,6 +8,7 @@ its BRDA branch records when it has any, and by line hits otherwise. from __future__ import annotations +import json import re import xml.etree.ElementTree as ET from dataclasses import dataclass, field @@ -232,10 +233,7 @@ def parse_form_coverage(html: str) -> dict[int, tuple[int, int]]: def _branch_hit(taken: str) -> bool: if taken == "-": return False - try: - return int(taken) > 0 - except ValueError: - return False + return int(taken) > 0 def _add_branch(record: FileCoverage, line: int, taken: str) -> None: @@ -369,6 +367,250 @@ def _segments_percent(segments, start: int, end: int) -> float | None: return coverage_percent(covered, total) +@dataclass +class SwiftFile: + """Regions `(line, count)` or xccov summaries `(line, covered, executable)`.""" + + regions: list[tuple[int, int]] = field(default_factory=list) + summaries: list[tuple[int, int, int]] = field(default_factory=list) + + +def _is_llvm(data) -> bool: + if not isinstance(data, dict): + return False + if data.get("type") == "llvm.coverage.json.export": + return True + return isinstance(data.get("data"), list) + + +def _pair(line, count) -> tuple[int, int] | None: + try: + return int(line), int(count) + except (TypeError, ValueError): + return None + + +def _code_region(region) -> tuple[int, int] | None: + """A code region. Branch, gap, skipped, and expansion regions are not lines.""" + + if not isinstance(region, list) or len(region) < 5: + return None + if len(region) >= 8 and region[7] not in (0, None): + return None + return _pair(region[0], region[4]) + + +def _segment_counts(segment) -> bool: + if not segment[3]: + return False + if len(segment) >= 5 and not segment[4]: + return False + if len(segment) >= 6 and segment[5]: + return False + return True + + +def _segment_region(segment) -> tuple[int, int] | None: + if not isinstance(segment, list) or len(segment) < 4: + return None + if not _segment_counts(segment): + return None + return _pair(segment[0], segment[2]) + + +def _regions_of(values, reader) -> list[tuple[int, int]]: + found = [] + if not isinstance(values, list): + return found + for value in values: + parsed = reader(value) + if parsed is not None: + found.append(parsed) + return found + + +def _region_file(region: list) -> int: + if len(region) <= 5: + return 0 + try: + return int(region[5]) + except (TypeError, ValueError): + return 0 + + +def _add_function_region(found: dict[int, list[tuple[int, int]]], region) -> None: + parsed = _code_region(region) + if parsed is None or not isinstance(region, list): + return + found.setdefault(_region_file(region), []).append(parsed) + + +def _llvm_function_regions(unit: dict) -> dict[int, list[tuple[int, int]]]: + found: dict[int, list[tuple[int, int]]] = {} + for function in unit.get("functions") or []: + if not isinstance(function, dict): + continue + for region in function.get("regions") or []: + _add_function_region(found, region) + return found + + +def _llvm_unit(found: dict[str, SwiftFile], unit: dict) -> None: + regions = _llvm_function_regions(unit) + for index, file in enumerate(unit.get("files") or []): + if not isinstance(file, dict): + continue + name = file.get("filename") + if not isinstance(name, str) or not name: + continue + chosen = regions.get(index) or _regions_of(file.get("segments"), _segment_region) + found.setdefault(name, SwiftFile()).regions.extend(chosen) + + +def _llvm_files(data: dict) -> dict[str, SwiftFile]: + found: dict[str, SwiftFile] = {} + for unit in data.get("data") or []: + if isinstance(unit, dict): + _llvm_unit(found, unit) + return found + + +def _summary(function) -> tuple[int, int, int] | None: + if not isinstance(function, dict): + return None + if "lineNumber" not in function or "executableLines" not in function: + return None + try: + return ( + int(function["lineNumber"]), + int(function.get("coveredLines") or 0), + int(function["executableLines"]), + ) + except (TypeError, ValueError): + return None + + +def _summaries(functions) -> list[tuple[int, int, int]]: + found = [] + if not isinstance(functions, list): + return found + for function in functions: + parsed = _summary(function) + if parsed is not None: + found.append(parsed) + return found + + +def _xccov_file(found: dict[str, SwiftFile], file: dict) -> None: + path = file.get("path") or file.get("name") + if not isinstance(path, str) or not path: + return + record = found.setdefault(path, SwiftFile()) + record.summaries.extend(_summaries(file.get("functions"))) + + +def _xccov_targets(data) -> list[dict]: + if isinstance(data, list): + return [item for item in data if isinstance(item, dict)] + if not isinstance(data, dict): + return [] + targets = data.get("targets") + if isinstance(targets, list): + return [item for item in targets if isinstance(item, dict)] + if isinstance(data.get("files"), list): + return [data] + return [] + + +def _xccov_files(data) -> dict[str, SwiftFile]: + found: dict[str, SwiftFile] = {} + for target in _xccov_targets(data): + for file in target.get("files") or []: + if isinstance(file, dict): + _xccov_file(found, file) + return found + + +def parse_swift_coverage(text: str) -> dict[str, SwiftFile]: + """llvm-cov JSON export, or `xcrun xccov view --report --json`.""" + + data = json.loads(text) + if _is_llvm(data): + return _llvm_files(data) + return _xccov_files(data) + + +def _covered_regions(regions, start: int, end: int) -> tuple[int, int]: + total = 0 + covered = 0 + for line, count in regions: + if line < start or line > end: + continue + total += 1 + if count > 0: + covered += 1 + return covered, total + + +def _region_percent(regions, start: int, end: int) -> float: + covered, total = _covered_regions(regions, start, end) + if total == 0: + return 0.0 + return coverage_percent(covered, total) + + +def _summary_percent(summaries, start: int, end: int) -> float: + inside = [item for item in summaries if start <= item[0] <= end] + if not inside: + return 0.0 + chosen = min(inside, key=lambda item: (abs(item[0] - start), item[0])) + return coverage_percent(chosen[1], chosen[2]) + + +def _java_percent(bundle, function: Function) -> float | None: + names = [] + if function.jacoco_class: + names.append(function.jacoco_class) + if function.namespace not in names: + names.append(function.namespace) + return _jacoco_from_index(bundle.jacoco or {}, names, function.name, function.start_line) + + +def _go_file_percent(bundle, function: Function) -> float | None: + segments = bundle._go_segments(function.path) + return _segments_percent(segments, function.start_line, function.end_line) + + +def _named_percent(bundle, function: Function) -> float | None: + if function.language == "java": + return _java_percent(bundle, function) + if function.language == "go": + return _go_file_percent(bundle, function) + return _swift_percent(bundle, function) + + +def _file_percent(bundle, function: Function) -> float | None: + html = bundle._html_lines(function.path) + if html is not None: + return percent_for_range(html, function.start_line, function.end_line) + record = bundle._lcov_lines(function.path) + if record is None: + return None + branched = branch_percent(record, function.start_line, function.end_line) + if branched is not None: + return branched + return percent_for_range(record, function.start_line, function.end_line) + + +def _swift_percent(bundle, function: Function) -> float | None: + record = _lookup(bundle.swift, function.path, bundle.source_parts) + if record is None: + return None + if record.regions: + return _region_percent(record.regions, function.start_line, function.end_line) + return _summary_percent(record.summaries, function.start_line, function.end_line) + + @dataclass class JacocoMethod: missed: int @@ -408,6 +650,10 @@ def _method_line(method) -> int: return 0 +def _counter_value(counter, name: str) -> int: + return int(counter.get(name) or "0") + + def _record_jacoco_method(found: dict[str, list[JacocoMethod]], class_name: str, method) -> None: if method.tag != "method": return @@ -417,8 +663,8 @@ def _record_jacoco_method(found: dict[str, list[JacocoMethod]], class_name: str, key = f"{class_name}#{method.get('name', '')}" found.setdefault(key, []).append( JacocoMethod( - missed=int(counter.get("missed") or "0"), - covered=int(counter.get("covered") or "0"), + missed=_counter_value(counter, "missed"), + covered=_counter_value(counter, "covered"), line=_method_line(method), ) ) @@ -443,6 +689,7 @@ class CoverageBundle: go_profile: dict[str, list[tuple[int, int, int, int]]] | None = None jacoco: dict[str, list[JacocoMethod]] | None = None form_html: dict[str, dict[int, tuple[int, int]]] = field(default_factory=dict) + swift: dict[str, SwiftFile] = field(default_factory=dict) source_parts: list[tuple[str, ...]] = field(default_factory=list) root: Path | None = None @@ -460,28 +707,9 @@ class CoverageBundle: self.source_parts = found def percent_for(self, function: Function) -> float | None: - if function.language == "java": - names = [] - if function.jacoco_class: - names.append(function.jacoco_class) - if function.namespace not in names: - names.append(function.namespace) - return _jacoco_from_index( - self.jacoco or {}, names, function.name, function.start_line - ) - if function.language == "go": - segments = self._go_segments(function.path) - return _segments_percent(segments, function.start_line, function.end_line) - html = self._html_lines(function.path) - if html is not None: - return percent_for_range(html, function.start_line, function.end_line) - record = self._lcov_lines(function.path) - if record is None: - return None - branched = branch_percent(record, function.start_line, function.end_line) - if branched is not None: - return branched - return percent_for_range(record, function.start_line, function.end_line) + if function.language in {"java", "go", "swift"}: + return _named_percent(self, function) + return _file_percent(self, function) def _go_segments(self, path: str) -> list[tuple[int, int, int, int]] | None: """Profile segments for one Go file: by import path, else by the longest path suffix.""" @@ -543,14 +771,17 @@ def _merge_lcov(root: Path) -> dict[str, dict[int, tuple[int, int]]]: return merged -def _merge_go(root: Path) -> dict[str, list[tuple[int, int, int, int]]]: - paths = [ - root / "target" / "coverage" / "coverage.out", - root / "target" / "coverage" / "go" / "coverage.out", - root / "coverage.out", - ] +def _go_report_paths(root: Path) -> list[Path]: + paths = [root / "target" / "coverage" / "coverage.out"] + paths.append(root / "target" / "coverage" / "go" / "coverage.out") + paths.append(root / "coverage.out") paths.extend(root.glob("*/target/coverage/go/coverage.out")) paths.extend(root.glob("*/*/target/coverage/go/coverage.out")) + return paths + + +def _merge_go(root: Path) -> dict[str, list[tuple[int, int, int, int]]]: + paths = _go_report_paths(root) merged: dict[str, list[tuple[int, int, int, int]]] = {} for text in _merge_texts(paths): for key, segments in parse_go_profile(text).items(): @@ -584,6 +815,27 @@ def _merge_forms(root: Path) -> dict[str, dict[int, tuple[int, int]]]: return found +def _merge_swift_text(merged: dict[str, SwiftFile], text: str) -> None: + try: + parsed = parse_swift_coverage(text) + except json.JSONDecodeError: + return + for key, record in parsed.items(): + current = merged.setdefault(key, SwiftFile()) + current.regions.extend(record.regions) + current.summaries.extend(record.summaries) + + +def _merge_swift(root: Path) -> dict[str, SwiftFile]: + coverage = root / "target" / "coverage" / "swift" + if not coverage.is_dir(): + return {} + merged: dict[str, SwiftFile] = {} + for text in _merge_texts(sorted(coverage.rglob("*.json"))): + _merge_swift_text(merged, text) + return merged + + def load_bundle(root: Path) -> CoverageBundle: go_profile = _merge_go(root) jacoco = _merge_jacoco(root) @@ -592,5 +844,6 @@ def load_bundle(root: Path) -> CoverageBundle: go_profile=go_profile or None, jacoco=jacoco or None, form_html=_merge_forms(root), + swift=_merge_swift(root), root=root, ) diff --git a/src/crapper/discover.py b/src/crapper/discover.py index 3e57a12..0ddb0d1 100644 --- a/src/crapper/discover.py +++ b/src/crapper/discover.py @@ -20,6 +20,7 @@ EXTENSIONS = { ".cjs": "typescript", ".rs": "rust", ".py": "python", + ".swift": "swift", } SKIP_DIRS = { @@ -40,6 +41,9 @@ SKIP_DIRS = { "testdata", "__pycache__", ".clj-kondo", + ".build", + ".swiftpm", + "DerivedData", } TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__"} @@ -74,6 +78,16 @@ def language_of(path: str | Path) -> str | None: return EXTENSIONS.get(file_path.suffix) +def _swift_test(file_path: Path) -> bool: + """XCTest and Swift Testing keep tests in `Tests/` or a `*Tests` target.""" + + if file_path.suffix != ".swift": + return False + if file_path.name.endswith("Tests.swift"): + return True + return any(part.endswith("Tests") for part in file_path.parts) + + def is_test_file(path: str | Path) -> bool: file_path = Path(path) name = file_path.name @@ -87,6 +101,8 @@ def is_test_file(path: str | Path) -> bool: return True if name.endswith("_test.py") or (name.startswith("test_") and name.endswith(".py")): return True + if _swift_test(file_path): + return True return any(part in TEST_DIRS for part in file_path.parts) diff --git a/src/crapper/languages/__init__.py b/src/crapper/languages/__init__.py index 0d38fea..a732f2d 100644 --- a/src/crapper/languages/__init__.py +++ b/src/crapper/languages/__init__.py @@ -5,6 +5,7 @@ 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 from crapper.languages.rust import functions_in_source as rust_functions +from crapper.languages.swift import functions_in_source as swift_functions from crapper.languages.typescript import functions_in_source as typescript_functions from crapper.model import Function @@ -15,6 +16,7 @@ _READERS = { "typescript": typescript_functions, "python": python_functions, "rust": rust_functions, + "swift": swift_functions, } diff --git a/src/crapper/languages/golang.py b/src/crapper/languages/golang.py index 94235ad..ed27ef4 100644 --- a/src/crapper/languages/golang.py +++ b/src/crapper/languages/golang.py @@ -13,6 +13,7 @@ from crapper.languages.treesitter import ( absolute_path as _absolute, binary_logic, child_of_type, + child_text, complexity, descendants, end_line, @@ -66,17 +67,11 @@ def _receiver_type(data: bytes, method) -> str | None: def _method_name(data: bytes, method) -> str | None: - ident = child_of_type(method, "field_identifier") - if ident is None: - return None - return node_text(data, ident) + return child_text(data, method, "field_identifier") def _function_name(data: bytes, fn) -> str | None: - ident = child_of_type(fn, "identifier") - if ident is None: - return None - return node_text(data, ident) + return child_text(data, fn, "identifier") def package_namespace(path: str, package_name: str) -> str: diff --git a/src/crapper/languages/python.py b/src/crapper/languages/python.py index cb9dbcc..4383178 100644 --- a/src/crapper/languages/python.py +++ b/src/crapper/languages/python.py @@ -8,6 +8,7 @@ enclosing function. A class method's namespace is `module.Class`. """ from crapper.languages.treesitter import ( + ancestor_names, child_of_type, complexity, descendants, @@ -15,6 +16,8 @@ from crapper.languages.treesitter import ( node_text, parse, start_line, + strip_root, + strip_src, ) from crapper.model import Function @@ -42,23 +45,6 @@ def _skip(node) -> bool: return node.type == "class_definition" -def _strip_root(relative: str, source_root: str | None) -> str: - root = (source_root or "").replace("\\", "/").rstrip("/") - if root and root != "." and relative.startswith(root + "/"): - return relative[len(root) + 1 :] - if relative.startswith("./"): - return relative[2:] - return relative - - -def _strip_src(relative: str) -> str: - if relative.startswith("src/"): - return relative[4:] - if "/src/" in relative: - return relative.split("/src/", 1)[1] - return relative - - def _strip_module_suffix(relative: str) -> str: if relative.endswith(".py"): relative = relative[: -len(".py")] @@ -70,7 +56,7 @@ def _strip_module_suffix(relative: str) -> str: def _module_namespace(path: str, source_root: str | None) -> str: - relative = _strip_module_suffix(_strip_src(_strip_root(path.replace("\\", "/"), source_root))) + relative = _strip_module_suffix(strip_src(strip_root(path.replace("\\", "/"), source_root))) if not relative: return "__init__" return relative.replace("/", ".") @@ -90,16 +76,7 @@ def _is_nested_function(node) -> bool: def _class_names(data: bytes, node) -> list[str]: - names: list[str] = [] - current = node.parent - while current is not None: - if current.type == "class_definition": - ident = child_of_type(current, "identifier") - if ident is not None: - names.append(node_text(data, ident)) - current = current.parent - names.reverse() - return names + return ancestor_names(data, node, "class_definition", "identifier") def functions_in_source( diff --git a/src/crapper/languages/rust.py b/src/crapper/languages/rust.py index 4c8f9fa..bdc53c3 100644 --- a/src/crapper/languages/rust.py +++ b/src/crapper/languages/rust.py @@ -12,6 +12,7 @@ from pathlib import Path from crapper.languages.treesitter import ( absolute_path as _absolute, + ancestor_names, binary_logic, child_of_type, complexity, @@ -48,16 +49,7 @@ def _has_block(node) -> bool: def _ancestor_mods(data: bytes, node) -> list[str]: - names: list[str] = [] - current = node.parent - while current is not None: - if current.type == "mod_item": - ident = child_of_type(current, "identifier") - if ident is not None: - names.append(node_text(data, ident)) - current = current.parent - names.reverse() - return names + return ancestor_names(data, node, "mod_item", "identifier") def _in_mod_named(data: bytes, node, name: str) -> bool: diff --git a/src/crapper/languages/swift.py b/src/crapper/languages/swift.py new file mode 100644 index 0000000..5f6fa39 --- /dev/null +++ b/src/crapper/languages/swift.py @@ -0,0 +1,451 @@ +"""Swift functions, methods, and cyclomatic complexity. + +Decision points follow the same structural rule as the other languages: +`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?`, and `try!` are not branches. +`as?`, `as!`, and `is` are not branches. A `where` clause belongs to the +case, loop, or type constraint it narrows, so it is not a second decision. +One `if` or `guard` is one decision even when it lists several conditions; +each `else if` is another `if`. `case 1, 2` is one case. `#if` is compile +time; a `&&` inside the directive is not a branch, and each runtime `if` +the grammar still parses is. `?` on an optional type (`Int?`) or a failable +`init?` is not a chain. Operators inside strings and comments are not +branches; an interpolated expression is. + +A top-level function, a method, an initializer, a deinitializer, a +subscript, and a computed property or property observer are entries. +`get`, `set`, `willSet`, and `didSet` stay inside that entry. A +requirement or accessor with no statements, such as `{ get set }`, is +not an entry. A closure +bound directly with `let` or `var` is an entry, at file scope or on a type. +Any other closure stays inside the enclosing function, the way a nested +callback stays inside its function in TypeScript. A local type's methods +are their own entries and are not also charged to the enclosing function. + +The namespace is the module, or `Module.Type` for a member. The module is +the SwiftPM target whose path contains the file, otherwise the directory +under `Sources/`, otherwise the nearest `.xcworkspace`, or an +`.xcodeproj` when that directory has no workspace, otherwise the +dotted directory path with `src/` removed. The +manifest is parsed, so a comment is not a target and a parenthesis +inside a string does not end one. Nested types keep each owner +(`Module.Outer.Inner`). An extension uses the extended type +(`Module.Box.Inner`, `Module.Array`). +""" + +from __future__ import annotations + +from pathlib import Path + +from crapper.languages.treesitter import ( + absolute_path, + child_of_type, + child_text, + complexity, + descendants, + end_line, + node_text, + parse, + start_line, +) +from crapper.runners import nearest_marker +from crapper.model import Function + +_DECISIONS = { + "if_statement", + "guard_statement", + "for_statement", + "while_statement", + "repeat_while_statement", + "catch_block", + "ternary_expression", + "switch_entry", + "conjunction_expression", + "disjunction_expression", + "nil_coalescing_expression", +} +# `?` is also the optional-type suffix, the ternary operator, `try?`, and `init?`. +_NOT_CHAIN = {"optional_type", "ternary_expression", "try_operator", "init_declaration", "?"} +_SKIP = {"class_declaration", "protocol_declaration"} +_FUNCTIONS = { + "function_declaration", + "protocol_function_declaration", + "init_declaration", + "deinit_declaration", +} +_CONTAINERS = _FUNCTIONS | { + "subscript_declaration", + "lambda_literal", + "computed_property", + "computed_getter", + "computed_setter", + "computed_modify", + "willset_clause", + "didset_clause", +} +_TYPES = {"class_declaration", "protocol_declaration"} +_FIXED_NAMES = { + "init_declaration": "init", + "deinit_declaration": "deinit", + "subscript_declaration": "subscript", +} +_TARGET_NAMES = {"target", "executableTarget"} + + +def _is_decision(node) -> bool: + if node.type in _DECISIONS: + return True + if node.type != "?": + return False + parent = node.parent + return parent is not None and parent.type not in _NOT_CHAIN + + +def _skip_nested_type(node, root_id: int): + def skip(current) -> bool: + if current.id == root_id: + return False + return current.type in _SKIP + + return skip + + +def _complexity_of(node) -> int: + return complexity(node, _is_decision, _skip_nested_type(node, node.id)) + + +def _is_nested(node) -> bool: + current = node.parent + while current is not None: + if current.type in _TYPES: + return False + if current.type in _CONTAINERS: + return True + current = current.parent + return False + + +def _function_name(data: bytes, node) -> str | None: + fixed = _FIXED_NAMES.get(node.type) + if fixed is not None: + return fixed + children = node.children + for index, child in enumerate(children): + if child.type == "func": + return node_text(data, children[index + 1]) + return None + + +def _named_child(data: bytes, node, kind: str) -> str | None: + child = child_of_type(node, kind) + if child is None: + return None + return child_text(data, child, "simple_identifier") + + +def _has_function_body(node) -> bool: + return child_of_type(node, "function_body") is not None + + +def _direct_lambda(node): + for child in node.children: + if child.type == "lambda_literal": + return child + return None + + +def _has_statements(node) -> bool: + if node.type == "statements": + return True + return any(_has_statements(child) for child in node.children) + + +def _property_is_entry(node) -> bool: + if _direct_lambda(node) is not None: + return True + accessor = child_of_type(node, "computed_property", "willset_didset_block") + if accessor is None: + return False + return _has_statements(accessor) + + +def _type_identifiers(data: bytes, node) -> list[str]: + return [node_text(data, child) for child in node.children if child.type == "type_identifier"] + + +def _type_name(data: bytes, node) -> str | None: + user = child_of_type(node, "user_type") + if user is not None: + parts = _type_identifiers(data, user) + if parts: + return ".".join(parts) + ident = child_of_type(node, "type_identifier") + if ident is None: + return None + return node_text(data, ident) + + +def _owner_types(data: bytes, node) -> list[str]: + names: list[str] = [] + current = node.parent + while current is not None: + if current.type in _TYPES: + name = _type_name(data, current) + if name: + names.append(name) + current = current.parent + names.reverse() + return names + + +def _namespace(module: str, data: bytes, node) -> str: + owners = _owner_types(data, node) + if not owners: + return module + if not module: + return ".".join(owners) + return f"{module}.{'.'.join(owners)}" + + +def _make(node, name: str, namespace: str, path: str) -> Function: + return Function( + name=name, + namespace=namespace, + complexity=_complexity_of(node), + start_line=start_line(node), + end_line=end_line(node), + path=path, + language="swift", + start_byte=node.start_byte, + end_byte=node.end_byte, + ) + + +def _record_function(data: bytes, node, module: str, path: str) -> Function | None: + if not _has_function_body(node) or _is_nested(node): + return None + name = _function_name(data, node) + if name is None: + return None + return _make(node, name, _namespace(module, data, node), path) + + +def _record_subscript(data: bytes, node, module: str, path: str) -> Function | None: + if _is_nested(node) or not _has_statements(node): + return None + return _make(node, "subscript", _namespace(module, data, node), path) + + +def _record_property(data: bytes, node, module: str, path: str) -> Function | None: + if _is_nested(node) or not _property_is_entry(node): + return None + name = _named_child(data, node, "pattern") + if name is None: + return None + return _make(node, name, _namespace(module, data, node), path) + + +def _recorded(data: bytes, node, module: str, path: str) -> Function | None: + if node.type in _FUNCTIONS: + return _record_function(data, node, module, path) + if node.type == "subscript_declaration": + return _record_subscript(data, node, module, path) + if node.type == "property_declaration": + return _record_property(data, node, module, path) + return None + + +def _parts(path: str) -> list[str]: + return [part for part in path.replace("\\", "/").split("/") if part and part != "."] + + +def _sources_name(parts: list[str]) -> str | None: + if "Sources" not in parts: + return None + index = parts.index("Sources") + if index + 1 >= len(parts) - 1: + return None + return parts[index + 1] + + +def _directory_module(path: str, project_root: str | None) -> str: + sources = _sources_name(_parts(path)) + if sources: + return sources + dirs = _parts(path)[:-1] + if dirs[:1] == ["src"]: + dirs = dirs[1:] + if dirs: + return ".".join(dirs) + if project_root: + return Path(project_root).name + return Path(path).stem + + +def _string_parts(data: bytes, node, quote: str, text_type: str) -> str | None: + parts = [] + for child in node.children: + if child.type == quote: + continue + if child.type != text_type: + return None + parts.append(node_text(data, child)) + return "".join(parts) + + +def _plain_string(data: bytes, node) -> str | None: + if node.type == "line_string_literal": + return _string_parts(data, node, '"', "line_str_text") + if node.type == "multi_line_string_literal": + text = _string_parts(data, node, '"""', "multi_line_str_text") + if text is None: + return None + return text.strip() + return None + + +def _suffix_name(data: bytes, node) -> str | None: + suffix = None + for child in node.children: + if child.type == "navigation_suffix": + suffix = child + if suffix is None: + return None + return child_text(data, suffix, "simple_identifier") + + +def _call_name(data: bytes, node) -> str | None: + """The called name. A later `.target` in a fragment is a navigation suffix.""" + + callee = child_of_type(node, "prefix_expression", "navigation_expression") + if callee is None: + return None + if callee.type == "prefix_expression": + return child_text(data, callee, "simple_identifier") + return _suffix_name(data, callee) + + +def _labeled_string(data: bytes, call, label: str) -> str | None: + suffix = child_of_type(call, "call_suffix") + if suffix is None: + return None + arguments = child_of_type(suffix, "value_arguments") + if arguments is None: + return None + for argument in arguments.children: + if argument.type != "value_argument" or _named_child(data, argument, "value_argument_label") != label: + continue + for child in argument.children: + text = _plain_string(data, child) + if text is not None: + return text + return None + + +def _target_calls(data: bytes, root) -> list: + calls = [] + for node in descendants(root): + if node.type != "call_expression" or _call_name(data, node) not in _TARGET_NAMES: + continue + calls.append(node) + # A fragment chains later calls inside the first, so the outer node starts + # at the same byte and ends later. End order is source order. + calls.sort(key=lambda node: (node.end_byte, node.start_byte)) + return calls + + +def _package_targets(text: str) -> list[tuple[str, str | None]]: + data, tree = parse(text, "swift") + found = [] + for node in _target_calls(data, tree.root_node): + name = _labeled_string(data, node, "name") + if name: + found.append((name, _labeled_string(data, node, "path"))) + return found + + +def _inside(file: Path, root: Path) -> bool: + try: + file.relative_to(root) + except ValueError: + return False + return True + + +def _best_target(package_dir: Path, file: Path, targets: list[tuple[str, str | None]]) -> str | None: + found = [] + resolved = file.resolve() + for index, (name, explicit) in enumerate(targets): + if not explicit: + continue + if not _inside(resolved, (package_dir / explicit).resolve()): + continue + found.append((len(Path(explicit).parts), -index, name)) + if not found: + return None + return max(found)[2] + + +def _target_for(package_dir: Path, file: Path) -> str | None: + manifest = package_dir / "Package.swift" + if not manifest.is_file(): + return None + text = manifest.read_text(encoding="utf-8", errors="replace") + return _best_target(package_dir, file, _package_targets(text)) + + +def _project_name(directory: Path) -> str | None: + for pattern in ("*.xcworkspace", "*.xcodeproj"): + matches = sorted(directory.glob(pattern)) + if matches: + return matches[0].stem + return None + + +def _xcode_name(start: Path, stop: Path) -> str | None: + current = start if start.is_dir() else start.parent + stop = stop.resolve() + while True: + name = _project_name(current) + if name: + return name + if current == stop or current.parent == current: + return None + current = current.parent + + +def _module_from_disk(path: str, project_root: str) -> str | None: + file_path = Path(absolute_path(path, project_root)) + stop = Path(project_root).resolve() + package = nearest_marker(file_path, "Package.swift", stop) + if package is not None: + target = _target_for(package, file_path) + if target: + return target + if _sources_name(_parts(path)): + return _sources_name(_parts(path)) + return _xcode_name(file_path, stop) + + +def _module_name(path: str, project_root: str | None) -> str: + if project_root: + found = _module_from_disk(path, project_root) + if found: + return found + return _directory_module(path, project_root) + + +def functions_in_source( + source: str, path: str, source_root: str | None = None +) -> list[Function]: + data, tree = parse(source, "swift") + module = _module_name(path, source_root) + found: list[Function] = [] + for node in descendants(tree.root_node): + recorded = _recorded(data, node, module, path) + if recorded is not None: + found.append(recorded) + return found diff --git a/src/crapper/languages/treesitter.py b/src/crapper/languages/treesitter.py index 9362829..768abe7 100644 --- a/src/crapper/languages/treesitter.py +++ b/src/crapper/languages/treesitter.py @@ -1,4 +1,4 @@ -"""Shared tree-sitter helpers for Java, Go, TypeScript, Rust, and Python.""" +"""Shared tree-sitter helpers for Java, Go, TypeScript, Rust, Python, and Swift.""" from functools import lru_cache from pathlib import Path @@ -40,6 +40,43 @@ def child_of_type(node, *types: str): return None +def child_text(data: bytes, node, *types: str) -> str | None: + ident = child_of_type(node, *types) + if ident is None: + return None + return node_text(data, ident) + + +def strip_root(relative: str, source_root: str | None) -> str: + root = (source_root or "").replace("\\", "/").rstrip("/") + if root and root != "." and relative.startswith(root + "/"): + return relative[len(root) + 1 :] + if relative.startswith("./"): + return relative[2:] + return relative + + +def strip_src(relative: str) -> str: + if relative.startswith("src/"): + return relative[4:] + if "/src/" in relative: + return relative.split("/src/", 1)[1] + return relative + + +def ancestor_names(data: bytes, node, kind: str, *name_types: str) -> list[str]: + names: list[str] = [] + current = node.parent + while current is not None: + if current.type == kind: + ident = child_of_type(current, *name_types) + if ident is not None: + names.append(node_text(data, ident)) + current = current.parent + names.reverse() + return names + + def descendants(node): stack = [node] while stack: diff --git a/src/crapper/languages/typescript.py b/src/crapper/languages/typescript.py index 378d1b5..67fad4a 100644 --- a/src/crapper/languages/typescript.py +++ b/src/crapper/languages/typescript.py @@ -20,6 +20,8 @@ from crapper.languages.treesitter import ( node_text, parse, start_line, + strip_root, + strip_src, ) from crapper.model import Function @@ -85,23 +87,6 @@ def _grammar(path: str) -> str: return "typescript" -def _strip_root_prefix(relative: str, source_root: str | None) -> str: - root = (source_root or "").replace("\\", "/").rstrip("/") - if root and root != "." and relative.startswith(root + "/"): - return relative[len(root) + 1 :] - if relative.startswith("./"): - return relative[2:] - return relative - - -def _strip_src_dir(relative: str) -> str: - if relative.startswith("src/"): - return relative[4:] - if "/src/" in relative: - return relative.split("/src/", 1)[1] - return relative - - def _strip_script_suffix(relative: str) -> str: for suffix in (".tsx", ".mts", ".cts", ".jsx", ".mjs", ".cjs", ".ts", ".js"): if relative.endswith(suffix): @@ -111,8 +96,8 @@ def _strip_script_suffix(relative: str) -> str: def _module_namespace(path: str, source_root: str | None) -> str: relative = path.replace("\\", "/") - relative = _strip_root_prefix(relative, source_root) - relative = _strip_src_dir(relative) + relative = strip_root(relative, source_root) + relative = strip_src(relative) return _strip_script_suffix(relative).replace("/", ".") diff --git a/src/crapper/runners.py b/src/crapper/runners.py index fdf3c0d..1277f71 100644 --- a/src/crapper/runners.py +++ b/src/crapper/runners.py @@ -70,6 +70,11 @@ def _clean_dir(path: Path) -> None: shutil.rmtree(path) +def _remove_file(path: Path) -> None: + if path.is_file(): + path.unlink() + + _COVERAGE_DIRS = {"typescript", "rust", "go", "python"} @@ -545,6 +550,237 @@ def _cover_python(root: Path, files: list[Path]) -> None: _record_python_lcov(package, run_shell(run_cmd, package), data_file, lcov_cmd) +def swift_test_command() -> list[str]: + return ["swift", "test", "--enable-code-coverage"] + + +def swift_export_command(tool: str, binary: Path, profdata: Path) -> list[str]: + return [tool, "export", "-format=json", f"-instr-profile={profdata}", str(binary)] + + +def xcode_export_command(result: Path) -> list[str]: + return ["xcrun", "xccov", "view", "--report", "--json", str(result)] + + +def swift_packages(root: Path, files: list[Path]) -> list[Path]: + root = root.resolve() + return [module.resolve() for module in _modules_with(files, ".swift", "Package.swift", root)] + + +def _first_file(package: Path, pattern: str) -> Path | None: + matches = [path for path in package.glob(pattern) if path.is_file()] + if not matches: + return None + return sorted(matches)[0] + + +def swift_profdata(package: Path) -> Path | None: + debug = _first_file(package, ".build/**/debug/**/codecov/default.profdata") + if debug is not None: + return debug + return _first_file(package, ".build/**/codecov/default.profdata") + + +def _in_dsym(path: Path) -> bool: + return any(part.endswith(".dSYM") for part in path.parts) + + +def _swift_binary(path: Path) -> bool: + if not path.is_file() or _in_dsym(path): + return False + return path.name.endswith("PackageTests") or path.name.endswith("PackageTests.xctest") + + +def swift_test_binary(package: Path) -> Path | None: + """The test executable. macOS nests it in the .xctest bundle; Linux names the file .xctest. + + A dSYM stores another file with the same name. That is debug info, not the executable. + """ + + found = [ + path + for pattern in (".build/**/*PackageTests", ".build/**/*PackageTests.xctest") + for path in package.glob(pattern) + if _swift_binary(path) + ] + if not found: + return None + return sorted(set(found))[0] + + +def llvm_cov_tool() -> str | None: + found = shutil.which("llvm-cov") + if found: + return found + swift = shutil.which("swift") + if not swift: + return None + sibling = Path(swift).resolve().parent / "llvm-cov" + if sibling.is_file(): + return str(sibling) + return None + + +def _xcode_bundle(directory: Path) -> Path | None: + if not directory.is_dir(): + return None + for pattern in ("*.xcworkspace", "*.xcodeproj"): + matches = sorted(path for path in directory.glob(pattern) if path.is_dir()) + if matches: + return matches[0] + return None + + +def _nearest_xcode(start: Path, stop: Path) -> Path | None: + current = start if start.is_dir() else start.parent + stop = stop.resolve() + while True: + bundle = _xcode_bundle(current) + if bundle is not None: + return bundle + if current == stop or current.parent == current: + return None + current = current.parent + + +def xcode_projects(root: Path, files: list[Path]) -> list[Path]: + found: set[Path] = set() + root = root.resolve() + for file in files: + if Path(file).suffix != ".swift": + continue + bundle = _nearest_xcode(Path(file), root) + if bundle is not None: + found.add(bundle.resolve()) + return sorted(found) + + +def xcode_schemes(project: Path) -> list[str]: + schemes = project / "xcshareddata" / "xcschemes" + if not schemes.is_dir(): + return [] + return sorted(path.stem for path in schemes.glob("*.xcscheme")) + + +def xcode_test_command(project: Path, scheme: str, result: Path) -> list[str]: + flag = "-workspace" if project.suffix == ".xcworkspace" else "-project" + return [ + "xcodebuild", + "test", + flag, + str(project), + "-scheme", + scheme, + "-enableCodeCoverage", + "YES", + "-resultBundlePath", + str(result), + ] + + +def _redirect(command: list[str], cwd: Path, destination: Path): + with destination.open("w", encoding="utf-8") as stdout: + return subprocess.run(list(command), cwd=cwd, stdout=stdout) + + +def write_command_output(command: list[str], cwd: Path, destination: Path) -> int: + """Run a command and store its stdout. llvm-cov and xccov write JSON there.""" + + _warn(f"+ ({cwd}) {_show(command)} > {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + try: + completed = _redirect(command, cwd, destination) + except OSError as exc: + _warn(f"Coverage command failed to start: {exc}") + return 127 + return completed.returncode + + +def _swift_report(root: Path, module: Path) -> Path: + return _coverage_report(root, module, "swift").with_name("llvm-cov.json") + + +def _within(path: Path, directory: Path) -> bool: + try: + Path(path).resolve().relative_to(directory.resolve()) + except ValueError: + return False + return True + + +def _swift_sources_outside(files: list[Path], packages: list[Path]) -> list[Path]: + found = [] + for file in files: + if Path(file).suffix != ".swift": + continue + if any(_within(file, package) for package in packages): + continue + found.append(Path(file)) + return found + + +def _export_swift_package(root: Path, package: Path) -> None: + profdata = swift_profdata(package) + binary = swift_test_binary(package) + tool = llvm_cov_tool() + report = _swift_report(root, package) + if profdata is None or binary is None or tool is None: + _remove_file(report) + _warn(f"Swift coverage data is missing in {package}. Swift coverage will score 0%.") + return + code = write_command_output(swift_export_command(tool, binary, profdata), package, report) + if code != 0: + _remove_file(report) + _warn(f"llvm-cov export exited {code} in {package}. Swift coverage will score 0%.") + + +def _cover_swift_package(root: Path, package: Path) -> None: + _remove_file(_swift_report(root, package)) + if shutil.which("swift") is None: + _warn(f"swift is not installed. Swift coverage will score 0% in {package}.") + return + code = run_shell(swift_test_command(), package) + if code != 0: + _warn(f"Swift coverage exited {code} in {package}. Swift coverage will score 0%.") + return + _export_swift_package(root, package) + + +def _cover_xcode(root: Path, project: Path) -> None: + exported = _swift_report(root, project).parent / "xccov.json" + _remove_file(exported) + if shutil.which("xcodebuild") is None: + _warn(f"xcodebuild is not installed. Swift coverage will score 0% for {project.name}.") + return + schemes = xcode_schemes(project) + if not schemes: + _warn(f"No shared Xcode scheme in {project}. Swift coverage will score 0%.") + return + result = exported.parent / "Test.xcresult" + if result.exists(): + shutil.rmtree(result) + code = run_shell(xcode_test_command(project, schemes[0], result), project.parent) + if code != 0: + _warn(f"Xcode coverage exited {code} in {project}. Swift coverage will score 0%.") + return + code = write_command_output(xcode_export_command(result), project.parent, exported) + if code != 0: + _remove_file(exported) + _warn(f"xccov exited {code} in {project}. Swift coverage will score 0%.") + + +def _cover_swift(root: Path, files: list[Path]) -> None: + packages = swift_packages(root, files) + for package in packages: + _cover_swift_package(root, package) + for project in xcode_projects(root, _swift_sources_outside(files, packages)): + _cover_xcode(root, project) + + +def _cover_clojure_files(root: Path, _files: list[Path]) -> None: + _cover_clojure(root) + + def _cover_rust(root: Path, files: list[Path]) -> None: modules = rust_modules(root, files) if not modules: @@ -562,6 +798,24 @@ def _cover_rust(root: Path, files: list[Path]) -> None: _warn(f"Rust coverage exited {code} in {module}. Rust coverage will score 0%.") +_COVERERS = { + "clojure": _cover_clojure_files, + "java": _cover_java, + "go": _cover_go, + "typescript": _cover_typescript, + "python": _cover_python, + "rust": _cover_rust, + "swift": _cover_swift, +} + + +def _cover_present(root: Path, files: list[Path]) -> None: + languages = _languages_in(files) + for language in ("clojure", "java", "go", "typescript", "python", "rust", "swift"): + if language in languages: + _COVERERS[language](root, files) + + def run_coverage(root: Path, files: list[Path], command: str | None) -> int: """Generate coverage reports for the languages present in `files`. @@ -580,17 +834,5 @@ def run_coverage(root: Path, files: list[Path], command: str | None) -> int: ) return code - languages = _languages_in(files) - if "clojure" in languages: - _cover_clojure(root) - if "java" in languages: - _cover_java(root, files) - if "go" in languages: - _cover_go(root, files) - if "typescript" in languages: - _cover_typescript(root, files) - if "python" in languages: - _cover_python(root, files) - if "rust" in languages: - _cover_rust(root, files) + _cover_present(root, files) return 0 diff --git a/tests/fixtures/swift/Box.swift b/tests/fixtures/swift/Box.swift new file mode 100644 index 0000000..34cc69f --- /dev/null +++ b/tests/fixtures/swift/Box.swift @@ -0,0 +1,12 @@ +func choose(x: Int) -> Int { + if x > 0 { + return 1 + } + return 0 +} + +struct Box { + func open() -> Int { + return 1 + } +} diff --git a/tests/fixtures/swift/llvm-cov.json b/tests/fixtures/swift/llvm-cov.json new file mode 100644 index 0000000..71f9c7b --- /dev/null +++ b/tests/fixtures/swift/llvm-cov.json @@ -0,0 +1,46 @@ +{ + "type": "llvm.coverage.json.export", + "version": "2.0.1", + "data": [ + { + "files": [ + { + "filename": "/Users/me/app/Sources/Demo/Box.swift", + "segments": [ + [2, 5, 1, true, true, false], + [5, 5, 1, true, true, false], + [10, 9, 1, true, true, false] + ] + }, + null, + {"summary": {}} + ], + "functions": [ + "ignored", + { + "name": "choose(x:)", + "count": 1, + "filenames": ["/Users/me/app/Sources/Demo/Box.swift"], + "regions": [ + "ignored", + [1, 1], + [2, 1, 2, 2, "nope", 0, 0, 0], + [1, 1, 1, 10, 1, "bad", 0, 0], + [6, 1, 6, 2, 0], + [3, 9, 3, 18, 0, 0, 0, 4], + [2, 1, 2, 2, 0, 0, 0, 2], + [20, 1, 20, 2, 0, "file", 0, 0] + ] + }, + { + "name": "Box.open()", + "count": 1, + "filenames": ["/Users/me/app/Sources/Demo/Box.swift"], + "regions": [ + [10, 9, 10, 18, 1, 0, 0, 0] + ] + } + ] + } + ] +} diff --git a/tests/fixtures/swift/segments.json b/tests/fixtures/swift/segments.json new file mode 100644 index 0000000..a4813ec --- /dev/null +++ b/tests/fixtures/swift/segments.json @@ -0,0 +1,22 @@ +{ + "version": "2.0.1", + "data": [ + { + "files": [ + { + "filename": "Sources/Demo/Box.swift", + "segments": [ + [2, 5, 1, true], + [5, 5, 0, true, true, false], + [6, 1, 0, false, false, true], + [2, 1, 0, true, false, false], + [2, 1, 0, true, true, true], + [20, 1, 1, true], + [10, 9, 0, true, true, false] + ] + } + ], + "functions": [] + } + ] +} diff --git a/tests/fixtures/swift/xccov.json b/tests/fixtures/swift/xccov.json new file mode 100644 index 0000000..c5427f5 --- /dev/null +++ b/tests/fixtures/swift/xccov.json @@ -0,0 +1,41 @@ +{ + "coveredLines": 2, + "executableLines": 3, + "lineCoverage": 0.6666666666666666, + "targets": [ + { + "buildProductPath": "/tmp/Demo.app", + "coveredLines": 2, + "executableLines": 3, + "lineCoverage": 0.6666666666666666, + "name": "Demo.app", + "files": [ + { + "coveredLines": 2, + "executableLines": 3, + "lineCoverage": 0.6666666666666666, + "name": "Box.swift", + "path": "/Users/me/app/Sources/Demo/Box.swift", + "functions": [ + { + "coveredLines": 1, + "executableLines": 2, + "executionCount": 1, + "lineCoverage": 0.5, + "lineNumber": 1, + "name": "choose(x:)" + }, + { + "coveredLines": 1, + "executableLines": 1, + "executionCount": 1, + "lineCoverage": 1.0, + "lineNumber": 9, + "name": "Box.open()" + } + ] + } + ] + } + ] +} diff --git a/tests/test_cli.py b/tests/test_cli.py index 3266096..cfe51ef 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -21,6 +21,10 @@ def test_language_detection(): assert language_of("src/app.jsx") == "typescript" assert language_of("src/lib.rs") == "rust" assert language_of("src/crapper/cli.py") == "python" + assert language_of("Sources/Demo/Box.swift") == "swift" + assert is_test_file("Tests/DemoTests/BoxTests.swift") is True + assert is_test_file("AppTests/Board.swift") is True + assert is_test_file("Sources/Demo/Box.swift") is False assert language_of("types.d.ts") is None assert language_of("notes.md") is None assert language_of("app.cts") == "typescript" @@ -161,6 +165,8 @@ def test_help_and_unknown_option(capsys): assert "uml-viewer" in help_text assert ".clj-kondo" in help_text assert ".test.cts" in help_text + assert ".swift" in help_text + assert "Module.Type" in help_text assert run(["--not-an-option"]) == 1 assert run(["--root"]) == 1 assert run(["--threshold", "nope"]) == 1 @@ -267,6 +273,16 @@ def test_changed_files_follow_git_status(tmp_path, monkeypatch, capsys): _changed_files(tmp_path) assert silent.value.code == 128 + def status_fails(args, **kwargs): + if "rev-parse" in args: + return _Completed(0, f"{tmp_path.resolve()}\n") + return _Completed(1, "", "") + + monkeypatch.setattr("crapper.cli.subprocess.run", status_fails) + with pytest.raises(GitError, match="git status failed") as status: + _changed_files(tmp_path) + assert status.value.code == 1 + def test_relative_paths_are_resolved_under_the_project_root(tmp_path): _write(tmp_path, "src/demo/core.clj", "(ns demo.core)\n\n(defn choose [x]\n (if x 1 0))\n") diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 4f85275..c3360d1 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -58,6 +58,13 @@ def test_lcov_branch_records_override_line_hits(): assert bundle.percent_for(scored) == 50.0 +def test_a_branch_count_that_is_not_a_number_is_ignored(): + text = "SF:src/demo/app.ts\nDA:3,1\nBRDA:3,0,0,nope\nend_of_record\n" + parsed = parse_lcov(text)["src/demo/app.ts"] + assert parsed[3] == (1, 1) + assert 3 not in parsed.branches + + def test_a_branchless_span_keeps_line_coverage(): text = "SF:src/demo/app.ts\nDA:2,1\nDA:3,0\nBRDA:8,0,0,1\nBRDA:8,0,1,0\nend_of_record\n" bundle = CoverageBundle(lcov=parse_lcov(text)) diff --git a/tests/test_languages.py b/tests/test_languages.py index 05f73b1..84c2363 100644 --- a/tests/test_languages.py +++ b/tests/test_languages.py @@ -9,6 +9,7 @@ _SOURCES = [ ("typescript", "export function view() { return 1 }\n", "src/ui.ts", "view"), ("python", "def run():\n return 1\n", "src/app.py", "run"), ("rust", "pub fn open() {}\n", "src/lib.rs", "open"), + ("swift", "func open() {}\n", "Sources/Demo/Box.swift", "open"), ] diff --git a/tests/test_runners.py b/tests/test_runners.py index 679e1ba..3e3e0af 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -76,6 +76,26 @@ def test_existing_coverage_script_is_left_alone(tmp_path): assert command == ["npm", "run", "coverage"] +def test_an_npm_coverage_script_does_not_install_a_provider(tmp_path, monkeypatch): + _write( + tmp_path, + "package.json", + json.dumps({"scripts": {"coverage": "vitest run --coverage"}}), + ) + source = _write(tmp_path, "src/app.ts", "export function view() { return 1 }\n") + commands = [] + monkeypatch.setattr( + "crapper.runners.run_shell", + lambda command, cwd: commands.append(list(command)) or 0, + ) + monkeypatch.setattr( + "crapper.runners._ensure_vitest_coverage", + lambda package: (_ for _ in ()).throw(AssertionError(package)), + ) + assert run_coverage(tmp_path, [source], None) == 0 + assert commands == [["npm", "run", "coverage"]] + + def test_node_test_script_still_uses_c8(tmp_path): _write(tmp_path, "package.json", json.dumps({"scripts": {"test": "node --test"}})) report_dir = tmp_path / "target" / "coverage" / "typescript" diff --git a/tests/test_swift.py b/tests/test_swift.py new file mode 100644 index 0000000..44f73ad --- /dev/null +++ b/tests/test_swift.py @@ -0,0 +1,744 @@ +"""Swift functions score the way a reader of the source would count branches.""" + +from pathlib import Path + +from crapper.cli import run +from crapper.discover import is_test_file, iter_source_files +from crapper.languages.swift import functions_in_source +from crapper.runners import run_coverage + +_FIXTURES = Path(__file__).parent / "fixtures" / "swift" +_BOX = (_FIXTURES / "Box.swift").read_text(encoding="utf-8") + + +def test_structural_decisions_match_the_other_languages(): + source = """ +func choose(x: Int, y: Int?) -> Int { + guard x > 0 else { return 0 } + if x > 1 && y != nil || x < 0 { return 1 } + for i in 0.. 0 { break } } + repeat { } while x > 2 + do { _ = y } catch { return 0 } + switch x { + case 1: return 1 + case 2: return 2 + default: return y ?? 0 + } + return y?.hashValue ?? (x > 0 ? 1 : 0) +} +""" + functions = functions_in_source(source, "Sources/Demo/Choose.swift", "/proj") + assert [(fn.namespace, fn.name, fn.complexity) for fn in functions] == [ + ("Demo", "choose", 16) + ] + + +def test_else_if_switch_where_and_optional_chains_follow_the_documented_rules(): + source = """ +func climb(a: Bool, b: Bool) { + if a { } else if b { } +} +func chained() -> Int { a?.b?.c() ?? d?[0] ?? e?() } +func cases(x: Int) -> Int { + switch x { + case let n where n > 0: return 1 + case 1, 2: return 2 + default: return 0 + } +} +func compiled(x: Bool) { +#if FOO && BAR + return 1 +#else + if x { return } +#endif +} +""" + functions = functions_in_source(source, "Sources/Demo/Choose.swift", "/proj") + assert [(fn.name, fn.complexity) for fn in functions] == [ + ("climb", 3), + ("chained", 7), + ("cases", 4), + ("compiled", 2), + ] + + +def test_casts_tries_strings_and_comments_are_not_decisions(): + source = r""" +func casted(x: Any) -> Int { (x as? Int) ?? 0 } +func attempted() -> Int? { try? risky() } +func text() -> String { "if x && y ?? z?.a" } +func mix() -> String { "if \(a ?? b)" } +func note() -> Int { + // if x && y ?? z?.a + return 1 +} +""" + functions = functions_in_source(source, "Sources/Demo/Choose.swift", "/proj") + assert [(fn.name, fn.complexity) for fn in functions] == [ + ("casted", 2), + ("attempted", 1), + ("text", 1), + ("mix", 2), + ("note", 1), + ] + + +def test_types_initializers_accessors_and_closures(): + source = """ +func top(n: Int) -> Int { + let f = { (x: Int) -> Int in + if x > 0 { return x } + return 0 + } + func inner() { if n > 0 { return } } + return f(n) +} +class Box { + init(n: Int) { if n > 0 { self.n = n } } + func open() -> Int { n > 0 ? 1 : 0 } + var n: Int = 0 { didSet { if n < 0 { n = 0 } } } + var shown: Int { + get { n > 0 ? 1 : 0 } + set { if newValue == 0 { n = 0 } } + } + subscript(i: Int) -> Int { i > 0 ? 1 : 0 } + deinit { if n == 0 { n = 1 } } + let arrow = { (n: Int) -> Int in n > 0 ? n : 0 } + static func == (lhs: Box, rhs: Box) -> Bool { lhs.n == rhs.n } +} +struct View { func body() -> Int { 1 } } +enum Move { func step() -> Int { 1 } } +actor Worker { func run() {} } +extension Box { func extra(flag: Bool) -> Int { flag ? 1 : 0 } } +extension Array where Element == String { + func blank() -> Bool { isEmpty ? true : false } +} +extension Box.Inner { func more() {} } +let arrow = { (n: Int) -> Int in n > 0 ? n : 0 } +protocol P { func req() } +private func hidden() { if true { } } +""" + functions = functions_in_source(source, "Sources/Demo/Box.swift", "/proj") + assert [(fn.namespace, fn.name, fn.complexity) for fn in functions] == [ + ("Demo", "top", 3), + ("Demo.Box", "init", 2), + ("Demo.Box", "open", 2), + ("Demo.Box", "n", 2), + ("Demo.Box", "shown", 3), + ("Demo.Box", "subscript", 2), + ("Demo.Box", "deinit", 2), + ("Demo.Box", "arrow", 2), + ("Demo.Box", "==", 1), + ("Demo.View", "body", 1), + ("Demo.Move", "step", 1), + ("Demo.Worker", "run", 1), + ("Demo.Box", "extra", 2), + ("Demo.Array", "blank", 2), + ("Demo.Box.Inner", "more", 1), + ("Demo", "arrow", 2), + ("Demo", "hidden", 2), + ] + hidden = functions[-1] + chunk = source.encode()[hidden.start_byte : hidden.end_byte].decode() + assert chunk.startswith("private func hidden") + + +def test_a_nested_callback_stays_inside_its_function(): + source = """ +let rows = items.map { item in item.ok ? 1 : 0 } +func make() -> Int { items.map { item in item.ok ? 1 : 0 }.count } +func outer(flag: Bool) -> Int { + struct Inner { func go() -> Int { if true { return 1 }; return 0 } } + if flag { return 1 } + return 0 +} +""" + functions = functions_in_source(source, "Sources/Demo/Box.swift", "/proj") + assert [(fn.namespace, fn.name, fn.complexity) for fn in functions] == [ + ("Demo", "make", 2), + ("Demo", "outer", 2), + ("Demo.Inner", "go", 2), + ] + make = functions[0] + assert "map" in source.encode()[make.start_byte : make.end_byte].decode() + + +def test_a_requirement_without_a_body_is_not_a_function(): + source = """ +protocol P { + func req() + var name: String { get set } + subscript(i: Int) -> Int { get set } + init() +} +struct S { + var name: String { get set } + subscript(i: Int) -> Int { i > 0 ? i : 0 } +} +class C { + var label: String { get set } +} +""" + functions = functions_in_source(source, "Sources/Demo/Box.swift", "/proj") + assert [(fn.namespace, fn.name, fn.complexity) for fn in functions] == [ + ("Demo.S", "subscript", 2) + ] + + +def test_swiftui_body_is_the_view_type(): + source = """ +import SwiftUI +struct ContentView: View { + var ready = true + var body: some View { + if ready { Text("hi") } + } +} +""" + functions = functions_in_source(source, "Sources/Demo/ContentView.swift", "/proj") + assert [(fn.namespace, fn.name, fn.complexity) for fn in functions] == [ + ("Demo.ContentView", "body", 2) + ] + + +def test_package_and_xcode_names_are_the_module(tmp_path): + (tmp_path / "Package.swift").write_text( + "\n".join( + [ + '.target(name: "RenamedPlain", path: "lib/plain"),', + '.target(name: "Core", path: "lib/core", dependencies: [.product(name: "X", package: "Y")]),', + '.target(name: "Also", path: "lib/core"),', + '.target(name: "CoreKit", path: "Sources/Renamed"),', + '.testTarget(name: "CoreTests", dependencies: ["Core"]),', + ] + ), + encoding="utf-8", + ) + (tmp_path / "App.xcodeproj").mkdir() + (tmp_path / "Sources" / "Renamed").mkdir(parents=True) + core = functions_in_source("public func ping() -> Int { 1 }\n", "lib/core/Ping.swift", str(tmp_path)) + assert [(fn.namespace, fn.name) for fn in core] == [("Core", "ping")] + plain = functions_in_source("func ping() {}\n", "lib/plain/A.swift", str(tmp_path)) + assert plain[0].namespace == "RenamedPlain" + renamed = functions_in_source("func renamed() {}\n", "Sources/Renamed/Box.swift", str(tmp_path)) + assert renamed[0].namespace == "CoreKit" + view = functions_in_source( + "struct ContentView { func body() -> Int { 1 } }\n", + "App/ContentView.swift", + str(tmp_path), + ) + assert [(fn.namespace, fn.name) for fn in view] == [("App.ContentView", "body")] + ui = functions_in_source("func view() -> Int { 1 }\n", "src/ui/theme.swift", "/proj") + assert ui[0].namespace == "ui" + flat = functions_in_source("func open() {}\n", "Sources/Box.swift", "/proj") + assert flat[0].namespace == "Sources" + doubled = functions_in_source("func open() {}\n", "Sources//Demo/Box.swift", "/proj") + assert doubled[0].namespace == "Demo" + (tmp_path / "mobile" / "IOS.xcodeproj").mkdir(parents=True) + ios = functions_in_source( + "struct ContentView { func body() {} }\n", + "mobile/feature/ContentView.swift", + str(tmp_path), + ) + assert [(fn.namespace, fn.name) for fn in ios] == [("IOS.ContentView", "body")] + + +def test_a_workspace_names_the_module_when_a_project_is_beside_it(tmp_path): + (tmp_path / "Proj.xcodeproj").mkdir() + (tmp_path / "Work.xcworkspace").mkdir() + functions = functions_in_source( + "struct ContentView { func body() {} }\n", + "App/ContentView.swift", + str(tmp_path), + ) + assert [(fn.namespace, fn.name) for fn in functions] == [("Work.ContentView", "body")] + + +def test_a_commented_target_does_not_name_the_module(tmp_path): + (tmp_path / "Package.swift").write_text( + "\n".join( + [ + '// .target(name: "Stale", path: "Sources/Demo"),', + '/* .target(name: "Blocked", path: "Sources/Demo") */', + '.testTarget(name: "DemoTests", path: "lib/demo"),', + '.target(name: "Demo", path: "lib/demo"),', + '.executableTarget(name: "Tool", path: "lib/tool"),', + '.target(name: "Weird", path: "lib/odd", cSettings: [.define("FOO", to: "a)b")]),', + '.target(name: "Wide", path: """', + "lib/wide", + '"""),', + ] + ), + encoding="utf-8", + ) + demo = functions_in_source("func open() {}\n", "lib/demo/Box.swift", str(tmp_path)) + assert demo[0].namespace == "Demo" + tool = functions_in_source("func main() {}\n", "lib/tool/Main.swift", str(tmp_path)) + assert tool[0].namespace == "Tool" + weird = functions_in_source("func open() {}\n", "lib/odd/Box.swift", str(tmp_path)) + assert weird[0].namespace == "Weird" + wide = functions_in_source("func open() {}\n", "lib/wide/Box.swift", str(tmp_path)) + assert wide[0].namespace == "Wide" + + +def test_swift_tests_and_build_products_are_not_scored(tmp_path): + source = tmp_path / "Sources" / "Demo" / "Box.swift" + source.parent.mkdir(parents=True) + source.write_text("func open() {}\n", encoding="utf-8") + for relative in ( + "Tests/DemoTests/BoxTests.swift", + "AppTests/Board.swift", + ".build/debug/Generated.swift", + ".swiftpm/cache/Generated.swift", + "DerivedData/App.swift", + ): + path = tmp_path / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("func hidden() {}\n", encoding="utf-8") + assert is_test_file(tmp_path / "Tests" / "DemoTests" / "BoxTests.swift") + assert is_test_file(tmp_path / "AppTests" / "Board.swift") + assert iter_source_files([tmp_path]) == [source.resolve()] + + +def _swift_project(tmp_path: Path, report_name: str) -> None: + source = tmp_path / "Sources" / "Demo" / "Box.swift" + source.parent.mkdir(parents=True) + source.write_text(_BOX, encoding="utf-8") + report = tmp_path / "target" / "coverage" / "swift" / report_name + report.parent.mkdir(parents=True) + report.write_text((_FIXTURES / report_name).read_text(encoding="utf-8"), encoding="utf-8") + + +def _snapshot(tmp_path: Path) -> str: + assert run(["--root", str(tmp_path), "--use-existing-coverage"]) == 0 + return (tmp_path / ".metrics" / "crap.edn").read_text(encoding="utf-8") + + +def test_llvm_cov_regions_join_the_swift_snapshot(tmp_path): + _swift_project(tmp_path, "llvm-cov.json") + text = _snapshot(tmp_path) + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text + assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 100.0, :crap 1.0' in text + + +def test_llvm_cov_segments_are_used_when_a_function_has_no_regions(tmp_path): + _swift_project(tmp_path, "segments.json") + text = _snapshot(tmp_path) + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text + assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 0.0, :crap 2.0' in text + + +def _plant(root: Path, relative: str, source: str = "") -> Path: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source, encoding="utf-8") + return path + + +def test_a_swift_package_exports_llvm_cov_json(tmp_path, monkeypatch, capsys): + _plant(tmp_path, "Package.swift", "// swift-tools-version: 5.9\n") + source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") + profdata = tmp_path / ".build" / "debug" / "codecov" / "default.profdata" + binary = tmp_path / ".build" / "debug" / "DemoPackageTests" + commands = [] + exports = [] + + def shell(command, cwd): + commands.append(list(command)) + profdata.parent.mkdir(parents=True, exist_ok=True) + profdata.write_text("prof", encoding="utf-8") + binary.write_text("bin", encoding="utf-8") + return 0 + + def export(command, cwd, destination): + exports.append(list(command)) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text("{}", encoding="utf-8") + return 0 + + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: f"/usr/bin/{name}" if name in {"swift", "llvm-cov"} else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", shell) + monkeypatch.setattr("crapper.runners.write_command_output", export) + assert run_coverage(tmp_path, [source], None) == 0 + assert commands == [["swift", "test", "--enable-code-coverage"]] + assert exports == [ + [ + "/usr/bin/llvm-cov", + "export", + "-format=json", + f"-instr-profile={profdata}", + str(binary), + ] + ] + assert (tmp_path / "target" / "coverage" / "swift" / "llvm-cov.json").is_file() + assert "exited" not in capsys.readouterr().err + + +def test_an_xcode_app_exports_an_xccov_report(tmp_path, monkeypatch): + project = tmp_path / "App.xcodeproj" + _plant(project, "xcshareddata/xcschemes/App.xcscheme", "\n") + source = _plant(tmp_path, "App/ContentView.swift", "func body() {}\n") + commands = [] + exports = [] + + def shell(command, cwd): + commands.append(list(command)) + return 0 + + def export(command, cwd, destination): + exports.append(list(command)) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text("{}", encoding="utf-8") + return 0 + + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: "/usr/bin/xcodebuild" if name == "xcodebuild" else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", shell) + monkeypatch.setattr("crapper.runners.write_command_output", export) + assert run_coverage(tmp_path, [source], None) == 0 + assert len(commands) == 1 + command = commands[0] + assert command[:8] == [ + "xcodebuild", + "test", + "-project", + str(project), + "-scheme", + "App", + "-enableCodeCoverage", + "YES", + ] + assert command[8] == "-resultBundlePath" + result = Path(command[9]) + assert result.name == "Test.xcresult" + assert "target/coverage/swift" in result.as_posix() + assert exports == [["xcrun", "xccov", "view", "--report", "--json", str(result)]] + + +def test_a_package_and_an_app_outside_it_are_both_measured(tmp_path, monkeypatch): + _plant(tmp_path, "libs/Demo/Package.swift", "") + package_source = _plant(tmp_path, "libs/Demo/Sources/Demo/Box.swift", "func open() {}\n") + _plant(tmp_path, "App.xcodeproj/xcshareddata/xcschemes/App.xcscheme", "\n") + app_source = _plant(tmp_path, "App/ContentView.swift", "func body() {}\n") + commands = [] + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: f"/usr/bin/{name}" if name in {"swift", "xcodebuild"} else None, + ) + monkeypatch.setattr( + "crapper.runners.run_shell", + lambda command, cwd: commands.append(command[0]) or 1, + ) + run_coverage(tmp_path, [package_source, app_source], None) + assert commands == ["swift", "xcodebuild"] + + +def test_a_package_is_not_also_measured_with_xcodebuild(tmp_path, monkeypatch): + _plant(tmp_path, "Package.swift", "") + _plant(tmp_path, "App.xcodeproj/xcshareddata/xcschemes/App.xcscheme", "\n") + source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") + commands = [] + monkeypatch.setattr("crapper.runners.shutil.which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr( + "crapper.runners.run_shell", + lambda command, cwd: commands.append(list(command)) or 1, + ) + monkeypatch.setattr("crapper.runners.write_command_output", lambda *args: 0) + run_coverage(tmp_path, [source], None) + assert commands == [["swift", "test", "--enable-code-coverage"]] + + +def test_a_workspace_is_measured_instead_of_a_nested_project(tmp_path, monkeypatch): + _plant(tmp_path, "App.xcworkspace/xcshareddata/xcschemes/App.xcscheme", "\n") + _plant(tmp_path, "App.xcodeproj/project.pbxproj", "") + source = _plant(tmp_path, "App/ContentView.swift", "func body() {}\n") + commands = [] + monkeypatch.setattr("crapper.runners.shutil.which", lambda name: "/usr/bin/xcodebuild" if name == "xcodebuild" else None) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: commands.append(list(command)) or 0) + monkeypatch.setattr("crapper.runners.write_command_output", lambda *args: 0) + run_coverage(tmp_path, [source], None) + assert commands[0][2] == "-workspace" + assert commands[0][3].endswith("App.xcworkspace") + + +def test_xcode_without_a_shared_scheme_does_not_build(tmp_path, monkeypatch, capsys): + (tmp_path / "App.xcodeproj").mkdir() + source = _plant(tmp_path, "App/ContentView.swift", "func body() {}\n") + monkeypatch.setattr("crapper.runners.shutil.which", lambda name: "/usr/bin/xcodebuild" if name == "xcodebuild" else None) + monkeypatch.setattr( + "crapper.runners.run_shell", + lambda command, cwd: (_ for _ in ()).throw(AssertionError(command)), + ) + assert run_coverage(tmp_path, [source], None) == 0 + assert "No shared Xcode scheme" in capsys.readouterr().err + + +def _plant_profdata(package: Path) -> None: + profdata = package / ".build" / "debug" / "codecov" / "default.profdata" + profdata.parent.mkdir(parents=True, exist_ok=True) + profdata.write_text("prof", encoding="utf-8") + + +def test_llvm_cov_exports_the_test_binary_not_the_dsym(tmp_path, monkeypatch): + _plant(tmp_path, "Package.swift", "") + source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") + _plant_profdata(tmp_path) + dsym = tmp_path / ".build" / "debug" / "DemoPackageTests.dSYM" / "Contents" / "Resources" / "DWARF" / "DemoPackageTests" + binary = tmp_path / ".build" / "debug" / "DemoPackageTests.xctest" / "Contents" / "MacOS" / "DemoPackageTests" + dsym.parent.mkdir(parents=True) + binary.parent.mkdir(parents=True) + dsym.write_text("dwarf", encoding="utf-8") + binary.write_text("bin", encoding="utf-8") + exports = [] + + def export(command, cwd, destination): + exports.append(list(command)) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text("{}", encoding="utf-8") + return 0 + + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: f"/usr/bin/{name}" if name in {"swift", "llvm-cov"} else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0) + monkeypatch.setattr("crapper.runners.write_command_output", export) + assert run_coverage(tmp_path, [source], None) == 0 + assert exports[0][-1] == str(binary) + + +def test_a_linux_xctest_file_is_the_swift_test_binary(tmp_path, monkeypatch): + _plant(tmp_path, "Package.swift", "") + source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") + _plant_profdata(tmp_path) + binary = tmp_path / ".build" / "x86_64-unknown-linux-gnu" / "debug" / "DemoPackageTests.xctest" + binary.parent.mkdir(parents=True) + binary.write_text("bin", encoding="utf-8") + exports = [] + + def export(command, cwd, destination): + exports.append(list(command)) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text("{}", encoding="utf-8") + return 0 + + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: f"/usr/bin/{name}" if name in {"swift", "llvm-cov"} else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0) + monkeypatch.setattr("crapper.runners.write_command_output", export) + assert run_coverage(tmp_path, [source], None) == 0 + assert exports[0][-1] == str(binary) + + +def test_llvm_cov_beside_swift_is_used_when_it_is_not_on_the_path(tmp_path, monkeypatch): + swift = tmp_path / "tool" / "swift" + llvm = tmp_path / "tool" / "llvm-cov" + swift.parent.mkdir() + swift.write_text("", encoding="utf-8") + llvm.write_text("", encoding="utf-8") + _plant(tmp_path, "Package.swift", "") + source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") + profdata = tmp_path / ".build" / "debug" / "codecov" / "default.profdata" + binary = tmp_path / ".build" / "debug" / "DemoPackageTests" + exports = [] + + def which(name): + if name == "swift": + return str(swift) + return None + + def shell(command, cwd): + profdata.parent.mkdir(parents=True, exist_ok=True) + profdata.write_text("prof", encoding="utf-8") + binary.write_text("bin", encoding="utf-8") + return 0 + + def export(command, cwd, destination): + exports.append(command[0]) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text("{}", encoding="utf-8") + return 0 + + monkeypatch.setattr("crapper.runners.shutil.which", which) + monkeypatch.setattr("crapper.runners.run_shell", shell) + monkeypatch.setattr("crapper.runners.write_command_output", export) + run_coverage(tmp_path, [source], None) + assert exports == [str(llvm)] + + +def test_command_output_is_the_report_file(tmp_path, monkeypatch): + from crapper.runners import write_command_output + + def fake_run(command, cwd, stdout): + stdout.write('{"ok": true}') + + class Completed: + returncode = 0 + + return Completed() + + monkeypatch.setattr("crapper.runners.subprocess.run", fake_run) + destination = tmp_path / "nested" / "out.json" + assert write_command_output(["llvm-cov"], tmp_path, destination) == 0 + assert destination.read_text(encoding="utf-8") == '{"ok": true}' + monkeypatch.setattr( + "crapper.runners.subprocess.run", + lambda *args, **kwargs: (_ for _ in ()).throw(OSError("missing")), + ) + assert write_command_output(["llvm-cov"], tmp_path, destination) == 127 + + +def test_xcode_failure_paths_do_not_export(tmp_path, monkeypatch, capsys): + project = tmp_path / "App.xcodeproj" + _plant(project, "xcshareddata/xcschemes/App.xcscheme", "\n") + source = _plant(tmp_path, "App/ContentView.swift", "func body() {}\n") + calls = [] + monkeypatch.setattr("crapper.runners.shutil.which", lambda name: None) + monkeypatch.setattr( + "crapper.runners.run_shell", + lambda command, cwd: (_ for _ in ()).throw(AssertionError(command)), + ) + run_coverage(tmp_path, [source], None) + assert "xcodebuild is not installed" in capsys.readouterr().err + + monkeypatch.setattr("crapper.runners.shutil.which", lambda name: "/usr/bin/xcodebuild" if name == "xcodebuild" else None) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: calls.append("test") or 1) + monkeypatch.setattr( + "crapper.runners.write_command_output", + lambda *args: calls.append("export") or 0, + ) + run_coverage(tmp_path, [source], None) + assert calls == ["test"] + assert "Xcode coverage exited" in capsys.readouterr().err + + calls.clear() + result = tmp_path / "target" / "coverage" / "swift" / "App.xcodeproj" / "Test.xcresult" + result.mkdir(parents=True) + (result / "old").write_text("stale", encoding="utf-8") + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: calls.append(command) or 0) + monkeypatch.setattr("crapper.runners.write_command_output", lambda *args: calls.append("export") or 3) + run_coverage(tmp_path, [source], None) + assert not (result / "old").exists() + assert calls[-1] == "export" + assert "xccov exited 3" in capsys.readouterr().err + + +def test_a_failed_swift_run_forgets_the_previous_report(tmp_path, monkeypatch): + _plant(tmp_path, "Package.swift", "// swift-tools-version: 5.9\n") + _swift_project(tmp_path, "llvm-cov.json") + source = tmp_path / "Sources" / "Demo" / "Box.swift" + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: "/usr/bin/swift" if name == "swift" else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 1) + assert run_coverage(tmp_path, [source], None) == 0 + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) + + +def test_a_failed_llvm_cov_export_is_not_scored(tmp_path, monkeypatch): + _plant(tmp_path, "Package.swift", "") + _swift_project(tmp_path, "llvm-cov.json") + _plant_profdata(tmp_path) + binary = tmp_path / ".build" / "debug" / "DemoPackageTests" + binary.write_text("bin", encoding="utf-8") + source = tmp_path / "Sources" / "Demo" / "Box.swift" + + def export(command, cwd, destination): + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text((_FIXTURES / "llvm-cov.json").read_text(encoding="utf-8"), encoding="utf-8") + return 1 + + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: f"/usr/bin/{name}" if name in {"swift", "llvm-cov"} else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 0) + monkeypatch.setattr("crapper.runners.write_command_output", export) + assert run_coverage(tmp_path, [source], None) == 0 + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) + + +def test_a_failed_xcode_run_forgets_the_previous_report(tmp_path, monkeypatch): + project = tmp_path / "App.xcodeproj" + _plant(project, "xcshareddata/xcschemes/App.xcscheme", "\n") + source = tmp_path / "Sources" / "Demo" / "Box.swift" + source.parent.mkdir(parents=True) + source.write_text(_BOX, encoding="utf-8") + report = tmp_path / "target" / "coverage" / "swift" / "App.xcodeproj" / "xccov.json" + report.parent.mkdir(parents=True) + report.write_text((_FIXTURES / "xccov.json").read_text(encoding="utf-8"), encoding="utf-8") + monkeypatch.setattr( + "crapper.runners.shutil.which", + lambda name: "/usr/bin/xcodebuild" if name == "xcodebuild" else None, + ) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: 1) + assert run_coverage(tmp_path, [source], None) == 0 + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) + + +def test_swift_without_a_toolchain_does_not_run_a_command(tmp_path, monkeypatch, capsys): + _plant(tmp_path, "Package.swift", "") + source = _plant(tmp_path, "Sources/Demo/Box.swift", "func open() {}\n") + monkeypatch.setattr("crapper.runners.shutil.which", lambda name: None) + monkeypatch.setattr("crapper.runners.run_shell", lambda command, cwd: (_ for _ in ()).throw(AssertionError(command))) + assert run_coverage(tmp_path, [source], None) == 0 + assert "swift is not installed" in capsys.readouterr().err + + +def test_a_broken_swift_report_does_not_hide_a_good_one(tmp_path): + _swift_project(tmp_path, "llvm-cov.json") + broken = tmp_path / "target" / "coverage" / "swift" / "broken.json" + broken.write_text("{", encoding="utf-8") + text = _snapshot(tmp_path) + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text + + +def test_xccov_accepts_a_target_list_and_a_bare_file(tmp_path): + import json + + report = json.loads((_FIXTURES / "xccov.json").read_text(encoding="utf-8")) + target = report["targets"][0] + _swift_project(tmp_path, "xccov.json") + destination = tmp_path / "target" / "coverage" / "swift" / "xccov.json" + destination.write_text(json.dumps([None, target]), encoding="utf-8") + text = _snapshot(tmp_path) + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text + report["targets"] = [None, target] + destination.write_text(json.dumps(report), encoding="utf-8") + assert ':coverage 50.0' in _snapshot(tmp_path) + bare = {"files": [{"name": "Sources/Demo/Box.swift", "functions": target["files"][0]["functions"]}]} + destination.write_text(json.dumps(bare), encoding="utf-8") + assert ':coverage 50.0' in _snapshot(tmp_path) + destination.write_text("null", encoding="utf-8") + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) + + +def test_an_xccov_function_without_counts_is_uncovered(tmp_path): + import json + + _swift_project(tmp_path, "xccov.json") + report = json.loads((_FIXTURES / "xccov.json").read_text(encoding="utf-8")) + function = report["targets"][0]["files"][0]["functions"][0] + function.pop("coveredLines") + destination = tmp_path / "target" / "coverage" / "swift" / "xccov.json" + destination.write_text(json.dumps(report), encoding="utf-8") + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) + function["executableLines"] = "nope" + destination.write_text(json.dumps(report), encoding="utf-8") + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 0.0, :crap 6.0' in _snapshot(tmp_path) + + +def test_xccov_report_joins_on_the_function_line(tmp_path): + _swift_project(tmp_path, "xccov.json") + text = _snapshot(tmp_path) + assert ':name "choose", :namespace "Demo", :complexity 2, :coverage 50.0, :crap 2.5' in text + assert ':name "open", :namespace "Demo.Box", :complexity 1, :coverage 100.0, :crap 1.0' in text diff --git a/tests/test_typescript.py b/tests/test_typescript.py index 918a3ea..2ac622a 100644 --- a/tests/test_typescript.py +++ b/tests/test_typescript.py @@ -69,6 +69,20 @@ export function text() { ] +def test_a_callback_outside_a_call_stays_inside_its_function(): + source = """ +export function outer(flag: boolean) { + const local = (n: number) => (n > 0 ? 1 : 0); + if (flag) return new Handler((req) => (req.ok ? 1 : 0)); + return 0; +} +""" + functions = functions_in_source(source, "src/demo/box.ts", "/proj") + assert [(fn.namespace, fn.name, fn.complexity) for fn in functions] == [ + ("demo.box", "outer", 4) + ] + + def test_express_handlers_are_entries_and_leave_the_parent(): source = """ export function mount(app) {