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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
27 changes: 27 additions & 0 deletions .github/actions/ci-plan/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Select CI checks
description: Select checks from the full Git diff of the commit or merge result
outputs:
csharp:
description: Run C# validation
value: ${{ steps.plan.outputs.csharp }}
cpp:
description: Run C++ validation
value: ${{ steps.plan.outputs.cpp }}
documentation:
description: Build API documentation
value: ${{ steps.plan.outputs.documentation }}
workflows:
description: Run workflow and script lint
value: ${{ steps.plan.outputs.workflows }}
badges:
description: Validate README, evidence Markdown and benchmark results
value: ${{ steps.plan.outputs.badges }}
runs:
using: composite
steps:
- name: Compare the checked out merge or push commit against its base
id: plan
shell: bash
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
run: node "$GITHUB_ACTION_PATH/../../scripts/plan-ci.mjs"
36 changes: 36 additions & 0 deletions .github/scripts/check-codeql-results.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

export const findings = (reports) => {
if (reports.length === 0 || reports.some((report) =>
!Array.isArray(report.runs) || report.runs.length === 0 ||
report.runs.some((run) => !Array.isArray(run.results)))) {
throw new Error("CodeQL did not produce a complete SARIF report.");
}
return reports.flatMap((report) =>
report.runs.flatMap((run) => run.results.map((result) => {
const location = result.locations?.[0]?.physicalLocation;
const file = location?.artifactLocation?.uri ?? "(location unavailable)";
const line = location?.region?.startLine ?? "?";
return `${file}:${line} ${result.ruleId ?? "(rule unavailable)"}`;
})));
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
const directory = process.argv[2];
const reports = readdirSync(directory).filter((entry) => entry.endsWith(".sarif"))
.map((entry) => JSON.parse(readFileSync(join(directory, entry), "utf8")));
const results = findings(reports);
if (results.length > 0) {
console.error(`CodeQL reported ${results.length} findings:\n${results.join("\n")}`);
process.exitCode = 1;
} else {
console.log("CodeQL reported zero findings.");
}
} catch (error) {
console.error(`CodeQL results could not be checked: ${error.message}`);
process.exitCode = 1;
}
}
26 changes: 26 additions & 0 deletions .github/scripts/check-codeql-results.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import test from "node:test";
import { findings } from "./check-codeql-results.mjs";

test("a completed analysis with no findings is green", () => {
assert.deepEqual(findings([{ runs: [{ results: [] }] }]), []);
});

test("a successful analyzer process still fails the quality gate when it finds an alert", () => {
const result = {
ruleId: "cs/useless-cast-to-self",
locations: [{ physicalLocation: {
artifactLocation: { uri: "csharp/TestExtensions.cs" },
region: { startLine: 22 },
} }],
};
assert.deepEqual(findings([{ runs: [{ results: [result] }] }]), [
"csharp/TestExtensions.cs:22 cs/useless-cast-to-self",
]);
});

test("a missing or malformed report fails closed", () => {
for (const reports of [[], [{}], [{ runs: [] }], [{ runs: [{}] }]]) {
assert.throws(() => findings(reports), /complete SARIF report/);
}
});
2 changes: 1 addition & 1 deletion .github/scripts/check-cpp-nuget-package.sh
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ cat > "$work/project/nuget.config" <<XML
</packageSourceMapping>
</configuration>
XML
dotnet restore "$work/project/check.csproj" --packages "$work/packages"
dotnet restore "$work/project/check.csproj" --packages "$work/packages" -warnaserror -p:NuGetAuditMode=all

lowercase() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
extracted="$work/packages/$(lowercase "$id")/$version"
Expand Down
4 changes: 2 additions & 2 deletions .github/scripts/check-csharp-nuget-consumer.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ fi

properties=(-p:CollectionsMethodsVersion="$version" -p:TargetFramework="${CONSUMER_FRAMEWORK:-net8.0}")
dotnet restore NuGetConsumer.csproj --nologo --packages "$work/packages" \
-p:RestoreNoCache=true -p:RestoreNoHttpCache=true "${sources[@]}" "${properties[@]}"
dotnet build NuGetConsumer.csproj --nologo --no-restore --configuration Release "${properties[@]}"
-warnaserror -p:NuGetAuditMode=all -p:RestoreNoCache=true -p:RestoreNoHttpCache=true "${sources[@]}" "${properties[@]}"
dotnet build NuGetConsumer.csproj --nologo --no-restore --configuration Release -warnaserror "${properties[@]}"
29 changes: 22 additions & 7 deletions .github/scripts/check-csharp-pipeline-status.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,27 @@ const allJobNames = [
"generatePdfWithCode",
"buildDocumentation",
"publishDocumentation",
"deployDocumentation",
];

export const evaluatePipeline = ({ eventName, documentationChanged, needs }) => {
// The tests, their full coverage and the self-validating trees gate every run.
const required = new Set(["test", "coverage", "treeValidation", "findChangedCsFiles"]);
export const evaluatePipeline = ({ csharpChanged, eventName, documentationChanged, releaseExpected, needs }) => {
const required = new Set(["findChangedCsFiles"]);
if (csharpChanged) {
required.add("test");
required.add("coverage");
required.add("treeValidation");
}

if (documentationChanged) {
required.add("generatePdfWithCode");
required.add("buildDocumentation");
required.add("publishDocumentation");
if (eventName === "push") {
required.add("deployDocumentation");
}
}

if (eventName === "push") {
if (releaseExpected) {
required.add("releasePreflight");
required.add("pushNuGetPackageToGitHubPackageRegistry");
required.add("pushToNuget");
Expand All @@ -38,15 +46,20 @@ export const evaluatePipeline = ({ eventName, documentationChanged, needs }) =>
failures.push(`${name}: result is missing`);
} else if (required.has(name) && result !== "success") {
failures.push(`${name}: required job finished with ${result}`);
} else if (!required.has(name) && !["success", "skipped"].includes(result)) {
failures.push(`${name}: optional job finished with ${result}`);
} else if (!required.has(name) && result !== "skipped") {
failures.push(`${name}: expected a skip, job finished with ${result}`);
}
}

return { passed: failures.length === 0, failures };
};

export const run = (environment = process.env) => {
if ([environment.CSHARP_CHANGED, environment.DOCUMENTATION_CHANGED, environment.RELEASE_EXPECTED]
.some((value) => value !== "true" && value !== "false")) {
console.error("::error title=C# pipeline status invalid::The CI plan did not provide every job selection.");
return 1;
}
let needs;
try {
needs = JSON.parse(environment.NEEDS_JSON ?? "");
Expand All @@ -56,16 +69,18 @@ export const run = (environment = process.env) => {
}

const result = evaluatePipeline({
csharpChanged: environment.CSHARP_CHANGED === "true",
eventName: environment.EVENT_NAME ?? "",
documentationChanged: environment.DOCUMENTATION_CHANGED === "true",
releaseExpected: environment.RELEASE_EXPECTED === "true",
needs,
});

for (const failure of result.failures) {
console.error(`::error title=C# pipeline failed::${failure}`);
}
if (result.passed) {
console.log("Every required C# pipeline job succeeded.");
console.log("Every selected C# pipeline job succeeded.");
}
return result.passed ? 0 : 1;
};
Expand Down
34 changes: 27 additions & 7 deletions .github/scripts/check-csharp-pipeline-status.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import assert from "node:assert/strict";
import test from "node:test";
import { evaluatePipeline } from "./check-csharp-pipeline-status.mjs";
import { evaluatePipeline, run } from "./check-csharp-pipeline-status.mjs";

const results = (overrides = {}) =>
Object.fromEntries(
Expand All @@ -18,6 +18,7 @@ const results = (overrides = {}) =>
"generatePdfWithCode",
"buildDocumentation",
"publishDocumentation",
"deployDocumentation",
].map((name) => [name, { result: overrides[name] ?? "skipped" }]),
);

Expand All @@ -32,7 +33,7 @@ test("accepts a pull request after validation and documentation builds pass", ()
publishDocumentation: "success",
});
assert.deepEqual(
evaluatePipeline({ eventName: "pull_request", documentationChanged: true, needs }),
evaluatePipeline({ eventName: "pull_request", csharpChanged: true, documentationChanged: true, needs }),
{ passed: true, failures: [] },
);
});
Expand All @@ -47,7 +48,7 @@ test("rejects a skipped documentation assembly on pull requests", () => {
buildDocumentation: "success",
});
assert.deepEqual(
evaluatePipeline({ eventName: "pull_request", documentationChanged: true, needs }),
evaluatePipeline({ eventName: "pull_request", csharpChanged: true, documentationChanged: true, needs }),
{
passed: false,
failures: ["publishDocumentation: required job finished with skipped"],
Expand All @@ -67,7 +68,7 @@ test("accepts expected documentation skips when no maintained input changed", ()
findChangedCsFiles: "success",
});
assert.deepEqual(
evaluatePipeline({ eventName: "push", documentationChanged: false, needs }),
evaluatePipeline({ eventName: "push", csharpChanged: true, releaseExpected: true, documentationChanged: false, needs }),
{ passed: true, failures: [] },
);
});
Expand All @@ -84,7 +85,7 @@ test("turns a failed publish and its skipped release into an explicit failure",
findChangedCsFiles: "success",
});
const result = evaluatePipeline({
eventName: "push",
eventName: "push", csharpChanged: true, releaseExpected: true,
documentationChanged: false,
needs,
});
Expand All @@ -104,7 +105,7 @@ test("rejects a pull request whose coverage or tree validation failed", () => {
findChangedCsFiles: "success",
});
const result = evaluatePipeline({
eventName: "pull_request",
eventName: "pull_request", csharpChanged: true,
documentationChanged: false,
needs,
});
Expand All @@ -122,11 +123,30 @@ test("reports cancelled jobs instead of allowing a grey timeout", () => {
findChangedCsFiles: "skipped",
});
const result = evaluatePipeline({
eventName: "pull_request",
eventName: "pull_request", csharpChanged: true,
documentationChanged: false,
needs,
});

assert.equal(result.passed, false);
assert.match(result.failures.join("\n"), /test: required job finished with cancelled/);
});

test("allows unrelated changes to skip tests with a successful planner", () => {
const needs = results({ findChangedCsFiles: "success" });
assert.deepEqual(evaluatePipeline({ eventName: "pull_request", needs }), { passed: true, failures: [] });
});

test("rejects a successful planner that omitted a job selection", () => {
assert.equal(run({
CSHARP_CHANGED: "false",
DOCUMENTATION_CHANGED: "false",
NEEDS_JSON: JSON.stringify(results({ findChangedCsFiles: "success" })),
}), 1);
});

test("rejects an unexpected PR publication", () => {
const needs = results({ findChangedCsFiles: "success", deployDocumentation: "success" });
const result = evaluatePipeline({ eventName: "pull_request", needs });
assert.deepEqual(result.failures, ["deployDocumentation: expected a skip, job finished with success"]);
});
45 changes: 45 additions & 0 deletions .github/scripts/check-dependabot-health.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const ageLimitDays = 14;
const day = 86_400_000;

export const overdueUpdates = (pages, now) => {
if (!Array.isArray(pages) || pages.length === 0 || pages.some((page) => !Array.isArray(page))) {
throw new Error("Expected paginated pull request results.");
}
const overdue = [];
for (const pull of pages.flat()) {
if (pull.state !== "open" || pull.user?.login !== "dependabot[bot]") {
continue;
}
const age = (now - Date.parse(pull.created_at)) / day;
if (!Number.isFinite(age) || !Number.isSafeInteger(pull.number)) {
throw new Error("An open Dependabot pull request has invalid metadata.");
}
if (age > ageLimitDays) {
overdue.push({ number: pull.number, age: Math.floor(age) });
}
}
return overdue;
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
const repository = process.env.GITHUB_REPOSITORY;
if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) {
throw new Error("Set GITHUB_REPOSITORY to owner/repository.");
}
const response = execFileSync("gh", ["api", "--paginate", "--slurp",
`repos/${repository}/pulls?state=open&per_page=100`], { encoding: "utf8" });
const updates = overdueUpdates(JSON.parse(response), Date.now());
for (const { number, age } of updates) {
console.error(`::error title=Overdue Dependabot update::PR #${number} has been open for ${age} days. Review it or close it if superseded. https://github.com/${repository}/pull/${number}`);
}
console.log(`${updates.length} open Dependabot updates older than ${ageLimitDays} days.`);
process.exitCode = updates.length === 0 ? 0 : 1;
} catch (error) {
console.error(`Dependabot health check failed: ${error.message}`);
process.exitCode = 1;
}
}
19 changes: 19 additions & 0 deletions .github/scripts/check-dependabot-health.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import test from "node:test";
import { overdueUpdates } from "./check-dependabot-health.mjs";

const now = Date.parse("2026-11-30T00:00:00Z");
const bot = { state: "open", user: { login: "dependabot[bot]" }, created_at: "2026-11-15T00:00:00Z" };

test("reports overdue open Dependabot updates across all pages", () => {
const pages = [[{ ...bot, number: 1, state: "closed" },
{ ...bot, number: 2, user: { login: "human" } },
{ ...bot, number: 3, created_at: "2026-11-16T00:00:00Z" }],
[{ ...bot, number: 4 }]];
assert.deepEqual(overdueUpdates(pages, now), [{ number: 4, age: 15 }]);
});

test("fails on an unexpected response or invalid Dependabot creation date", () => {
assert.throws(() => overdueUpdates([{ message: "API error" }], now), /paginated/);
assert.throws(() => overdueUpdates([[{ ...bot, number: 4, created_at: "bad" }]], now), /invalid metadata/);
});
21 changes: 21 additions & 0 deletions .github/scripts/check-file-sizes.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { execFileSync } from "node:child_process";
import { lstatSync, readFileSync } from "node:fs";

const code = /(?:\.(?:c|cc|cpp|cs|h|hpp|mjs|py|sh|ya?ml)|\/CMakeLists\.txt)$/i;
const documentation = /\.md$/i;

const paths = execFileSync("git", ["ls-files", "-z", "--",
".github", "benchmarks", "cpp", "csharp", "experiments", "README.md"], { encoding: "utf8" });

for (const path of paths.split("\0")) {
const limit = code.test(path) ? 1500 : documentation.test(path) ? 2500 : 0;
if (limit === 0 || !lstatSync(path).isFile()) {
continue;
}
const file = readFileSync(path, "utf8");
const lines = file.split("\n").length - Number(file.endsWith("\n") || file === "");
if (lines > limit) {
console.error(`${JSON.stringify(path)} has ${lines} lines. The limit is ${limit}.`);
process.exitCode = 1;
}
}
8 changes: 4 additions & 4 deletions .github/scripts/codeql-workflow-policy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ test("does not duplicate the repositories' language build pipelines", () => {
});

test("uses action versions backed by the current Node runtime", () => {
assert.match(workflow, /actions\/checkout@v7/);
assert.match(workflow, /github\/codeql-action\/init@v4/);
assert.match(workflow, /github\/codeql-action\/analyze@v4/);
assert.match(workflow, /actions\/checkout@[0-9a-f]{40} # v7/);
assert.match(workflow, /github\/codeql-action\/init@[0-9a-f]{40} # v4/);
assert.match(workflow, /github\/codeql-action\/analyze@[0-9a-f]{40} # v4/);
assert.doesNotMatch(workflow, /actions\/setup-dotnet@/);
});

Expand All @@ -40,7 +40,7 @@ test("prevents checkout's default-branch warning", () => {
});

test("reviews dependency changes on pull requests", () => {
assert.match(workflow, /actions\/dependency-review-action@v5/);
assert.match(workflow, /actions\/dependency-review-action@[0-9a-f]{40} # v5/);
assert.match(workflow, /fail-on-severity: high/);
});

Expand Down
Loading
Loading