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
39 changes: 39 additions & 0 deletions .github/actions/setup/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Setup .NET
description: Install the SDK pinned by global.json, warm the NuGet cache and restore.

inputs:
solution:
required: false
default: EpochSim.slnx
restore:
required: false
default: 'true'
cache:
required: false
default: 'true'

runs:
using: composite
steps:
- shell: bash
run: |
{
echo "NUGET_PACKAGES=${GITHUB_WORKSPACE}/.nuget/packages"
echo "DOTNET_NOLOGO=true"
echo "DOTNET_CLI_TELEMETRY_OPTOUT=true"
} >> "$GITHUB_ENV"

- uses: actions/setup-dotnet@v6
with:
global-json-file: global.json

- if: inputs.cache == 'true'
uses: actions/cache@v6
with:
path: ${{ github.workspace }}/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('**/packages.lock.json', '**/*.csproj', '**/*.props', 'global.json') }}
restore-keys: nuget-${{ runner.os }}-

- if: inputs.restore == 'true'
shell: bash
run: dotnet restore "${{ inputs.solution }}"
31 changes: 31 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
version: 2

updates:
- package-ecosystem: github-actions
directories: [/, /.github/actions/setup]
schedule:
interval: weekly
day: monday
commit-message:
prefix: ci
groups:
actions:
patterns: ['*']

- package-ecosystem: nuget
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 10
commit-message:
prefix: deps
groups:
test-tooling:
patterns: ['xunit*', 'MSTest*', 'NUnit*', 'Microsoft.NET.Test.Sdk', 'coverlet*']
roslyn:
patterns: ['Microsoft.CodeAnalysis*']
minor-and-patch:
update-types: [minor, patch]
ignore:
- dependency-name: EpochSim*
104 changes: 104 additions & 0 deletions .github/scripts/audit_packages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
import argparse
import json
import os
import sys
from pathlib import Path

SEVERITIES = ["low", "moderate", "high", "critical"]


def load(path: str | None) -> dict:
if not path:
return {}
file = Path(path)
if not file.is_file() or not file.stat().st_size:
return {}
try:
return json.loads(file.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return {}


def walk(report: dict):
for project in report.get("projects", []):
name = Path(project.get("path", "?")).stem
for framework in project.get("frameworks") or []:
for key in ("topLevelPackages", "transitivePackages"):
for package in framework.get(key) or []:
yield name, package, key == "transitivePackages"


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--vulnerable", help="json from dotnet list package --vulnerable")
parser.add_argument("--deprecated", help="json from dotnet list package --deprecated")
parser.add_argument("--fail-on", choices=SEVERITIES + ["never"], default="moderate")
args = parser.parse_args()

floor = SEVERITIES.index(args.fail_on) if args.fail_on != "never" else len(SEVERITIES)

findings = []
for project, package, transitive in walk(load(args.vulnerable)):
for advisory in package.get("vulnerabilities") or []:
findings.append({
"project": project,
"id": package.get("id", "?"),
"version": package.get("resolvedVersion") or package.get("requestedVersion", "?"),
"severity": (advisory.get("severity") or "unknown").lower(),
"url": advisory.get("advisoryurl") or advisory.get("advisoryUrl", ""),
"transitive": transitive,
})

deprecations = [
(project, package.get("id", "?"), package.get("resolvedVersion", "?"),
", ".join(package.get("deprecationReasons") or []))
for project, package, _ in walk(load(args.deprecated))
if package.get("deprecationReasons")
]

blocking = [f for f in findings
if f["severity"] in SEVERITIES and SEVERITIES.index(f["severity"]) >= floor]

lines = [f"## Dependency audit: {'failed' if blocking else 'passed'}", ""]
if findings:
lines += [
f"**{len(findings)} advisory finding(s)**, {len(blocking)} at or above `{args.fail_on}`.",
"",
"| Package | Scope | Version | Severity | Project | Advisory |",
"|---|---|---|---|---|---|",
]
rank = lambda f: SEVERITIES.index(f["severity"]) if f["severity"] in SEVERITIES else -1
for finding in sorted(findings, key=rank, reverse=True):
link = f"[details]({finding['url']})" if finding["url"] else "n/a"
lines.append(
f"| `{finding['id']}` | {'transitive' if finding['transitive'] else 'direct'} | "
f"{finding['version']} | {finding['severity']} | "
f"`{finding['project']}` | {link} |"
)
lines.append("")
else:
lines += ["No known advisories against any direct or transitive package.", ""]

if deprecations:
lines += ["<details><summary>Deprecated packages</summary>", "",
"| Package | Version | Project | Reason |", "|---|---|---|---|"]
lines += [f"| `{pkg}` | {version} | `{project}` | {reason} |"
for project, pkg, version, reason in deprecations]
lines += ["", "</details>", ""]

report = "\n".join(lines)
print(report)
if path := os.environ.get("GITHUB_STEP_SUMMARY"):
with open(path, "a", encoding="utf-8") as handle:
handle.write(report + "\n")

for finding in blocking:
print(f"::error title=Vulnerable package::{finding['id']} {finding['version']} "
f"({finding['severity']}) in {finding['project']} {finding['url']}")

return 1 if blocking else 0


if __name__ == "__main__":
sys.exit(main())
106 changes: 106 additions & 0 deletions .github/scripts/coverage_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
import argparse
import os
import sys
import xml.etree.ElementTree as ET
from pathlib import Path


def bar(rate: float, width: int = 20) -> str:
filled = round(rate * width)
return "#" * filled + "." * (width - filled)


def counters(node: ET.Element) -> tuple[int, int, int, int]:
lines_covered = lines_valid = branches_covered = branches_valid = 0
for line in node.iter("line"):
lines_valid += 1
if int(line.get("hits", "0")) > 0:
lines_covered += 1
coverage = line.get("condition-coverage", "") if line.get("branch") == "True" else ""
if "(" in coverage and "/" in coverage:
covered, valid = coverage.split("(", 1)[1].rstrip(")").split("/")
branches_covered += int(covered)
branches_valid += int(valid)
return lines_covered, lines_valid, branches_covered, branches_valid


def gather(paths: list[str]) -> list[Path]:
files: list[Path] = []
for raw in paths:
path = Path(raw)
if path.is_dir():
files.extend(sorted(path.rglob("*.cobertura.xml")))
elif path.is_file():
files.append(path)
return files


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("paths", nargs="+", help="cobertura files or directories to scan")
parser.add_argument("--min-line", type=float, default=0.0)
parser.add_argument("--min-branch", type=float, default=0.0)
parser.add_argument("--title", default="Coverage")
args = parser.parse_args()

files = gather(args.paths)
if not files:
emit(f"## {args.title}: no data\n\n> No Cobertura report was produced.\n")
return 1

packages: dict[str, list[int]] = {}
total = [0, 0, 0, 0]
for file in files:
for package in ET.parse(file).getroot().iter("package"):
slot = packages.setdefault(package.get("name") or "(unnamed)", [0, 0, 0, 0])
for index, value in enumerate(counters(package)):
slot[index] += value
total[index] += value

line_rate = total[0] / total[1] if total[1] else 0.0
branch_rate = total[2] / total[3] if total[3] else 0.0
min_line = args.min_line / 100
min_branch = args.min_branch / 100
ok = line_rate >= min_line and branch_rate >= min_branch

lines = [
f"## {args.title}: {'passed' if ok else 'failed'}",
"",
f"`{bar(line_rate)}` **{line_rate * 100:.1f}%** lines ({total[0]}/{total[1]}), floor {args.min_line:.0f}%",
"",
f"`{bar(branch_rate)}` **{branch_rate * 100:.1f}%** branches ({total[2]}/{total[3]}), floor {args.min_branch:.0f}%",
"",
"| Result | Assembly | Lines | Branches |",
"|---|---|---:|---:|",
]
for name, (lc, lv, bc, bv) in sorted(packages.items(), key=lambda kv: kv[1][0] / max(kv[1][1], 1)):
rate = lc / lv if lv else 0.0
lines.append(
f"| {'ok' if rate >= min_line else 'FAIL'} | `{name}` | "
f"{rate * 100:.1f}% <sub>{lc}/{lv}</sub> | "
f"{(bc / bv * 100) if bv else 0:.1f}% <sub>{bc}/{bv}</sub> |"
)
lines.append("")

if not ok:
lines += [f"> Below the floor: lines {line_rate * 100:.1f}%, branches {branch_rate * 100:.1f}%.", ""]

emit("\n".join(lines))

if path := os.environ.get("GITHUB_OUTPUT"):
with open(path, "a", encoding="utf-8") as handle:
handle.write(f"line-rate={line_rate * 100:.1f}\nbranch-rate={branch_rate * 100:.1f}\n")

return 0 if ok else 1


def emit(report: str) -> None:
print(report)
if path := os.environ.get("GITHUB_STEP_SUMMARY"):
with open(path, "a", encoding="utf-8") as handle:
handle.write(report + "\n")


if __name__ == "__main__":
sys.exit(main())
33 changes: 33 additions & 0 deletions .github/scripts/nuget_push.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -euo pipefail

: "${NUGET_API_KEY:?NUGET_API_KEY is not set}"

source=https://api.nuget.org/v3/index.json
failed=0

if [ "$#" -eq 0 ]; then
echo "::error::nuget_push.sh got no packages to push"
exit 1
fi

for package in "$@"; do
echo "::group::push ${package##*/}"
if output=$(dotnet nuget push "$package" \
--source "$source" \
--api-key "$NUGET_API_KEY" \
--skip-duplicate 2>&1); then
echo "$output"
else
echo "$output"
if grep -qiE 'already exists|conflict|409' <<<"$output"; then
echo "::notice::${package##*/} is already on nuget.org, skipping"
else
echo "::error::failed to push ${package##*/}"
failed=1
fi
fi
echo "::endgroup::"
done

exit "$failed"
Loading
Loading