From 29c4096b7e8296caf1d91bdc9d7ea2c52edee82e Mon Sep 17 00:00:00 2001 From: Arif Burak Demiray Date: Thu, 12 Nov 2026 20:08:24 +0300 Subject: [PATCH 1/3] ci: report static analysis findings --- .github/scripts/clang_tidy_sarif.py | 81 +++++++++++++++++++++++ .github/scripts/sarif_summary.py | 93 +++++++++++++++++++++++++++ .github/workflows/static_analysis.yml | 43 +++++++++++++ 3 files changed, 217 insertions(+) create mode 100644 .github/scripts/clang_tidy_sarif.py create mode 100644 .github/scripts/sarif_summary.py create mode 100644 .github/workflows/static_analysis.yml diff --git a/.github/scripts/clang_tidy_sarif.py b/.github/scripts/clang_tidy_sarif.py new file mode 100644 index 0000000..2209695 --- /dev/null +++ b/.github/scripts/clang_tidy_sarif.py @@ -0,0 +1,81 @@ +""" +Converts clang-tidy output to a SARIF 2.1.0 file. + +Usage: python3 clang_tidy_sarif.py + +Reads the "::: : []" diagnostics and keeps one copy of each, because a +header's findings repeat for every source file that includes it. Notes are left out: they explain the finding above. +Paths inside the working directory are written relative to it. +""" +import json +import pathlib +import re +import sys + +DIAGNOSTIC = re.compile( + r"^(?P.+?):(?P\d+):(?P\d+): (?Pwarning|error): (?P.*) \[(?P[^\]]+)\]$") + + +def diagnostics(output): + """Yields each distinct diagnostic in the clang-tidy output as a dictionary.""" + seen = set() + for line in output.splitlines(): + match = DIAGNOSTIC.match(line.rstrip()) + if match and match.group("file", "line", "column", "check") not in seen: + seen.add(match.group("file", "line", "column", "check")) + yield match.groupdict() + + +def relative(path): + """Returns the path relative to the working directory when it lies inside it, else unchanged.""" + try: + return pathlib.Path(path).resolve().relative_to(pathlib.Path.cwd().resolve()).as_posix() + except ValueError: + return pathlib.PurePath(path).as_posix() + + +def help_uri(check): + """Returns the documentation page of a clang-tidy check.""" + group, _, name = check.partition("-") + if group == "clang" and name.startswith("analyzer-"): + return "https://clang.llvm.org/docs/analyzer/checkers.html" + if group == "clang" and name.startswith("diagnostic-"): + return "https://clang.llvm.org/docs/DiagnosticsReference.html" + return f"https://clang.llvm.org/extra/clang-tidy/checks/{group}/{name}.html" + + +def to_sarif(found): + """Returns a SARIF document holding the diagnostics as one clang-tidy run.""" + checks = sorted({item["check"] for item in found}) + return { + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [{ + "tool": {"driver": { + "name": "clang-tidy", + "informationUri": "https://clang.llvm.org/extra/clang-tidy/", + "rules": [{"id": check, "helpUri": help_uri(check)} for check in checks], + }}, + "results": [{ + "ruleId": item["check"], + "level": item["level"], + "message": {"text": item["message"]}, + "locations": [{"physicalLocation": { + "artifactLocation": {"uri": relative(item["file"])}, + "region": {"startLine": int(item["line"]), "startColumn": int(item["column"])}, + }}], + } for item in found], + }], + } + + +def main(): + """Converts the clang-tidy output file named on the command line.""" + if len(sys.argv) != 3: + sys.exit(__doc__) + found = list(diagnostics(pathlib.Path(sys.argv[1]).read_text(errors="replace"))) + pathlib.Path(sys.argv[2]).write_text(json.dumps(to_sarif(found), indent=1)) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/sarif_summary.py b/.github/scripts/sarif_summary.py new file mode 100644 index 0000000..d35f0cd --- /dev/null +++ b/.github/scripts/sarif_summary.py @@ -0,0 +1,93 @@ +""" +Writes a Markdown summary of static analysis results stored as SARIF. + +Usage: python3 sarif_summary.py <file.sarif or directory> [...] + +Prints the number of distinct findings per rule and level, then the first findings with their location. Exits with 1 +when no SARIF file is found, so an analyzer that silently wrote nothing never reads as a clean result. +""" +import collections +import json +import pathlib +import sys +import urllib.parse +import urllib.request + +MAX_LISTED = 50 + + +def sarif_files(arguments): + """Returns the SARIF files named by the arguments, expanding directories.""" + files = [] + for argument in arguments: + path = pathlib.Path(argument) + files.extend(sorted(path.rglob("*.sarif")) if path.is_dir() else [path] if path.is_file() else []) + return files + + +def relative_path(uri): + """Returns the path of a SARIF artifact URI, relative to the working directory when it lies inside it.""" + parsed = urllib.parse.urlparse(uri) + path = urllib.request.url2pathname(parsed.path) if parsed.scheme == "file" else urllib.parse.unquote(uri) + try: + return pathlib.Path(path).resolve().relative_to(pathlib.Path.cwd().resolve()).as_posix() + except (ValueError, OSError): + return pathlib.PurePath(path).as_posix() + + +def location(result): + """Returns 'path:line' for the first location of a result.""" + for loc in result.get("locations", []): + physical = loc.get("physicalLocation", {}) + path = relative_path(physical.get("artifactLocation", {}).get("uri", "")) + line = physical.get("region", {}).get("startLine") + return f"{path}:{line}" if line else path + return "" + + +def findings(files): + """Yields (rule, level, description, location, message) for every result in the SARIF files.""" + for file in files: + for run in json.loads(file.read_text(encoding="utf-8-sig")).get("runs", []): + driver = run.get("tool", {}).get("driver", {}) + rules = {rule.get("id"): rule for rule in driver.get("rules", [])} + for result in run.get("results", []): + rule_id = result.get("ruleId") or result.get("rule", {}).get("id", "unknown") + rule = rules.get(rule_id, {}) + level = result.get("level") or rule.get("defaultConfiguration", {}).get("level", "warning") + description = (rule.get("shortDescription", {}).get("text") + or rule.get("fullDescription", {}).get("text") or rule.get("helpUri", "")) + message = result.get("message", {}).get("text", "").splitlines()[0] if result.get("message") else "" + yield rule_id, level, description, location(result), message + + +def cell(text): + """Escapes text for a Markdown table cell.""" + return text.replace("|", "\\|").replace("\n", " ")[:160] + + +def main(): + """Prints the summary for the title and SARIF paths given on the command line.""" + if len(sys.argv) < 3: + sys.exit(__doc__) + title, files = sys.argv[1], sarif_files(sys.argv[2:]) + if not files: + sys.exit(f"::error title={title}::No SARIF file found in {' '.join(sys.argv[2:])}") + # The same finding in a shared header is reported once per source file that includes it. + rows = list(dict.fromkeys(findings(files))) + print(f"### {title}: {len(rows)} finding{'s' if len(rows) != 1 else ''}\n") + if not rows: + return + counts = collections.Counter((rule, level, description) for rule, level, description, _, _ in rows) + print("| Rule | Level | Count | Description |\n|---|---|---|---|") + for (rule, level, description), count in sorted(counts.items(), key=lambda item: (-item[1], item[0])): + print(f"| {cell(rule)} | {level} | {count} | {cell(description)} |") + print(f"\n<details><summary>First {min(MAX_LISTED, len(rows))} findings</summary>\n") + print("| Location | Rule | Message |\n|---|---|---|") + for rule, _, _, where, message in sorted(rows, key=lambda row: row[3])[:MAX_LISTED]: + print(f"| {cell(where)} | {cell(rule)} | {cell(message)} |") + print("\n</details>") + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml new file mode 100644 index 0000000..cdcd4f8 --- /dev/null +++ b/.github/workflows/static_analysis.yml @@ -0,0 +1,43 @@ +name: Static analysis + +on: + pull_request: + push: + branches: + - master + - staging + workflow_dispatch: + +permissions: + contents: read + +jobs: + clang-tidy: + name: clang-tidy + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + submodules: recursive + persist-credentials: false + + - name: Install dependencies + run: | + sudo apt-get -qq update + sudo apt-get -qq install -y --no-install-recommends clang-18 clang-tidy-18 libcurl4-openssl-dev libssl-dev + + # Report-only: the findings go to the job summary and never fail the job, only a clang-tidy failure does. + - name: Analyze the SDK + run: | + cmake -DCOUNTLY_USE_SQLITE=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 -B build . + if ! run-clang-tidy-18 -clang-tidy-binary clang-tidy-18 -p build -quiet -header-filter="^$PWD/(include|src)/" \ + -checks='-*,bugprone-*,clang-analyzer-*,concurrency-*,performance-*,portability-*,-bugprone-easily-swappable-parameters' \ + "^$PWD/src/" > "$RUNNER_TEMP/clang-tidy.log" 2>&1; then + tail -n 50 "$RUNNER_TEMP/clang-tidy.log" + exit 1 + fi + python3 .github/scripts/clang_tidy_sarif.py "$RUNNER_TEMP/clang-tidy.log" "$RUNNER_TEMP/clang-tidy.sarif" + + - name: Summarize the findings + run: python3 .github/scripts/sarif_summary.py clang-tidy "$RUNNER_TEMP/clang-tidy.sarif" >> "$GITHUB_STEP_SUMMARY" From af2a5fc2fdfb2f68f80c6dac086dc78fa70b9291 Mon Sep 17 00:00:00 2001 From: Arif Burak Demiray <burakdemiray09@hotmail.com> Date: Thu, 12 Nov 2026 20:51:27 +0300 Subject: [PATCH 2/3] ci: keep the analysis scripts' docstrings on one line --- .github/scripts/clang_tidy_sarif.py | 16 +++++----------- .github/scripts/sarif_summary.py | 13 ++++--------- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/.github/scripts/clang_tidy_sarif.py b/.github/scripts/clang_tidy_sarif.py index 2209695..1ce08bd 100644 --- a/.github/scripts/clang_tidy_sarif.py +++ b/.github/scripts/clang_tidy_sarif.py @@ -1,23 +1,17 @@ -""" -Converts clang-tidy output to a SARIF 2.1.0 file. - -Usage: python3 clang_tidy_sarif.py <clang-tidy output> <output.sarif> - -Reads the "<file>:<line>:<column>: <level>: <message> [<check>]" diagnostics and keeps one copy of each, because a -header's findings repeat for every source file that includes it. Notes are left out: they explain the finding above. -Paths inside the working directory are written relative to it. -""" +"""Converts clang-tidy output to a SARIF 2.1.0 file with one result per distinct diagnostic.""" import json import pathlib import re import sys +USAGE = "Usage: python3 clang_tidy_sarif.py <clang-tidy output> <output.sarif>" +# Notes are left out: they explain the warning or error above them. DIAGNOSTIC = re.compile( r"^(?P<file>.+?):(?P<line>\d+):(?P<column>\d+): (?P<level>warning|error): (?P<message>.*) \[(?P<check>[^\]]+)\]$") def diagnostics(output): - """Yields each distinct diagnostic in the clang-tidy output as a dictionary.""" + """Yields each distinct diagnostic once: a header's findings repeat for every source file that includes it.""" seen = set() for line in output.splitlines(): match = DIAGNOSTIC.match(line.rstrip()) @@ -72,7 +66,7 @@ def to_sarif(found): def main(): """Converts the clang-tidy output file named on the command line.""" if len(sys.argv) != 3: - sys.exit(__doc__) + sys.exit(USAGE) found = list(diagnostics(pathlib.Path(sys.argv[1]).read_text(errors="replace"))) pathlib.Path(sys.argv[2]).write_text(json.dumps(to_sarif(found), indent=1)) diff --git a/.github/scripts/sarif_summary.py b/.github/scripts/sarif_summary.py index d35f0cd..31faaec 100644 --- a/.github/scripts/sarif_summary.py +++ b/.github/scripts/sarif_summary.py @@ -1,11 +1,4 @@ -""" -Writes a Markdown summary of static analysis results stored as SARIF. - -Usage: python3 sarif_summary.py <title> <file.sarif or directory> [...] - -Prints the number of distinct findings per rule and level, then the first findings with their location. Exits with 1 -when no SARIF file is found, so an analyzer that silently wrote nothing never reads as a clean result. -""" +"""Writes a Markdown summary of static analysis results stored as SARIF: findings per rule, then the first 50.""" import collections import json import pathlib @@ -13,6 +6,7 @@ import urllib.parse import urllib.request +USAGE = "Usage: python3 sarif_summary.py <title> <file.sarif or directory> [...]" MAX_LISTED = 50 @@ -69,9 +63,10 @@ def cell(text): def main(): """Prints the summary for the title and SARIF paths given on the command line.""" if len(sys.argv) < 3: - sys.exit(__doc__) + sys.exit(USAGE) title, files = sys.argv[1], sarif_files(sys.argv[2:]) if not files: + # An analyzer that silently wrote nothing must not read as a clean result. sys.exit(f"::error title={title}::No SARIF file found in {' '.join(sys.argv[2:])}") # The same finding in a shared header is reported once per source file that includes it. rows = list(dict.fromkeys(findings(files))) From 3b24a8d21ed140e978f54650bdac82ef1fb03838 Mon Sep 17 00:00:00 2001 From: Arif Burak Demiray <burakdemiray09@hotmail.com> Date: Thu, 12 Nov 2026 22:10:18 +0300 Subject: [PATCH 3/3] ci: fail pull requests on new static analysis findings --- .github/scripts/sarif_summary.py | 136 +++++++++++++++++++------- .github/workflows/static_analysis.yml | 42 ++++++-- 2 files changed, 132 insertions(+), 46 deletions(-) diff --git a/.github/scripts/sarif_summary.py b/.github/scripts/sarif_summary.py index 31faaec..a741a42 100644 --- a/.github/scripts/sarif_summary.py +++ b/.github/scripts/sarif_summary.py @@ -1,13 +1,16 @@ -"""Writes a Markdown summary of static analysis results stored as SARIF: findings per rule, then the first 50.""" +"""Summarizes SARIF static analysis results as Markdown and, given the base's results, fails on new findings.""" +import argparse import collections import json import pathlib +import re import sys import urllib.parse import urllib.request -USAGE = "Usage: python3 sarif_summary.py <title> <file.sarif or directory> [...]" MAX_LISTED = 50 +GATED_LEVELS = ("error", "warning") +Finding = collections.namedtuple("Finding", "rule level description path line column message") def sarif_files(arguments): @@ -19,69 +22,128 @@ def sarif_files(arguments): return files -def relative_path(uri): - """Returns the path of a SARIF artifact URI, relative to the working directory when it lies inside it.""" +def relative_path(uri, root): + """Returns the path of a SARIF artifact URI, relative to root when it lies inside it.""" parsed = urllib.parse.urlparse(uri) path = urllib.request.url2pathname(parsed.path) if parsed.scheme == "file" else urllib.parse.unquote(uri) try: - return pathlib.Path(path).resolve().relative_to(pathlib.Path.cwd().resolve()).as_posix() + return (root / path).resolve().relative_to(root.resolve()).as_posix() except (ValueError, OSError): return pathlib.PurePath(path).as_posix() -def location(result): - """Returns 'path:line' for the first location of a result.""" - for loc in result.get("locations", []): - physical = loc.get("physicalLocation", {}) - path = relative_path(physical.get("artifactLocation", {}).get("uri", "")) - line = physical.get("region", {}).get("startLine") - return f"{path}:{line}" if line else path - return "" +def artifact_uri(location, base_ids): + """Returns the artifact URI of a SARIF location, resolved against its uriBaseId when the run defines it.""" + uri = location.get("uri", "") + base = base_ids.get(location.get("uriBaseId"), {}).get("uri") + return urllib.parse.urljoin(base, uri) if base else uri -def findings(files): - """Yields (rule, level, description, location, message) for every result in the SARIF files.""" +def findings(files, root): + """Yields every distinct finding in the SARIF files, with paths relative to root.""" + seen = set() for file in files: for run in json.loads(file.read_text(encoding="utf-8-sig")).get("runs", []): - driver = run.get("tool", {}).get("driver", {}) - rules = {rule.get("id"): rule for rule in driver.get("rules", [])} + rules = {rule.get("id"): rule for rule in run.get("tool", {}).get("driver", {}).get("rules", [])} + base_ids = run.get("originalUriBaseIds", {}) for result in run.get("results", []): rule_id = result.get("ruleId") or result.get("rule", {}).get("id", "unknown") rule = rules.get(rule_id, {}) - level = result.get("level") or rule.get("defaultConfiguration", {}).get("level", "warning") - description = (rule.get("shortDescription", {}).get("text") - or rule.get("fullDescription", {}).get("text") or rule.get("helpUri", "")) - message = result.get("message", {}).get("text", "").splitlines()[0] if result.get("message") else "" - yield rule_id, level, description, location(result), message + physical = (result.get("locations") or [{}])[0].get("physicalLocation", {}) + finding = Finding( + rule_id, + result.get("level") or rule.get("defaultConfiguration", {}).get("level", "warning"), + rule.get("shortDescription", {}).get("text") + or rule.get("fullDescription", {}).get("text") or rule.get("helpUri", ""), + relative_path(artifact_uri(physical.get("artifactLocation", {}), base_ids), root), + physical.get("region", {}).get("startLine"), + physical.get("region", {}).get("startColumn"), + (result.get("message", {}).get("text") or "").split("\n")[0], + ) + # The same finding in a shared header is reported once per source file that includes it. + if finding not in seen: + seen.add(finding) + yield finding + + +def fingerprint(finding): + """Returns what identifies a finding across commits: rule, file and message, with numbers masked.""" + return finding.rule, finding.path, re.sub(r"\d+", "#", finding.message) def cell(text): """Escapes text for a Markdown table cell.""" - return text.replace("|", "\\|").replace("\n", " ")[:160] + return str(text).replace("|", "\\|").replace("\n", " ")[:160] -def main(): - """Prints the summary for the title and SARIF paths given on the command line.""" - if len(sys.argv) < 3: - sys.exit(USAGE) - title, files = sys.argv[1], sarif_files(sys.argv[2:]) - if not files: - # An analyzer that silently wrote nothing must not read as a clean result. - sys.exit(f"::error title={title}::No SARIF file found in {' '.join(sys.argv[2:])}") - # The same finding in a shared header is reported once per source file that includes it. - rows = list(dict.fromkeys(findings(files))) +def where(finding): + """Returns 'path:line', or the path alone when the finding has no line.""" + return f"{finding.path}:{finding.line}" if finding.line else finding.path + + +def print_summary(title, rows): + """Prints the findings per rule and level, then the first findings with their location.""" print(f"### {title}: {len(rows)} finding{'s' if len(rows) != 1 else ''}\n") if not rows: return - counts = collections.Counter((rule, level, description) for rule, level, description, _, _ in rows) + counts = collections.Counter((row.rule, row.level, row.description) for row in rows) print("| Rule | Level | Count | Description |\n|---|---|---|---|") for (rule, level, description), count in sorted(counts.items(), key=lambda item: (-item[1], item[0])): print(f"| {cell(rule)} | {level} | {count} | {cell(description)} |") print(f"\n<details><summary>First {min(MAX_LISTED, len(rows))} findings</summary>\n") print("| Location | Rule | Message |\n|---|---|---|") - for rule, _, _, where, message in sorted(rows, key=lambda row: row[3])[:MAX_LISTED]: - print(f"| {cell(where)} | {cell(rule)} | {cell(message)} |") - print("\n</details>") + for row in sorted(rows, key=lambda row: (row.path, row.line or 0))[:MAX_LISTED]: + print(f"| {cell(where(row))} | {cell(row.rule)} | {cell(row.message)} |") + print("\n</details>\n") + + +def print_new(title, rows, base_rows): + """Prints the findings that outnumber the base's findings with the same fingerprint; returns the gated count.""" + base_counts = collections.Counter(fingerprint(row) for row in base_rows) + groups = collections.defaultdict(list) + for row in rows: + groups[fingerprint(row)].append(row) + new = {key: group for key, group in groups.items() if len(group) > base_counts[key]} + added = sum(len(group) - base_counts[key] for key, group in new.items()) + gated = sum(len(group) - base_counts[key] for key, group in new.items() if group[0].level in GATED_LEVELS) + print(f"### New compared with the base branch: {added}\n") + if not new: + print("No finding that the base branch does not have.\n") + return 0 + print("| Location | Rule | Level | Message | Base | Head |\n|---|---|---|---|---|---|") + for key, group in sorted(new.items()): + locations = ", ".join(where(row) for row in group[:5]) + (", ..." if len(group) > 5 else "") + print(f"| {cell(locations)} | {cell(key[0])} | {group[0].level} | {cell(group[0].message)} " + f"| {base_counts[key]} | {len(group)} |") + print() + if gated: + print(f"::error title={title}::{gated} new finding{'s' if gated != 1 else ''} at " + f"{' or '.join(GATED_LEVELS)} level: fix or suppress them, the job summary lists them.", file=sys.stderr) + return gated + + +def load(title, paths, root): + """Returns the findings of the SARIF files under paths, failing when there is no SARIF at all.""" + files = sarif_files(paths) + if not files: + # An analyzer that silently wrote nothing must not read as a clean result. + sys.exit(f"::error title={title}::No SARIF file found in {' '.join(paths)}") + return list(findings(files, root)) + + +def main(): + """Prints the summary; with --base, also the new findings, and exits with 1 when any is gated.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("title", help="the analyzer's name, used as the heading") + parser.add_argument("sarif", nargs="+", help="SARIF files or directories of the working directory's analysis") + parser.add_argument("--base", nargs="+", help="SARIF files or directories of the pull request base's analysis") + parser.add_argument("--base-root", default=".", help="the base checkout, which the base's paths are relative to") + arguments = parser.parse_args() + rows = load(arguments.title, arguments.sarif, pathlib.Path.cwd()) + print_summary(arguments.title, rows) + if arguments.base and print_new(arguments.title, rows, + load(arguments.title, arguments.base, pathlib.Path(arguments.base_root))): + sys.exit(1) if __name__ == "__main__": diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml index cdcd4f8..c6e7ce7 100644 --- a/.github/workflows/static_analysis.yml +++ b/.github/workflows/static_analysis.yml @@ -19,6 +19,7 @@ jobs: steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: + fetch-depth: 2 submodules: recursive persist-credentials: false @@ -27,17 +28,40 @@ jobs: sudo apt-get -qq update sudo apt-get -qq install -y --no-install-recommends clang-18 clang-tidy-18 libcurl4-openssl-dev libssl-dev - # Report-only: the findings go to the job summary and never fail the job, only a clang-tidy failure does. + # On pull requests the base branch is analyzed too, so that only findings it lacks can fail the job. - name: Analyze the SDK run: | - cmake -DCOUNTLY_USE_SQLITE=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 -B build . - if ! run-clang-tidy-18 -clang-tidy-binary clang-tidy-18 -p build -quiet -header-filter="^$PWD/(include|src)/" \ - -checks='-*,bugprone-*,clang-analyzer-*,concurrency-*,performance-*,portability-*,-bugprone-easily-swappable-parameters' \ - "^$PWD/src/" > "$RUNNER_TEMP/clang-tidy.log" 2>&1; then - tail -n 50 "$RUNNER_TEMP/clang-tidy.log" - exit 1 + # Runs clang-tidy over the sources of the checkout in $1 and writes the findings as SARIF to $2.sarif. + analyze() { + cd "$1" + cmake -DCOUNTLY_USE_SQLITE=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 -B build . + # run-clang-tidy analyzes nothing, and reports nothing, when its file pattern matches no source. + if ! grep -qF "\"file\": \"$PWD/src/" build/compile_commands.json; then + echo "::error title=clang-tidy::The compilation database has no source under $PWD/src" + exit 1 + fi + if ! run-clang-tidy-18 -clang-tidy-binary clang-tidy-18 -p build -quiet -header-filter="^$PWD/(include|src)/" \ + -checks='-*,bugprone-*,clang-analyzer-*,concurrency-*,performance-*,portability-*,-bugprone-easily-swappable-parameters' \ + "^$PWD/src/" > "$2.log" 2>&1; then + tail -n 50 "$2.log" + exit 1 + fi + python3 "$GITHUB_WORKSPACE/.github/scripts/clang_tidy_sarif.py" "$2.log" "$2.sarif" + cd "$GITHUB_WORKSPACE" + } + analyze "$GITHUB_WORKSPACE" "$RUNNER_TEMP/clang-tidy" + if [ "$GITHUB_EVENT_NAME" = pull_request ]; then + # The first parent of the pull request's merge commit is the base branch it merges into. + git worktree add "$RUNNER_TEMP/base" HEAD^1 + git -C "$RUNNER_TEMP/base" submodule update --init --recursive + analyze "$RUNNER_TEMP/base" "$RUNNER_TEMP/clang-tidy-base" fi - python3 .github/scripts/clang_tidy_sarif.py "$RUNNER_TEMP/clang-tidy.log" "$RUNNER_TEMP/clang-tidy.sarif" + # Every finding goes to the job summary; a new one at warning or error level fails the job. - name: Summarize the findings - run: python3 .github/scripts/sarif_summary.py clang-tidy "$RUNNER_TEMP/clang-tidy.sarif" >> "$GITHUB_STEP_SUMMARY" + run: | + base=() + if [ -f "$RUNNER_TEMP/clang-tidy-base.sarif" ]; then + base=(--base "$RUNNER_TEMP/clang-tidy-base.sarif" --base-root "$RUNNER_TEMP/base") + fi + python3 .github/scripts/sarif_summary.py clang-tidy "$RUNNER_TEMP/clang-tidy.sarif" "${base[@]}" | tee -a "$GITHUB_STEP_SUMMARY"