mirror of
https://github.com/unclebob/crapper.git
synced 2026-11-26 18:18:49 +00:00
Add Swift function CRAP scores, coverage, and test discovery.
Swift packages and iOS apps had no per-function complexity or coverage join, so crapper could not write a .metrics/crap.edn entry that uml-viewer and mutator can attach to a function. The Swift reader scores top-level functions, methods, initializers, subscripts, computed properties, and closures bound with let or var. Nested closures stay inside the enclosing function. Decision points match the other languages: if, guard, loops, catch, ternary, each switch case, &&, ||, ??, and optional chaining. Coverage reads llvm-cov JSON from swift test and xccov JSON from xcodebuild, joined on the file suffix and the function's line span. A package runs swift test --enable-code-coverage; an Xcode project runs xcodebuild and xcrun xccov view --report --json. Proved by tests/test_swift.py against checked-in llvm-cov and xccov fixtures, the existing suite (174 passed), crapper with every function under CRAP 10, dryer with no duplicate at 0.8 or above, and mutator killing every mutant in the Swift reader. Co-authored-by: Robert C. Martin <[email protected]>
This commit is contained in:
co-authored by
Robert C. Martin
parent
c757ec79a6
commit
10c4e43f7b
@@ -1,6 +1,6 @@
|
|||||||
# crapper
|
# 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):
|
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 |
|
| 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 |
|
| 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 |
|
| 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.
|
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.
|
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. `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 `.xcodeproj` or `.xcworkspace` name, 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
|
## Coverage commands
|
||||||
|
|
||||||
By default a run deletes the previous report for each language it is about to measure and regenerates it:
|
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` |
|
| 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` |
|
| 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` |
|
| 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.
|
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' -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
|
## Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "crapper"
|
name = "crapper"
|
||||||
version = "0.1.0"
|
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"
|
readme = "README.md"
|
||||||
license = { file = "LICENSE" }
|
license = { file = "LICENSE" }
|
||||||
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
|
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
|
||||||
|
|||||||
+73
-46
@@ -32,6 +32,7 @@ _TEST_PATTERNS = ", ".join(
|
|||||||
"test_*.py",
|
"test_*.py",
|
||||||
"*_test.py",
|
"*_test.py",
|
||||||
"conftest.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),
|
Languages: Clojure (.clj .cljc .cljs .bb), Java (.java), Go (.go),
|
||||||
TypeScript and JavaScript (.ts .tsx .mts .cts .js .jsx .mjs .cjs),
|
TypeScript and JavaScript (.ts .tsx .mts .cts .js .jsx .mjs .cjs),
|
||||||
Rust (.rs), Python (.py).
|
Rust (.rs), Python (.py), Swift (.swift).
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
-h, --help Print this help and exit.
|
-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
|
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
|
Rust cargo llvm-cov, or cargo tarpaulin, in the nearest Cargo.toml
|
||||||
Python coverage.py LCOV, via pytest or unittest, per project
|
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.
|
uml-viewer joins .metrics/crap.edn on :namespace and :name.
|
||||||
Clojure the ns, and the defn 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
|
TypeScript dotted module path, or module.Class for methods
|
||||||
Rust crate::module, or crate::module::Type for methods
|
Rust crate::module, or crate::module::Type for methods
|
||||||
Python dotted module path, or module.Class 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]
|
return args[index + 1]
|
||||||
|
|
||||||
|
|
||||||
def parse_args(argv: list[str] | None = None) -> Options:
|
def _append_source(options: Options, value: str) -> None:
|
||||||
args = list(sys.argv[1:] if argv is None else argv)
|
options.source_roots.append(value)
|
||||||
if any(arg in {"-h", "--help"} for arg in args):
|
|
||||||
return Options(action="help", message=HELP, exit_code=0)
|
|
||||||
|
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")
|
options = Options(action="analyze")
|
||||||
index = 0
|
index = 0
|
||||||
try:
|
while index < len(args):
|
||||||
while index < len(args):
|
index = _apply_arg(options, args, index)
|
||||||
arg = args[index]
|
return options
|
||||||
if arg in {"-s", "--source-root"}:
|
|
||||||
options.source_roots.append(_take(args, index, arg))
|
|
||||||
index += 2
|
def _coverage_conflict(options: Options) -> Options | None:
|
||||||
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)
|
|
||||||
if options.no_coverage and options.coverage_command:
|
if options.no_coverage and options.coverage_command:
|
||||||
return Options(
|
return Options(
|
||||||
action="help",
|
action="help",
|
||||||
message=f"--no-coverage cannot be combined with --coverage-command\n\n{HELP}",
|
message=f"--no-coverage cannot be combined with --coverage-command\n\n{HELP}",
|
||||||
exit_code=1,
|
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
|
return options
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+272
-23
@@ -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
|
Clojure prefers Cloverage's per-line form counts, then LCOV. Java uses JaCoCo
|
||||||
instruction counters. Go uses statement profiles. LCOV scores a function by
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
import xml.etree.ElementTree as ET
|
import xml.etree.ElementTree as ET
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
@@ -369,6 +370,250 @@ def _segments_percent(segments, start: int, end: int) -> float | None:
|
|||||||
return coverage_percent(covered, total)
|
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
|
@dataclass
|
||||||
class JacocoMethod:
|
class JacocoMethod:
|
||||||
missed: int
|
missed: int
|
||||||
@@ -443,6 +688,7 @@ class CoverageBundle:
|
|||||||
go_profile: dict[str, list[tuple[int, int, int, int]]] | None = None
|
go_profile: dict[str, list[tuple[int, int, int, int]]] | None = None
|
||||||
jacoco: dict[str, list[JacocoMethod]] | None = None
|
jacoco: dict[str, list[JacocoMethod]] | None = None
|
||||||
form_html: dict[str, dict[int, tuple[int, int]]] = field(default_factory=dict)
|
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)
|
source_parts: list[tuple[str, ...]] = field(default_factory=list)
|
||||||
root: Path | None = None
|
root: Path | None = None
|
||||||
|
|
||||||
@@ -460,28 +706,9 @@ class CoverageBundle:
|
|||||||
self.source_parts = found
|
self.source_parts = found
|
||||||
|
|
||||||
def percent_for(self, function: Function) -> float | None:
|
def percent_for(self, function: Function) -> float | None:
|
||||||
if function.language == "java":
|
if function.language in {"java", "go", "swift"}:
|
||||||
names = []
|
return _named_percent(self, function)
|
||||||
if function.jacoco_class:
|
return _file_percent(self, function)
|
||||||
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)
|
|
||||||
|
|
||||||
def _go_segments(self, path: str) -> list[tuple[int, int, int, int]] | None:
|
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."""
|
"""Profile segments for one Go file: by import path, else by the longest path suffix."""
|
||||||
@@ -584,6 +811,27 @@ def _merge_forms(root: Path) -> dict[str, dict[int, tuple[int, int]]]:
|
|||||||
return found
|
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:
|
def load_bundle(root: Path) -> CoverageBundle:
|
||||||
go_profile = _merge_go(root)
|
go_profile = _merge_go(root)
|
||||||
jacoco = _merge_jacoco(root)
|
jacoco = _merge_jacoco(root)
|
||||||
@@ -592,5 +840,6 @@ def load_bundle(root: Path) -> CoverageBundle:
|
|||||||
go_profile=go_profile or None,
|
go_profile=go_profile or None,
|
||||||
jacoco=jacoco or None,
|
jacoco=jacoco or None,
|
||||||
form_html=_merge_forms(root),
|
form_html=_merge_forms(root),
|
||||||
|
swift=_merge_swift(root),
|
||||||
root=root,
|
root=root,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ EXTENSIONS = {
|
|||||||
".cjs": "typescript",
|
".cjs": "typescript",
|
||||||
".rs": "rust",
|
".rs": "rust",
|
||||||
".py": "python",
|
".py": "python",
|
||||||
|
".swift": "swift",
|
||||||
}
|
}
|
||||||
|
|
||||||
SKIP_DIRS = {
|
SKIP_DIRS = {
|
||||||
@@ -40,6 +41,9 @@ SKIP_DIRS = {
|
|||||||
"testdata",
|
"testdata",
|
||||||
"__pycache__",
|
"__pycache__",
|
||||||
".clj-kondo",
|
".clj-kondo",
|
||||||
|
".build",
|
||||||
|
".swiftpm",
|
||||||
|
"DerivedData",
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__"}
|
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)
|
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:
|
def is_test_file(path: str | Path) -> bool:
|
||||||
file_path = Path(path)
|
file_path = Path(path)
|
||||||
name = file_path.name
|
name = file_path.name
|
||||||
@@ -87,6 +101,8 @@ def is_test_file(path: str | Path) -> bool:
|
|||||||
return True
|
return True
|
||||||
if name.endswith("_test.py") or (name.startswith("test_") and name.endswith(".py")):
|
if name.endswith("_test.py") or (name.startswith("test_") and name.endswith(".py")):
|
||||||
return True
|
return True
|
||||||
|
if _swift_test(file_path):
|
||||||
|
return True
|
||||||
return any(part in TEST_DIRS for part in file_path.parts)
|
return any(part in TEST_DIRS for part in file_path.parts)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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.java import functions_in_source as java_functions
|
||||||
from crapper.languages.python import functions_in_source as python_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.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.languages.typescript import functions_in_source as typescript_functions
|
||||||
from crapper.model import Function
|
from crapper.model import Function
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ _READERS = {
|
|||||||
"typescript": typescript_functions,
|
"typescript": typescript_functions,
|
||||||
"python": python_functions,
|
"python": python_functions,
|
||||||
"rust": rust_functions,
|
"rust": rust_functions,
|
||||||
|
"swift": swift_functions,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from crapper.languages.treesitter import (
|
|||||||
absolute_path as _absolute,
|
absolute_path as _absolute,
|
||||||
binary_logic,
|
binary_logic,
|
||||||
child_of_type,
|
child_of_type,
|
||||||
|
child_text,
|
||||||
complexity,
|
complexity,
|
||||||
descendants,
|
descendants,
|
||||||
end_line,
|
end_line,
|
||||||
@@ -66,17 +67,11 @@ def _receiver_type(data: bytes, method) -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
def _method_name(data: bytes, method) -> str | None:
|
def _method_name(data: bytes, method) -> str | None:
|
||||||
ident = child_of_type(method, "field_identifier")
|
return child_text(data, method, "field_identifier")
|
||||||
if ident is None:
|
|
||||||
return None
|
|
||||||
return node_text(data, ident)
|
|
||||||
|
|
||||||
|
|
||||||
def _function_name(data: bytes, fn) -> str | None:
|
def _function_name(data: bytes, fn) -> str | None:
|
||||||
ident = child_of_type(fn, "identifier")
|
return child_text(data, fn, "identifier")
|
||||||
if ident is None:
|
|
||||||
return None
|
|
||||||
return node_text(data, ident)
|
|
||||||
|
|
||||||
|
|
||||||
def package_namespace(path: str, package_name: str) -> str:
|
def package_namespace(path: str, package_name: str) -> str:
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ enclosing function. A class method's namespace is `module.Class`.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from crapper.languages.treesitter import (
|
from crapper.languages.treesitter import (
|
||||||
|
ancestor_names,
|
||||||
child_of_type,
|
child_of_type,
|
||||||
complexity,
|
complexity,
|
||||||
descendants,
|
descendants,
|
||||||
@@ -15,6 +16,8 @@ from crapper.languages.treesitter import (
|
|||||||
node_text,
|
node_text,
|
||||||
parse,
|
parse,
|
||||||
start_line,
|
start_line,
|
||||||
|
strip_root,
|
||||||
|
strip_src,
|
||||||
)
|
)
|
||||||
from crapper.model import Function
|
from crapper.model import Function
|
||||||
|
|
||||||
@@ -42,23 +45,6 @@ def _skip(node) -> bool:
|
|||||||
return node.type == "class_definition"
|
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:
|
def _strip_module_suffix(relative: str) -> str:
|
||||||
if relative.endswith(".py"):
|
if relative.endswith(".py"):
|
||||||
relative = relative[: -len(".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:
|
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:
|
if not relative:
|
||||||
return "__init__"
|
return "__init__"
|
||||||
return relative.replace("/", ".")
|
return relative.replace("/", ".")
|
||||||
@@ -90,16 +76,7 @@ def _is_nested_function(node) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def _class_names(data: bytes, node) -> list[str]:
|
def _class_names(data: bytes, node) -> list[str]:
|
||||||
names: list[str] = []
|
return ancestor_names(data, node, "class_definition", "identifier")
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def functions_in_source(
|
def functions_in_source(
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
from crapper.languages.treesitter import (
|
from crapper.languages.treesitter import (
|
||||||
absolute_path as _absolute,
|
absolute_path as _absolute,
|
||||||
|
ancestor_names,
|
||||||
binary_logic,
|
binary_logic,
|
||||||
child_of_type,
|
child_of_type,
|
||||||
complexity,
|
complexity,
|
||||||
@@ -48,16 +49,7 @@ def _has_block(node) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def _ancestor_mods(data: bytes, node) -> list[str]:
|
def _ancestor_mods(data: bytes, node) -> list[str]:
|
||||||
names: list[str] = []
|
return ancestor_names(data, node, "mod_item", "identifier")
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def _in_mod_named(data: bytes, node, name: str) -> bool:
|
def _in_mod_named(data: bytes, node, name: str) -> bool:
|
||||||
|
|||||||
@@ -0,0 +1,406 @@
|
|||||||
|
"""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 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 `.xcodeproj` or `.xcworkspace`
|
||||||
|
name, otherwise the dotted directory path with `src/` removed. Nested
|
||||||
|
types keep each owner (`Module.Outer.Inner`). An extension uses the
|
||||||
|
extended type (`Module.Box.Inner`, `Module.Array`).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
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_MARKERS = (".target(", ".executableTarget(")
|
||||||
|
_FIELD = re.compile(r'{name}:\s*"([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
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 _binding_name(data: bytes, node) -> str | None:
|
||||||
|
pattern = child_of_type(node, "pattern")
|
||||||
|
if pattern is None:
|
||||||
|
return None
|
||||||
|
return child_text(data, pattern, "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 _property_is_entry(node) -> bool:
|
||||||
|
if child_of_type(node, "computed_property", "willset_didset_block") is not None:
|
||||||
|
return True
|
||||||
|
return _direct_lambda(node) is not None
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
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 = _binding_name(data, node)
|
||||||
|
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 _balanced(text: str, open_at: int) -> str:
|
||||||
|
depth = 0
|
||||||
|
for index in range(open_at, len(text)):
|
||||||
|
depth += _paren_delta(text[index])
|
||||||
|
if depth == 0:
|
||||||
|
return text[open_at : index + 1]
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _paren_delta(char: str) -> int:
|
||||||
|
if char == "(":
|
||||||
|
return 1
|
||||||
|
if char == ")":
|
||||||
|
return -1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _target_blocks(text: str) -> list[str]:
|
||||||
|
blocks: list[str] = []
|
||||||
|
for marker in _TARGET_MARKERS:
|
||||||
|
start = 0
|
||||||
|
while True:
|
||||||
|
index = text.find(marker, start)
|
||||||
|
if index < 0:
|
||||||
|
break
|
||||||
|
blocks.append(_balanced(text, index + len(marker) - 1))
|
||||||
|
start = index + len(marker)
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
|
def _field(block: str, name: str) -> str | None:
|
||||||
|
match = _FIELD.pattern
|
||||||
|
found = re.search(match.format(name=name), block)
|
||||||
|
if found is None:
|
||||||
|
return None
|
||||||
|
return found.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def _package_targets(text: str) -> list[tuple[str, str | None]]:
|
||||||
|
found = []
|
||||||
|
for block in _target_blocks(text):
|
||||||
|
if not block.endswith(")"):
|
||||||
|
continue
|
||||||
|
name = _field(block, "name")
|
||||||
|
if name:
|
||||||
|
found.append((name, _field(block, "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 ("*.xcodeproj", "*.xcworkspace"):
|
||||||
|
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
|
||||||
@@ -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 functools import lru_cache
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -40,6 +40,43 @@ def child_of_type(node, *types: str):
|
|||||||
return None
|
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):
|
def descendants(node):
|
||||||
stack = [node]
|
stack = [node]
|
||||||
while stack:
|
while stack:
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ from crapper.languages.treesitter import (
|
|||||||
node_text,
|
node_text,
|
||||||
parse,
|
parse,
|
||||||
start_line,
|
start_line,
|
||||||
|
strip_root,
|
||||||
|
strip_src,
|
||||||
)
|
)
|
||||||
from crapper.model import Function
|
from crapper.model import Function
|
||||||
|
|
||||||
@@ -85,23 +87,6 @@ def _grammar(path: str) -> str:
|
|||||||
return "typescript"
|
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:
|
def _strip_script_suffix(relative: str) -> str:
|
||||||
for suffix in (".tsx", ".mts", ".cts", ".jsx", ".mjs", ".cjs", ".ts", ".js"):
|
for suffix in (".tsx", ".mts", ".cts", ".jsx", ".mjs", ".cjs", ".ts", ".js"):
|
||||||
if relative.endswith(suffix):
|
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:
|
def _module_namespace(path: str, source_root: str | None) -> str:
|
||||||
relative = path.replace("\\", "/")
|
relative = path.replace("\\", "/")
|
||||||
relative = _strip_root_prefix(relative, source_root)
|
relative = strip_root(relative, source_root)
|
||||||
relative = _strip_src_dir(relative)
|
relative = strip_src(relative)
|
||||||
return _strip_script_suffix(relative).replace("/", ".")
|
return _strip_script_suffix(relative).replace("/", ".")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+222
-13
@@ -545,6 +545,209 @@ def _cover_python(root: Path, files: list[Path]) -> None:
|
|||||||
_record_python_lcov(package, run_shell(run_cmd, package), data_file, lcov_cmd)
|
_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 swift_test_binary(package: Path) -> Path | None:
|
||||||
|
return _first_file(package, ".build/**/*PackageTests")
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
if profdata is None or binary is None or tool is None:
|
||||||
|
_warn(f"Swift coverage data is missing in {package}. Swift coverage will score 0%.")
|
||||||
|
return
|
||||||
|
report = _swift_report(root, package)
|
||||||
|
code = write_command_output(swift_export_command(tool, binary, profdata), package, report)
|
||||||
|
if code != 0:
|
||||||
|
_warn(f"llvm-cov export exited {code} in {package}. Swift coverage will score 0%.")
|
||||||
|
|
||||||
|
|
||||||
|
def _cover_swift_package(root: Path, package: Path) -> None:
|
||||||
|
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:
|
||||||
|
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 = _swift_report(root, project).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
|
||||||
|
exported = result.parent / "xccov.json"
|
||||||
|
code = write_command_output(xcode_export_command(result), project.parent, exported)
|
||||||
|
if code != 0:
|
||||||
|
_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:
|
def _cover_rust(root: Path, files: list[Path]) -> None:
|
||||||
modules = rust_modules(root, files)
|
modules = rust_modules(root, files)
|
||||||
if not modules:
|
if not modules:
|
||||||
@@ -562,6 +765,24 @@ def _cover_rust(root: Path, files: list[Path]) -> None:
|
|||||||
_warn(f"Rust coverage exited {code} in {module}. Rust coverage will score 0%.")
|
_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:
|
def run_coverage(root: Path, files: list[Path], command: str | None) -> int:
|
||||||
"""Generate coverage reports for the languages present in `files`.
|
"""Generate coverage reports for the languages present in `files`.
|
||||||
|
|
||||||
@@ -580,17 +801,5 @@ def run_coverage(root: Path, files: list[Path], command: str | None) -> int:
|
|||||||
)
|
)
|
||||||
return code
|
return code
|
||||||
|
|
||||||
languages = _languages_in(files)
|
_cover_present(root, 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)
|
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
Vendored
+12
@@ -0,0 +1,12 @@
|
|||||||
|
func choose(x: Int) -> Int {
|
||||||
|
if x > 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Box {
|
||||||
|
func open() -> Int {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+46
@@ -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]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+22
@@ -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": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+41
@@ -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()"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -21,6 +21,10 @@ def test_language_detection():
|
|||||||
assert language_of("src/app.jsx") == "typescript"
|
assert language_of("src/app.jsx") == "typescript"
|
||||||
assert language_of("src/lib.rs") == "rust"
|
assert language_of("src/lib.rs") == "rust"
|
||||||
assert language_of("src/crapper/cli.py") == "python"
|
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("types.d.ts") is None
|
||||||
assert language_of("notes.md") is None
|
assert language_of("notes.md") is None
|
||||||
assert language_of("app.cts") == "typescript"
|
assert language_of("app.cts") == "typescript"
|
||||||
@@ -161,6 +165,8 @@ def test_help_and_unknown_option(capsys):
|
|||||||
assert "uml-viewer" in help_text
|
assert "uml-viewer" in help_text
|
||||||
assert ".clj-kondo" in help_text
|
assert ".clj-kondo" in help_text
|
||||||
assert ".test.cts" 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(["--not-an-option"]) == 1
|
||||||
assert run(["--root"]) == 1
|
assert run(["--root"]) == 1
|
||||||
assert run(["--threshold", "nope"]) == 1
|
assert run(["--threshold", "nope"]) == 1
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ _SOURCES = [
|
|||||||
("typescript", "export function view() { return 1 }\n", "src/ui.ts", "view"),
|
("typescript", "export function view() { return 1 }\n", "src/ui.ts", "view"),
|
||||||
("python", "def run():\n return 1\n", "src/app.py", "run"),
|
("python", "def run():\n return 1\n", "src/app.py", "run"),
|
||||||
("rust", "pub fn open() {}\n", "src/lib.rs", "open"),
|
("rust", "pub fn open() {}\n", "src/lib.rs", "open"),
|
||||||
|
("swift", "func open() {}\n", "Sources/Demo/Box.swift", "open"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,571 @@
|
|||||||
|
"""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..<x { while i > 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_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_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", "<Scheme/>\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", "<Scheme/>\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", "<Scheme/>\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", "<Scheme/>\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 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", "<Scheme/>\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_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
|
||||||
Reference in New Issue
Block a user