diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 77f9078..684c1fd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,18 +5,57 @@ on: branches: [main] pull_request: +permissions: + contents: read + jobs: docker-build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Test coverage comparison + run: python3 -m unittest discover -s scripts -p 'check_coverage_test.py' - name: Build and test via Docker run: docker build -t j1939 . - - name: Check coverage hasn't regressed + - name: Measure current coverage + run: | + mkdir -p coverage-reports/head + docker run --rm \ + -v "$GITHUB_WORKSPACE:/input:ro" \ + -v "$GITHUB_WORKSPACE/scripts/collect_coverage.sh:/collect.sh:ro" \ + -v "$GITHUB_WORKSPACE/coverage-reports/head:/reports" \ + j1939 bash /collect.sh 2>&1 | tee coverage-reports/head/run.log + - name: Measure PR base coverage + if: github.event_name == 'pull_request' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | - docker run --rm j1939 sh -c " - cmake -S /src -B /src/build_cov -DENABLE_COVERAGE=ON && - cmake --build /src/build_cov --target coverage" + base_dir="$RUNNER_TEMP/coverage-base" + mkdir -p "$base_dir" coverage-reports/base + git archive "$BASE_SHA" | tar -x -C "$base_dir" + docker run --rm \ + -v "$base_dir:/input:ro" \ + -v "$GITHUB_WORKSPACE/scripts/collect_coverage.sh:/collect.sh:ro" \ + -v "$GITHUB_WORKSPACE/coverage-reports/base:/reports" \ + j1939 bash /collect.sh 2>&1 | tee coverage-reports/base/run.log + - name: Reject coverage regressions + env: + EVENT_NAME: ${{ github.event_name }} + run: | + args=(--head coverage-reports/head/summary.json --markdown "$GITHUB_STEP_SUMMARY") + if [[ "$EVENT_NAME" == pull_request ]]; then + args+=(--base coverage-reports/base/summary.json) + fi + python3 scripts/check_coverage.py "${args[@]}" + - name: Upload coverage reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage-reports + path: coverage-reports/ + if-no-files-found: warn vcan-tests: # ubuntu-latest became Ubuntu 26.04 on 2026-10-19; its azure kernel has no diff --git a/README.md b/README.md index 08959c9..a98452d 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,15 @@ Short excerpts are committed under `testdata/canboat/`, and the tests that use t The full captures (~216 MB) are not committed. Fetch them with `scripts/fetch_test_logs.sh`; until you do, those tests skip. See [testdata/README.md](testdata/README.md). +#### Coverage in CI + +The Build workflow measures C and C++ coverage for each pull request and its base +commit with the same toolchain and filters. Any decrease in line, branch, or +function coverage fails the check, using exact covered/total counts. Line coverage +must also remain at least 97.8%, and branch coverage at least 93.3%. Pushes to +`main` enforce those minimums. The job summary shows the comparison; download +`coverage-reports` from the workflow run for HTML, text, JSON, and test logs. + #### Using can_sandbox This tool decodes CAN traffic log files in several text formats (ASC, LOG, TRC, OUT, ROS, and Actisense `.raw`/`.all` as written by canboat's actisense-serial) and prints the content to the console. A sample log file is provided. diff --git a/scripts/check_coverage.py b/scripts/check_coverage.py new file mode 100644 index 0000000..78f4eed --- /dev/null +++ b/scripts/check_coverage.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Enforce coverage floors and reject any exact-ratio decrease from a PR's base.""" +import argparse +from fractions import Fraction +import json +from pathlib import Path +import sys + +METRICS = {"line": Fraction("97.8"), "branch": Fraction("93.3"), "function": None} + + +def read_summary(path): + data = json.loads(Path(path).read_text()) + result = {} + for metric in METRICS: + total, covered = data[metric + "_total"], data[metric + "_covered"] + if (type(total) is not int or type(covered) is not int + or total <= 0 or not 0 <= covered <= total): + raise ValueError(f"{path}: invalid or empty {metric} coverage counts") + result[metric] = Fraction(covered, total) + return result + + +def compare(head, base=None): + rows = ["| Coverage | Base | PR / main | Change |", "|---|---:|---:|---:|"] + errors = [] + for metric, minimum in METRICS.items(): + current = head[metric] * 100 + previous = base[metric] * 100 if base is not None else None + delta = f"{float(current - previous):+.6f} pp" if previous is not None else "—" + rows.append(f"| {metric.title()} | {float(previous):.6f}% | {float(current):.6f}% | {delta} |" + if previous is not None else + f"| {metric.title()} | — | {float(current):.6f}% | {delta} |") + if minimum is not None and current < minimum: + errors.append(f"{metric} coverage is below the {float(minimum):g}% minimum") + # Use exact counts rather than gcovr's rounded percentages. Even a small + # decrease must fail; an unchanged ratio with more code must pass. + if base is not None and head[metric] < base[metric]: + errors.append(f"{metric} coverage decreased from the base commit") + return "\n".join(rows), errors + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--head", required=True) + parser.add_argument("--base") + parser.add_argument("--markdown", help="Write a GitHub Actions job summary") + args = parser.parse_args() + try: + table, errors = compare(read_summary(args.head), + read_summary(args.base) if args.base else None) + except (OSError, ValueError, KeyError, TypeError) as error: + print(f"Coverage comparison failed: {error}", file=sys.stderr) + return 1 + report = "## Coverage\n\n" + table + "\n" + if errors: + report += "\n" + "\n".join(f"- {error}" for error in errors) + "\n" + print(report) + if args.markdown: + with open(args.markdown, "a") as summary: + summary.write(report) + return int(bool(errors)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_coverage_test.py b/scripts/check_coverage_test.py new file mode 100644 index 0000000..e062647 --- /dev/null +++ b/scripts/check_coverage_test.py @@ -0,0 +1,53 @@ +import json +from fractions import Fraction +from pathlib import Path +import tempfile +import unittest + +from check_coverage import compare, read_summary + + +class CoverageCheckTest(unittest.TestCase): + def summary(self, line="99", branch="95", function="99"): + return {key: Fraction(value) / 100 for key, value in + zip(("line", "branch", "function"), (line, branch, function))} + + def test_equal_ratios_and_improvements_pass(self): + base = self.summary() + self.assertFalse(compare(base, base)[1]) + self.assertFalse(compare(self.summary("99.1", "95.1", "100"), base)[1]) + + def test_tiny_drop_fails_even_when_display_rounds_the_same(self): + for metric in ("line", "branch", "function"): + base = self.summary() + head = dict(base) + head[metric] -= Fraction(1, 100000000) + self.assertIn(f"{metric} coverage decreased from the base commit", compare(head, base)[1]) + + def test_floors_apply_without_a_base_and_even_if_base_is_worse(self): + head = self.summary("97.7", "93.2") + self.assertEqual(len(compare(head)[1]), 2) + self.assertEqual(len(compare(head, self.summary("90", "90"))[1]), 2) + self.assertFalse(compare(self.summary("97.8", "93.3"))[1]) + + def test_reads_counts_without_using_rounded_percentages(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "summary.json" + data = {f"{metric}_{suffix}": value + for metric in ("line", "branch", "function") + for suffix, value in (("total", 101), ("covered", 100), ("percent", 99.0))} + path.write_text(json.dumps(data)) + self.assertEqual(read_summary(path)["line"], Fraction(100, 101)) + for invalid in (0, -1, "100", True): + data["line_total"] = invalid + path.write_text(json.dumps(data)) + with self.assertRaises(ValueError): + read_summary(path) + data["line_total"] = 99 + path.write_text(json.dumps(data)) + with self.assertRaises(ValueError): + read_summary(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/collect_coverage.sh b/scripts/collect_coverage.sh new file mode 100644 index 0000000..4d408ed --- /dev/null +++ b/scripts/collect_coverage.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Run inside the CI image with source at /input and a writable /reports mount. +set -euo pipefail + +source_dir=$(mktemp -d /tmp/j1939-coverage.XXXXXX) +trap 'rm -rf "$source_dir"' EXIT +# Discard existing build data so stale gcda/gcno files cannot affect the result. +tar -C /input --exclude=.git --exclude=build --exclude=build_cov \ + --exclude=coverage-reports -cf - . | tar -C "$source_dir" -xf - +cmake -S "$source_dir" -B "$source_dir/build_cov" -DENABLE_COVERAGE=ON \ + -DCMAKE_C_FLAGS='--coverage -O0 -g' +cmake --build "$source_dir/build_cov" --target all_tests -j2 +"$source_dir/build_cov/bin/all_tests" + +cd "$source_dir" +gcovr --root "$source_dir" "$source_dir/build_cov" \ + --exclude '.*_tests?\.cpp$' --exclude 'tests/' \ + --exclude '(.*/)?CMakeFiles/' --exclude-throw-branches \ + --print-summary --json-summary /reports/summary.json \ + --html-details /reports/coverage.html --txt /reports/coverage.txt