From 095f1f12da372b4731f0ca24786377d2e565f8b1 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 2 Dec 2026 08:18:47 +0100 Subject: [PATCH] Lint only changed sources in CI and the full tree in the release matrix clang-tidy over every source has grown to 20-35 minutes and ran in series inside check-extended. It now runs in its own CI job, which checks the sources a change touches and each changed header through one source that includes it. A change to .clang-tidy or misc/check.py still lints everything. The release matrix gets a job that lints every source. check.py lint takes --changed-from, and all takes --skip-lint. --- .github/workflows/build.yml | 70 +++++++++++- .github/workflows/release-matrix.yml | 51 ++++++++- docs/code-style.md | 10 +- misc/check.py | 163 ++++++++++++++++++++++++--- 4 files changed, 271 insertions(+), 23 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ece8c1ed9c..ed5baaaab8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,8 +20,9 @@ env: BUILD_TYPE: Release jobs: - # Formatting, changelog, generated sources, Clang build, clang-tidy, the - # full test suite with audit and fault injection, packages, and docs. + # Formatting, changelog, generated sources, Clang build, the full test suite + # with audit and fault injection, packages, and docs. The lint job runs + # clang-tidy on this configuration. check-extended: runs-on: ubuntu-24.04 @@ -76,7 +77,7 @@ jobs: - name: Run all checks shell: bash - run: uv run misc/check.py all --build-dir build/check-extended --jobs 4 + run: uv run misc/check.py all --build-dir build/check-extended --jobs 4 --skip-lint - name: Qt/Gist consumer smoke test shell: bash @@ -92,6 +93,69 @@ jobs: CXX: clang++-22 run: bash .github/ci/cmake-custom-vis-smoke.sh + # clang-tidy on the check-extended configuration, limited to the sources and + # headers that the change touches. The release matrix lints everything. + lint: + runs-on: ubuntu-24.04 + + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 + with: + # A pull request checks out its merge commit; the first parent is the base. + fetch-depth: 2 + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 + with: + enable-cache: false + + - name: Install LLVM 22 and build dependencies + shell: bash + run: | + curl --fail --location --retry 3 https://apt.llvm.org/llvm-snapshot.gpg.key -o "$RUNNER_TEMP/llvm.asc" + sudo install -m 644 "$RUNNER_TEMP/llvm.asc" /usr/share/keyrings/llvm.asc + echo 'deb [signed-by=/usr/share/keyrings/llvm.asc] https://apt.llvm.org/noble/ llvm-toolchain-noble-22 main' | sudo tee /etc/apt/sources.list.d/llvm.list + # The runner's packages.microsoft.com source has failed apt-get update with 403; no job needs it. + sudo find /etc/apt/sources.list.d -type f -exec grep -q packages.microsoft.com {} \; -delete + # Ubuntu mirrors have answered 503 for minutes; apt backs off between retries. + echo 'Acquire::Retries "10";' | sudo tee /etc/apt/apt.conf.d/80-retries + sudo apt-get update + sudo apt-get install -y clang-22 clang-format-22 clang-tidy-22 clang-tools-22 \ + ninja-build libgmp-dev libmpfr-dev qt6-base-dev qt6-base-dev-tools libgl1-mesa-dev + + - name: Configure the check-extended build + shell: bash + run: > + cmake -S . -B build/lint -G Ninja + -DCMAKE_BUILD_TYPE=Debug + -DCMAKE_C_COMPILER=clang-22 -DCMAKE_CXX_COMPILER=clang++-22 + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + -DGECODE_ENABLE_EXPERIMENTAL=ON -DGECODE_ENABLE_CBS=ON + -DGECODE_ENABLE_AUDIT=ON -DGECODE_ENABLE_FAULT_INJECTION=ON + -DGECODE_ENABLE_QT=ON -DGECODE_ENABLE_GIST=ON -DGECODE_ENABLE_MPFR=ON + -DGECODE_ENABLE_EXAMPLES=ON -DGECODE_REGENERATE_VARIMP=ON + + # clang-tidy parses sources, so only the generated headers are built. + - name: Generate variable headers + shell: bash + run: cmake --build build/lint --target gecode-varimp-gen + + - name: Lint changed sources + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + BEFORE: ${{ github.event.before }} + run: | + set -euo pipefail + # A new branch, or a force push whose old tip is gone, lints everything. + base="" + if [ "$EVENT_NAME" = pull_request ]; then + base=HEAD^1 + elif [[ -n "$BEFORE" && ! "$BEFORE" =~ ^0+$ ]] && git fetch --no-tags --depth=1 origin "$BEFORE"; then + base="$BEFORE" + fi + uv run misc/check.py lint --build-dir build/lint --jobs 4 ${base:+--changed-from "$base"} + # GCC Release build without experimental APIs, plus the installed-package, # FlatZinc, allocator, and 32-bit smokes. build-linux: diff --git a/.github/workflows/release-matrix.yml b/.github/workflows/release-matrix.yml index e2def1171f..bd4abba32f 100644 --- a/.github/workflows/release-matrix.yml +++ b/.github/workflows/release-matrix.yml @@ -1,7 +1,8 @@ name: Release matrix # Broader checks for release preparation, or whenever wanted: the standard -# test suite, plus the platforms and build variants that per-PR CI leaves out. +# test suite, clang-tidy on every source, plus the platforms and build variants +# that per-PR CI leaves out. # It runs on release candidate branches, on pull requests that change it, and # on demand: # gh workflow run release-matrix.yml --repo Gecode/gecode --ref @@ -75,6 +76,54 @@ jobs: GECODE_TEST_BLACKBOX_LOG="$build/gecode-test-blackbox" \ "$build/bin/gecode-test" -tag standard -threads 0 + # CI lints only the changed sources. This lints every source in the + # check-extended configuration. + lint-full: + runs-on: ubuntu-24.04 + + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 + + - name: Install uv + uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 + with: + enable-cache: false + + - name: Install LLVM 22 and build dependencies + shell: bash + run: | + curl --fail --location --retry 3 https://apt.llvm.org/llvm-snapshot.gpg.key -o "$RUNNER_TEMP/llvm.asc" + sudo install -m 644 "$RUNNER_TEMP/llvm.asc" /usr/share/keyrings/llvm.asc + echo 'deb [signed-by=/usr/share/keyrings/llvm.asc] https://apt.llvm.org/noble/ llvm-toolchain-noble-22 main' | sudo tee /etc/apt/sources.list.d/llvm.list + # The runner's packages.microsoft.com source has failed apt-get update with 403; no job needs it. + sudo find /etc/apt/sources.list.d -type f -exec grep -q packages.microsoft.com {} \; -delete + # Ubuntu mirrors have answered 503 for minutes; apt backs off between retries. + echo 'Acquire::Retries "10";' | sudo tee /etc/apt/apt.conf.d/80-retries + sudo apt-get update + sudo apt-get install -y clang-22 clang-format-22 clang-tidy-22 clang-tools-22 \ + ninja-build libgmp-dev libmpfr-dev qt6-base-dev qt6-base-dev-tools libgl1-mesa-dev + + - name: Configure the check-extended build + shell: bash + run: > + cmake -S . -B build/lint -G Ninja + -DCMAKE_BUILD_TYPE=Debug + -DCMAKE_C_COMPILER=clang-22 -DCMAKE_CXX_COMPILER=clang++-22 + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + -DGECODE_ENABLE_EXPERIMENTAL=ON -DGECODE_ENABLE_CBS=ON + -DGECODE_ENABLE_AUDIT=ON -DGECODE_ENABLE_FAULT_INJECTION=ON + -DGECODE_ENABLE_QT=ON -DGECODE_ENABLE_GIST=ON -DGECODE_ENABLE_MPFR=ON + -DGECODE_ENABLE_EXAMPLES=ON -DGECODE_REGENERATE_VARIMP=ON + + # clang-tidy parses sources, so only the generated headers are built. + - name: Generate variable headers + shell: bash + run: cmake --build build/lint --target gecode-varimp-gen + + - name: Lint every source + shell: bash + run: uv run misc/check.py lint --build-dir build/lint --jobs 4 + build-macos: runs-on: macos-15 diff --git a/docs/code-style.md b/docs/code-style.md index 547b4fec5d..97e8ff3e01 100644 --- a/docs/code-style.md +++ b/docs/code-style.md @@ -155,6 +155,7 @@ major versions are rejected): uv run misc/check.py format uv run misc/check.py format-check uv run misc/check.py lint --build-dir build/local +uv run misc/check.py lint --build-dir build/local --changed-from origin/main uv run misc/check.py all --build-dir build/local --jobs 4 ``` @@ -167,12 +168,19 @@ headers, and the owned C++ action ranges inside the generated FlatZinc parser and lexer, and lists any sources outside the build so disabled modules are visible. Lint undefines `NDEBUG` so assertions are always analyzed. +With `--changed-from`, lint checks only the sources that differ from the given +commit, and each changed header through one source that includes it; this needs +`clang-scan-deps` 22 (or `CLANG_SCAN_DEPS`). A change to `.clang-tidy` or the +checker lints everything. Per-PR CI lints this way; the release matrix lints +every source. + `all` / `check-extended` runs formatting, lint, changelog and generated-source freshness checks, build, CTest integrity and enabled fault suites, package installation and downstream consumer tests, and Doxygen (`1.18.0+`). It needs LLVM 22, `uv`, Bison 3.8.2, Flex 2.6.4, Ninja, Doxygen 1.18.0+, and a build with `BUILD_TESTING`, `GECODE_INSTALL`, `GECODE_ENABLE_ALLOCATOR`, search, int, -minimodel, and driver enabled. The full `check-standard` and `check-sweep` +minimodel, and driver enabled. `--skip-lint` leaves linting the build to a +separate lint run. The full `check-standard` and `check-sweep` suites remain separate targets. ## Clang-tidy check selection diff --git a/misc/check.py b/misc/check.py index e18078e343..1d45abf4bd 100644 --- a/misc/check.py +++ b/misc/check.py @@ -9,14 +9,17 @@ and the Bison/Flex outputs retain their upstream formatting. Lint covers owned translation units in the selected compilation database and their owned headers; optional features and platform branches require corresponding build settings. -The all command runs CTest, installed-package fixtures, and documentation -(Doxygen >= 1.18 required). check-standard and check-sweep remain separate -deliberate long runs. +Lint with --changed-from checks only the sources changed since a commit, and +each changed header through one translation unit that includes it. The all +command runs CTest, installed-package fixtures, and documentation (Doxygen >= +1.18 required). check-standard and check-sweep remain separate deliberate long +runs. """ from __future__ import annotations import argparse +from dataclasses import dataclass import json import os from pathlib import Path @@ -24,6 +27,7 @@ import shutil import subprocess import sys +import tempfile ROOT = Path(__file__).resolve().parents[1] LLVM_MAJOR = 22 @@ -34,6 +38,14 @@ "gecode/flatzinc/parser.tab.hpp", "gecode/flatzinc/lexer.yy.cpp", } +# Generated translation units whose actions are linted, and their inputs. +GRAMMARS = {"parser.tab.cpp": "parser.yxx", "lexer.yy.cpp": "lexer.lxx"} +# Headers that the build regenerates when GECODE_REGENERATE_VARIMP is on. +GENERATED_VARIABLE_HEADERS = {"gecode/kernel/var-type.hpp", "gecode/kernel/var-imp.hpp"} +# A change to these affects every file, so the lint covers everything. +FULL_LINT_TRIGGERS = {".clang-tidy", "misc/check.py"} +# Top-level directories whose sources and headers are linted. +OWNED_DIRECTORIES = ("gecode", "test", "examples", "tools") def run(command: list[str], *, env: dict[str, str] | None = None) -> None: @@ -106,7 +118,99 @@ def trimmed(first: int, last: int) -> list[int]: trimmed(find('#define YYTABLES_NAME "yytables"') + 1, len(lines) - 1)] -def lint(build_dir: Path, jobs: int, *, report_missing: bool = True) -> None: +@dataclass +class LintScope: + """What one lint run covers.""" + + # Owned translation units passed to run-clang-tidy. + sources: list[Path] + # Bison and Flex translation units whose owned C++ actions are linted. + generated: set[Path] + # Whether parser.hh is linted with the parser compilation settings. + parser_header: bool + + +def display(path: Path) -> str: + return str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path) + + +def changed_paths(base: str) -> set[str]: + """Return the existing files that differ between base and the work tree.""" + output = subprocess.check_output( + ["git", "diff", "--name-only", "--no-renames", "--diff-filter=d", "-z", base, "--"], cwd=ROOT) + return {name for name in output.decode().split("\0") if name} + + +def scan_dependencies(entries: list[dict], sources: set[Path], jobs: int) -> dict[Path, set[Path]]: + """Return the headers that each of the given translation units includes.""" + scanner = llvm_tool("clang-scan-deps") + selected = [entry for entry in entries if (Path(entry["directory"]) / entry["file"]).resolve() in sources] + resolved: dict[str, Path] = {} + dependencies: dict[Path, set[Path]] = {} + with tempfile.TemporaryDirectory() as directory: + database = Path(directory) / "compile_commands.json" + database.write_text(json.dumps(selected)) + # Use the resource directory of each compiler, as the build does. + output = subprocess.run( + [scanner, "-compilation-database", str(database), "-j", str(jobs), "-format", "make", + "-resource-dir-recipe=invoke-compiler"], + cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True).stdout + for rule in output.replace("\\\n", " ").splitlines(): + _, separator, prerequisites = rule.partition(": ") + if not separator: + continue + files = [] + for name in re.findall(r"(?:\\.|\S)+", prerequisites): + name = name.replace("\\ ", " ") + if name not in resolved: + resolved[name] = Path(name).resolve() + files.append(resolved[name]) + if files: + dependencies[files[0]] = set(files[1:]) + return dependencies + + +def changed_scope(build_dir: Path, entries: list[dict], base: str, changed: set[str], + full: LintScope, jobs: int) -> LintScope: + """Return the part of full that the files changed since base affect. + + A changed source is linted itself. A changed header is linted through one + translation unit that includes it, preferring a source with the same name + and then the one with the fewest includes. + """ + triggers = sorted(changed & FULL_LINT_TRIGGERS) + if triggers: + print(f"{', '.join(triggers)} changed since {base}; linting everything", flush=True) + return full + print(f"Selecting sources affected by changes since {base}", flush=True) + paths = {ROOT / name for name in changed} + headers = {ROOT / name for name in changed + if Path(name).suffix in HEADER_SUFFIXES and name not in GENERATED_PARSER + and Path(name).parts[0] in OWNED_DIRECTORIES} + # A regenerating build includes its own copies of the variable headers. + for name in GENERATED_VARIABLE_HEADERS: + if ROOT / name in headers and (build_dir / name).is_file(): + headers = headers - {ROOT / name} | {build_dir / name} + dependencies = scan_dependencies(entries, set(full.sources) | full.generated, jobs) if headers else {} + sources = {source for source in full.sources if source in paths} + generated = {source for source in full.generated + if source in paths or source.with_name(GRAMMARS[source.name]) in paths + or headers & dependencies.get(source, set())} + parser_header = ROOT / "gecode/flatzinc/parser.hh" + lint_parser_header = full.parser_header and (parser_header in headers or any( + source.name == "parser.tab.cpp" for source in generated)) + for header in sorted(headers): + users = [source for source in full.sources if header in dependencies.get(source, set())] + if users: + user = min(users, key=lambda source: (source.stem != header.stem, len(dependencies[source]), source)) + sources.add(user) + print(f" {display(header)} through {display(user)}", flush=True) + elif header != parser_header or not lint_parser_header: + print(f" {display(header)} is not included by a source in this build", flush=True) + return LintScope(sorted(sources), generated, lint_parser_header) + + +def lint(build_dir: Path, jobs: int, *, report_missing: bool = True, changed_from: str | None = None) -> None: configuration = ROOT / ".clang-tidy" if not configuration.is_file(): raise ValueError(f"Missing {configuration}") @@ -130,7 +234,18 @@ def lint(build_dir: Path, jobs: int, *, report_missing: bool = True) -> None: if not selected: raise ValueError("The compilation database contains no tracked Gecode source files") missing = sorted(sources - compiled) - print(f"Linting {len(selected)} source files and their owned headers", flush=True) + full = LintScope(selected, {ROOT / "gecode/flatzinc" / name for name in GRAMMARS} & compiled, + ROOT / "gecode/flatzinc/parser.tab.cpp" in compiled) + scope = full + if changed_from is not None: + changed = changed_paths(changed_from) + scope = changed_scope(build_dir, entries, changed_from, changed, full, jobs) + if scope is not full: + missing = [path for path in missing if path.relative_to(ROOT).as_posix() in changed] + if scope is full: + print(f"Linting {len(selected)} source files and their owned headers", flush=True) + else: + print(f"Linting {len(scope.sources)} of {len(selected)} source files and their owned headers", flush=True) print("Coverage follows this build's enabled features and platform branches.", flush=True) if missing and report_missing: print(f"{len(missing)} owned source files are outside this build:", flush=True) @@ -144,7 +259,7 @@ def path_pattern(path: Path) -> str: excluded_sources = "|".join( path_pattern(Path(path)) + "$" for path in sorted(GENERATED_PARSER) ) - owned_directory = "(gecode|test|examples|tools)" + separator + owned_directory = "(" + "|".join(OWNED_DIRECTORIES) + ")" + separator source_filter = ("^" + path_pattern(ROOT) + separator + "(?!" + excluded_sources + ")" + owned_directory) # LLVM header filters use POSIX regular expressions, without lookarounds. @@ -153,15 +268,18 @@ def path_pattern(path: Path) -> str: exclude_filter = (separator + path_pattern(Path("gecode/flatzinc")) + separator + r"(parser\.tab\.(cpp|hpp)|lexer\.yy\.cpp)$") runner_command = [sys.executable, runner] if os.name == "nt" else [runner] - run([*runner_command, "-clang-tidy-binary", tidy, "-config-file", str(configuration), - "-p", str(build_dir), "-j", str(jobs), "-extra-arg=-UNDEBUG", - "-header-filter", f"({header_filter}|{generated_headers})", - "-exclude-header-filter", exclude_filter, "-source-filter", source_filter, - "-warnings-as-errors", "*"]) + # run-clang-tidy selects the files that match any positional pattern. + files = [] if scope is full else ["^" + path_pattern(source) + "$" for source in scope.sources] + if scope is full or files: + run([*runner_command, "-clang-tidy-binary", tidy, "-config-file", str(configuration), + "-p", str(build_dir), "-j", str(jobs), "-extra-arg=-UNDEBUG", + "-header-filter", f"({header_filter}|{generated_headers})", + "-exclude-header-filter", exclude_filter, "-source-filter", source_filter, + "-warnings-as-errors", "*", *files]) # Line filters use physical generated-file locations, not #line filenames. - for generated, grammar in (("parser.tab.cpp", "parser.yxx"), ("lexer.yy.cpp", "lexer.lxx")): + for generated, grammar in GRAMMARS.items(): source = ROOT / "gecode/flatzinc" / generated - if source not in compiled: + if source not in scope.generated: continue ranges = [] start = None @@ -186,7 +304,7 @@ def path_pattern(path: Path) -> str: "--warnings-as-errors=*", str(source)]) # This owned header is otherwise reached only through excluded Bison/Flex # translation units. Clang borrows the parser's compilation command. - if ROOT / "gecode/flatzinc/parser.tab.cpp" in compiled: + if scope.parser_header: parser_header = ROOT / "gecode/flatzinc/parser.hh" print("Linting parser.hh with the parser compilation settings", flush=True) run([tidy, "--extra-arg=-UNDEBUG", "-p", str(build_dir), @@ -238,7 +356,7 @@ def check_packages(build_dir: Path, jobs: int, config: str | None, lint(package_build, jobs, report_missing=False) -def check_all(build_dir: Path, jobs: int, config: str | None) -> None: +def check_all(build_dir: Path, jobs: int, config: str | None, *, lint_build: bool = True) -> None: cache = build_dir / "CMakeCache.txt" if not cache.is_file(): raise ValueError(f"Missing {cache}; configure the CMake build first") @@ -258,7 +376,8 @@ def check_all(build_dir: Path, jobs: int, config: str | None) -> None: if config: build += ["--config", config] run(build) - lint(build_dir, jobs) + if lint_build: + lint(build_dir, jobs) ctest = ["ctest", "--test-dir", str(build_dir), "--output-on-failure"] if config: ctest += ["--build-config", config] @@ -273,18 +392,26 @@ def main() -> int: parser.add_argument("--build-dir", type=Path, help="configured CMake build (required for lint/all)") parser.add_argument("--jobs", "-j", type=int, default=4, help="parallel build/lint jobs (default: 4)") parser.add_argument("--config", help="configuration for multi-config CMake builds") + parser.add_argument("--changed-from", metavar="COMMIT", + help="lint only what changed between COMMIT and the work tree") + parser.add_argument("--skip-lint", action="store_true", + help="leave linting the build itself to a separate lint run (all only)") args = parser.parse_args() if args.jobs < 1: parser.error("--jobs must be positive") if args.command in {"lint", "all"} and args.build_dir is None: parser.error("--build-dir is required for lint/all") + if args.changed_from is not None and args.command != "lint": + parser.error("--changed-from applies only to lint") + if args.skip_lint and args.command != "all": + parser.error("--skip-lint applies only to all") try: if args.command in {"format", "format-check"}: format_sources(args.command == "format") elif args.command == "lint": - lint(args.build_dir.resolve(), args.jobs) + lint(args.build_dir.resolve(), args.jobs, changed_from=args.changed_from) else: - check_all(args.build_dir.resolve(), args.jobs, args.config) + check_all(args.build_dir.resolve(), args.jobs, args.config, lint_build=not args.skip_lint) except (OSError, ValueError, subprocess.CalledProcessError) as error: print(f"check: {error}", file=sys.stderr) return 1