Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions .github/scripts/clang_tidy_sarif.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""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 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())
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(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))


if __name__ == "__main__":
main()
150 changes: 150 additions & 0 deletions .github/scripts/sarif_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""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

MAX_LISTED = 50
GATED_LEVELS = ("error", "warning")
Finding = collections.namedtuple("Finding", "rule level description path line column message")


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, 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 (root / path).resolve().relative_to(root.resolve()).as_posix()
except (ValueError, OSError):
return pathlib.PurePath(path).as_posix()


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, 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", []):
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, {})
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 str(text).replace("|", "\\|").replace("\n", " ")[:160]


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((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 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__":
main()
67 changes: 67 additions & 0 deletions .github/workflows/static_analysis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
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:
fetch-depth: 2
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

# On pull requests the base branch is analyzed too, so that only findings it lacks can fail the job.
- name: Analyze the SDK
run: |
# 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

# Every finding goes to the job summary; a new one at warning or error level fails the job.
- name: Summarize the findings
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"
Loading