diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml new file mode 100644 index 0000000..8a9df61 --- /dev/null +++ b/.github/codeql/codeql-config.yml @@ -0,0 +1,18 @@ +name: Collections.Methods CodeQL config + +# Both excluded queries only report the way the C++ tests and benchmarks are +# built, not defects. Every other query of the security-extended and +# security-and-quality suites still runs. +query-filters: + # The C++ tests and benchmarks are unity builds: AllTests.cpp and + # AllBenchmarks.cpp include the other .cpp files of their directory, as in + # every linksplatform C++ library, so each is one translation unit. + - exclude: + id: cpp/include-non-header + # Without a build (build-mode: none) the Google Test and Google Benchmark + # headers, which CMake fetches at configure time, are missing, so CodeQL + # cannot tell that benchmark::State is a type and reads the function + # template "void AttachAndDetach(benchmark::State& state)" as a static + # variable initialized with "benchmark::State & state". + - exclude: + id: cpp/unused-static-variable diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aec207e..2c408a6 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,4 +4,13 @@ updates: directory: "/" schedule: interval: daily + cooldown: + default-days: 7 + open-pull-requests-limit: 10 +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + cooldown: + default-days: 7 open-pull-requests-limit: 10 diff --git a/.github/scripts/check-cpp-nuget-package.sh b/.github/scripts/check-cpp-nuget-package.sh new file mode 100755 index 0000000..5b73591 --- /dev/null +++ b/.github/scripts/check-cpp-nuget-package.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# Consume the packed C++ NuGet package the way a project does, so a package +# that packs but cannot be used fails before it is published. Adapted from +# link-foundation/cpp-ai-driven-development-pipeline-template +# (scripts/check-nuget-package.sh): push it to a local folder feed, let +# `dotnet restore` extract it through (which skips the TFM +# check that a native package fails in an SDK-style project), check the MSBuild +# targets and headers, then compile a program against the restored headers. +# +# Usage: check-cpp-nuget-package.sh +# Environment: +# CXX C++20 compiler for the consumer program (default: c++) +# VERBOSE=1 or RUNNER_DEBUG=1 traces every command (off by default) +set -euo pipefail + +if [ "${VERBOSE:-}" = 1 ] || [ "${RUNNER_DEBUG:-}" = 1 ]; then + set -x +fi + +package="${1:?Usage: check-cpp-nuget-package.sh }" +package="$(cd "$(dirname "$package")" && pwd)/$(basename "$package")" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# ..nupkg; the version is the last three dot-separated fields. +name="$(basename "$package" .nupkg)" +version="$(printf '%s\n' "$name" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+([-+].*)?$')" +id="${name%."$version"}" + +# Native dependencies of the package, as "id version" lines. PackageDownload +# does not restore dependencies, so each one is downloaded from nuget.org. +dependencies="$(unzip -p "$package" "$id.nuspec" | grep -oE '" +while read -r dependency_id dependency_version; do + [ -n "$dependency_id" ] || continue + downloads+="" +done <<< "$dependencies" +cat > "$work/project/check.csproj" < + netstandard2.0truetrue + $downloads + +XML +# The package under test comes only from the local feed; its dependencies only from nuget.org. +cat > "$work/project/nuget.config" < + + + + + + +XML +dotnet restore "$work/project/check.csproj" --packages "$work/packages" + +lowercase() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; } +extracted="$work/packages/$(lowercase "$id")/$version" +include_flags=(-I "$extracted/lib/native/include") +while read -r dependency_id dependency_version; do + [ -n "$dependency_id" ] || continue + include_flags+=(-I "$work/packages/$(lowercase "$dependency_id")/$dependency_version/lib/native/include") +done <<< "$dependencies" +# nuget.org shows README.md, which carries the benchmark results. +if ! grep -q '' "$extracted/README.md" 2>/dev/null; then + echo "::error title=C++ NuGet package unusable::README.md with the benchmark results is missing" + exit 1 +fi +if [ ! -f "$extracted/build/native/$id.targets" ]; then + echo "::error title=C++ NuGet package unusable::build/native/$id.targets is missing" + exit 1 +fi +if ! grep -q 'lib\\native\\include' "$extracted/build/native/$id.targets"; then + echo "::error title=C++ NuGet package unusable::build/native/$id.targets does not add lib/native/include to the include path" + exit 1 +fi + +# The nuspec tells users to include Platform.Collections.Methods.h only, so it +# has to pull in every header it needs from the package and its dependencies. +# The consumer builds a small size balanced tree with the restored headers. +cat > "$work/consumer.cpp" <<'CPP' +#include +#include + +using namespace Platform::Collections::Methods::Trees; + +struct Tree : SizeBalancedTreeMethods +{ + struct Node { std::uint32_t Left, Right, Size; } Nodes[8]{}; + std::uint32_t Root = 0; + std::uint32_t* GetLeftReference(std::uint32_t node) { return &Nodes[node].Left; } + std::uint32_t* GetRightReference(std::uint32_t node) { return &Nodes[node].Right; } + std::uint32_t GetLeft(std::uint32_t node) { return Nodes[node].Left; } + std::uint32_t GetRight(std::uint32_t node) { return Nodes[node].Right; } + std::uint32_t GetSize(std::uint32_t node) { return Nodes[node].Size; } + void SetLeft(std::uint32_t node, std::uint32_t left) { Nodes[node].Left = left; } + void SetRight(std::uint32_t node, std::uint32_t right) { Nodes[node].Right = right; } + void SetSize(std::uint32_t node, std::uint32_t size) { Nodes[node].Size = size; } + bool FirstIsToTheLeftOfSecond(std::uint32_t first, std::uint32_t second) { return first < second; } + bool FirstIsToTheRightOfSecond(std::uint32_t first, std::uint32_t second) { return first > second; } + void ClearNode(std::uint32_t node) { Nodes[node] = {}; } +}; + +int main() +{ + Tree tree; + for (std::uint32_t node = 1; node < 8; node++) + { + tree.Attach(&tree.Root, node); + } + // 1..7 attached in ascending order form the perfect tree of height 3 rooted at 4. + return tree.Root == 4 && tree.GetSize(tree.Root) == 7 ? 0 : 1; +} +CPP +if ! "${CXX:-c++}" -std=c++20 "${include_flags[@]}" -o "$work/consumer" "$work/consumer.cpp"; then + echo "::error title=C++ NuGet package unusable::A program that includes Platform.Collections.Methods.h from the restored package does not compile" + exit 1 +fi +if ! "$work/consumer"; then + echo "::error title=C++ NuGet package unusable::A size balanced tree built with the restored headers has a wrong shape" + exit 1 +fi +echo "NuGet restore and use of $id $version: OK" diff --git a/.github/scripts/check-cpp-nuget-package.test.mjs b/.github/scripts/check-cpp-nuget-package.test.mjs new file mode 100644 index 0000000..7fe663d --- /dev/null +++ b/.github/scripts/check-cpp-nuget-package.test.mjs @@ -0,0 +1,67 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, test } from "node:test"; + +// Packs the real package once, then checks it and broken copies of it with +// the real dotnet client and compiler, so this needs the .NET SDK, zip and c++. +const script = new URL("./check-cpp-nuget-package.sh", import.meta.url).pathname; +const packScript = new URL("./pack-cpp-nuget.mjs", import.meta.url).pathname; +const missing = ["dotnet", "zip", "c++"].filter( + (tool) => spawnSync("bash", ["-c", `command -v ${tool}`]).status !== 0, +); +const options = { skip: missing.length > 0 && `${missing.join(", ")} not installed`, timeout: 300_000 }; + +let directory; +let packed; +before(() => { + if (missing.length > 0) { + return; + } + directory = mkdtempSync(path.join(tmpdir(), "check-cpp-nuget-")); + const pack = spawnSync("node", [packScript, path.join(directory, "packed")], { encoding: "utf8" }); + assert.equal(pack.status, 0, pack.stdout + pack.stderr); + const name = readdirSync(path.join(directory, "packed")).find((file) => file.endsWith(".nupkg")); + packed = path.join(directory, "packed", name); +}); +after(() => directory && rmSync(directory, { recursive: true, force: true })); + +// Copies the package into its own folder, deletes `entries` from it and checks it. +const checkWithout = (label, entries) => { + const copy = path.join(directory, label, path.basename(packed)); + spawnSync("mkdir", ["-p", path.dirname(copy)]); + copyFileSync(packed, copy); + if (entries.length > 0) { + const zip = spawnSync("zip", ["-q", "-d", copy, ...entries], { encoding: "utf8" }); + assert.equal(zip.status, 0, zip.stderr); + } + return spawnSync("bash", [script, copy], { encoding: "utf8" }); +}; + +test("restores and compiles against the packed package", options, () => { + const result = checkWithout("complete", []); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.match(result.stdout, /NuGet restore and use of Platform\.Collections\.Methods\.TemplateLibrary .*: OK/); +}); + +test("fails when the README with the benchmark results is missing", options, () => { + const result = checkWithout("no-readme", ["README.md"]); + assert.notEqual(result.status, 0); + assert.match(result.stdout, /README\.md with the benchmark results is missing/); +}); + +test("fails when the MSBuild targets are missing", options, () => { + const result = checkWithout("no-targets", ["build/native/*"]); + assert.notEqual(result.status, 0); + assert.match(result.stdout, /::error title=C\+\+ NuGet package unusable::build\/native\/.*\.targets is missing/); +}); + +test("fails when a header that Platform.Collections.Methods.h includes is missing", options, () => { + const result = checkWithout("no-header", ["lib/native/include/Trees/SizeBalancedTreeMethods.h"]); + assert.notEqual(result.status, 0); + assert.match(result.stdout, /does not compile/); +}); diff --git a/.github/scripts/check-csharp-coverage.mjs b/.github/scripts/check-csharp-coverage.mjs new file mode 100644 index 0000000..df1013e --- /dev/null +++ b/.github/scripts/check-csharp-coverage.mjs @@ -0,0 +1,122 @@ +#!/usr/bin/env node + +/** + * Require full line coverage of the library by the C# tests. + * + * Reads the Cobertura reports that coverlet writes for + * `dotnet test --collect "XPlat Code Coverage"` and fails with the file and + * line of every library line that no test executed. Only the package named + * by --package (default: Platform.Collections.Methods) is checked, so test + * and benchmark code does not count. + * + * Usage: node check-csharp-coverage.mjs [--package ] [--verbose] ... + * `--verbose`, VERBOSE=1 or RUNNER_DEBUG=1 prints the coverage of every file. + * Writes a Markdown summary to GITHUB_STEP_SUMMARY when it is set. File names + * are reported relative to GITHUB_WORKSPACE (or the current directory), so + * the annotations point at the repository files. + */ + +import { appendFileSync, readFileSync } from "node:fs"; +import { isAbsolute, join, relative } from "node:path"; + +const attribute = (element, name) => new RegExp(`\\b${name}="([^"]*)"`).exec(element)?.[1]; + +// Line hits of every class of the package: Map>. +// Hits of the same line in several classes (e.g. nested or partial classes, +// or several reports) are summed, so a line counts as covered if any run hit it. +export const collectLines = (reports, packageName, files = new Map(), root = undefined) => { + let found = false; + for (const report of reports) { + // coverlet writes class file names relative to the single directory. + const source = /([^<]*)<\/source>/.exec(report)?.[1]; + const resolve = (file) => { + const path = source && !isAbsolute(file) ? join(source, file) : file; + return root && isAbsolute(path) ? relative(root, path) : path; + }; + const packagePattern = /]*>[\s\S]*?<\/package>/g; + for (const [packageSource] of report.matchAll(packagePattern)) { + if (attribute(packageSource.slice(0, packageSource.indexOf(">")), "name") !== packageName) { + continue; + } + found = true; + for (const [classSource] of packageSource.matchAll(/]*>[\s\S]*?<\/class>/g)) { + const file = resolve(attribute(classSource.slice(0, classSource.indexOf(">")), "filename")); + const lines = files.get(file) ?? new Map(); + files.set(file, lines); + // Method bodies repeat the class lines; the class level list is enough. + const classLines = classSource.slice(classSource.lastIndexOf("") + 1); + for (const [line] of classLines.matchAll(/]*>/g)) { + const number = Number(attribute(line, "number")); + lines.set(number, (lines.get(number) ?? 0) + Number(attribute(line, "hits"))); + } + } + } + } + if (!found) { + throw new Error(`No coverage report contains the package ${packageName}`); + } + return files; +}; + +export const summarize = (files) => { + const summary = [...files].map(([file, lines]) => { + const missed = [...lines].filter(([, hits]) => hits === 0).map(([number]) => number).sort((a, b) => a - b); + return { file, total: lines.size, missed }; + }); + summary.sort((a, b) => a.file.localeCompare(b.file)); + const total = summary.reduce((sum, { total: lines }) => sum + lines, 0); + const missed = summary.reduce((sum, file) => sum + file.missed.length, 0); + return { files: summary, total, covered: total - missed }; +}; + +const percent = ({ total, covered }) => (total === 0 ? 100 : (100 * covered) / total).toFixed(2); + +export const run = (args = process.argv.slice(2), environment = process.env) => { + let verbose = environment.VERBOSE === "1" || environment.RUNNER_DEBUG === "1"; + let packageName = "Platform.Collections.Methods"; + const paths = []; + for (let index = 0; index < args.length; index++) { + if (args[index] === "--verbose") { + verbose = true; + } else if (args[index] === "--package") { + packageName = args[++index]; + } else { + paths.push(args[index]); + } + } + if (paths.length === 0 || !packageName) { + console.error("Usage: node check-csharp-coverage.mjs [--package ] [--verbose] ..."); + return 2; + } + + let result; + try { + const reports = paths.map((path) => readFileSync(path, "utf8")); + result = summarize(collectLines(reports, packageName, new Map(), environment.GITHUB_WORKSPACE || process.cwd())); + } catch (error) { + console.error(`::error title=C# coverage check failed::${error.message}`); + return 1; + } + + const rows = result.files.map((file) => `| ${file.file} | ${percent({ total: file.total, covered: file.total - file.missed.length })}% | ${file.missed.join(", ")} |`); + if (verbose) { + console.log(rows.join("\n")); + } + if (environment.GITHUB_STEP_SUMMARY) { + appendFileSync( + environment.GITHUB_STEP_SUMMARY, + [`### C# line coverage of ${packageName}: ${percent(result)}%`, "", "| File | Lines | Missed lines |", "| --- | --- | --- |", ...rows, ""].join("\n"), + ); + } + for (const file of result.files) { + for (const line of file.missed) { + console.error(`::error file=${file.file},line=${line},title=Line not covered::No C# test executes this line.`); + } + } + console.log(`${packageName}: ${result.covered} of ${result.total} lines covered (${percent(result)}%).`); + return result.covered === result.total ? 0 : 1; +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = run(); +} diff --git a/.github/scripts/check-csharp-coverage.test.mjs b/.github/scripts/check-csharp-coverage.test.mjs new file mode 100644 index 0000000..a889061 --- /dev/null +++ b/.github/scripts/check-csharp-coverage.test.mjs @@ -0,0 +1,134 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { collectLines, run, summarize } from "./check-csharp-coverage.mjs"; + +const report = (packages) => ` + + +${packages} + +`; + +const classSource = (file, lines) => ` + + + +${lines.map(([number, hits]) => ` `).join("\n")} + + + + +${lines.map(([number, hits]) => ` `).join("\n")} + + `; + +const packageSource = (name, classes) => ` + +${classes.join("\n")} + + `; + +const library = "Platform.Collections.Methods"; + +const withReports = (sources, callback) => { + const directory = mkdtempSync(join(tmpdir(), "coverage-")); + try { + const paths = sources.map((source, index) => { + const path = join(directory, `coverage${index}.cobertura.xml`); + writeFileSync(path, source); + return path; + }); + return callback(paths, directory); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const capture = (callback) => { + const errors = []; + const logs = []; + const { error, log } = console; + console.error = (message) => errors.push(message); + console.log = (message) => logs.push(message); + try { + return { status: callback(), errors, logs }; + } finally { + console.error = error; + console.log = log; + } +}; + +test("counts only the library package and each line once per class", () => { + const source = report( + [ + packageSource(library, [classSource("Trees/A.cs", [[1, 2], [2, 0]])]), + packageSource("Platform.Collections.Methods.Tests", [classSource("Tests/T.cs", [[1, 0]])]), + ].join("\n"), + ); + const summary = summarize(collectLines([source], library)); + assert.deepEqual(summary, { files: [{ file: "Trees/A.cs", total: 2, missed: [2] }], total: 2, covered: 1 }); +}); + +test("treats a line hit in any report or class as covered", () => { + const first = report(packageSource(library, [classSource("Trees/A.cs", [[1, 0], [2, 1]])])); + const second = report(packageSource(library, [classSource("Trees/A.cs", [[1, 3], [2, 0]])])); + assert.deepEqual(summarize(collectLines([first, second], library)).covered, 2); +}); + +test("fails with the file and line of every uncovered line", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 1], [7, 0]]), classSource("Lists/B.cs", [[3, 0]])])); + withReports([source], (paths, directory) => { + const summaryPath = join(directory, "summary.md"); + const { status, errors, logs } = capture(() => run(paths, { GITHUB_STEP_SUMMARY: summaryPath })); + assert.equal(status, 1); + assert.deepEqual(errors, [ + "::error file=Lists/B.cs,line=3,title=Line not covered::No C# test executes this line.", + "::error file=Trees/A.cs,line=7,title=Line not covered::No C# test executes this line.", + ]); + assert.deepEqual(logs, [`${library}: 1 of 3 lines covered (33.33%).`]); + assert.match(readFileSync(summaryPath, "utf8"), /\| Trees\/A\.cs \| 50\.00% \| 7 \|/); + }); +}); + +test("passes when every line is covered", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 1], [2, 4]])])); + withReports([source], (paths) => { + const { status, errors } = capture(() => run(["--verbose", ...paths], {})); + assert.equal(status, 0); + assert.deepEqual(errors, []); + }); +}); + +test("fails when the report has no such package instead of passing vacuously", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 1]])])); + withReports([source], (paths) => { + const { status, errors } = capture(() => run(["--package", "Other", ...paths], {})); + assert.equal(status, 1); + assert.deepEqual(errors, ["::error title=C# coverage check failed::No coverage report contains the package Other"]); + }); +}); + +test("reports files relative to the workspace, so annotations find them", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 0]])])).replace( + " ", + " \n /work/repo/csharp/Platform.Collections.Methods/\n \n ", + ); + withReports([source], (paths) => { + const { status, errors } = capture(() => run(paths, { GITHUB_WORKSPACE: "/work/repo" })); + assert.equal(status, 1); + assert.deepEqual(errors, [ + "::error file=csharp/Platform.Collections.Methods/Trees/A.cs,line=1,title=Line not covered::No C# test executes this line.", + ]); + }); +}); + +test("prints the usage without reports", () => { + const { status, errors } = capture(() => run([], {})); + assert.equal(status, 2); + assert.match(errors[0], /^Usage:/); +}); diff --git a/.github/scripts/check-csharp-pipeline-status.mjs b/.github/scripts/check-csharp-pipeline-status.mjs new file mode 100644 index 0000000..b5a85a2 --- /dev/null +++ b/.github/scripts/check-csharp-pipeline-status.mjs @@ -0,0 +1,75 @@ +#!/usr/bin/env node + +const allJobNames = [ + "test", + "coverage", + "treeValidation", + "releasePreflight", + "pushNuGetPackageToGitHubPackageRegistry", + "pushToNuget", + "publishRelease", + "findChangedCsFiles", + "generatePdfWithCode", + "buildDocumentation", + "publishDocumentation", +]; + +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"]); + + if (documentationChanged) { + required.add("generatePdfWithCode"); + required.add("buildDocumentation"); + required.add("publishDocumentation"); + } + + if (eventName === "push") { + required.add("releasePreflight"); + required.add("pushNuGetPackageToGitHubPackageRegistry"); + required.add("pushToNuget"); + required.add("publishRelease"); + } + + const failures = []; + for (const name of allJobNames) { + const result = needs[name]?.result; + if (!result) { + 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}`); + } + } + + return { passed: failures.length === 0, failures }; +}; + +export const run = (environment = process.env) => { + let needs; + try { + needs = JSON.parse(environment.NEEDS_JSON ?? ""); + } catch (error) { + console.error(`::error title=C# pipeline status invalid::${error.message}`); + return 1; + } + + const result = evaluatePipeline({ + eventName: environment.EVENT_NAME ?? "", + documentationChanged: environment.DOCUMENTATION_CHANGED === "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."); + } + return result.passed ? 0 : 1; +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = run(); +} diff --git a/.github/scripts/check-csharp-pipeline-status.test.mjs b/.github/scripts/check-csharp-pipeline-status.test.mjs new file mode 100644 index 0000000..be77c73 --- /dev/null +++ b/.github/scripts/check-csharp-pipeline-status.test.mjs @@ -0,0 +1,132 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import test from "node:test"; +import { evaluatePipeline } from "./check-csharp-pipeline-status.mjs"; + +const results = (overrides = {}) => + Object.fromEntries( + [ + "test", + "coverage", + "treeValidation", + "releasePreflight", + "pushNuGetPackageToGitHubPackageRegistry", + "pushToNuget", + "publishRelease", + "findChangedCsFiles", + "generatePdfWithCode", + "buildDocumentation", + "publishDocumentation", + ].map((name) => [name, { result: overrides[name] ?? "skipped" }]), + ); + +test("accepts a pull request after validation and documentation builds pass", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + findChangedCsFiles: "success", + generatePdfWithCode: "success", + buildDocumentation: "success", + publishDocumentation: "success", + }); + assert.deepEqual( + evaluatePipeline({ eventName: "pull_request", documentationChanged: true, needs }), + { passed: true, failures: [] }, + ); +}); + +test("rejects a skipped documentation assembly on pull requests", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + findChangedCsFiles: "success", + generatePdfWithCode: "success", + buildDocumentation: "success", + }); + assert.deepEqual( + evaluatePipeline({ eventName: "pull_request", documentationChanged: true, needs }), + { + passed: false, + failures: ["publishDocumentation: required job finished with skipped"], + }, + ); +}); + +test("accepts expected documentation skips when no maintained input changed", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + releasePreflight: "success", + pushNuGetPackageToGitHubPackageRegistry: "success", + pushToNuget: "success", + publishRelease: "success", + findChangedCsFiles: "success", + }); + assert.deepEqual( + evaluatePipeline({ eventName: "push", documentationChanged: false, needs }), + { passed: true, failures: [] }, + ); +}); + +test("turns a failed publish and its skipped release into an explicit failure", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + releasePreflight: "success", + pushNuGetPackageToGitHubPackageRegistry: "success", + pushToNuget: "failure", + publishRelease: "skipped", + findChangedCsFiles: "success", + }); + const result = evaluatePipeline({ + eventName: "push", + documentationChanged: false, + needs, + }); + + assert.equal(result.passed, false); + assert.deepEqual(result.failures, [ + "pushToNuget: required job finished with failure", + "publishRelease: required job finished with skipped", + ]); +}); + +test("rejects a pull request whose coverage or tree validation failed", () => { + const needs = results({ + test: "success", + coverage: "failure", + treeValidation: "skipped", + findChangedCsFiles: "success", + }); + const result = evaluatePipeline({ + eventName: "pull_request", + documentationChanged: false, + needs, + }); + + assert.equal(result.passed, false); + assert.deepEqual(result.failures, [ + "coverage: required job finished with failure", + "treeValidation: required job finished with skipped", + ]); +}); + +test("reports cancelled jobs instead of allowing a grey timeout", () => { + const needs = results({ + test: "cancelled", + findChangedCsFiles: "skipped", + }); + const result = evaluatePipeline({ + eventName: "pull_request", + documentationChanged: false, + needs, + }); + + assert.equal(result.passed, false); + assert.match(result.failures.join("\n"), /test: required job finished with cancelled/); +}); diff --git a/.github/scripts/check-readme-badges.mjs b/.github/scripts/check-readme-badges.mjs new file mode 100644 index 0000000..43439bb --- /dev/null +++ b/.github/scripts/check-readme-badges.mjs @@ -0,0 +1,160 @@ +#!/usr/bin/env node + +/** + * Verifies that every GitHub Actions badge in README.md points at a workflow + * that actually exists in .github/workflows. + * + * Background (linksplatform/Interfaces#141): the C++ badge used + * https://github.com/linksplatform/Interfaces/workflows/deploy-cpp/badge.svg + * The path segment after /workflows/ must be the workflow *name* (the `name:` + * field inside the YAML file), not the file name. No workflow is named + * "deploy-cpp" (deploy-cpp.yml is named "Deploy new cpp version"), so GitHub + * answered 404 and the badge rendered as a broken image. + * + * Usage: + * node .github/scripts/check-readme-badges.mjs [--verbose] + * [--readme ] [--workflows ] + * + * --readme and --workflows default to this repository's README.md and + * .github/workflows, and exist so the test suite can point the check at + * fixtures. + * + * Exits with code 1 and a description of every unresolved badge when a badge + * references a workflow that does not exist. + */ + +import { readFileSync, readdirSync, existsSync } from "fs"; +import { join, dirname, resolve } from "path"; +import { fileURLToPath } from "url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repositoryRoot = resolve(__dirname, "..", ".."); + +const readOption = (option, fallback) => { + const index = process.argv.indexOf(option); + return index === -1 || index === process.argv.length - 1 + ? fallback + : resolve(process.argv[index + 1]); +}; + +const workflowsDirectory = readOption("--workflows", join(repositoryRoot, ".github", "workflows")); +const readmePath = readOption("--readme", join(repositoryRoot, "README.md")); + +const verbose = process.argv.includes("--verbose"); +const trace = (...args) => { + if (verbose) { + console.log("[trace]", ...args); + } +}; + +/** Reads the top-level `name:` of a workflow file, unquoting it when needed. */ +const readWorkflowName = (filePath) => { + const nameLine = readFileSync(filePath, "utf8") + .split(/\r?\n/) + .find((line) => /^name:\s*\S/.test(line)); + if (!nameLine) { + return null; + } + return nameLine.replace(/^name:\s*/, "").trim().replace(/^["'](.*)["']$/, "$1"); +}; + +const collectWorkflows = () => { + if (!existsSync(workflowsDirectory)) { + return []; + } + return readdirSync(workflowsDirectory) + .filter((fileName) => /\.ya?ml$/.test(fileName)) + .map((fileName) => ({ + fileName, + name: readWorkflowName(join(workflowsDirectory, fileName)), + })); +}; + +/** + * `actions?workflow=Deploy+new+cpp+version` encodes spaces as `+`, while + * `workflows/Deploy%20new%20cpp%20version/badge.svg` encodes them as `%20`. + */ +const decodeWorkflowReference = (value, isQueryParameter) => + decodeURIComponent(isQueryParameter ? value.replace(/\+/g, "%20") : value); + +/** Every way README.md can refer to a workflow of this repository. */ +const referencePatterns = [ + { + kind: "badge (workflow name)", + pattern: /https:\/\/github\.com\/[^/\s)]+\/[^/\s)]+\/workflows\/([^/\s)]+)\/badge\.svg/g, + resolve: (match) => ({ by: "name", value: decodeWorkflowReference(match[1], false) }), + }, + { + kind: "link (workflow name)", + pattern: /https:\/\/github\.com\/[^/\s)]+\/[^/\s)]+\/actions\?workflow=([^\s)]+)/g, + resolve: (match) => ({ by: "name", value: decodeWorkflowReference(match[1], true) }), + }, + { + // Covers both the badge form (.../actions/workflows//badge.svg) and the + // plain link form (.../actions/workflows/). The trailing boundary keeps + // the capture from backtracking into a truncated file name such as "cpp-test.ym". + kind: "workflow file", + pattern: /https:\/\/github\.com\/[^/\s)]+\/[^/\s)]+\/actions\/workflows\/([^/\s)?#]+)(\/badge\.svg)?(?=[\s)?#]|$)/g, + resolve: (match) => ({ + kind: match[2] ? "badge (workflow file)" : "link (workflow file)", + by: "file", + value: decodeWorkflowReference(match[1], false), + }), + }, +]; + +const collectReferences = (readme) => { + const references = []; + for (const { kind, pattern, resolve: resolveReference } of referencePatterns) { + for (const match of readme.matchAll(pattern)) { + references.push({ kind, url: match[0], ...resolveReference(match) }); + } + } + return references; +}; + +const main = () => { + const workflows = collectWorkflows(); + const readme = readFileSync(readmePath, "utf8"); + const references = collectReferences(readme); + + trace(`workflows directory: ${workflowsDirectory}`); + for (const workflow of workflows) { + trace(`workflow ${workflow.fileName} -> name ${JSON.stringify(workflow.name)}`); + } + trace(`found ${references.length} workflow reference(s) in README.md`); + + const knownNames = workflows.map((workflow) => workflow.name).filter(Boolean); + const knownFiles = workflows.map((workflow) => workflow.fileName); + + const failures = []; + for (const reference of references) { + const known = reference.by === "name" ? knownNames : knownFiles; + const resolved = known.includes(reference.value); + trace(`${resolved ? "ok" : "FAIL"} ${reference.kind} by ${reference.by}: ${JSON.stringify(reference.value)}`); + if (!resolved) { + failures.push(reference); + } + } + + if (references.length === 0) { + console.error("No GitHub Actions badges found in README.md, the check would pass vacuously."); + process.exit(1); + } + + if (failures.length > 0) { + console.error(`README.md references ${failures.length} workflow(s) that do not exist:\n`); + for (const failure of failures) { + console.error(` ${failure.kind}: ${failure.url}`); + console.error(` referenced workflow ${failure.by}: ${JSON.stringify(failure.value)}`); + } + console.error(`\nAvailable workflow names: ${knownNames.map((name) => JSON.stringify(name)).join(", ")}`); + console.error(`Available workflow files: ${knownFiles.join(", ")}`); + console.error("\nThe segment after /workflows/ is the workflow `name:`, not the file name."); + process.exit(1); + } + + console.log(`All ${references.length} workflow reference(s) in README.md resolve to existing workflows.`); +}; + +main(); diff --git a/.github/scripts/check-readme-badges.test.mjs b/.github/scripts/check-readme-badges.test.mjs new file mode 100644 index 0000000..758ad52 --- /dev/null +++ b/.github/scripts/check-readme-badges.test.mjs @@ -0,0 +1,112 @@ +#!/usr/bin/env node + +/** + * Tests for check-readme-badges.mjs. + * + * Run with: node --test .github/scripts/check-readme-badges.test.mjs + */ + +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { join, dirname, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; + +const scriptPath = join(dirname(fileURLToPath(import.meta.url)), "check-readme-badges.mjs"); +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); + +/** Workflows mirroring the real ones, so the fixtures stay realistic. */ +const workflowFixtures = { + "cpp-test.yml": "name: Test cpp\n", + "csharp.yml": "name: csharp\n", + "deploy-cpp.yml": "name: Deploy new cpp version\n", + "quoted.yml": 'name: "Quoted name"\n', +}; + +/** Runs the check against a throwaway README and workflow directory. */ +const runCheck = (readmeContents) => { + const directory = mkdtempSync(join(tmpdir(), "readme-badges-")); + try { + const workflowsDirectory = join(directory, "workflows"); + mkdirSync(workflowsDirectory); + for (const [fileName, contents] of Object.entries(workflowFixtures)) { + writeFileSync(join(workflowsDirectory, fileName), contents); + } + const readmePath = join(directory, "README.md"); + writeFileSync(readmePath, readmeContents); + + const result = spawnSync( + process.execPath, + [scriptPath, "--readme", readmePath, "--workflows", workflowsDirectory, "--verbose"], + { encoding: "utf8" }, + ); + return { status: result.status, output: `${result.stdout}${result.stderr}` }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const badge = (path) => `[![Actions Status](https://github.com/linksplatform/Collections.Methods/${path})](https://github.com/linksplatform/Collections.Methods/actions)`; + +test("rejects the badge that broke in linksplatform/Interfaces#141", () => { + const { status, output } = runCheck(badge("workflows/deploy-cpp/badge.svg")); + assert.equal(status, 1); + assert.match(output, /workflow\(s\) that do not exist/); + assert.match(output, /"deploy-cpp"/); +}); + +test("accepts a badge naming an existing workflow", () => { + const { status, output } = runCheck(badge("workflows/Test%20cpp/badge.svg")); + assert.equal(status, 0, output); + assert.match(output, /ok badge \(workflow name\) by name: "Test cpp"/); +}); + +test("accepts the actions/workflows badge form without truncating the file name", () => { + const { status, output } = runCheck(badge("actions/workflows/cpp-test.yml/badge.svg")); + assert.equal(status, 0, output); + assert.match(output, /ok badge \(workflow file\) by file: "cpp-test\.yml"/); + assert.doesNotMatch(output, /cpp-test\.ym"/); +}); + +test("accepts a plain actions/workflows link", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions/workflows/csharp.yml)`); + assert.equal(status, 0, output); + assert.match(output, /ok link \(workflow file\) by file: "csharp\.yml"/); +}); + +test("rejects a link to a workflow file that does not exist", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions/workflows/missing.yml)`); + assert.equal(status, 1); + assert.match(output, /"missing\.yml"/); +}); + +test("decodes + as a space in actions?workflow= links", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions?workflow=Deploy+new+cpp+version)`); + assert.equal(status, 0, output); + assert.match(output, /ok link \(workflow name\) by name: "Deploy new cpp version"/); +}); + +test("decodes %20 as a space in actions?workflow= links", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions?workflow=Test%20cpp)`); + assert.equal(status, 0, output); + assert.match(output, /ok link \(workflow name\) by name: "Test cpp"/); +}); + +test("reads a quoted workflow name", () => { + const { status, output } = runCheck(badge("workflows/Quoted%20name/badge.svg")); + assert.equal(status, 0, output); + assert.match(output, /ok badge \(workflow name\) by name: "Quoted name"/); +}); + +test("fails when README has no workflow badges at all", () => { + const { status, output } = runCheck("# Collections.Methods\n\nNo badges here.\n"); + assert.equal(status, 1); + assert.match(output, /No GitHub Actions badges found/); +}); + +test("the real README of this repository passes the check", () => { + const result = spawnSync(process.execPath, [scriptPath], { cwd: repositoryRoot, encoding: "utf8" }); + assert.equal(result.status, 0, `${result.stdout}${result.stderr}`); +}); diff --git a/.github/scripts/codeql-workflow-policy.test.mjs b/.github/scripts/codeql-workflow-policy.test.mjs new file mode 100644 index 0000000..0f26e44 --- /dev/null +++ b/.github/scripts/codeql-workflow-policy.test.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const workflowPath = new URL("../workflows/codeql.yml", import.meta.url); +const workflow = readFileSync(workflowPath, "utf8"); + +test("uses current CodeQL language identifiers and build-free extraction", () => { + assert.match(workflow, /language: \[ 'actions', 'c-cpp', 'csharp' \]/); + assert.match(workflow, /build-mode: none/); + assert.doesNotMatch(workflow, /language: \[ 'cpp'/); + assert.doesNotMatch(workflow, /build-mode: manual/); +}); + +test("does not duplicate the repositories' language build pipelines", () => { + assert.doesNotMatch(workflow, /apt-get/); + assert.doesNotMatch(workflow, /dotnet (?:restore|build)/); + assert.doesNotMatch(workflow, /cmake/); +}); + +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.doesNotMatch(workflow, /actions\/setup-dotnet@/); +}); + +test("pins the runner and disables persisted checkout credentials", () => { + assert.match(workflow, /runs-on: ubuntu-24\.04/); + assert.doesNotMatch(workflow, /runs-on: ubuntu-latest/); + assert.match(workflow, /persist-credentials: false/); +}); + +test("prevents checkout's default-branch warning", () => { + assert.match(workflow, /GIT_CONFIG_COUNT: '1'/); + assert.match(workflow, /GIT_CONFIG_KEY_0: init\.defaultBranch/); + assert.match(workflow, /GIT_CONFIG_VALUE_0: main/); +}); + +test("reviews dependency changes on pull requests", () => { + assert.match(workflow, /actions\/dependency-review-action@v5/); + assert.match(workflow, /fail-on-severity: high/); +}); + +test("turns off the C# feed check that warns about an empty feed set", () => { + // github/codeql#22766: the check logs "No NuGet feeds are reachable" for an + // empty set even when nuget.org is reachable. + assert.match(workflow, /CODEQL_EXTRACTOR_CSHARP_BUILDLESS_NUGET_FEEDS_CHECK: 'false'/); +}); + +test("excludes only the queries that report the unity builds of the C++ tests and benchmarks", () => { + assert.match(workflow, /config-file: \.\/\.github\/codeql\/codeql-config\.yml/); + const config = readFileSync(new URL("../codeql/codeql-config.yml", import.meta.url), "utf8"); + const excluded = [...config.matchAll(/^\s+id: (\S+)$/gm)].map(([, id]) => id); + assert.deepEqual(excluded, ["cpp/include-non-header", "cpp/unused-static-variable"]); + assert.doesNotMatch(config, /paths-ignore|disable-default-queries/); +}); diff --git a/.github/scripts/cpp-build-and-test.test.mjs b/.github/scripts/cpp-build-and-test.test.mjs new file mode 100644 index 0000000..59c9bc3 --- /dev/null +++ b/.github/scripts/cpp-build-and-test.test.mjs @@ -0,0 +1,99 @@ +#!/usr/bin/env node + +// Runs cpp/build-and-test.sh against stub cmake and ctest commands that log +// their arguments, so the options CI passes through the environment are +// checked without building anything. + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const script = fileURLToPath(new URL("../../cpp/build-and-test.sh", import.meta.url)); + +const runWithStubs = (environment = {}, failing = "") => { + const bin = mkdtempSync(join(tmpdir(), "cmake-stub-")); + try { + for (const tool of ["cmake", "ctest"]) { + writeFileSync( + join(bin, tool), + [ + "#!/usr/bin/env bash", + `printf '${tool}' >> "${join(bin, "calls")}"`, + `printf ' [%s]' "$@" >> "${join(bin, "calls")}"`, + `echo >> "${join(bin, "calls")}"`, + tool === failing ? "exit 7" : "exit 0", + "", + ].join("\n"), + ); + chmodSync(join(bin, tool), 0o755); + } + const result = spawnSync("bash", [script], { + encoding: "utf8", + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + VERBOSE: "", + RUNNER_DEBUG: "", + BUILD_TYPE: "", + SANITIZERS: "", + TREE_VALIDATION: "", + COVERAGE: "", + BENCHMARKS: "", + CMAKE_ARGS: "", + ...environment, + }, + }); + let calls = []; + try { + calls = readFileSync(join(bin, "calls"), "utf8").trim().split("\n"); + } catch { + // No tool was called. + } + return { ...result, calls }; + } finally { + rmSync(bin, { recursive: true, force: true }); + } +}; + +test("configures, builds and runs the tests, failing when no test ran", () => { + const { status, calls } = runWithStubs(); + assert.equal(status, 0); + assert.equal(calls.length, 3); + assert.match(calls[0], /^cmake \[-S\] \[\.\] \[-B\] \[build\] \[-DCMAKE_BUILD_TYPE=Release\] \[-DLINKS_PLATFORM_TESTS=ON\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_BENCHMARKS=OFF\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_TREE_VALIDATION=OFF\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_COVERAGE=OFF\]/); + assert.equal(calls[1], "cmake [--build] [build] [--config] [Release] [--parallel]"); + assert.match(calls[2], /^ctest .*\[--build-config\] \[Release\].*\[--no-tests=error\]/); +}); + +test("passes the CI options through to CMake", () => { + const { status, calls } = runWithStubs({ + BUILD_TYPE: "Debug", + SANITIZERS: "address;undefined", + TREE_VALIDATION: "1", + COVERAGE: "1", + BENCHMARKS: "1", + CMAKE_ARGS: "-DA=1 -DB=2", + }); + assert.equal(status, 0); + assert.match(calls[0], /\[-DCMAKE_BUILD_TYPE=Debug\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_SANITIZERS=address;undefined\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_TREE_VALIDATION=ON\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_COVERAGE=ON\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_BENCHMARKS=ON\] .*\[-DA=1\] \[-DB=2\]$/); + assert.match(calls[2], /\[--build-config\] \[Debug\]/); +}); + +test("stops at the first failing step", () => { + const configure = runWithStubs({}, "cmake"); + assert.equal(configure.status, 7); + assert.equal(configure.calls.length, 1); + const tests = runWithStubs({}, "ctest"); + assert.equal(tests.status, 7); + assert.equal(tests.calls.length, 3); +}); diff --git a/.github/scripts/cpp-workflow-policy.test.mjs b/.github/scripts/cpp-workflow-policy.test.mjs new file mode 100644 index 0000000..98a398a --- /dev/null +++ b/.github/scripts/cpp-workflow-policy.test.mjs @@ -0,0 +1,107 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { getJobs } from "./workflow-jobs.mjs"; + +const read = (path) => readFileSync(new URL(path, import.meta.url), "utf8"); +const testWorkflow = read("../workflows/cpp-test.yml"); +const deployWorkflow = read("../workflows/deploy-cpp.yml"); +const benchmarksWorkflow = read("../workflows/benchmarks.yml"); +const buildScript = read("../../cpp/build-and-test.sh"); +const cmake = read("../../cpp/CMakeLists.txt"); +const testJobs = getJobs(testWorkflow); +const deployJobs = getJobs(deployWorkflow); + +test("keeps the workflow names that README badges reference", () => { + assert.match(testWorkflow, /^name: Test cpp$/m); + assert.match(deployWorkflow, /^name: Deploy new cpp version$/m); +}); + +test("tests pull requests and main whenever C++ sources change", () => { + const push = testWorkflow.slice(testWorkflow.indexOf(" push:"), testWorkflow.indexOf(" pull_request:")); + const pullRequest = testWorkflow.slice(testWorkflow.indexOf(" pull_request:"), testWorkflow.indexOf(" workflow_call:")); + assert.match(push, /branches: \[main\]/); + for (const trigger of [push, pullRequest]) { + assert.doesNotMatch(trigger, /types:/); + assert.match(trigger, /- 'cpp\/\*\*'/); + } +}); + +test("runs the tests instead of only compiling them", () => { + assert.match(testJobs.get("test"), /\n {10}cpp\/build-and-test\.sh\n/); + assert.match(buildScript, /ctest .*--no-tests=error/); +}); + +test("tests every compiler that consumes the headers, with sanitizers and tree validation", () => { + const job = testJobs.get("test"); + for (const os of ["ubuntu-24.04", "macos-15", "windows-2025"]) { + assert.match(job, new RegExp(`os: ${os}\\n`)); + } + assert.match(job, /cxx: g\+\+/); + assert.match(job, /cxx: clang\+\+/); + assert.match(job, /sanitizers: address;undefined/); + assert.match(job, /tree-validation: '1'/); + assert.match(job, /fail-fast: false/); + // Matrix jobs share a job-level group unless it names the matrix entry. + assert.match(job, /group: .*\$\{\{ matrix\.name \}\}/); + assert.match(cmake, /-fsanitize=\$\{sanitizers\}/); + assert.match(cmake, /ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION=1/); +}); + +test("lets the build script decide what is built", () => { + assert.doesNotMatch(cmake, /CMAKE_CXX_FLAGS.*-march/); + assert.match(buildScript, /-DLINKS_PLATFORM_TESTS=ON/); + assert.match(buildScript, /-DLINKS_PLATFORM_TREE_VALIDATION=/); + assert.match(buildScript, /-DLINKS_PLATFORM_COVERAGE=/); + assert.match(buildScript, /cmake --build .*--config "\$build_type"/); + assert.match(buildScript, /ctest .*--build-config "\$build_type"/); +}); + +test("requires every line of the headers to be covered by the tests", () => { + const job = testJobs.get("coverage"); + assert.match(job, /COVERAGE: '1'/); + assert.match(job, /pipx run gcovr==\d+\.\d+ /); + assert.match(job, /--filter '\.\*\/Platform\\\.Collections\\\.Methods\/\.\*'/); + assert.match(job, /--fail-under-line 100/); +}); + +test("packs with dotnet and verifies the package on every run", () => { + const job = testJobs.get("pack"); + assert.match(job, /pack-cpp-nuget\.mjs "\$RUNNER_TEMP\/cpp-nuget"/); + assert.match(job, /check-cpp-nuget-package\.sh "\$PACKAGE_PATH"/); + assert.match(job, /check-cpp-nuget-package\.test\.mjs/); + assert.match(job, /name: cpp-nuget-package/); + assert.match(job, /if-no-files-found: error/); +}); + +test("deploys only what the local test workflow built and tested", () => { + assert.match(deployJobs.get("test"), /uses: \.\/\.github\/workflows\/cpp-test\.yml/); + assert.match(deployJobs.get("releasePreflight"), /needs: test/); + assert.match(deployJobs.get("releasePreflight"), /preflight-nuget-release\.mjs/); + assert.match(deployJobs.get("pushToNuget"), /needs: \[test, releasePreflight\]/); + assert.match(deployJobs.get("pushToNuget"), /push-nuget-package\.sh "\$RUNNER_TEMP\/cpp-nuget"\/\*\.nupkg/); +}); + +test("supports trusted publishing with the API key as a fallback", () => { + const job = deployJobs.get("pushToNuget"); + assert.match(job, /\n id-token: write/); + assert.match(job, /uses: NuGet\/login@[0-9a-f]{40} # v\d/); + assert.match(job, /NUGET_API_KEY: \$\{\{ steps\.nuget-login\.outputs\.NUGET_API_KEY \|\| secrets\.NUGET_TOKEN \}\}/); +}); + +test("creates the GitHub release only after the NuGet push succeeded", () => { + const job = deployJobs.get("publishRelease"); + assert.match(job, /needs: \[test, pushToNuget\]/); + assert.doesNotMatch(job, /\n if:/); + assert.match(job, /gh release create "\$tag" "\$archive"/); +}); + +test("runs the benchmarks only on request, but keeps them compiling on every change", () => { + const triggers = benchmarksWorkflow.slice(benchmarksWorkflow.indexOf("\non:\n"), benchmarksWorkflow.indexOf("\npermissions:")); + assert.match(triggers, /\n {2}workflow_dispatch:/); + assert.doesNotMatch(triggers, /\n {2}(?:push|pull_request|pull_request_target|schedule):/); + assert.match(getJobs(benchmarksWorkflow).get("cpp"), /BENCHMARKS: '1'/); + assert.match(testJobs.get("test"), /benchmarks: '1'/); +}); diff --git a/.github/scripts/csharp-workflow-policy.test.mjs b/.github/scripts/csharp-workflow-policy.test.mjs new file mode 100644 index 0000000..3434361 --- /dev/null +++ b/.github/scripts/csharp-workflow-policy.test.mjs @@ -0,0 +1,267 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import { getJobs } from "./workflow-jobs.mjs"; + +const workflowPath = new URL("../workflows/csharp.yml", import.meta.url); +const workflow = readFileSync(workflowPath, "utf8"); + +const jobs = getJobs(workflow); + +test("configures Git's initial branch before checkout runs", () => { + const topLevel = workflow.slice(0, workflow.indexOf("\ndefaults:")); + assert.match(topLevel, /\n GIT_CONFIG_COUNT: '1'/); + assert.match(topLevel, /\n GIT_CONFIG_KEY_0: init\.defaultBranch/); + assert.match(topLevel, /\n GIT_CONFIG_VALUE_0: main/); +}); + +test("validates every maintained C# workflow input on pull requests", () => { + assert.match(workflow, /pull_request:/); + assert.match(workflow, /- '\.github\/scripts\/\*csharp\*'/); + assert.match(workflow, /- 'csharp\/\*\*'/); +}); + +test("uses repository-owned build scripts instead of mutable downloads", () => { + assert.doesNotMatch(workflow, /raw\.githubusercontent\.com/); + assert.doesNotMatch(workflow, /\bwget\b/); + assert.doesNotMatch(workflow, /python-pygments/); + assert.doesNotMatch(workflow, /apt-get install(?:\s+-y)?\s+nuget/); +}); + +test("declares least-privilege checkout credentials", () => { + const lines = workflow.split("\n"); + const failures = []; + + for (let index = 0; index < lines.length; index += 1) { + if (!lines[index].includes("uses: actions/checkout@")) { + continue; + } + const step = lines.slice(index, index + 8).join("\n"); + if (!/persist-credentials:\s*false/.test(step)) { + failures.push(`line ${index + 1}: ${lines[index].trim()}`); + } + } + + assert.deepEqual(failures, []); +}); + +test("caps every job so hangs cannot run indefinitely", () => { + assert.ok(jobs.size > 0, "workflow jobs should be parsed"); + for (const [name, job] of jobs) { + assert.match(job, /\n timeout-minutes:\s*\d+/, `${name} has no timeout`); + } +}); + +test("pins the runner image so latest-image migrations do not create warnings", () => { + assert.doesNotMatch(workflow, /runs-on: ubuntu-latest/); + for (const [name, job] of jobs) { + assert.match(job, /\n runs-on: ubuntu-24\.04/, `${name} has an unpinned runner`); + } +}); + +test("gates both package publishers on a release preflight", () => { + const preflight = jobs.get("releasePreflight"); + assert.ok(preflight, "releasePreflight job should exist"); + assert.match(preflight, /NUGET_TOKEN: \$\{\{ secrets\.NUGET_TOKEN \}\}/); + assert.match(preflight, /GITHUB_TOKEN: \$\{\{ secrets\.GITHUB_TOKEN \}\}/); + assert.match(preflight, /NUGET_USER: \$\{\{ vars\.NUGET_USER \}\}/); + assert.match(preflight, /preflight-nuget-release\.mjs/); + + for (const name of [ + "pushNuGetPackageToGitHubPackageRegistry", + "pushToNuget", + ]) { + assert.match( + jobs.get(name), + /needs: \[test, coverage, treeValidation, releasePreflight\]/, + `${name} must wait for the tests, coverage, tree validation and preflight`, + ); + } +}); + +test("packs and publishes each NuGet package in separate ordered steps", () => { + for (const [jobName, outputDirectory] of [ + ["pushNuGetPackageToGitHubPackageRegistry", "github-packages"], + ["pushToNuget", "nuget-packages"], + ]) { + const job = jobs.get(jobName); + const output = `"$RUNNER_TEMP/${outputDirectory}"`; + const pack = job.indexOf("- name: Pack NuGet package"); + const push = job.indexOf("- name: Push NuGet package"); + + assert.ok(pack >= 0, `${jobName} has no pack step`); + assert.ok(push > pack, `${jobName} must push after packing`); + assert.match(job.slice(pack, push), /run: dotnet pack /); + assert.ok(job.slice(pack, push).includes(`--output ${output}`)); + assert.match(job.slice(push), /run: (?:dotnet nuget push|\.\.\/\.github\/scripts\/push-nuget-package\.sh) /); + assert.ok(job.slice(push).includes(`${output}/*.nupkg`)); + assert.equal( + job.slice(pack, push).includes("dotnet nuget push"), + false, + `${jobName} pushes inside the pack step`, + ); + } + + const github = jobs.get("pushNuGetPackageToGitHubPackageRegistry"); + const addSource = github.indexOf("- name: Add GitHub NuGet source"); + assert.ok(addSource > github.indexOf("- name: Pack NuGet package")); + assert.ok(addSource < github.indexOf("- name: Push NuGet package")); + assert.match(github.slice(addSource), /run: dotnet nuget add source /); + assert.match(github, /--source GitHub --api-key "\$GITHUB_TOKEN"/); +}); + +test("publishes to nuget.org only when the preflight found the version missing", () => { + const job = jobs.get("pushToNuget"); + assert.match(job, /\n id-token: write/); + assert.match(job, /uses: NuGet\/login@[0-9a-f]{40} # v\d/); + assert.match( + job, + /if: \$\{\{ needs\.releasePreflight\.outputs\.auth == 'trusted-publishing' && needs\.releasePreflight\.outputs\.publishRequired == 'true' \}\}/, + ); + assert.match(job, /PUBLISH_REQUIRED: \$\{\{ needs\.releasePreflight\.outputs\.publishRequired \}\}/); + assert.match(job, /NUGET_API_KEY: \$\{\{ steps\.nuget-login\.outputs\.NUGET_API_KEY \|\| secrets\.NUGET_TOKEN \}\}/); + assert.doesNotMatch(job, /run: dotnet nuget push/); +}); + +test("detects changed documentation inputs without third-party actions", () => { + const job = jobs.get("findChangedCsFiles"); + assert.doesNotMatch(workflow, /uses: tj-actions\//); + assert.match(job, /fetch-depth: 0/); + assert.match(job, /git diff --name-only "\$BASE_SHA" "\$GITHUB_SHA"/); + assert.match(job, /git cat-file -e/); +}); + +test("builds PDF and API documentation in parallel before publishing both", () => { + const pdf = jobs.get("generatePdfWithCode"); + const documentation = jobs.get("buildDocumentation"); + const publisher = jobs.get("publishDocumentation"); + + assert.ok(pdf, "generatePdfWithCode job should exist"); + assert.ok(documentation, "buildDocumentation job should exist"); + assert.ok(publisher, "publishDocumentation job should exist"); + assert.match(pdf, /needs: \[findChangedCsFiles\]/); + assert.match(documentation, /needs: \[findChangedCsFiles\]/); + assert.doesNotMatch(documentation, /needs:.*generatePdfWithCode/); + assert.doesNotMatch(pdf, /github\.event_name == 'push'/); + assert.doesNotMatch(documentation, /github\.event_name == 'push'/); + assert.match(pdf, /name: csharp-pdf/); + assert.match(documentation, /name: csharp-documentation/); + assert.doesNotMatch(workflow, /actions\/download-artifact@/); + assert.match( + publisher, + /needs: \[findChangedCsFiles, generatePdfWithCode, buildDocumentation\]/, + ); + assert.match(publisher, /--name csharp-documentation/); + assert.match(publisher, /--name csharp-pdf/); + assert.match( + publisher, + /if: \$\{\{ needs\.findChangedCsFiles\.outputs\.documentationChanged == 'true' \}\}/, + ); + assert.match( + publisher, + /- name: Publish documentation to gh-pages\n if: \$\{\{ github\.event_name == 'push' \}\}/, + ); +}); + +test("validates generated API pages before upload and after download", () => { + const documentation = jobs.get("buildDocumentation"); + const publisher = jobs.get("publishDocumentation"); + + assert.match(documentation, /docfx" docfx\.json --warningsAsErrors/); + assert.match(documentation, /validate-csharp-docs\.sh _site/); + assert.match(publisher, /validate-csharp-docs\.sh _site/); +}); + +test("aggregates every job result so skipped dependents cannot hide failures", () => { + const gate = jobs.get("pipelineStatus"); + assert.ok(gate, "pipelineStatus job should exist"); + assert.match(gate, /if: \$\{\{ !cancelled\(\) \}\}/); + assert.match(gate, /check-csharp-pipeline-status\.mjs/); + + for (const name of [...jobs.keys()].filter((name) => name !== "pipelineStatus")) { + assert.match(gate, new RegExp(`\\n - ${name}(?:\\n|$)`), `${name} is not observed`); + } +}); + +test("requires full line coverage of the library", () => { + const job = jobs.get("coverage"); + assert.ok(job, "coverage job should exist"); + assert.match(job, /--collect "XPlat Code Coverage"/); + assert.match(job, /check-csharp-coverage\.mjs "\$RUNNER_TEMP"\/coverage\/\*\*\/coverage\.cobertura\.xml/); + assert.match(workflow, /- '\.github\/scripts\/\*csharp\*'/); +}); + +test("runs the tests with trees that validate themselves after every change", () => { + const job = jobs.get("treeValidation"); + assert.ok(job, "treeValidation job should exist"); + assert.match(job, /-p:TreeValidation=true/); + // Debug would evaluate the tree dumps passed to Debug.WriteLine. + assert.match(job, /--configuration Release/); + const project = readFileSync(new URL("../../csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj", import.meta.url), "utf8"); + assert.match(project, /Condition="'\$\(TreeValidation\)' == 'true'"/); + assert.match(project, /ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION/); +}); + +test("runs the C# benchmarks only on request", () => { + const benchmarks = readFileSync(new URL("../workflows/benchmarks.yml", import.meta.url), "utf8"); + assert.match(getJobs(benchmarks).get("csharp"), /dotnet run --project Platform\.Collections\.Methods\.Benchmarks/); + assert.doesNotMatch(benchmarks, /\n {2}(?:push|pull_request|schedule):/); + // The tests build the whole solution, so the benchmarks keep compiling. + assert.match(readFileSync(new URL("./validate-csharp-package.sh", import.meta.url), "utf8"), /dotnet (?:build|test)/); +}); + +// pdflatex stops at the first character it has no mapping for. inputenc maps +// Latin-1, Cyrillic and the typographic dashes, quotes and dots; every other +// character of the C# sources needs a \DeclareUnicodeCharacter of its own. +test("maps every character of the C# sources in the PDF preamble", () => { + const script = readFileSync(new URL("./generate-csharp-pdf.sh", import.meta.url), "utf8"); + const declared = new Set([...script.matchAll(/\\DeclareUnicodeCharacter\{([0-9A-F]+)\}/g)].map(([, code]) => Number.parseInt(code, 16))); + // The workflow runs the tests from csharp/, so pathspecs and files are + // resolved against the repository root, not the working directory. + const repositoryUrl = new URL("../../", import.meta.url); + const repository = fileURLToPath(repositoryUrl); + const mappedByInputenc = (code) => code < 0x100 || (code >= 0x400 && code <= 0x4ff) || (code >= 0x2013 && code <= 0x2026); + const sources = execFileSync("git", ["ls-files", "-z", "--", "csharp/Platform.Collections.Methods/*.cs", "csharp/Platform.Collections.Methods.Tests/*.cs"], { cwd: repository, encoding: "utf8" }) + .split("\0") + .filter(Boolean); + assert.ok(sources.length > 0); + const unmapped = new Set(); + for (const source of sources) { + for (const character of readFileSync(new URL(source, repositoryUrl), "utf8").replace(/^/, "")) { + const code = character.codePointAt(0); + if (!mappedByInputenc(code) && !declared.has(code)) { + unmapped.add(`U+${code.toString(16).toUpperCase().padStart(4, "0")} ${character} in ${source}`); + } + } + } + assert.deepEqual([...unmapped], []); +}); + +// docfx builds README.md into the documentation site, which contains only the +// README and the API pages, so a relative link to any other repository file +// is an invalid link there and fails the --warningsAsErrors build. +test("links the README only to absolute URLs and anchors", () => { + const readme = readFileSync(new URL("../../README.md", import.meta.url), "utf8"); + const relative = [...readme.matchAll(/\]\(([^)\s]+)\)|(?:src|href)="([^"]+)"/g)] + .map(([, markdown, html]) => markdown ?? html) + .filter((target) => !/^(?:https?:|mailto:|#)/.test(target)); + assert.deepEqual(relative, []); +}); + +// The documentation home page is the README, and validate-csharp-docs.sh +// requires it to link the PDF that DocFX writes; the namespace links must +// name pages DocFX writes, which it does only for namespaces with types. +test("links the README to the DocFX PDF and to the namespace pages", () => { + const readme = readFileSync(new URL("../../README.md", import.meta.url), "utf8"); + const docfx = JSON.parse(readFileSync(new URL("../../csharp/docfx.json", import.meta.url), "utf8")); + assert.ok(readme.includes(`/csharp/${docfx.build.globalMetadata.pdfFileName})`)); + const validator = readFileSync(new URL("./validate-csharp-docs.sh", import.meta.url), "utf8"); + const pages = new Set([...validator.matchAll(/^\s+(api\/\S+\.html)/gm)].map(([, page]) => page)); + const linked = [...readme.matchAll(/linksplatform\.github\.io\/Collections\.Methods\/csharp\/(api\/[^)]+\.html)\)/g)].map(([, page]) => page); + assert.ok(linked.length > 0); + assert.deepEqual(linked.filter((page) => !pages.has(page)), []); +}); diff --git a/.github/scripts/generate-csharp-pdf.sh b/.github/scripts/generate-csharp-pdf.sh new file mode 100755 index 0000000..29463c6 --- /dev/null +++ b/.github/scripts/generate-csharp-pdf.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +output_directory=${1:-"$repository_root/csharp/_site"} +work_directory=$(mktemp -d) + +cleanup() { + rm -rf "$work_directory" +} +trap cleanup EXIT + +sudo apt-get update & +update_pid=$! +wait "$update_pid" +sudo apt-get install -y \ + ghostscript \ + python3-pygments \ + texlive \ + texlive-lang-cyrillic \ + texlive-latex-extra & +install_pid=$! +wait "$install_pid" + +document="$work_directory/document.tex" +cat > "$document" <<'LATEX' +\documentclass[11pt,a4paper,fleqn]{report} +\usepackage[left=5mm,top=5mm,right=5mm,bottom=5mm]{geometry} +\usepackage[T1]{fontenc} +\usepackage[T2A]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{fvextra} +\usepackage{minted} +\usemintedstyle{vs} +\usepackage{makeidx} +\usepackage[columns=1]{idxlayout} +\usepackage[tiny]{titlesec} +\makeindex +\titlespacing\chapter{0mm}{0mm}{0mm} +\titlespacing\section{0mm}{0mm}{0mm} +% inputenc maps Latin-1, Cyrillic and typographic dashes and quotes; the +% mathematical symbols the comments use need a mapping of their own. +\DeclareUnicodeCharacter{2190}{\ensuremath{\leftarrow}} +\DeclareUnicodeCharacter{2192}{\ensuremath{\rightarrow}} +\DeclareUnicodeCharacter{2208}{\ensuremath{\in}} +\DeclareUnicodeCharacter{2211}{\ensuremath{\sum}} +\DeclareUnicodeCharacter{2212}{\ensuremath{-}} +\DeclareUnicodeCharacter{221A}{\ensuremath{\surd}} +\DeclareUnicodeCharacter{221E}{\ensuremath{\infty}} +\DeclareUnicodeCharacter{2248}{\ensuremath{\approx}} +\DeclareUnicodeCharacter{2260}{\ensuremath{\neq}} +\DeclareUnicodeCharacter{2264}{\ensuremath{\leq}} +\DeclareUnicodeCharacter{2265}{\ensuremath{\geq}} +\DeclareUnicodeCharacter{230A}{\ensuremath{\lfloor}} +\DeclareUnicodeCharacter{230B}{\ensuremath{\rfloor}} +\DeclareUnicodeCharacter{2308}{\ensuremath{\lceil}} +\DeclareUnicodeCharacter{2309}{\ensuremath{\rceil}} +\DeclareUnicodeCharacter{FFFD}{\ensuremath{ }} +\begin{document} +\sffamily +\chapter*{LinksPlatform's Platform.Collections.Methods Class Library} +LATEX + +while IFS= read -r -d '' source_file; do + relative_path=${source_file#"$repository_root/"} + latex_path=${relative_path//_/\\_} + { + printf '\\index{%s}\n' "$latex_path" + printf '\\section{%s}\n' "$latex_path" + printf '%s\n' '\begin{minted}[tabsize=2,breaklines,breakanywhere,linenos=true,xleftmargin=7mm,framesep=4mm]{csharp}' + sed $'1s/^\xEF\xBB\xBF//' "$source_file" + printf '%s\n' '\end{minted}' + } >> "$document" +done < <( + find \ + "$repository_root/csharp/Platform.Collections.Methods" \ + "$repository_root/csharp/Platform.Collections.Methods.Tests" \ + -type f -name '*.cs' ! -path '*/bin/*' ! -path '*/obj/*' -print0 | + sort -z +) + +cat >> "$document" <<'LATEX' +\printindex +\end{document} +LATEX + +( + cd "$work_directory" + pdflatex -shell-escape -interaction=nonstopmode -halt-on-error document.tex + makeindex document.idx + pdflatex -shell-escape -interaction=nonstopmode -halt-on-error document.tex +) + +mkdir -p "$output_directory" +cp "$work_directory/document.pdf" "$output_directory/Platform.Collections.Methods.pdf" +echo "Generated $output_directory/Platform.Collections.Methods.pdf" diff --git a/.github/scripts/pack-cpp-nuget.mjs b/.github/scripts/pack-cpp-nuget.mjs new file mode 100644 index 0000000..1eb0578 --- /dev/null +++ b/.github/scripts/pack-cpp-nuget.mjs @@ -0,0 +1,197 @@ +#!/usr/bin/env node + +/** + * Pack the header-only C++ library as a native NuGet package. + * + * The shared linksplatform/Workflows deploy-cpp job ran + * `sudo apt-get install nuget`, but Ubuntu 24.04 no longer ships the Mono + * NuGet CLI, and its recipe_folder pointed at another library, so the C++ + * package could not be released. This script stages the layout of the last + * published package (0.3.0) and packs it with the .NET SDK through a throwaway + * project that points at the nuspec: + * + * README.md (the repository README with the benchmark results, added in 0.4.0) + * images/icon.png + * build/native/.targets + * lib/native/include/[Lists/|Trees/]
.h + * + * Usage: node pack-cpp-nuget.mjs [--verbose] + * `--verbose`, VERBOSE=1 or RUNNER_DEBUG=1 prints the staged files and the + * full dotnet output. Writes package_id, version and package_path to + * GITHUB_OUTPUT and the release notes to /release-notes.md. + */ + +import { execFileSync } from "node:child_process"; +import { + appendFileSync, + copyFileSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const repositoryRoot = path.resolve(import.meta.dirname, "../.."); +export const nuspecPath = path.join( + repositoryRoot, + "cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec", +); +const headersDirectory = path.dirname(nuspecPath); +const assetsDirectory = path.join(repositoryRoot, "cpp/nuget"); + +const readElement = (nuspec, name) => { + const match = new RegExp(`<${name}>([^<]+)`).exec(nuspec); + if (!match) { + throw new Error(`The nuspec has no <${name}> element`); + } + return match[1].trim(); +}; + +export const readPackageInfo = (nuspec) => ({ + id: readElement(nuspec, "id"), + version: readElement(nuspec, "version"), + releaseNotes: readElement(nuspec, "releaseNotes"), +}); + +export const expectedEntries = (id, headers) => [ + "README.md", + "images/icon.png", + `build/native/${id}.targets`, + ...headers.map((header) => `lib/native/include/${header}`), +]; + +export const withStagedFiles = (nuspec) => { + if (//.test(nuspec)) { + throw new Error("The nuspec already lists ; the pack layout is generated"); + } + return nuspec.replace( + "", + '\n \n \n ', + ); +}; + +export const findMissingEntries = (expected, actual) => { + const present = new Set(actual); + return expected.filter((entry) => !present.has(entry)); +}; + +// Header paths relative to the nuspec directory, with "/" separators. +export const listHeaders = (directory = headersDirectory) => + readdirSync(directory, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".h")) + .map((entry) => path.relative(directory, path.join(entry.parentPath, entry.name)).split(path.sep).join("/")) + .sort(); + +const listPackageEntries = (packagePath) => + execFileSync("unzip", ["-Z1", packagePath], { encoding: "utf8" }) + .split("\n") + .filter(Boolean); + +const setOutput = (name, value) => { + console.log(`${name}=${value}`); + if (process.env.GITHUB_OUTPUT) { + appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`); + } +}; + +export const run = (args = process.argv.slice(2), environment = process.env) => { + const verbose = + args.includes("--verbose") || + environment.VERBOSE === "1" || + environment.RUNNER_DEBUG === "1"; + const outputDirectory = args.find((arg) => !arg.startsWith("--")); + if (!outputDirectory) { + console.error("Usage: node pack-cpp-nuget.mjs [--verbose]"); + return 2; + } + + const nuspec = readFileSync(nuspecPath, "utf8"); + const { id, version, releaseNotes } = readPackageInfo(nuspec); + const headers = listHeaders(); + if (headers.length === 0) { + console.error(`::error title=C++ NuGet pack failed::No headers in ${headersDirectory}`); + return 1; + } + + const staging = mkdtempSync(path.join(tmpdir(), "cpp-nuget-")); + try { + const content = path.join(staging, "content"); + for (const directory of ["images", "build/native", "lib/native/include"]) { + mkdirSync(path.join(content, directory), { recursive: true }); + } + copyFileSync(path.join(repositoryRoot, "README.md"), path.join(content, "README.md")); + copyFileSync(path.join(assetsDirectory, "icon.png"), path.join(content, "images/icon.png")); + copyFileSync( + path.join(assetsDirectory, "TemplateLibrary.targets"), + path.join(content, `build/native/${id}.targets`), + ); + for (const header of headers) { + mkdirSync(path.dirname(path.join(content, "lib/native/include", header)), { recursive: true }); + copyFileSync( + path.join(headersDirectory, header), + path.join(content, "lib/native/include", header), + ); + } + writeFileSync(path.join(staging, `${id}.nuspec`), withStagedFiles(nuspec)); + writeFileSync( + path.join(staging, "pack.csproj"), + [ + '', + " ", + " netstandard2.0", + " false", + " true", + ` ${id}.nuspec`, + " $(MSBuildProjectDirectory)", + " ", + "", + "", + ].join("\n"), + ); + + const absoluteOutput = path.resolve(outputDirectory); + mkdirSync(absoluteOutput, { recursive: true }); + const packOutput = execFileSync( + "dotnet", + ["pack", path.join(staging, "pack.csproj"), "--output", absoluteOutput, "--nologo"], + { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }, + ); + if (verbose) { + console.log(packOutput); + } + + const packagePath = path.join(absoluteOutput, `${id}.${version}.nupkg`); + const entries = listPackageEntries(packagePath); + if (verbose) { + console.log(entries.join("\n")); + } + const missing = findMissingEntries(expectedEntries(id, headers), entries); + const stray = entries.filter((entry) => /(^|\/)(obj|bin)\/|\.csproj$/.test(entry)); + for (const entry of missing) { + console.error(`::error title=C++ NuGet pack failed::${entry} is missing from ${packagePath}`); + } + for (const entry of stray) { + console.error(`::error title=C++ NuGet pack failed::${entry} must not be packed`); + } + if (missing.length > 0 || stray.length > 0) { + return 1; + } + + writeFileSync(path.join(absoluteOutput, "release-notes.md"), `${releaseNotes}\n`); + console.log(`Packed ${id} ${version} with ${headers.length} headers.`); + setOutput("package_id", id); + setOutput("version", version); + setOutput("package_path", packagePath); + return 0; + } finally { + rmSync(staging, { recursive: true, force: true }); + } +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = run(); +} diff --git a/.github/scripts/pack-cpp-nuget.test.mjs b/.github/scripts/pack-cpp-nuget.test.mjs new file mode 100644 index 0000000..e14fd93 --- /dev/null +++ b/.github/scripts/pack-cpp-nuget.test.mjs @@ -0,0 +1,74 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { + expectedEntries, + findMissingEntries, + listHeaders, + nuspecPath, + readPackageInfo, + withStagedFiles, +} from "./pack-cpp-nuget.mjs"; + +const nuspec = readFileSync(nuspecPath, "utf8"); + +test("reads the package identity and release notes from the nuspec", () => { + const info = readPackageInfo(nuspec); + assert.equal(info.id, "Platform.Collections.Methods.TemplateLibrary"); + assert.match(info.version, /^\d+\.\d+\.\d+$/); + assert.ok(info.releaseNotes.length > 0); +}); + +test("shows the README with the benchmark results on nuget.org", () => { + assert.match(nuspec, /README\.md<\/readme>/); + assert.match(nuspec, /[^<]*benchmark/); +}); + +test("fails loudly when a required nuspec element is missing", () => { + assert.throws( + () => readPackageInfo("x"), + /no element/, + ); +}); + +test("adds the staged content after the metadata without editing it", () => { + const staged = withStagedFiles(nuspec); + assert.ok(staged.startsWith(nuspec.slice(0, nuspec.indexOf("")))); + assert.match(staged, /<\/metadata>\n \n \n <\/files>/); + assert.throws(() => withStagedFiles(staged), /already lists /); +}); + +test("expects the layout of the last package published to nuget.org (0.3.0) and the README", () => { + assert.deepEqual(expectedEntries("Id", ["A.h", "B[T].h"]), [ + "README.md", + "images/icon.png", + "build/native/Id.targets", + "lib/native/include/A.h", + "lib/native/include/B[T].h", + ]); +}); + +test("reports every expected entry that the package lacks", () => { + assert.deepEqual( + findMissingEntries(["images/icon.png", "lib/native/include/A.h"], ["images/icon.png"]), + ["lib/native/include/A.h"], + ); +}); + +test("packs the headers of the Lists and Trees folders as in 0.3.0", () => { + const headers = listHeaders(); + for (const header of [ + "Platform.Collections.Methods.h", + "GenericCollectionMethodsBase.h", + "Lists/AbsoluteCircularDoublyLinkedListMethods.h", + "Trees/RecursionlessSizeBalancedTreeMethods.h", + "Trees/SizeBalancedTreeMethods.h", + "Trees/SizedAndThreadedAVLBalancedTreeMethods.h", + "Trees/SizedBinaryTreeMethodsBase.h", + ]) { + assert.ok(headers.includes(header), `${header} is not packed`); + } + assert.deepEqual(headers.filter((header) => header.includes("\\")), []); +}); diff --git a/.github/scripts/preflight-nuget-release.mjs b/.github/scripts/preflight-nuget-release.mjs new file mode 100644 index 0000000..3b7e60f --- /dev/null +++ b/.github/scripts/preflight-nuget-release.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node + +/** + * Decide whether a NuGet release still has to be published and check the + * credentials that publishing needs, before any package is pushed. + * + * linksplatform/Interfaces#150 found two blind spots in the previous presence-only check: + * - every push to main tried to push an already published version, so an + * expired NUGET_TOKEN failed runs that had nothing to publish; + * - an unpublished version (C# 0.5.1-0.6.1, C++ 0.3.43-0.4.1) was never + * reported as such, and the C++ release was created anyway. + * + * The version check uses the public flat-container index, which needs no key. + * An API key is checked without publishing anything, through the same two + * calls that `nuget push` makes for symbol packages (NuGetGallery + * ApiController): POST /api/v2/package/create-verification-key/ rejects an + * invalid, expired or non-push key with 401/403, and GET + * /api/v2/verifykey// with the returned one-time key + * rejects a key whose glob or owner does not cover the package. The gallery + * deletes the one-time key after that call. Trusted publishing (NUGET_USER) + * avoids long-lived keys altogether. + * + * Environment: PACKAGE_ID, PACKAGE_VERSION (or CSPROJ to read both), + * GITHUB_TOKEN, NUGET_TOKEN, NUGET_USER, NUGET_INDEX_URL and NUGET_GALLERY_URL + * (tests), VERBOSE=1 or RUNNER_DEBUG=1 for diagnostic output. + * Outputs: publish_required=true|false, auth=trusted-publishing|api-key|none. + */ + +import { appendFileSync, readFileSync } from "node:fs"; + +const defaultIndexUrl = "https://api.nuget.org/v3-flatcontainer"; +const defaultGalleryUrl = "https://www.nuget.org"; + +export const readCsproj = (source) => { + const read = (name) => new RegExp(`<${name}>([^<]+)`).exec(source)?.[1]?.trim(); + return { + packageId: read("PackageId") ?? read("AssemblyName"), + version: read("Version") ?? read("VersionPrefix"), + }; +}; + +export const versionIndexUrl = (packageId, indexUrl = defaultIndexUrl) => + `${indexUrl}/${packageId.toLowerCase()}/index.json`; + +/** + * @returns {Promise<{ published: boolean | undefined, latest?: string, detail: string }>} + * `published` is undefined when nuget.org could not be queried; `latest` is + * the newest published version, if any. + */ +export const fetchPublished = async ({ packageId, version, indexUrl, fetchImpl = fetch }) => { + const url = versionIndexUrl(packageId, indexUrl); + try { + const response = await fetchImpl(url, { signal: AbortSignal.timeout(30_000) }); + if (response.status === 404) { + return { published: false, detail: `${url} returned 404` }; + } + if (!response.ok) { + return { published: undefined, detail: `${url} returned ${response.status}` }; + } + const { versions = [] } = await response.json(); + return { + published: versions.includes(version.toLowerCase()), + latest: versions.at(-1), + detail: `${url} lists ${versions.length} versions`, + }; + } catch (error) { + return { published: undefined, detail: `${url} failed: ${error.message}` }; + } +}; + +/** + * @returns {Promise<{ valid: boolean | undefined, detail: string }>} + * `valid` is undefined when nuget.org could not answer, and also when no + * version is published yet: then only the key itself can be checked, not + * whether it may push this package. + */ +export const verifyApiKey = async ({ + packageId, + publishedVersion, + apiKey, + galleryUrl = defaultGalleryUrl, + fetchImpl = fetch, +}) => { + const id = encodeURIComponent(packageId); + const createUrl = `${galleryUrl}/api/v2/package/create-verification-key/${id}`; + let key; + try { + const response = await fetchImpl(createUrl, { + method: "POST", + headers: { "X-NuGet-ApiKey": apiKey }, + body: "", + signal: AbortSignal.timeout(30_000), + }); + if (response.status === 401 || response.status === 403) { + return { valid: false, detail: `${createUrl} returned ${response.status}` }; + } + if (!response.ok) { + return { valid: undefined, detail: `${createUrl} returned ${response.status}` }; + } + key = (await response.json()).Key; + } catch (error) { + return { valid: undefined, detail: `${createUrl} failed: ${error.message}` }; + } + if (!key) { + return { valid: undefined, detail: `${createUrl} returned no verification key` }; + } + if (!publishedVersion) { + return { + valid: undefined, + detail: `${createUrl} accepted the key, but no published version exists to check its package scope`, + }; + } + + const verifyUrl = `${galleryUrl}/api/v2/verifykey/${id}/${encodeURIComponent(publishedVersion)}`; + try { + const response = await fetchImpl(verifyUrl, { + headers: { "X-NuGet-ApiKey": key }, + signal: AbortSignal.timeout(30_000), + }); + if (response.status === 401 || response.status === 403) { + return { valid: false, detail: `${verifyUrl} returned ${response.status}` }; + } + return { + valid: response.ok ? true : undefined, + detail: `${verifyUrl} returned ${response.status}`, + }; + } catch (error) { + return { valid: undefined, detail: `${verifyUrl} failed: ${error.message}` }; + } +}; + +export const evaluateRelease = ({ published, githubToken, nugetToken, nugetUser, keyValid, keyDetail }) => { + const failures = []; + const warnings = []; + + if (!githubToken) { + failures.push("GITHUB_TOKEN is unavailable"); + } + if (published === undefined) { + warnings.push( + "nuget.org could not be queried; the push will run with --skip-duplicate", + ); + } + + const publishRequired = published !== true; + let auth = "none"; + if (nugetUser) { + auth = "trusted-publishing"; + } else if (nugetToken) { + auth = "api-key"; + } + + if (publishRequired && auth === "none") { + failures.push( + "The version is not on nuget.org but neither the NUGET_USER variable (trusted publishing) nor the NUGET_TOKEN secret is configured", + ); + } + if (publishRequired && auth === "api-key") { + if (keyValid === false) { + failures.push( + "nuget.org rejected the NUGET_TOKEN secret: it is invalid, expired, or not scoped to push this package. Create a new key at https://www.nuget.org/account/apikeys with push scope for the package and store it as the NUGET_TOKEN repository secret, or configure trusted publishing (https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) and set the NUGET_USER repository variable", + ); + } else if (keyValid === undefined) { + const reason = keyDetail ? ` (${keyDetail})` : ""; + warnings.push(`nuget.org could not verify the NUGET_TOKEN secret${reason}; the push will show whether it is accepted`); + } + } + + return { passed: failures.length === 0, publishRequired, auth, failures, warnings }; +}; + +const setOutput = (environment, name, value) => { + console.log(`${name}=${value}`); + if (environment.GITHUB_OUTPUT) { + appendFileSync(environment.GITHUB_OUTPUT, `${name}=${value}\n`); + } +}; + +export const run = async (environment = process.env, fetchImpl = fetch) => { + const verbose = environment.VERBOSE === "1" || environment.RUNNER_DEBUG === "1"; + let packageId = environment.PACKAGE_ID; + let version = environment.PACKAGE_VERSION; + if (environment.CSPROJ) { + const project = readCsproj(readFileSync(environment.CSPROJ, "utf8")); + packageId ||= project.packageId; + version ||= project.version; + } + if (!packageId || !version) { + console.error("::error title=NuGet release preflight failed::Package id or version is unknown"); + return 1; + } + + const { published, latest, detail } = await fetchPublished({ + packageId, + version, + indexUrl: environment.NUGET_INDEX_URL || defaultIndexUrl, + fetchImpl, + }); + if (verbose) { + console.log(`Version index: ${detail}`); + } + + const nugetToken = environment.NUGET_TOKEN ?? ""; + const nugetUser = environment.NUGET_USER ?? ""; + let keyValid; + let keyDetail; + if (published !== true && nugetToken && !nugetUser) { + const verification = await verifyApiKey({ + packageId, + publishedVersion: latest, + apiKey: nugetToken, + galleryUrl: environment.NUGET_GALLERY_URL || defaultGalleryUrl, + fetchImpl, + }); + keyValid = verification.valid; + keyDetail = verification.detail; + if (verbose) { + console.log(`API key verification: ${verification.detail}`); + } + } + + const result = evaluateRelease({ + published, + githubToken: environment.GITHUB_TOKEN ?? "", + nugetToken, + nugetUser, + keyValid, + keyDetail, + }); + + for (const warning of result.warnings) { + console.log(`::warning title=NuGet release preflight::${warning}`); + } + for (const failure of result.failures) { + console.error(`::error title=NuGet release preflight failed::${failure}`); + } + + if (result.publishRequired) { + console.log(`${packageId} ${version} is not on nuget.org yet; it will be published using ${result.auth}.`); + if (result.auth === "api-key" && keyValid) { + console.log("nuget.org accepted NUGET_TOKEN for pushing this package."); + } + } else { + console.log(`${packageId} ${version} is already on nuget.org; publishing will be skipped.`); + } + + setOutput(environment, "publish_required", String(result.publishRequired)); + setOutput(environment, "auth", result.auth); + return result.passed ? 0 : 1; +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = await run(); +} diff --git a/.github/scripts/preflight-nuget-release.test.mjs b/.github/scripts/preflight-nuget-release.test.mjs new file mode 100644 index 0000000..792e95e --- /dev/null +++ b/.github/scripts/preflight-nuget-release.test.mjs @@ -0,0 +1,250 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + evaluateRelease, + fetchPublished, + readCsproj, + run, + verifyApiKey, + versionIndexUrl, +} from "./preflight-nuget-release.mjs"; + +const respond = (status, body = {}) => async () => ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, +}); + +test("reads the C# package identity from the project file", () => { + const csproj = readFileSync( + new URL("../../csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj", import.meta.url), + "utf8", + ); + const project = readCsproj(csproj); + assert.equal(project.packageId, "Platform.Collections.Methods"); + assert.match(project.version, /^\d+\.\d+\.\d+$/); +}); + +test("queries the lower-case flat-container index", () => { + assert.equal( + versionIndexUrl("Platform.Collections.Methods.TemplateLibrary"), + "https://api.nuget.org/v3-flatcontainer/platform.collections.methods.templatelibrary/index.json", + ); +}); + +test("detects published, unpublished, unknown and unreachable packages", async () => { + const query = (fetchImpl) => + fetchPublished({ packageId: "P", version: "1.0.0-Beta", fetchImpl }); + assert.equal((await query(respond(200, { versions: ["1.0.0-beta"] }))).published, true); + assert.equal((await query(respond(200, { versions: ["0.9.0"] }))).published, false); + assert.equal((await query(respond(404))).published, false); + assert.equal((await query(respond(503))).published, undefined); + assert.equal( + (await query(async () => { + throw new Error("offline"); + })).published, + undefined, + ); +}); + +test("skips publishing an existing version without NuGet credentials", () => { + assert.deepEqual( + evaluateRelease({ published: true, githubToken: "g", nugetToken: "", nugetUser: "" }), + { passed: true, publishRequired: false, auth: "none", failures: [], warnings: [] }, + ); +}); + +test("fails before pushing when an unpublished version has no credentials", () => { + const result = evaluateRelease({ published: false, githubToken: "", nugetToken: "", nugetUser: "" }); + assert.equal(result.passed, false); + assert.equal(result.publishRequired, true); + assert.deepEqual(result.failures.length, 2); + assert.match(result.failures[1], /NUGET_USER .* NUGET_TOKEN/); +}); + +test("prefers trusted publishing over the long-lived API key", () => { + const result = evaluateRelease({ published: false, githubToken: "g", nugetToken: "k", nugetUser: "linksplatform" }); + assert.equal(result.auth, "trusted-publishing"); + assert.equal(result.passed, true); +}); + +test("still publishes with --skip-duplicate when nuget.org is unreachable", () => { + const result = evaluateRelease({ published: undefined, githubToken: "g", nugetToken: "k", nugetUser: "" }); + assert.equal(result.passed, true); + assert.equal(result.publishRequired, true); + assert.equal(result.auth, "api-key"); + assert.equal(result.warnings.length, 2); + assert.match(result.warnings[1], /could not verify the NUGET_TOKEN/); +}); + +test("says why the API key could not be verified", () => { + const result = evaluateRelease({ + published: false, + githubToken: "g", + nugetToken: "k", + nugetUser: "", + keyValid: undefined, + keyDetail: "no published version exists to check its package scope", + }); + assert.equal(result.passed, true); + assert.match(result.warnings[0], /NUGET_TOKEN secret \(no published version exists .*\); the push/); +}); + +// Answers each request from a "METHOD url" -> [status, body] table and records the calls. +const gallery = (routes) => { + const calls = []; + const fetchImpl = async (url, options = {}) => { + const request = `${options.method ?? "GET"} ${url}`; + calls.push({ request, key: options.headers?.["X-NuGet-ApiKey"] }); + const route = routes[request]; + if (!route) { + throw new Error(`unexpected ${request}`); + } + return respond(...route)(); + }; + return { calls, fetchImpl }; +}; +const createUrl = "POST https://www.nuget.org/api/v2/package/create-verification-key/Platform.Collections.Methods"; +const verifyUrl = "GET https://www.nuget.org/api/v2/verifykey/Platform.Collections.Methods/0.5.0"; + +test("verifies an API key in two steps without publishing", async () => { + const { calls, fetchImpl } = gallery({ + [createUrl]: [200, { Key: "one-time", Expires: "2026-10-07T00:00:00Z" }], + [verifyUrl]: [200], + }); + const result = await verifyApiKey({ + packageId: "Platform.Collections.Methods", + publishedVersion: "0.5.0", + apiKey: "secret", + fetchImpl, + }); + assert.equal(result.valid, true); + assert.deepEqual(calls, [ + { request: createUrl, key: "secret" }, + { request: verifyUrl, key: "one-time" }, + ]); +}); + +test("rejects an invalid or expired API key (linksplatform/Interfaces#150)", async () => { + for (const status of [401, 403]) { + const { calls, fetchImpl } = gallery({ [createUrl]: [status] }); + const result = await verifyApiKey({ + packageId: "Platform.Collections.Methods", + publishedVersion: "0.5.0", + apiKey: "expired", + fetchImpl, + }); + assert.equal(result.valid, false); + assert.equal(calls.length, 1); + } +}); + +test("rejects an API key that is not scoped to the package", async () => { + const { fetchImpl } = gallery({ + [createUrl]: [200, { Key: "one-time" }], + [verifyUrl]: [403], + }); + const result = await verifyApiKey({ + packageId: "Platform.Collections.Methods", + publishedVersion: "0.5.0", + apiKey: "other-glob", + fetchImpl, + }); + assert.equal(result.valid, false); +}); + +test("does not claim a package scope it cannot check for a package that was never published", async () => { + const { calls, fetchImpl } = gallery({ [createUrl]: [200, { Key: "one-time" }] }); + const result = await verifyApiKey({ packageId: "Platform.Collections.Methods", apiKey: "k", fetchImpl }); + assert.equal(result.valid, undefined); + assert.match(result.detail, /no published version/); + assert.equal(calls.length, 1); +}); + +test("reports an unknown key state when nuget.org cannot answer", async () => { + const verify = (fetchImpl) => + verifyApiKey({ packageId: "Platform.Collections.Methods", publishedVersion: "0.5.0", apiKey: "k", fetchImpl }); + assert.equal((await verify(gallery({ [createUrl]: [503] }).fetchImpl)).valid, undefined); + assert.equal((await verify(gallery({ [createUrl]: [200, {}] }).fetchImpl)).valid, undefined); + assert.equal( + (await verify(gallery({ [createUrl]: [200, { Key: "one-time" }], [verifyUrl]: [500] }).fetchImpl)).valid, + undefined, + ); + assert.equal((await verify(gallery({}).fetchImpl)).valid, undefined); +}); + +test("fails before pushing when nuget.org rejects NUGET_TOKEN", () => { + const result = evaluateRelease({ + published: false, + githubToken: "g", + nugetToken: "expired", + nugetUser: "", + keyValid: false, + }); + assert.equal(result.passed, false); + assert.match(result.failures[0], /rejected the NUGET_TOKEN secret/); +}); + +test("does not verify NUGET_TOKEN when nothing has to be published", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.5.0"] }], + }); + const exitCode = await run( + { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.5.0", GITHUB_TOKEN: "g", NUGET_TOKEN: "expired" }, + fetchImpl, + ); + assert.equal(exitCode, 0); + assert.equal(calls.length, 1); +}); + +test("fails the preflight with an expired NUGET_TOKEN for an unpublished version", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.4.0", "0.5.0"] }], + [createUrl]: [403], + }); + const exitCode = await run( + { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.6.1", GITHUB_TOKEN: "g", NUGET_TOKEN: "expired" }, + fetchImpl, + ); + assert.equal(exitCode, 1); + assert.equal(calls.length, 2); +}); + +test("verifies the package scope against the newest published version", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.4.0", "0.5.0"] }], + [createUrl]: [200, { Key: "one-time" }], + [verifyUrl]: [200], + }); + const exitCode = await run( + { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.6.1", GITHUB_TOKEN: "g", NUGET_TOKEN: "valid" }, + fetchImpl, + ); + assert.equal(exitCode, 0); + assert.equal(calls.at(-1).request, verifyUrl); +}); + +test("writes the decision to GITHUB_OUTPUT", async () => { + const directory = mkdtempSync(path.join(tmpdir(), "preflight-")); + const output = path.join(directory, "output"); + try { + const exitCode = await run( + { + PACKAGE_ID: "Platform.Collections.Methods", + PACKAGE_VERSION: "0.5.0", + GITHUB_TOKEN: "g", + GITHUB_OUTPUT: output, + }, + respond(200, { versions: ["0.5.0"] }), + ); + assert.equal(exitCode, 0); + assert.equal(readFileSync(output, "utf8"), "publish_required=false\nauth=none\n"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/.github/scripts/publish-csharp-docs.sh b/.github/scripts/publish-csharp-docs.sh new file mode 100755 index 0000000..7e0eb59 --- /dev/null +++ b/.github/scripts/publish-csharp-docs.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash + +set -euo pipefail + +if [[ -z ${GITHUB_REPOSITORY:-} || -z ${GITHUB_TOKEN:-} ]]; then + echo "GITHUB_REPOSITORY and GITHUB_TOKEN are required." >&2 + exit 1 +fi + +site_directory=${1:-_site} +if [[ ! -f "$site_directory/index.html" || ! -f "$site_directory/Platform.Collections.Methods.pdf" ]]; then + echo "$site_directory must contain index.html and Platform.Collections.Methods.pdf." >&2 + exit 1 +fi + +site_directory=$(cd "$site_directory" && pwd) +deploy_directory=$(mktemp -d) + +cleanup() { + rm -rf "$deploy_directory" +} +trap cleanup EXIT + +authorization=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0) +repository_url="https://github.com/${GITHUB_REPOSITORY}.git" +git -c http.extraheader="AUTHORIZATION: basic $authorization" clone \ + --branch gh-pages --depth 1 "$repository_url" "$deploy_directory" + +destination="$deploy_directory/csharp" +mkdir -p "$destination" +find "$destination" -mindepth 1 -delete +cp -a "$site_directory/." "$destination/" + +git -C "$deploy_directory" config user.name linksplatform +git -C "$deploy_directory" config user.email linksplatformtechnologies@gmail.com +git -C "$deploy_directory" add --all + +if git -C "$deploy_directory" diff --cached --quiet; then + echo "Documentation is already current." + exit 0 +fi + +git -C "$deploy_directory" commit -m "Deploy C# documentation: ${GITHUB_SHA:-unknown}" +git -C "$deploy_directory" -c http.extraheader="AUTHORIZATION: basic $authorization" \ + push origin HEAD:gh-pages diff --git a/.github/scripts/push-nuget-package.sh b/.github/scripts/push-nuget-package.sh new file mode 100755 index 0000000..91e1786 --- /dev/null +++ b/.github/scripts/push-nuget-package.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Push one package to nuget.org, or skip when the release preflight found the +# version already published. A rejected key only surfaced as a bare +# "403 (The specified API key is invalid, has expired, ...)" line (linksplatform/Interfaces#150); +# this prints what the maintainer has to change instead. +# +# Usage: push-nuget-package.sh +# Environment: +# NUGET_API_KEY short-lived trusted-publishing key or the NUGET_TOKEN secret +# PUBLISH_REQUIRED output of preflight-nuget-release.mjs (default: true) +# AUTH trusted-publishing or api-key, used in the guidance +# VERBOSE=1 or RUNNER_DEBUG=1 traces every command (off by default) +set -euo pipefail + +if [ "${VERBOSE:-}" = 1 ] || [ "${RUNNER_DEBUG:-}" = 1 ]; then + set -x +fi + +package="${1:?Usage: push-nuget-package.sh }" +if [ "${PUBLISH_REQUIRED:-true}" != true ]; then + echo "$(basename "$package") is already on nuget.org; nothing to publish." + exit 0 +fi +if [ ! -s "$package" ]; then + echo "::error title=NuGet push failed::$package does not exist" + exit 1 +fi +if [ -z "${NUGET_API_KEY:-}" ]; then + echo "::error title=NuGet push failed::No API key: configure the NUGET_USER variable for trusted publishing or the NUGET_TOKEN secret" + exit 1 +fi + +log="$(mktemp)" +trap 'rm -f "$log"' EXIT +if dotnet nuget push "$package" \ + --source https://api.nuget.org/v3/index.json \ + --api-key "$NUGET_API_KEY" \ + --skip-duplicate 2>&1 | tee "$log"; then + exit 0 +fi + +if grep -qE '(^|[^0-9])403([^0-9]|$)|Forbidden' "$log"; then + if [ "${AUTH:-api-key}" = trusted-publishing ]; then + echo "::error title=nuget.org rejected the trusted publishing key::Check that the nuget.org trusted publishing policy for this package names repository ${GITHUB_REPOSITORY:-} and workflow file $(basename "${GITHUB_WORKFLOW_REF%@*}") and that its owner still owns the package." + else + echo "::error title=nuget.org rejected NUGET_TOKEN::The NUGET_TOKEN secret is invalid, expired, or not scoped to push this package. Create a new key at https://www.nuget.org/account/apikeys with push scope for the package and store it as the NUGET_TOKEN repository secret, or configure trusted publishing (https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) and set the NUGET_USER repository variable." + fi +fi +exit 1 diff --git a/.github/scripts/push-nuget-package.test.mjs b/.github/scripts/push-nuget-package.test.mjs new file mode 100644 index 0000000..cab896b --- /dev/null +++ b/.github/scripts/push-nuget-package.test.mjs @@ -0,0 +1,88 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const script = new URL("./push-nuget-package.sh", import.meta.url).pathname; +// The exact line nuget.org returned in run 36213154898 (linksplatform/Interfaces#150). +const rejectedKey = + "error: Response status code does not indicate success: 403 (The specified API key is invalid, has expired, or does not have permission to access the specified package.)."; + +const withFakeDotnet = (dotnetBody, callback) => { + const directory = mkdtempSync(path.join(tmpdir(), "push-nuget-")); + try { + const dotnet = path.join(directory, "dotnet"); + writeFileSync(dotnet, `#!/usr/bin/env bash\necho "$@" > "${directory}/args"\n${dotnetBody}\n`); + chmodSync(dotnet, 0o755); + const nupkg = path.join(directory, "P.1.0.0.nupkg"); + writeFileSync(nupkg, "package"); + return callback({ directory, nupkg }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const push = (directory, nupkg, environment) => + spawnSync("bash", [script, nupkg], { + encoding: "utf8", + env: { PATH: `${directory}:${process.env.PATH}`, ...environment }, + }); + +test("skips the push when the version is already published", () => { + withFakeDotnet("exit 99", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { PUBLISH_REQUIRED: "false" }); + assert.equal(result.status, 0); + assert.match(result.stdout, /already on nuget\.org/); + }); +}); + +test("fails without a key instead of silently skipping", () => { + withFakeDotnet("exit 0", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { PUBLISH_REQUIRED: "true" }); + assert.equal(result.status, 1); + assert.match(result.stdout, /::error title=NuGet push failed::No API key/); + }); +}); + +test("pushes with --skip-duplicate to nuget.org", () => { + withFakeDotnet("exit 0", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { NUGET_API_KEY: "key" }); + assert.equal(result.status, 0); + const args = spawnSync("cat", [path.join(directory, "args")], { encoding: "utf8" }).stdout; + assert.match(args, /^nuget push .*P\.1\.0\.0\.nupkg --source https:\/\/api\.nuget\.org\/v3\/index\.json --api-key key --skip-duplicate/); + }); +}); + +test("explains how to renew an expired NUGET_TOKEN", () => { + withFakeDotnet(`echo '${rejectedKey}'; exit 1`, ({ directory, nupkg }) => { + const result = push(directory, nupkg, { NUGET_API_KEY: "expired", AUTH: "api-key" }); + assert.equal(result.status, 1); + assert.match(result.stdout, /::error title=nuget\.org rejected NUGET_TOKEN::/); + assert.match(result.stdout, /trusted-publishing/); + }); +}); + +test("explains how to fix a rejected trusted publishing policy", () => { + withFakeDotnet(`echo '${rejectedKey}'; exit 1`, ({ directory, nupkg }) => { + const result = push(directory, nupkg, { + NUGET_API_KEY: "short-lived", + AUTH: "trusted-publishing", + GITHUB_REPOSITORY: "linksplatform/Collections.Methods", + GITHUB_WORKFLOW_REF: "linksplatform/Collections.Methods/.github/workflows/csharp.yml@refs/heads/main", + }); + assert.equal(result.status, 1); + assert.match(result.stdout, /rejected the trusted publishing key::.*linksplatform\/Collections\.Methods .*csharp\.yml/); + }); +}); + +test("keeps other push failures red without misleading guidance", () => { + withFakeDotnet("echo 'error: 500 (Internal Server Error)'; exit 1", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { NUGET_API_KEY: "key" }); + assert.equal(result.status, 1); + assert.doesNotMatch(result.stdout, /rejected/); + }); +}); diff --git a/.github/scripts/render-benchmarks.mjs b/.github/scripts/render-benchmarks.mjs new file mode 100644 index 0000000..8939229 --- /dev/null +++ b/.github/scripts/render-benchmarks.mjs @@ -0,0 +1,413 @@ +#!/usr/bin/env node + +/** + * Turns the results of the C# (BenchmarkDotNet) and C++ (Google Benchmark) + * benchmarks into benchmarks/results.json and renders that file into the + * benchmark section of README.md, which both NuGet packages ship. + * + * node render-benchmarks.mjs normalize [--csharp ] + * [--cpp ] [--cpp-compiler ] [--run-url ] + * [--commit ] [--results benchmarks/results.json] + * node render-benchmarks.mjs readme [--results benchmarks/results.json] [--readme README.md] [--check] + * + * normalize replaces the records of the languages it is given and keeps the + * others, so the C# and C++ benchmarks can be measured separately. readme + * --check fails when README.md does not show what results.json holds. + */ + +import { readFileSync, readdirSync, writeFileSync, existsSync } from "node:fs"; +import { join, resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); + +export const START_MARKER = ""; +export const END_MARKER = ""; + +export const LANGUAGES = ["C#", "C++"]; + +/** The structures in the order of the tables; the first of each kind is the baseline of the ratios. */ +export const TREES = ["SizeBalancedTree", "RecursionlessSizeBalancedTree", "SizedAndThreadedAVLBalancedTree"]; +export const LISTS = [ + "AbsoluteCircularDoublyLinkedList", + "AbsoluteOpenDoublyLinkedList", + "RelativeCircularDoublyLinkedList", + "RelativeOpenDoublyLinkedList", +]; + +/** The benchmark groups, named as the C# benchmark classes, in the order of the README. */ +export const GROUPS = [ + { + name: "TreeBenchmarks", + title: "Trees: attach and detach", + description: + "Attaches the nodes 1..N to an empty tree in the given order, then detaches all of them (in another random order for Random).", + structures: TREES, + parameters: ["N", "Order"], + }, + { + name: "TreeSearchBenchmarks", + title: "Trees: search", + description: "Looks every one of the N nodes up (Contains) in a tree built by attaching them in the given order.", + structures: TREES, + parameters: ["N", "Order"], + }, + { + name: "ListBenchmarks", + title: "Lists: attach and detach", + description: "Attaches the elements 1..N to an empty list as last ones, then detaches all of them from the first one.", + structures: LISTS, + parameters: ["N"], + }, + { + name: "StorageBenchmarks", + title: "Memory: storage of N nodes", + description: + "Creates an empty tree or list that can hold N nodes besides the zero node; the allocated bytes are the memory it uses, the bytes per node divide them by N + 1.", + structures: [...TREES, ...LISTS], + parameters: ["N"], + storage: true, + }, +]; + +const ORDERS = ["Ascending", "Descending", "Random"]; + +const TIME_UNITS = { ns: 1, us: 1e3, ms: 1e6, s: 1e9 }; + +/** Parses "N=1000&Order=Random" (BenchmarkDotNet) or "N:1000/Order:Random" (Google Benchmark). */ +export const parseParameters = (text, separator, assignment) => + Object.fromEntries( + text + .split(separator) + .filter(Boolean) + .map((pair) => { + const index = pair.indexOf(assignment); + const name = pair.slice(0, index); + const value = pair.slice(index + 1); + return [name, /^\d+$/.test(value) ? Number(value) : value]; + }), + ); + +/** Reads the *-report-full*.json files that BenchmarkDotNet's json exporter writes into a results directory. */ +export const readBenchmarkDotNet = (directory) => { + const files = readdirSync(directory) + .filter((name) => /-report-full(?:-compressed)?\.json$/.test(name)) + .sort(); + if (files.length === 0) { + throw new Error(`No BenchmarkDotNet JSON reports in ${directory}.`); + } + let environment; + const records = []; + for (const file of files) { + const report = JSON.parse(readFileSync(join(directory, file), "utf8")); + const host = report.HostEnvironmentInfo; + environment = { + benchmarkDotNet: host.BenchmarkDotNetVersion, + runtime: host.RuntimeVersion, + os: host.OsVersion, + processor: host.ProcessorName, + logicalCores: host.LogicalCoreCount, + }; + for (const benchmark of report.Benchmarks) { + if (!benchmark.Statistics) { + continue; // The benchmark failed; BenchmarkDotNet already reported why. + } + records.push({ + language: "C#", + group: benchmark.Type, + structure: benchmark.Method, + parameters: parseParameters(benchmark.Parameters ?? "", "&", "="), + meanNanoseconds: benchmark.Statistics.Mean, + allocatedBytes: benchmark.Memory?.BytesAllocatedPerOperation ?? null, + }); + } + } + return { environment, records }; +}; + +/** Reads the JSON output of Google Benchmark, preferring the mean aggregates of repeated runs. */ +export const readGoogleBenchmark = (file, compiler) => { + const output = JSON.parse(readFileSync(file, "utf8")); + const context = output.context; + const environment = { + googleBenchmark: context.library_version, + compiler: compiler || null, + cpus: context.num_cpus, + mhzPerCpu: context.mhz_per_cpu, + buildType: context.library_build_type, + }; + const runs = output.benchmarks.filter((run) => !run.error_occurred); + const means = runs.filter((run) => run.run_type === "aggregate" && run.aggregate_name === "mean"); + const selected = means.length > 0 ? means : runs.filter((run) => run.run_type !== "aggregate"); + const records = selected.map((run) => { + const [group, structure, ...parameters] = run.run_name.split("/"); + return { + language: "C++", + group, + structure, + parameters: parseParameters(parameters.join("/"), "/", ":"), + meanNanoseconds: run.real_time * TIME_UNITS[run.time_unit ?? "ns"], + allocatedBytes: run.AllocatedBytes ?? null, + }; + }); + return { environment, records }; +}; + +const sortRecords = (records) => + [...records].sort( + (a, b) => + LANGUAGES.indexOf(a.language) - LANGUAGES.indexOf(b.language) || + GROUPS.findIndex(({ name }) => name === a.group) - GROUPS.findIndex(({ name }) => name === b.group) || + (a.parameters.N ?? 0) - (b.parameters.N ?? 0) || + ORDERS.indexOf(a.parameters.Order) - ORDERS.indexOf(b.parameters.Order) || + [...TREES, ...LISTS].indexOf(a.structure) - [...TREES, ...LISTS].indexOf(b.structure), + ); + +/** Merges new measurements into the existing results: the languages measured now replace their old records. */ +export const mergeResults = (existing, measured, details) => { + const languages = new Set(measured.map(({ language }) => language)); + const environments = { ...(existing?.environments ?? {}) }; + for (const [language, environment] of Object.entries(details.environments)) { + environments[language] = { ...environment, date: details.date, commit: details.commit, runUrl: details.runUrl }; + } + return { + environments, + records: sortRecords([...(existing?.records ?? []).filter(({ language }) => !languages.has(language)), ...measured]), + }; +}; + +/** Formats a duration in nanoseconds with three significant digits. */ +export const formatTime = (nanoseconds) => { + if (nanoseconds == null) { + return "–"; + } + const [unit, scale] = + nanoseconds >= 1e9 ? ["s", 1e9] : nanoseconds >= 1e6 ? ["ms", 1e6] : nanoseconds >= 1e3 ? ["μs", 1e3] : ["ns", 1]; + return `${Number((nanoseconds / scale).toPrecision(3))} ${unit}`; +}; + +/** Formats a byte count in binary units, as BenchmarkDotNet does. */ +export const formatBytes = (bytes) => { + if (bytes == null) { + return "–"; + } + const rounded = Math.round(bytes); + if (rounded < 1024) { + return `${rounded} B`; + } + const [unit, scale] = rounded >= 1024 * 1024 ? ["MB", 1024 * 1024] : ["KB", 1024]; + return `${(rounded / scale).toFixed(2)} ${unit}`; +}; + +export const formatRatio = (value, baseline) => (value == null || !baseline ? "–" : (value / baseline).toFixed(2)); + +const parameterKey = (parameters) => JSON.stringify(parameters); + +/** The longest line of generated prose, which markdownlint (MD013) checks; tables may be longer. */ +export const LINE_WIDTH = 80; + +/** Whether a word at the start of a line would begin a list, heading or quote. */ +const startsMarkdown = (word) => /^(#|>|[-*+]$|\d+[.)]$)/.test(word); + +/** + * Wraps text at spaces into lines of at most LINE_WIDTH characters; the first + * line starts with prefix and the others with as many spaces. A word longer + * than a line, such as a link, stays whole, and a word that would start a + * list, heading or quote at the start of a line stays on the line before. + */ +export const wrap = (text, prefix = "") => { + const indent = " ".repeat(prefix.length); + const lines = []; + let line = prefix; + for (const word of text.split(/\s+/).filter(Boolean)) { + const start = lines.length === 0 ? prefix : indent; + if (line.length > start.length && line.length + 1 + word.length > LINE_WIDTH && !startsMarkdown(word)) { + lines.push(line); + line = indent + word; + } else { + line = line.length > start.length ? `${line} ${word}` : line + word; + } + } + lines.push(line); + return lines.join("\n"); +}; + +const describeEnvironment = (language, environment) => { + if (!environment) { + return `${language}: not measured yet.`; + } + const where = + language === "C#" + ? `${environment.runtime}, BenchmarkDotNet ${environment.benchmarkDotNet}, ${environment.os}, ${environment.processor}, ${environment.logicalCores} logical cores` + : `${environment.compiler ? `${environment.compiler}, ` : ""}Google Benchmark ${environment.googleBenchmark}, ${environment.cpus} CPUs at ${environment.mhzPerCpu} MHz`; + const source = environment.runUrl ? `[Benchmarks workflow run](${environment.runUrl})` : "local run"; + const commit = environment.commit ? ` of commit \`${environment.commit.slice(0, 7)}\`` : ""; + const date = environment.date ? ` on ${environment.date.slice(0, 10)}` : ""; + return `${language}: ${where} (${source}${commit}${date}).`; +}; + +const renderGroup = (group, records) => { + const inGroup = records.filter((record) => record.group === group.name); + const find = (language, structure, parameters) => + inGroup.find( + (record) => + record.language === language && + record.structure === structure && + parameterKey(record.parameters) === parameterKey(parameters), + ); + const parameterSets = []; + for (const record of sortRecords(inGroup)) { + const parameters = Object.fromEntries(group.parameters.map((name) => [name, record.parameters[name]])); + if (!parameterSets.some((known) => parameterKey(known) === parameterKey(parameters))) { + parameterSets.push(parameters); + } + } + parameterSets.sort( + (a, b) => (a.N ?? 0) - (b.N ?? 0) || ORDERS.indexOf(a.Order) - ORDERS.indexOf(b.Order), + ); + const kind = group.storage ? "Structure" : group.structures === LISTS ? "List" : "Tree"; + const columns = group.storage + ? LANGUAGES.flatMap((language) => [`${language} allocated`, `${language} bytes per node`]) + : LANGUAGES.flatMap((language) => [`${language} mean`, `${language} ratio`, `${language} allocated`]); + const header = [...group.parameters, kind, ...columns]; + const lines = [ + `### ${group.title}`, + "", + wrap(group.description), + "", + `| ${header.join(" | ")} |`, + `| ${header.map((_, index) => (index < group.parameters.length + 1 ? "---" : "---:")).join(" | ")} |`, + ]; + for (const parameters of parameterSets) { + for (const structure of group.structures) { + const cells = LANGUAGES.flatMap((language) => { + const record = find(language, structure, parameters); + if (group.storage) { + const perNode = record?.allocatedBytes == null ? null : record.allocatedBytes / (parameters.N + 1); + return [formatBytes(record?.allocatedBytes), perNode == null ? "–" : perNode.toFixed(1)]; + } + const baseline = find(language, group.structures[0], parameters); + return [ + formatTime(record?.meanNanoseconds), + formatRatio(record?.meanNanoseconds, baseline?.meanNanoseconds), + formatBytes(record?.allocatedBytes), + ]; + }); + if (cells.every((cell) => cell === "–")) { + continue; + } + lines.push(`| ${[...group.parameters.map((name) => parameters[name]), structure, ...cells].join(" | ")} |`); + } + } + return lines.join("\n"); +}; + +/** Renders the benchmark section of the README, between and including its markers. */ +export const renderSection = (results) => { + const parts = [ + START_MARKER, + "", + "", + wrap( + "Run the [Benchmarks workflow](https://github.com/linksplatform/Collections.Methods/actions/workflows/benchmarks.yml) with commit-results to update these results, which come from:", + ), + "", + ...LANGUAGES.map((language) => wrap(describeEnvironment(language, results.environments?.[language]), "* ")), + "", + wrap( + "Mean is the time of one invocation, which handles all N nodes; ratio compares it with the first structure of the same table, language and parameters; allocated is the heap memory one invocation allocates. Shared runners are noisy, so compare ratios rather than absolute times, and measure on your own hardware for decisions.", + ), + ...GROUPS.flatMap((group) => ["", renderGroup(group, results.records ?? [])]), + "", + END_MARKER, + ]; + return parts.join("\n"); +}; + +/** Replaces the benchmark section of a README. */ +export const replaceSection = (readme, section) => { + const start = readme.indexOf(START_MARKER); + const end = readme.indexOf(END_MARKER); + if (start < 0 || end < start) { + throw new Error(`README.md must contain ${START_MARKER} followed by ${END_MARKER}.`); + } + return readme.slice(0, start) + section + readme.slice(end + END_MARKER.length); +}; + +const parseArguments = (argv) => { + const [command, ...rest] = argv; + const options = {}; + for (let index = 0; index < rest.length; index++) { + const name = rest[index]; + if (!name.startsWith("--")) { + throw new Error(`Unexpected argument ${name}.`); + } + if (name === "--check") { + options.check = true; + } else { + options[name.slice(2)] = rest[++index]; + } + } + return { command, options }; +}; + +export const main = (argv) => { + const { command, options } = parseArguments(argv); + const resultsPath = resolve(options.results ?? join(repositoryRoot, "benchmarks", "results.json")); + if (command === "normalize") { + const measured = []; + const environments = {}; + if (options.csharp) { + const { environment, records } = readBenchmarkDotNet(options.csharp); + environments["C#"] = environment; + measured.push(...records); + } + if (options.cpp) { + const { environment, records } = readGoogleBenchmark(options.cpp, options["cpp-compiler"]); + environments["C++"] = environment; + measured.push(...records); + } + if (measured.length === 0) { + throw new Error("Pass --csharp, --cpp or both."); + } + const existing = existsSync(resultsPath) ? JSON.parse(readFileSync(resultsPath, "utf8")) : undefined; + const results = mergeResults(existing, measured, { + environments, + date: options.date ?? new Date().toISOString(), + commit: options.commit ?? null, + runUrl: options["run-url"] ?? null, + }); + writeFileSync(resultsPath, `${JSON.stringify(results, null, 2)}\n`); + console.log(`Wrote ${results.records.length} results to ${resultsPath}.`); + return 0; + } + if (command === "readme") { + const readmePath = resolve(options.readme ?? join(repositoryRoot, "README.md")); + const results = JSON.parse(readFileSync(resultsPath, "utf8")); + const readme = readFileSync(readmePath, "utf8"); + const updated = replaceSection(readme, renderSection(results)); + if (options.check) { + if (updated !== readme) { + console.error( + `${readmePath} does not show ${resultsPath}; run: node .github/scripts/render-benchmarks.mjs readme`, + ); + return 1; + } + console.log(`${readmePath} shows ${resultsPath}.`); + return 0; + } + writeFileSync(readmePath, updated); + console.log(`Rendered ${resultsPath} into ${readmePath}.`); + return 0; + } + throw new Error("Usage: render-benchmarks.mjs normalize|readme [options]"); +}; + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try { + process.exitCode = main(process.argv.slice(2)); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} diff --git a/.github/scripts/render-benchmarks.test.mjs b/.github/scripts/render-benchmarks.test.mjs new file mode 100644 index 0000000..56faf27 --- /dev/null +++ b/.github/scripts/render-benchmarks.test.mjs @@ -0,0 +1,270 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { + END_MARKER, + GROUPS, + LISTS, + START_MARKER, + TREES, + formatBytes, + formatTime, + main, + mergeResults, + parseParameters, + readBenchmarkDotNet, + readGoogleBenchmark, + LINE_WIDTH, + renderSection, + replaceSection, + wrap, +} from "./render-benchmarks.mjs"; + +const withDirectory = (body) => { + const directory = mkdtempSync(join(tmpdir(), "render-benchmarks-")); + try { + return body(directory); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const benchmarkDotNetReport = { + HostEnvironmentInfo: { + BenchmarkDotNetVersion: "0.14.0", + RuntimeVersion: ".NET 8.0.11", + OsVersion: "Ubuntu 24.04", + ProcessorName: "AMD EPYC", + LogicalCoreCount: 4, + }, + Benchmarks: [ + { + Type: "TreeBenchmarks", + Method: "SizeBalancedTree", + Parameters: "N=1000&Order=Random", + Statistics: { Mean: 200000 }, + Memory: { BytesAllocatedPerOperation: 0 }, + }, + { + Type: "TreeBenchmarks", + Method: "SizedAndThreadedAVLBalancedTree", + Parameters: "N=1000&Order=Random", + Statistics: { Mean: 100000 }, + Memory: { BytesAllocatedPerOperation: 0 }, + }, + { Type: "TreeBenchmarks", Method: "RecursionlessSizeBalancedTree", Parameters: "N=1000&Order=Random", Statistics: null }, + ], +}; + +const googleBenchmarkOutput = { + context: { library_version: "v1.9.1", num_cpus: 4, mhz_per_cpu: 3000, library_build_type: "release" }, + benchmarks: [ + { + run_name: "StorageBenchmarks/AbsoluteOpenDoublyLinkedList/N:1000", + run_type: "iteration", + real_time: 1, + time_unit: "us", + AllocatedBytes: 16000, + }, + { + run_name: "StorageBenchmarks/AbsoluteOpenDoublyLinkedList/N:1000", + run_type: "aggregate", + aggregate_name: "mean", + real_time: 2, + time_unit: "us", + AllocatedBytes: 8016, + }, + { + run_name: "StorageBenchmarks/AbsoluteOpenDoublyLinkedList/N:1000", + run_type: "aggregate", + aggregate_name: "stddev", + real_time: 0.1, + time_unit: "us", + AllocatedBytes: 0, + }, + ], +}; + +test("parses the parameters of both frameworks", () => { + assert.deepEqual(parseParameters("N=1000&Order=Random", "&", "="), { N: 1000, Order: "Random" }); + assert.deepEqual(parseParameters("N:100000/Order:Ascending", "/", ":"), { N: 100000, Order: "Ascending" }); + assert.deepEqual(parseParameters("", "&", "="), {}); +}); + +test("reads the BenchmarkDotNet reports and skips failed benchmarks", () => + withDirectory((directory) => { + writeFileSync(join(directory, "TreeBenchmarks-report-full-compressed.json"), JSON.stringify(benchmarkDotNetReport)); + writeFileSync(join(directory, "TreeBenchmarks-report-github.md"), "ignored"); + const { environment, records } = readBenchmarkDotNet(directory); + assert.equal(environment.runtime, ".NET 8.0.11"); + assert.deepEqual(records, [ + { + language: "C#", + group: "TreeBenchmarks", + structure: "SizeBalancedTree", + parameters: { N: 1000, Order: "Random" }, + meanNanoseconds: 200000, + allocatedBytes: 0, + }, + { + language: "C#", + group: "TreeBenchmarks", + structure: "SizedAndThreadedAVLBalancedTree", + parameters: { N: 1000, Order: "Random" }, + meanNanoseconds: 100000, + allocatedBytes: 0, + }, + ]); + })); + +test("refuses a directory without BenchmarkDotNet reports", () => + withDirectory((directory) => assert.throws(() => readBenchmarkDotNet(directory), /No BenchmarkDotNet JSON reports/))); + +test("reads the means of repeated Google Benchmark runs", () => + withDirectory((directory) => { + const file = join(directory, "cpp.json"); + writeFileSync(file, JSON.stringify(googleBenchmarkOutput)); + const { environment, records } = readGoogleBenchmark(file, "g++ 13.3.0"); + assert.equal(environment.compiler, "g++ 13.3.0"); + assert.deepEqual(records, [ + { + language: "C++", + group: "StorageBenchmarks", + structure: "AbsoluteOpenDoublyLinkedList", + parameters: { N: 1000 }, + meanNanoseconds: 2000, + allocatedBytes: 8016, + }, + ]); + })); + +test("reads single Google Benchmark runs", () => + withDirectory((directory) => { + const file = join(directory, "cpp.json"); + writeFileSync(file, JSON.stringify({ ...googleBenchmarkOutput, benchmarks: googleBenchmarkOutput.benchmarks.slice(0, 1) })); + assert.equal(readGoogleBenchmark(file).records[0].allocatedBytes, 16000); + })); + +test("replaces only the languages that were measured again", () => { + const old = (language, meanNanoseconds) => ({ + language, + group: "ListBenchmarks", + structure: LISTS[0], + parameters: { N: 1000 }, + meanNanoseconds, + allocatedBytes: 0, + }); + const existing = { environments: { "C#": { runtime: "old" }, "C++": { compiler: "old" } }, records: [old("C++", 1), old("C#", 2)] }; + const merged = mergeResults(existing, [old("C++", 3)], { + environments: { "C++": { compiler: "new" } }, + date: "2026-01-02T03:04:05Z", + commit: "0123456789", + runUrl: null, + }); + assert.deepEqual( + merged.records.map(({ language, meanNanoseconds }) => [language, meanNanoseconds]), + [ + ["C#", 2], + ["C++", 3], + ], + ); + assert.equal(merged.environments["C#"].runtime, "old"); + assert.deepEqual(merged.environments["C++"], { compiler: "new", date: "2026-01-02T03:04:05Z", commit: "0123456789", runUrl: null }); +}); + +test("formats times and sizes like BenchmarkDotNet", () => { + assert.equal(formatTime(999), "999 ns"); + assert.equal(formatTime(12345), "12.3 μs"); + assert.equal(formatTime(2.5e6), "2.5 ms"); + assert.equal(formatTime(3e9), "3 s"); + assert.equal(formatTime(null), "–"); + assert.equal(formatBytes(0), "0 B"); + assert.equal(formatBytes(1023.6), "1.00 KB"); + assert.equal(formatBytes(12312), "12.02 KB"); + assert.equal(formatBytes(1.5 * 1024 * 1024), "1.50 MB"); + assert.equal(formatBytes(undefined), "–"); +}); + +test("renders a table for every group with ratios against the first structure", () => { + const record = (language, group, structure, parameters, meanNanoseconds, allocatedBytes) => ({ + language, + group, + structure, + parameters, + meanNanoseconds, + allocatedBytes, + }); + const section = renderSection({ + environments: { + "C#": { runtime: ".NET 8", benchmarkDotNet: "0.14.0", os: "Ubuntu", processor: "EPYC", logicalCores: 4, date: "2026-01-02T00:00:00Z", commit: "abcdef0123", runUrl: "https://github.com/linksplatform/Collections.Methods/actions/runs/1" }, + }, + records: [ + record("C#", "TreeBenchmarks", TREES[2], { N: 1000, Order: "Random" }, 50, 0), + record("C#", "TreeBenchmarks", TREES[0], { N: 1000, Order: "Random" }, 100, 0), + record("C++", "TreeBenchmarks", TREES[0], { N: 1000, Order: "Random" }, 40, 0), + record("C++", "StorageBenchmarks", LISTS[1], { N: 1000 }, 1, 8016), + ], + }); + assert.ok(section.startsWith(START_MARKER) && section.endsWith(END_MARKER)); + for (const group of GROUPS) { + assert.match(section, new RegExp(`^### ${group.title}$`, "m")); + } + assert.match(section, /\[Benchmarks\s+workflow\s+run\]\(https:\/\/github\.com\/linksplatform\/Collections\.Methods\/actions\/runs\/1\)\s+of\s+commit\s+`abcdef0`\s+on\s+2026-01-02/); + assert.match(section, /^\* C\+\+: not measured yet\./m); + // markdownlint (MD013) allows longer table rows and lines whose overflow is one word, such as a link. + for (const line of section.split("\n")) { + const fits = line.startsWith("|") || line.length <= LINE_WIDTH || !/\s/.test(line.slice(LINE_WIDTH)); + assert.ok(fits, `${line.length} characters: ${line}`); + } + assert.match(section, /\| 1000 \| Random \| SizeBalancedTree \| 100 ns \| 1\.00 \| 0 B \| 40 ns \| 1\.00 \| 0 B \|/); + assert.match(section, /\| 1000 \| Random \| SizedAndThreadedAVLBalancedTree \| 50 ns \| 0\.50 \| 0 B \| – \| – \| – \|/); + assert.doesNotMatch(section, /RecursionlessSizeBalancedTree \|/); + assert.match(section, /\| 1000 \| AbsoluteOpenDoublyLinkedList \| – \| – \| 7\.83 KB \| 8\.0 \|/); +}); + +test("wraps prose at the line width without starting markdown on a new line", () => { + assert.equal(wrap("short text", "* "), "* short text"); + const words = Array.from({ length: 30 }, (_, index) => `word${index}`).join(" "); + const wrapped = wrap(words, "* ").split("\n"); + assert.ok(wrapped.length > 1); + assert.ok(wrapped.every((line) => line.length <= LINE_WIDTH)); + assert.ok(wrapped[0].startsWith("* word0 ") && wrapped.slice(1).every((line) => line.startsWith(" word"))); + assert.equal(wrapped.join(" ").replace(/\s+/g, " ").slice(2), words); + const link = `[run](https://example.com/${"x".repeat(LINE_WIDTH)})`; + assert.equal(wrap(`see ${link} now`), `see\n${link}\nnow`); + const beforeList = `${"a".repeat(LINE_WIDTH - 2)} - b`; + assert.equal(wrap(beforeList), `${"a".repeat(LINE_WIDTH - 2)} -\nb`); + assert.equal(wrap(`${"a".repeat(LINE_WIDTH - 5)} 1. # > + b`), `${"a".repeat(LINE_WIDTH - 5)} 1. # > +\nb`); +}); + +test("replaces the section between the markers", () => { + const readme = `a\n${START_MARKER}\nold\n${END_MARKER}\nb\n`; + assert.equal(replaceSection(readme, `${START_MARKER}\nnew\n${END_MARKER}`), `a\n${START_MARKER}\nnew\n${END_MARKER}\nb\n`); + assert.throws(() => replaceSection("no markers", "x"), /must contain/); +}); + +test("normalizes, renders and checks the README from the command line", () => + withDirectory((directory) => { + const cpp = join(directory, "cpp.json"); + const results = join(directory, "results.json"); + const readme = join(directory, "README.md"); + writeFileSync(cpp, JSON.stringify(googleBenchmarkOutput)); + writeFileSync(readme, `# Title\n\n${START_MARKER}\n${END_MARKER}\n`); + assert.throws(() => main(["normalize", "--results", results]), /Pass --csharp, --cpp or both/); + assert.equal(main(["normalize", "--cpp", cpp, "--cpp-compiler", "g++", "--results", results, "--date", "2026-01-02"]), 0); + assert.equal(JSON.parse(readFileSync(results, "utf8")).records.length, 1); + assert.equal(main(["readme", "--check", "--results", results, "--readme", readme]), 1); + assert.equal(main(["readme", "--results", results, "--readme", readme]), 0); + assert.equal(main(["readme", "--check", "--results", results, "--readme", readme]), 0); + assert.match(readFileSync(readme, "utf8"), /AbsoluteOpenDoublyLinkedList \| – \| – \| 7\.83 KB/); + assert.throws(() => main(["unknown"]), /Usage/); + assert.throws(() => main(["readme", "stray"]), /Unexpected argument/); + })); + +test("keeps the README in sync with the committed results", () => { + assert.equal(main(["readme", "--check"]), 0); +}); diff --git a/.github/scripts/validate-csharp-docs.sh b/.github/scripts/validate-csharp-docs.sh new file mode 100755 index 0000000..b72b6b3 --- /dev/null +++ b/.github/scripts/validate-csharp-docs.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +set -euo pipefail + +site=${1:?Usage: validate-csharp-docs.sh SITE_DIRECTORY} + +for file in \ + index.html \ + api/Platform.Collections.Methods.Lists.html \ + api/Platform.Collections.Methods.Trees.html \ + api/Platform.Collections.Methods.Trees.SizeBalancedTreeMethods-1.html \ + api/Platform.Collections.Methods.Trees.RecursionlessSizeBalancedTreeMethods-1.html \ + Platform.Collections.Methods.Documentation.pdf \ + xrefmap.yml; do + if [[ ! -s "$site/$file" ]]; then + echo "Documentation site is missing $site/$file." >&2 + exit 1 + fi +done + +if [[ $(head -c 5 "$site/Platform.Collections.Methods.Documentation.pdf") != '%PDF-' ]]; then + echo "Documentation PDF is invalid: $site/Platform.Collections.Methods.Documentation.pdf." >&2 + exit 1 +fi + +if ! grep -Fq 'Platform.Collections.Methods.Documentation.pdf' "$site/index.html"; then + echo "Documentation home page is missing its PDF link: $site/index.html." >&2 + exit 1 +fi + +echo "Validated DocFX home page, API pages, documentation PDF, and cross-reference map." diff --git a/.github/scripts/validate-csharp-docs.test.mjs b/.github/scripts/validate-csharp-docs.test.mjs new file mode 100644 index 0000000..adcf3e7 --- /dev/null +++ b/.github/scripts/validate-csharp-docs.test.mjs @@ -0,0 +1,92 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; + +const validator = new URL("./validate-csharp-docs.sh", import.meta.url).pathname; + +const withSite = (files, check, contents = {}) => { + const site = mkdtempSync(join(tmpdir(), "csharp-docs-")); + try { + for (const file of files) { + const path = join(site, file); + mkdirSync(join(path, ".."), { recursive: true }); + const content = file === "index.html" + ? 'Documentation PDF' + : file.endsWith(".pdf") ? "%PDF-1.7\n" : "generated content"; + writeFileSync(path, contents[file] ?? content); + } + check(spawnSync("bash", [validator, site], { encoding: "utf8" })); + } finally { + rmSync(site, { recursive: true, force: true }); + } +}; + +const requiredFiles = [ + "index.html", + "api/Platform.Collections.Methods.Lists.html", + "api/Platform.Collections.Methods.Trees.html", + "api/Platform.Collections.Methods.Trees.SizeBalancedTreeMethods-1.html", + "api/Platform.Collections.Methods.Trees.RecursionlessSizeBalancedTreeMethods-1.html", + "xrefmap.yml", + "Platform.Collections.Methods.Documentation.pdf", +]; + +test("accepts a complete DocFX site", () => { + withSite(requiredFiles, ({ status, stderr }) => { + assert.equal(status, 0, stderr); + }); +}); + +for (const missingFile of requiredFiles) { + test(`rejects a site missing ${missingFile}`, () => { + withSite(requiredFiles.filter((file) => file !== missingFile), ({ status, stderr }) => { + assert.notEqual(status, 0); + assert.ok(stderr.includes(missingFile), stderr); + }); + }); +} + +test("rejects an invalid documentation PDF", () => { + withSite(requiredFiles, ({ status, stderr }) => { + assert.notEqual(status, 0); + assert.match(stderr, /Documentation PDF is invalid/); + }, { "Platform.Collections.Methods.Documentation.pdf": "not a PDF" }); +}); + +test("rejects a site with no documentation PDF link", () => { + withSite(requiredFiles, ({ status, stderr }) => { + assert.notEqual(status, 0); + assert.match(stderr, /home page is missing its PDF link/); + }, { "index.html": "generated content" }); +}); + +// DocFX writes a page only for a namespace that has types and for each type +// (generic types get a - suffix), so a required page that names +// neither can never exist and would fail every documentation build. +test("requires only pages that DocFX generates for the library", () => { + const library = new URL("../../csharp/Platform.Collections.Methods/", import.meta.url); + const pages = new Set(); + for (const file of readdirSync(library, { recursive: true })) { + if (!file.endsWith(".cs") || /(^|\/)(bin|obj)\//.test(file)) { + continue; + } + const source = readFileSync(new URL(file, library), "utf8"); + const namespace = /^\s*namespace\s+([\w.]+)/m.exec(source)?.[1]; + if (!namespace) { + continue; + } + pages.add(`api/${namespace}.html`); + for (const [, type, parameters] of source.matchAll(/\bpublic\s+(?:\w+\s+)*(?:class|struct|interface)\s+(\w+)(?:<([^>]*)>)?/g)) { + pages.add(`api/${namespace}.${type}${parameters ? `-${parameters.split(",").length}` : ""}.html`); + } + } + const script = readFileSync(validator, "utf8"); + const required = [...script.matchAll(/^\s+(api\/\S+\.html)/gm)].map(([, page]) => page); + assert.ok(required.length > 0); + assert.deepEqual(required.filter((page) => !pages.has(page)), []); +}); diff --git a/.github/scripts/validate-csharp-package.sh b/.github/scripts/validate-csharp-package.sh new file mode 100755 index 0000000..d0b76bd --- /dev/null +++ b/.github/scripts/validate-csharp-package.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +solution="$repository_root/csharp/Platform.Collections.Methods.sln" +test_project="$repository_root/csharp/Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj" +package_project="$repository_root/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj" +package_output=$(mktemp -d) + +cleanup() { + rm -rf "$package_output" +} +trap cleanup EXIT + +dotnet restore "$solution" --nologo +dotnet build "$solution" --configuration Release --no-restore --no-incremental --nologo -warnaserror +dotnet test "$test_project" --configuration Release --framework net8 --no-build --no-restore --nologo +dotnet pack "$package_project" --configuration Release --no-build --no-restore \ + --output "$package_output" --nologo -warnaserror + +mapfile -t packages < <(find "$package_output" -maxdepth 1 -type f -name '*.nupkg' -print) +mapfile -t symbol_packages < <(find "$package_output" -maxdepth 1 -type f -name '*.snupkg' -print) + +if [[ ${#packages[@]} -ne 1 ]]; then + echo "Expected one .nupkg, found ${#packages[@]}." >&2 + exit 1 +fi + +if [[ ${#symbol_packages[@]} -ne 0 ]]; then + echo "Expected embedded symbols instead of a separate .snupkg." >&2 + exit 1 +fi + +package_contents=$(unzip -Z1 "${packages[0]}") +for expected_file in README.md icon.png lib/net8.0/Platform.Collections.Methods.dll lib/net8.0/Platform.Collections.Methods.xml; do + if ! grep -Fxq "$expected_file" <<< "$package_contents"; then + echo "${packages[0]} is missing $expected_file." >&2 + exit 1 + fi +done + +# nuget.org shows README.md, which carries the benchmark results. +if ! unzip -p "${packages[0]}" README.md | grep -q ''; then + echo "${packages[0]} has no benchmark results in README.md." >&2 + exit 1 +fi + +echo "Validated ${packages[0]} with embedded symbols." diff --git a/.github/scripts/workflow-jobs.mjs b/.github/scripts/workflow-jobs.mjs new file mode 100644 index 0000000..de5cb29 --- /dev/null +++ b/.github/scripts/workflow-jobs.mjs @@ -0,0 +1,25 @@ +// Splits a workflow file into its jobs without a YAML dependency, for the +// workflow policy tests. +export const getJobs = (source) => { + const jobs = new Map(); + const lines = source.slice(source.indexOf("\njobs:\n") + 1).split("\n"); + let currentName; + let currentLines = []; + + for (const line of lines.slice(1)) { + const match = /^ ([A-Za-z_][\w-]*):\s*$/.exec(line); + if (match) { + if (currentName) { + jobs.set(currentName, currentLines.join("\n")); + } + currentName = match[1]; + currentLines = [line]; + } else if (currentName) { + currentLines.push(line); + } + } + if (currentName) { + jobs.set(currentName, currentLines.join("\n")); + } + return jobs; +}; diff --git a/.github/scripts/workflow-policy.test.mjs b/.github/scripts/workflow-policy.test.mjs new file mode 100644 index 0000000..a2ab729 --- /dev/null +++ b/.github/scripts/workflow-policy.test.mjs @@ -0,0 +1,159 @@ +#!/usr/bin/env node + +// Repository-wide guards for the CI/CD problems found in linksplatform/Interfaces#150, so a +// fix applied to one workflow cannot regress in another. + +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { readdirSync, readFileSync } from "node:fs"; +import test from "node:test"; +import { getJobs } from "./workflow-jobs.mjs"; + +const workflowsDirectory = new URL("../workflows/", import.meta.url); +const workflows = readdirSync(workflowsDirectory) + .filter((name) => /\.ya?ml$/.test(name)) + .map((name) => ({ name, source: readFileSync(new URL(name, workflowsDirectory), "utf8") })); + +const findLines = (pattern) => + workflows.flatMap(({ name, source }) => + source + .split("\n") + .map((line, index) => ({ line, location: `${name}:${index + 1}` })) + .filter(({ line }) => !line.trimStart().startsWith("#") && pattern.test(line)) + .map(({ line, location }) => `${location}: ${line.trim()}`), + ); + +test("finds every workflow", () => { + assert.ok(workflows.length >= 8, `only ${workflows.length} workflows found`); +}); + +test("pins runner images so -latest label migrations cannot change builds", () => { + assert.deepEqual(findLines(/(runs-on|os):\s*[\w-]*-latest/), []); +}); + +test("caps every job that runs on a runner", () => { + const failures = []; + for (const { name, source } of workflows) { + for (const [job, body] of getJobs(source)) { + if (/\n runs-on:/.test(body) && !/\n timeout-minutes:\s*\d+/.test(body)) { + failures.push(`${name}: ${job}`); + } + } + } + assert.deepEqual(failures, []); +}); + +test("declares least-privilege token permissions in every workflow", () => { + const failures = workflows + .filter(({ source }) => !/^permissions:/m.test(source)) + .map(({ name }) => name); + assert.deepEqual(failures, []); +}); + +test("never persists checkout credentials", () => { + const failures = []; + for (const { name, source } of workflows) { + const lines = source.split("\n"); + lines.forEach((line, index) => { + if (line.includes("uses: actions/checkout@")) { + const step = lines.slice(index, index + 8).join("\n"); + if (!/persist-credentials:\s*false/.test(step)) { + failures.push(`${name}:${index + 1}`); + } + } + }); + } + assert.deepEqual(failures, []); +}); + +test("names the default branch so checkout prints no 'Using master' hint", () => { + const missing = workflows + .filter(({ source }) => source.includes("uses: actions/checkout@")) + .filter(({ source }) => !/^env:\n(?: {2}.*\n)*? {2}GIT_CONFIG_KEY_0: init\.defaultBranch\n {2}GIT_CONFIG_VALUE_0: main\n/m.test(source)) + .map(({ name }) => name); + assert.deepEqual(missing, []); +}); + +test("uses no actions that run on the deprecated Node 20 runtime", () => { + assert.deepEqual( + findLines( + /uses:\s*(?:actions\/(?:checkout|setup-dotnet|setup-node|setup-python|cache)@v[1-4]\b|actions\/(?:upload|download)-artifact@v[1-4]\b|ncipollo\/release-action|egor-tensin\/setup-gcc|ahmadnassri\/)/, + ), + [], + ); +}); + +test("pins third-party actions to a full commit hash", () => { + const trusted = /^(?:actions|github)\//; + const failures = findLines(/^\s*(?:-\s*)?uses:\s*[^.\s]/).filter((entry) => { + const reference = /uses:\s*(\S+)/.exec(entry)[1]; + if (reference.startsWith("docker://")) { + return !/@sha256:[0-9a-f]{64}$/.test(reference); + } + return !trusted.test(reference) && !/@[0-9a-f]{40}$/.test(reference); + }); + assert.deepEqual(failures, []); +}); + +test("keeps CI definitions in this repository instead of a mutable @main", () => { + assert.deepEqual(findLines(/uses:\s*linksplatform\/Workflows\//), []); + assert.deepEqual(findLines(/uses:\s*[^#\s]+@(?:main|master)\b/), []); +}); + +test("does not install the nuget CLI that Ubuntu 24.04 no longer ships", () => { + assert.deepEqual(findLines(/apt-get install[^#\n]*\bnuget\b/), []); +}); + +test("runs pull request checks on code changes, not only on edits", () => { + assert.deepEqual(findLines(/^\s*-\s*edited\s*$|types:\s*\[\s*edited\s*\]/), []); +}); + +test("does not trust the spoofable github.actor for bot checks", () => { + assert.deepEqual(findLines(/github\.(?:triggering_)?actor\s*==/), []); +}); + +test("lets cancelled runs stop instead of forcing jobs with always()", () => { + assert.deepEqual(findLines(/\balways\(\)/), []); +}); + +test("lets every workflow supersede stale runs without cancelling a writer", () => { + const missing = workflows + .filter(({ source }) => !/^concurrency:/m.test(source)) + .filter(({ source }) => + [...getJobs(source).values()].some((body) => /\n runs-on:/.test(body) && !/\n concurrency:/.test(body)), + ) + .map(({ name }) => name); + assert.deepEqual(missing, []); + + const writers = workflows + .filter(({ source }) => /^\s+(?:contents|packages|id-token|pages):\s*write/m.test(source)) + .filter(({ source }) => /cancel-in-progress:\s*true/.test(source)) + .map(({ name }) => name); + assert.deepEqual(writers, []); +}); + +test("scans the repository for committed secrets with a pinned scanner", () => { + const secrets = workflows.find(({ name }) => name === "secrets.yml"); + assert.ok(secrets, "secrets.yml is missing"); + assert.match(secrets.source, /secretlint@\d+\.\d+\.\d+/); + assert.match(secrets.source, /@secretlint\/secretlint-rule-preset-recommend@\d+\.\d+\.\d+/); + assert.doesNotMatch(secrets.source, /\n paths:/); +}); + +test("runs the extra zizmor pass offline on purpose, so it prints no fallback warning", () => { + const workflow = workflows.find(({ name }) => name === "workflows.yml").source; + // Without a token zizmor warns "running in offline mode by default"; the + // action step before it already runs the online audits. + assert.match(workflow, /uses: zizmorcore\/zizmor-action@/); + assert.match(workflow, /pipx run zizmor==[\d.]+ --offline /); +}); + +test("keeps every shell script executable, since the workflows run them directly", () => { + // A script added without the executable bit fails in CI with "Permission denied" (exit code 126). + const repository = new URL("../../", import.meta.url).pathname; + const failures = execFileSync("git", ["ls-files", "--stage", "--", "*.sh"], { cwd: repository, encoding: "utf8" }) + .split("\n") + .filter((line) => line && !line.startsWith("100755 ")) + .map((line) => line.split("\t")[1]); + assert.deepEqual(failures, []); +}); diff --git a/.github/workflows/AutoMerge.yml b/.github/workflows/AutoMerge.yml index d5c5e0c..0a90560 100644 --- a/.github/workflows/AutoMerge.yml +++ b/.github/workflows/AutoMerge.yml @@ -1,14 +1,48 @@ name: auto-merge +# pull_request_target is required because DEPENDABOT_AUTO_MERGE_TOKEN is an +# Actions secret, and Dependabot's pull_request runs only receive Dependabot +# secrets. No step checks out or executes code from the pull request. on: - pull_request_target: + pull_request_target: # zizmor: ignore[dangerous-triggers] + +permissions: {} + +# github.ref is the base branch for pull_request_target, so the group is keyed +# by pull request; a newer event for the same pull request supersedes an older one. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true jobs: auto-merge: - runs-on: ubuntu-latest + # The pull request author cannot be spoofed by re-running or commenting, + # unlike github.actor. + if: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read steps: - - uses: actions/checkout@v2 - - uses: ahmadnassri/action-dependabot-auto-merge@v2 - with: - target: minor - github-token: ${{ secrets.DEPENDABOT_AUTO_MERGE_TOKEN }} + - name: Read Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + # The previous action posted "@dependabot merge" comments, which GitHub + # removed on 2026-01-27, so it succeeded without merging (linksplatform/Interfaces#150). + - name: Enable auto-merge for patch and minor updates + if: ${{ steps.metadata.outputs.update-type != 'version-update:semver-major' }} + env: + GH_TOKEN: ${{ secrets.DEPENDABOT_AUTO_MERGE_TOKEN }} + PR_URL: ${{ github.event.pull_request.html_url }} + run: | + if [ -z "$GH_TOKEN" ]; then + echo "::error title=Auto-merge token missing::Configure the DEPENDABOT_AUTO_MERGE_TOKEN Actions secret with a token that can merge pull requests." + exit 1 + fi + if [ "$(gh api "repos/$GITHUB_REPOSITORY" --jq .allow_auto_merge)" != true ]; then + echo "::error title=Auto-merge is disabled::Enable 'Allow auto-merge' in Settings > General > Pull Requests, otherwise Dependabot pull requests are never merged." + exit 1 + fi + gh pr merge --auto --merge "$PR_URL" diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml new file mode 100644 index 0000000..8821349 --- /dev/null +++ b/.github/workflows/benchmarks.yml @@ -0,0 +1,229 @@ +name: Benchmarks + +# Benchmarks take long and are noisy on shared runners, so they only run on +# request (Actions > Benchmarks > Run workflow). Pull requests and main run the +# unit tests in csharp.yml and cpp-test.yml instead, which also keep the +# benchmarks compiling. The report job renders the results into the tables of +# README.md, which both NuGet packages ship; commit-results commits them to the +# branch the workflow runs on. +on: + workflow_dispatch: + inputs: + language: + description: Which benchmarks to run + type: choice + options: [both, csharp, cpp] + default: both + csharp-filter: + description: BenchmarkDotNet --filter pattern + type: string + default: '*' + cpp-filter: + description: Google Benchmark --benchmark_filter regular expression + type: string + default: '.*' + cpp-repetitions: + description: Google Benchmark --benchmark_repetitions + type: number + default: 5 + commit-results: + description: Commit benchmarks/results.json and the README tables to the branch + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # A run takes up to two hours and may commit its results, so a new run waits + # for it instead of cancelling it. + cancel-in-progress: false + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + csharp: + if: ${{ inputs.language != 'cpp' }} + runs-on: ubuntu-24.04 + timeout-minutes: 120 + defaults: + run: + working-directory: csharp + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + # Attach and detach and search of every node of the recursive and + # recursionless size balanced trees (the baseline) and of the AVL tree in + # ascending, descending and random order, attach and detach of the four + # doubly linked lists, and the storage of all of them. + - name: Run C# benchmarks + env: + FILTER: ${{ inputs.csharp-filter || '*' }} + run: >- + dotnet run --project Platform.Collections.Methods.Benchmarks + --configuration Release --framework net8 + -- --filter "$FILTER" --exporters github json + --artifacts "$RUNNER_TEMP/csharp-benchmarks" + + - name: Summarize C# benchmarks + run: cat "$RUNNER_TEMP"/csharp-benchmarks/results/*-report-github.md >> "$GITHUB_STEP_SUMMARY" + + - name: Upload C# benchmark results + uses: actions/upload-artifact@v7 + with: + name: csharp-benchmarks + path: ${{ runner.temp }}/csharp-benchmarks/results + if-no-files-found: error + retention-days: 30 + + cpp: + if: ${{ inputs.language != 'csharp' }} + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Build the benchmarks and run the tests + env: + CC: gcc + CXX: g++ + BENCHMARKS: '1' + run: cpp/build-and-test.sh + + - name: Run C++ benchmarks + env: + FILTER: ${{ inputs.cpp-filter || '.*' }} + REPETITIONS: ${{ inputs.cpp-repetitions || 5 }} + run: >- + cpp/build/bin/Platform.Collections.Methods.Benchmarks + --benchmark_filter="$FILTER" + --benchmark_repetitions="$REPETITIONS" + --benchmark_report_aggregates_only=true + --benchmark_out="$RUNNER_TEMP/cpp-benchmarks.json" + --benchmark_out_format=json + | tee "$RUNNER_TEMP/cpp-benchmarks.txt" + + - name: Record the compiler + run: g++ --version | head -n 1 > "$RUNNER_TEMP/cpp-compiler.txt" + + - name: Summarize C++ benchmarks + run: | + { + echo '### C++ benchmarks' + echo + echo '```' + cat "$RUNNER_TEMP/cpp-benchmarks.txt" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload C++ benchmark results + uses: actions/upload-artifact@v7 + with: + name: cpp-benchmarks + path: | + ${{ runner.temp }}/cpp-benchmarks.json + ${{ runner.temp }}/cpp-benchmarks.txt + ${{ runner.temp }}/cpp-compiler.txt + if-no-files-found: error + retention-days: 30 + + # Merges the results of the languages that ran into benchmarks/results.json + # and renders it into README.md. + report: + needs: [csharp, cpp] + if: ${{ !cancelled() && !contains(needs.*.result, 'failure') }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: '24' + + - name: Download the benchmark results + uses: actions/download-artifact@v8 + with: + pattern: '*-benchmarks' + path: ${{ runner.temp }}/results + + - name: Render the results into README.md + env: + RESULTS: ${{ runner.temp }}/results + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + arguments=() + if [[ -d "$RESULTS/csharp-benchmarks" ]]; then + arguments+=(--csharp "$RESULTS/csharp-benchmarks") + fi + if [[ -d "$RESULTS/cpp-benchmarks" ]]; then + arguments+=(--cpp "$RESULTS/cpp-benchmarks/cpp-benchmarks.json") + arguments+=(--cpp-compiler "$(cat "$RESULTS/cpp-benchmarks/cpp-compiler.txt")") + fi + node .github/scripts/render-benchmarks.mjs normalize "${arguments[@]}" --commit "$GITHUB_SHA" --run-url "$RUN_URL" + node .github/scripts/render-benchmarks.mjs readme + sed -n '//,//p' README.md >> "$GITHUB_STEP_SUMMARY" + + - name: Upload the report + uses: actions/upload-artifact@v7 + with: + name: benchmark-report + path: | + README.md + benchmarks/results.json + if-no-files-found: error + retention-days: 30 + + # The only job that can write: it commits the report to the branch the + # workflow runs on. Protected branches reject the push; run the workflow on + # another branch and open a pull request from it instead. + publish: + needs: report + if: ${{ inputs.commit-results }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + steps: + # The commit the report was rendered from: if the branch moved on since, + # the push is rejected instead of overwriting newer README changes. + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Download the report + uses: actions/download-artifact@v8 + with: + name: benchmark-report + + - name: Commit the report + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BRANCH: ${{ github.ref_name }} + run: | + git config user.name github-actions[bot] + git config user.email 41898282+github-actions[bot]@users.noreply.github.com + git add README.md benchmarks/results.json + if git diff --cached --quiet; then + echo "The benchmark results are already current." + exit 0 + fi + git commit -m "Update the benchmark results from run $GITHUB_RUN_ID" + authorization=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0) + git -c http.extraheader="AUTHORIZATION: basic $authorization" push origin "HEAD:refs/heads/$BRANCH" diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..524e8e1 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,79 @@ +name: CodeQL + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + schedule: + - cron: '43 3 * * 0' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'actions', 'c-cpp', 'csharp' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: none + queries: security-extended,security-and-quality + config-file: ./.github/codeql/codeql-config.yml + + # The C# buildless restore warns "No NuGet feeds are reachable" whenever + # one of its feed sets is empty, although nuget.org, the only feed here, + # is reachable (github/codeql#22766). With the check off it restores from + # nuget.org directly. The variable is read only by the C# extractor. + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + env: + CODEQL_EXTRACTOR_CSHARP_BUILDLESS_NUGET_FEEDS_CHECK: 'false' + with: + category: "/language:${{ matrix.language }}" + + dependency-review: + name: Dependency review + if: ${{ github.event_name == 'pull_request' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Review dependency changes + uses: actions/dependency-review-action@v5 + with: + fail-on-severity: high diff --git a/.github/workflows/cpp-test.yml b/.github/workflows/cpp-test.yml index fc4d56b..e2e5e7c 100644 --- a/.github/workflows/cpp-test.yml +++ b/.github/workflows/cpp-test.yml @@ -2,24 +2,178 @@ name: Test cpp on: push: - branches: - - 'main' + branches: [main] paths: - - 'cpp/**.h' - - 'cpp/**.cpp' - - 'cpp/CMakeLists.txt' - - 'cpp/conanfile.txt' + - 'cpp/**' + - '.github/scripts/cpp-*' + - '.github/scripts/*cpp-nuget*' + - '.github/scripts/*nuget-*' + - '.github/workflows/cpp-test.yml' pull_request: - types: - - edited - branches: - - 'main' + branches: [main] paths: - - 'cpp/**.h' - - 'cpp/**.cpp' - - 'cpp/CMakeLists.txt' - - 'cpp/conanfile.txt' - + - 'cpp/**' + - '.github/scripts/cpp-*' + - '.github/scripts/*cpp-nuget*' + - '.github/scripts/*nuget-*' + - '.github/workflows/cpp-test.yml' + workflow_call: + outputs: + package_id: + description: NuGet package id read from the nuspec + value: ${{ jobs.pack.outputs.package_id }} + version: + description: NuGet package version read from the nuspec + value: ${{ jobs.pack.outputs.version }} + workflow_dispatch: + +permissions: + contents: read + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + jobs: - main: - uses: linksplatform/Workflows/.github/workflows/cpp-test.yml@main + test: + name: test (${{ matrix.name }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + # Job-level groups: deploy-cpp.yml calls this workflow, and its own + # workflow-level group must not be shared with these jobs. The matrix name + # keeps the matrix jobs from cancelling each other. + concurrency: + group: check-${{ github.workflow }}-${{ github.ref }}-test-${{ matrix.name }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + # The headers are consumed by every compiler that restores the NuGet or + # Conan package, so each one has to build and pass the tests. + strategy: + fail-fast: false + matrix: + include: + # Also builds the benchmarks, so they keep compiling; they run only + # in the manual Benchmarks workflow. + - name: linux-gcc + os: ubuntu-24.04 + cc: gcc + cxx: g++ + benchmarks: '1' + - name: linux-clang + os: ubuntu-24.04 + cc: clang + cxx: clang++ + # Every attach and detach validates the whole tree (sizes, order and + # the size balanced property) under AddressSanitizer and UBSan. + - name: linux-gcc-sanitizers-validation + os: ubuntu-24.04 + cc: gcc + cxx: g++ + build-type: Debug + sanitizers: address;undefined + tree-validation: '1' + - name: macos-appleclang + os: macos-15 + - name: windows-msvc + os: windows-2025 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # The previous shared workflow only compiled the tests, so failing tests + # still passed CI. The script runs them through CTest. + - name: Build and run the tests + env: + MATRIX_CC: ${{ matrix.cc }} + MATRIX_CXX: ${{ matrix.cxx }} + BUILD_TYPE: ${{ matrix.build-type || 'Release' }} + SANITIZERS: ${{ matrix.sanitizers }} + TREE_VALIDATION: ${{ matrix.tree-validation }} + BENCHMARKS: ${{ matrix.benchmarks }} + run: | + # macOS and Windows use the platform compiler that CMake detects. + if [ -n "$MATRIX_CXX" ]; then + export CC="$MATRIX_CC" CXX="$MATRIX_CXX" + fi + cpp/build-and-test.sh + + coverage: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + concurrency: + group: check-${{ github.workflow }}-${{ github.ref }}-coverage + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Build and run the tests with gcov + env: + CC: gcc + CXX: g++ + BUILD_TYPE: Debug + COVERAGE: '1' + run: cpp/build-and-test.sh + + # Every line of the library headers has to be executed by the tests. + # --merge-lines merges the lines of all template instantiations. + - name: Require full line coverage of the headers + run: | + pipx run gcovr==8.8 --root cpp --object-directory cpp/build \ + --filter '.*/Platform\.Collections\.Methods/.*' \ + --merge-lines --gcov-ignore-parse-errors=all \ + --txt --txt-summary --fail-under-line 100 \ + --markdown "$RUNNER_TEMP/coverage.md" + cat "$RUNNER_TEMP/coverage.md" >> "$GITHUB_STEP_SUMMARY" + + pack: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + concurrency: + group: check-${{ github.workflow }}-${{ github.ref }}-pack + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + outputs: + package_id: ${{ steps.pack.outputs.package_id }} + version: ${{ steps.pack.outputs.version }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Test the build script + run: node --test .github/scripts/cpp-build-and-test.test.mjs + + - name: Test the NuGet release scripts + run: node --test .github/scripts/pack-cpp-nuget.test.mjs .github/scripts/check-cpp-nuget-package.test.mjs .github/scripts/preflight-nuget-release.test.mjs .github/scripts/push-nuget-package.test.mjs + + # Ubuntu 24.04 has no nuget apt package, which the shared deploy workflow + # installed; dotnet pack builds the package layout of 0.3.0 from the nuspec. + - name: Pack NuGet package + id: pack + run: node .github/scripts/pack-cpp-nuget.mjs "$RUNNER_TEMP/cpp-nuget" + + # A package that packs is not necessarily usable: restore it and its + # Platform.Interfaces dependency like a consumer and build a tree with + # its headers before it can be published. + - name: Restore and use the NuGet package + env: + PACKAGE_PATH: ${{ steps.pack.outputs.package_path }} + run: .github/scripts/check-cpp-nuget-package.sh "$PACKAGE_PATH" + + - name: Upload NuGet package + uses: actions/upload-artifact@v7 + with: + name: cpp-nuget-package + path: ${{ runner.temp }}/cpp-nuget + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/csharp.yml b/.github/workflows/csharp.yml index 19ce60a..9cc72e5 100644 --- a/.github/workflows/csharp.yml +++ b/.github/workflows/csharp.yml @@ -2,134 +2,383 @@ name: csharp on: push: - branches: main + branches: main paths: - 'csharp/**' + - 'README.md' + - '.github/scripts/*csharp*' + - '.github/scripts/*nuget-*' - '.github/workflows/csharp.yml' + pull_request: + branches: main + paths: + - 'csharp/**' + - 'README.md' + - '.github/scripts/*csharp*' + - '.github/scripts/*nuget-*' + - '.github/workflows/csharp.yml' + +permissions: + actions: read + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + env: - NUGETTOKEN: ${{ secrets.NUGET_TOKEN }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SCRIPTS_BASE_URL: https://raw.githubusercontent.com/linksplatform/Scripts/main/MultiProjectRepository - + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + defaults: run: working-directory: csharp jobs: test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Validate tests and NuGet package + run: ../.github/scripts/validate-csharp-package.sh + + - name: Test C# workflow safeguards + run: node --test ../.github/scripts/*csharp*.test.mjs ../.github/scripts/*nuget-*.test.mjs + + # Every line of the library has to be executed by the tests, so a change + # cannot leave a rotation, a rebuild or an error path untested. + coverage: + runs-on: ubuntu-24.04 + timeout-minutes: 15 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 with: - submodules: true - - name: Test + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Run the tests with coverage + run: >- + dotnet test Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj + --configuration Release --framework net8 --nologo + --collect "XPlat Code Coverage" + --results-directory "$RUNNER_TEMP/coverage" + + - name: Require full line coverage of the library run: | - dotnet test -c Release -f net8 + shopt -s globstar + node ../.github/scripts/check-csharp-coverage.mjs "$RUNNER_TEMP"/coverage/**/coverage.cobertura.xml + + # ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION makes every attach and detach check + # the sizes of the whole tree, so the tests also prove that no operation + # leaves a broken tree behind, even for a moment the tests do not inspect. + # Release keeps the Debug.WriteLine tree dumps compiled out. + treeValidation: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Run the tests with self-validating trees + run: >- + dotnet test Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj + --configuration Release --framework net8 --nologo -warnaserror + -p:TreeValidation=true + + releasePreflight: + if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + publishRequired: ${{ steps.preflight.outputs.publish_required }} + auth: ${{ steps.preflight.outputs.auth }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Check release state and credentials + id: preflight + env: + CSPROJ: Platform.Collections.Methods/Platform.Collections.Methods.csproj + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + NUGET_USER: ${{ vars.NUGET_USER }} + run: node ../.github/scripts/preflight-nuget-release.mjs + pushNuGetPackageToGitHubPackageRegistry: - needs: test - runs-on: ubuntu-latest + needs: [test, coverage, treeValidation, releasePreflight] + if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: write steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 with: - submodules: true - - uses: nuget/setup-nuget@v1 - - name: Publish NuGet package to GitHub Package Registry - run: | - dotnet build -c Release - dotnet pack -c Release - nuget source Add -Name "GitHub" -Source "https://nuget.pkg.github.com/linksplatform/index.json" -UserName linksplatform -Password ${{ secrets.GITHUB_TOKEN }} - nuget push **/*.nupkg -Source "GitHub" -SkipDuplicate - pusnToNuget: - runs-on: ubuntu-latest - needs: test + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Pack NuGet package + run: dotnet pack Platform.Collections.Methods/Platform.Collections.Methods.csproj --configuration Release --output "$RUNNER_TEMP/github-packages" --nologo -warnaserror + + - name: Add GitHub NuGet source + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: dotnet nuget add source https://nuget.pkg.github.com/linksplatform/index.json --name GitHub --username linksplatform --password "$GITHUB_TOKEN" --store-password-in-clear-text + + # GitHub Packages authenticates with GITHUB_TOKEN; trusted publishing is + # a nuget.org feature, so zizmor's suggestion does not apply here. + - name: Push NuGet package to GitHub Package Registry + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: dotnet nuget push "$RUNNER_TEMP/github-packages"/*.nupkg --source GitHub --api-key "$GITHUB_TOKEN" --skip-duplicate # zizmor: ignore[use-trusted-publishing] + + pushToNuget: + needs: [test, coverage, treeValidation, releasePreflight] + if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + id-token: write steps: - - uses: actions/checkout@v1 - with: - submodules: true - - name: Read project information - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/read_csharp_package_info.sh" - bash ./read_csharp_package_info.sh - - name: Publish NuGet package - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/push-csharp-nuget.sh" - bash ./push-csharp-nuget.sh - publiseRelease: - runs-on: ubuntu-latest - needs: test + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Pack NuGet package + run: dotnet pack Platform.Collections.Methods/Platform.Collections.Methods.csproj --configuration Release --output "$RUNNER_TEMP/nuget-packages" --nologo -warnaserror + + - name: Log in to NuGet with trusted publishing + id: nuget-login + if: ${{ needs.releasePreflight.outputs.auth == 'trusted-publishing' && needs.releasePreflight.outputs.publishRequired == 'true' }} + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ vars.NUGET_USER }} + + - name: Push NuGet package to NuGet.org + env: + AUTH: ${{ needs.releasePreflight.outputs.auth }} + PUBLISH_REQUIRED: ${{ needs.releasePreflight.outputs.publishRequired }} + NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY || secrets.NUGET_TOKEN }} + run: ../.github/scripts/push-nuget-package.sh "$RUNNER_TEMP/nuget-packages"/*.nupkg + + publishRelease: + needs: [pushNuGetPackageToGitHubPackageRegistry, pushToNuget] + if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 with: - submodules: true - - name: Read project information - if: ${{ github.event_name == 'push' }} - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/read_csharp_package_info.sh" - bash ./read_csharp_package_info.sh - - name: Publish release + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Publish GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/publish-release.sh" - chmod +x ./publish-release.sh - wget "$SCRIPTS_BASE_URL/publish-csharp-release.sh" - bash ./publish-csharp-release.sh + project=Platform.Collections.Methods/Platform.Collections.Methods.csproj + version=$(dotnet msbuild "$project" -nologo -getProperty:VersionPrefix) + release_notes=$(dotnet msbuild "$project" -nologo -getProperty:PackageReleaseNotes) + tag="csharp_${version}" + title="[C#] ${version}" + package_url="https://www.nuget.org/packages/Platform.Collections.Methods/${version}" + notes="${package_url}"$'\n\n'"${release_notes}" + if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "Release ${tag} already exists." + else + gh release create "$tag" --repo "$GITHUB_REPOSITORY" --title "$title" --notes "$notes" + fi + findChangedCsFiles: - runs-on: ubuntu-latest needs: test + runs-on: ubuntu-24.04 + timeout-minutes: 10 outputs: - isCsFilesChanged: ${{ steps.setIsCsFilesChangedOutput.outputs.isCsFilesChanged }} + documentationChanged: ${{ steps.detect.outputs.documentationChanged }} steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - name: Get changed files using defaults - id: changed-files - uses: tj-actions/changed-files@v21 - - name: Set output isCsFilesChanged - id: setIsCsFilesChangedOutput - run: | - isCsFilesChanged='false' - echo "Changed files: ${{ steps.changed-files.outputs.all_changed_files }}" - for changedFile in ${{ steps.changed-files.outputs.all_changed_files }}; do - if [[ $changedFile == *.cs ]] - then - echo "isCsFilesChanged='true'" - isCsFilesChanged='true' + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + # git diff replaces tj-actions/changed-files, which was compromised in + # March 2025 (CVE-2025-30066) and was referenced by a mutable tag. + - name: Detect documentation inputs + id: detect + env: + BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + run: | + if [ -n "$BASE_SHA" ] && git cat-file -e "${BASE_SHA}^{commit}" 2>/dev/null; then + changed_files=$(git diff --name-only "$BASE_SHA" "$GITHUB_SHA") + else + echo "No base commit to compare with; treating documentation inputs as changed." + changed_files=README.md fi - done - echo "::set-output name=isCsFilesChanged::${isCsFilesChanged}" - echo "isCsFilesChanged: ${isCsFilesChanged}" + if [ "${RUNNER_DEBUG:-}" = 1 ]; then + printf 'Changed files:\n%s\n' "$changed_files" + fi + documentation_changed=false + for changed_file in $changed_files; do + case "$changed_file" in + *.cs|README.md|.github/workflows/csharp.yml|.github/scripts/*csharp*|csharp/docfx.json|csharp/filter.yml|csharp/toc.yml) + documentation_changed=true + ;; + esac + done + echo "documentationChanged=${documentation_changed}" >> "$GITHUB_OUTPUT" + echo "Documentation inputs changed: ${documentation_changed}" + generatePdfWithCode: - runs-on: ubuntu-latest needs: [findChangedCsFiles] - if: ${{ needs.findChangedCsFiles.outputs.isCsFilesChanged == 'true' }} + if: ${{ needs.findChangedCsFiles.outputs.documentationChanged == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 steps: - - uses: actions/checkout@v1 - with: - submodules: true - - name: Generate PDF with code - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/format-csharp-files.py" - wget "$SCRIPTS_BASE_URL/format-csharp-document.sh" - wget "$SCRIPTS_BASE_URL/generate-csharp-pdf.sh" - bash ./generate-csharp-pdf.sh - publishDocumentation: - runs-on: ubuntu-latest + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Generate PDF with code + run: ../.github/scripts/generate-csharp-pdf.sh + + - name: Upload generated PDF + timeout-minutes: 5 + uses: actions/upload-artifact@v7 + with: + name: csharp-pdf + path: csharp/_site/Platform.Collections.Methods.pdf + if-no-files-found: error + retention-days: 1 + + buildDocumentation: needs: [findChangedCsFiles] - if: ${{ needs.findChangedCsFiles.outputs.isCsFilesChanged == 'true' }} + if: ${{ needs.findChangedCsFiles.outputs.documentationChanged == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 steps: - - uses: actions/checkout@v1 - with: - submodules: true - - name: Publish documentation to gh-pages branch - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/docfx.json" - wget "$SCRIPTS_BASE_URL/filter.yml" - wget "$SCRIPTS_BASE_URL/toc.yml" - wget "$SCRIPTS_BASE_URL/publish-csharp-docs.sh" - bash ./publish-csharp-docs.sh + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Build API documentation + run: | + dotnet tool install docfx --tool-path "$RUNNER_TEMP/docfx" --version 2.80.1 + "$RUNNER_TEMP/docfx/docfx" docfx.json --warningsAsErrors + cp _site/README.html _site/index.html + + - name: Validate documentation output + run: ../.github/scripts/validate-csharp-docs.sh _site + + - name: Upload documentation site + timeout-minutes: 5 + uses: actions/upload-artifact@v7 + with: + name: csharp-documentation + path: csharp/_site + if-no-files-found: error + retention-days: 1 + + publishDocumentation: + needs: [findChangedCsFiles, generatePdfWithCode, buildDocumentation] + if: ${{ needs.findChangedCsFiles.outputs.documentationChanged == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Download documentation artifacts + env: + GH_TOKEN: ${{ github.token }} + run: | + gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --name csharp-documentation --dir _site + gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --name csharp-pdf --dir _site + + - name: Validate documentation site + run: | + ../.github/scripts/validate-csharp-docs.sh _site + test -s _site/Platform.Collections.Methods.pdf + + - name: Publish documentation to gh-pages + if: ${{ github.event_name == 'push' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: ../.github/scripts/publish-csharp-docs.sh _site + + pipelineStatus: + needs: + - test + - coverage + - treeValidation + - releasePreflight + - pushNuGetPackageToGitHubPackageRegistry + - pushToNuget + - publishRelease + - findChangedCsFiles + - generatePdfWithCode + - buildDocumentation + - publishDocumentation + if: ${{ !cancelled() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Check aggregate pipeline status + env: + DOCUMENTATION_CHANGED: ${{ needs.findChangedCsFiles.outputs.documentationChanged }} + EVENT_NAME: ${{ github.event_name }} + NEEDS_JSON: ${{ toJSON(needs) }} + run: node ../.github/scripts/check-csharp-pipeline-status.mjs diff --git a/.github/workflows/deploy-cpp.yml b/.github/workflows/deploy-cpp.yml index 9304934..586aab9 100644 --- a/.github/workflows/deploy-cpp.yml +++ b/.github/workflows/deploy-cpp.yml @@ -2,15 +2,122 @@ name: Deploy new cpp version on: push: - branches: main + branches: [main] paths: - 'cpp/**/*.nuspec' + - '.github/scripts/pack-cpp-nuget.mjs' + - '.github/scripts/check-cpp-nuget-package.sh' + - '.github/scripts/preflight-nuget-release.mjs' + - '.github/scripts/push-nuget-package.sh' + - '.github/workflows/cpp-test.yml' + - '.github/workflows/deploy-cpp.yml' workflow_dispatch: +permissions: + contents: read + +concurrency: + group: deploy-cpp-${{ github.ref }} + cancel-in-progress: false + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + jobs: - main: - uses: linksplatform/Workflows/.github/workflows/deploy-cpp.yml@main - with: - recipe_folder: "platform.delegates" - secrets: - NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + test: + uses: ./.github/workflows/cpp-test.yml + + releasePreflight: + needs: test + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + publishRequired: ${{ steps.preflight.outputs.publish_required }} + auth: ${{ steps.preflight.outputs.auth }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Check release state and credentials + id: preflight + env: + PACKAGE_ID: ${{ needs.test.outputs.package_id }} + PACKAGE_VERSION: ${{ needs.test.outputs.version }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + NUGET_USER: ${{ vars.NUGET_USER }} + run: node .github/scripts/preflight-nuget-release.mjs + + pushToNuget: + needs: [test, releasePreflight] + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Download NuGet package + uses: actions/download-artifact@v8 + with: + name: cpp-nuget-package + path: ${{ runner.temp }}/cpp-nuget + + - name: Log in to NuGet with trusted publishing + id: nuget-login + if: ${{ needs.releasePreflight.outputs.auth == 'trusted-publishing' && needs.releasePreflight.outputs.publishRequired == 'true' }} + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ vars.NUGET_USER }} + + - name: Push NuGet package to NuGet.org + env: + AUTH: ${{ needs.releasePreflight.outputs.auth }} + PUBLISH_REQUIRED: ${{ needs.releasePreflight.outputs.publishRequired }} + NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY || secrets.NUGET_TOKEN }} + run: .github/scripts/push-nuget-package.sh "$RUNNER_TEMP/cpp-nuget"/*.nupkg + + # Waits for the push, so a release always has its package on nuget.org. + publishRelease: + needs: [test, pushToNuget] + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Download NuGet package + uses: actions/download-artifact@v8 + with: + name: cpp-nuget-package + path: ${{ runner.temp }}/cpp-nuget + + - name: Publish GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PACKAGE_ID: ${{ needs.test.outputs.package_id }} + VERSION: ${{ needs.test.outputs.version }} + run: | + tag="cpp_${VERSION}" + if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "Release ${tag} already exists." + exit 0 + fi + archive="$RUNNER_TEMP/platform.collections.methods_${VERSION}.zip" + (cd cpp && zip -q -r "$archive" Platform.Collections.Methods) + notes="https://www.nuget.org/packages/${PACKAGE_ID}/${VERSION}"$'\n\n'"$(cat "$RUNNER_TEMP/cpp-nuget/release-notes.md")" + gh release create "$tag" "$archive" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "[C++] ${VERSION}" --notes "$notes" diff --git a/.github/workflows/readme-badges.yml b/.github/workflows/readme-badges.yml new file mode 100644 index 0000000..17f68cc --- /dev/null +++ b/.github/workflows/readme-badges.yml @@ -0,0 +1,52 @@ +name: Check README badges + +on: + push: + branches: + - 'main' + paths: + - 'README.md' + - 'benchmarks/**' + - '.github/workflows/**' + - '.github/scripts/**' + pull_request: + paths: + - 'README.md' + - 'benchmarks/**' + - '.github/workflows/**' + - '.github/scripts/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + check: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-node@v7 + with: + node-version: '24' + - name: Test the badge check + run: node --test .github/scripts/check-readme-badges.test.mjs + - name: Check that README badges reference existing workflows + run: node .github/scripts/check-readme-badges.mjs --verbose + - name: Test the benchmark report + run: node --test .github/scripts/render-benchmarks.test.mjs + - name: Check that README shows the committed benchmark results + run: node .github/scripts/render-benchmarks.mjs readme --check diff --git a/.github/workflows/secrets.yml b/.github/workflows/secrets.yml new file mode 100644 index 0000000..868c6de --- /dev/null +++ b/.github/workflows/secrets.yml @@ -0,0 +1,44 @@ +name: Secrets + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + secretlint: + name: Scan for committed secrets + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: 24 + + # Scans every tracked file, including the experiments and the case study + # logs. The scan is proven able to fail by + # experiments/secretlint-detects-planted-secret.sh. + - name: Check for secrets + run: >- + npx --yes + -p secretlint@13.0.7 + -p @secretlint/secretlint-rule-preset-recommend@13.0.7 + secretlint "**/*" diff --git a/.github/workflows/workflows.yml b/.github/workflows/workflows.yml new file mode 100644 index 0000000..77a7346 --- /dev/null +++ b/.github/workflows/workflows.yml @@ -0,0 +1,85 @@ +name: Workflows + +on: + push: + branches: [main] + paths: + - '.github/**' + pull_request: + branches: [main] + paths: + - '.github/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + actionlint: + name: Lint workflows + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # The image bundles shellcheck, so every run: block is linted as well. + # Pinned by digest; re-resolve when bumping: + # docker pull rhysd/actionlint: && + # docker inspect --format='{{index .RepoDigests 0}}' rhysd/actionlint: + - name: Lint workflow files + uses: docker://rhysd/actionlint@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 # v1.7.12 + with: + args: -color + + zizmor: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Audit workflow files + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + with: + advanced-security: false + annotations: true + config: .github/zizmor.yml + inputs: .github + min-confidence: medium + version: 1.29.0 + + # Image pinning audits are pedantic-only; this pass keeps them enforced + # without the stylistic findings of the full pedantic persona. The online + # audits already ran in the step above; --offline says so, instead of + # zizmor warning that it fell back to offline mode without a token. + - name: Audit for pedantic-only high-severity findings + run: | + pipx run zizmor==1.29.0 --offline --config .github/zizmor.yml \ + --persona pedantic --min-severity high --min-confidence high \ + .github + + policy: + name: Workflow policy + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Test workflow policies + run: node --test .github/scripts/*workflow-policy.test.mjs diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000..d1092ff --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,13 @@ +# zizmor configuration — https://docs.zizmor.sh/configuration/ +# Adopted from link-foundation/csharp-ai-driven-development-pipeline-template. +rules: + unpinned-uses: + config: + policies: + # These publishers are trusted at tag granularity. Everything else + # must be pinned to a full commit hash (linksplatform/Interfaces#150 replaced + # tj-actions/changed-files, compromised through a mutable tag in + # CVE-2025-30066). + actions/*: ref-pin + github/*: ref-pin + '*': hash-pin diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 0000000..12f6af6 --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,8 @@ +{ + "MD013": { + "line_length": 80, + "tables": false, + "code_blocks": false + }, + "MD041": false +} diff --git a/.secretlintrc.json b/.secretlintrc.json new file mode 100644 index 0000000..7a1a5df --- /dev/null +++ b/.secretlintrc.json @@ -0,0 +1,7 @@ +{ + "rules": [ + { + "id": "@secretlint/secretlint-rule-preset-recommend" + } + ] +} diff --git a/README.md b/README.md index 84cfe5f..8176a0a 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,329 @@ -[![Actions Status](https://github.com/linksplatform/Collections.Methods/workflows/CD/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions?workflow=CD) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/93884a3e5b184aafbf9e900369766972)](https://app.codacy.com/gh/linksplatform/Collections.Methods?utm_source=github.com&utm_medium=referral&utm_content=linksplatform/Collections.Methods&utm_campaign=Badge_Grade_Settings) [![CodeFactor](https://www.codefactor.io/repository/github/linksplatform/collections.methods/badge)](https://www.codefactor.io/repository/github/linksplatform/collections.methods) +[![CodeQL](https://github.com/linksplatform/Collections.Methods/actions/workflows/codeql.yml/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions/workflows/codeql.yml) -| [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods) | C# | -|-|-| -| [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods.TemplateLibrary?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods.TemplateLibrary) | __C++__ | +| [![Actions Status](https://github.com/linksplatform/Collections.Methods/workflows/csharp/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions?workflow=csharp) | [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods) | C# | +| --- | --- | --- | +| [![Actions Status](https://github.com/linksplatform/Collections.Methods/workflows/Test%20cpp/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions?workflow=Test%20cpp) | [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods.TemplateLibrary?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods.TemplateLibrary) | __C++__ | # [Collections.Methods](https://github.com/linksplatform/Collections.Methods) LinksPlatform's Platform.Collections.Methods Class Library. -Namespace: [Platform.Collections.Methods](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.html) +Namespaces: +[Platform.Collections.Methods.Lists](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Lists.html), +[Platform.Collections.Methods.Trees](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Trees.html) Forked from: [Konard/LinksPlatform/Platform/Platform.Data.Core/Collections](https://github.com/Konard/LinksPlatform/tree/b6866f278712c317b4c895e27e49f2d0b3fe561f/Platform/Platform.Data.Core/Collections) NuGet package: [Platform.Collections.Methods](https://www.nuget.org/packages/Platform.Collections.Methods) ## [Documentation](https://linksplatform.github.io/Collections.Methods) -[PDF file](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.pdf) with code for e-readers. + +[PDF file](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.pdf) +with code for e-readers. + +The +[C# workflow](https://github.com/linksplatform/Collections.Methods/actions/workflows/csharp.yml) +builds the DocFX site on every pull request and publishes it from `main`, +including the +[API documentation PDF](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.Documentation.pdf). ## Depend on -* [Platform.Numbers](https://github.com/linksplatform/Numbers) + +* [Platform.Numbers](https://github.com/linksplatform/Numbers) ## Dependent libraries -* [Platform.Data.Doublets](https://github.com/linksplatform/Data.Doublets) + +* [Platform.Data.Doublets](https://github.com/linksplatform/Data.Doublets) + +## Trees + +* `SizeBalancedTreeMethods` runs Chen's recursive *Maintain* on the way back + from every attach and detach. Its height is at most the AVL bound + 1.44 log₂(n + 2). +* `RecursionlessSizeBalancedTreeMethods` makes the same rotations as the + recursive tree, without recursion: the attach path is remembered while + descending and only its nodes are maintained. It builds identical trees to + `SizeBalancedTreeMethods`. +* `SizedAndThreadedAVLBalancedTreeMethods` keeps AVL balance factors and + threaded leaves. Its height is at most the AVL bound. + +Every node `t` of a size balanced tree satisfies Chen's property: +`size(t.left) >= size(t.right.left), size(t.right.right)` and +`size(t.right) >= size(t.left.left), size(t.left.right)`. Trees that an older +version left unbalanced are rebuilt once, in linear time, when an attach or +detach passes more levels than any size balanced tree of their size has. + +## Lists + +The four doubly linked lists keep `previous` and `next` links in every +element: + +* `Absolute*` lists keep one list: its first and last element and its size + are stored once, for example in fields. +* `Relative*` lists keep a list per head element, so one storage can hold many + lists, for example the lists of all links that share a source. +* `*Circular*` lists link the last element back to the first one; `*Open*` + lists end with 0 on both sides. + +Attach and detach are O(1) for all of them. + +## Choosing a structure + +The [benchmarks](https://github.com/linksplatform/Collections.Methods#benchmarks) +below measure these trade-offs: + +* Use `SizedAndThreadedAVLBalancedTreeMethods` when nodes are attached and + detached more often than searched: it attaches and detaches in 0.4–0.75 of + the time of the size balanced tree. Its threads also give the inheritor the + next and previous node (`GetNext`, `GetPrevious`) without a stack. The price + is 16 instead of 12 bytes per `uint` node (a balance factor and two thread + flags) and searches that take 1.06–2.1 times as long, because every step checks + a thread flag. +* Use `SizeBalancedTreeMethods` when searches dominate or memory matters: it + searches as fast as the recursionless tree and faster than the AVL tree, + stores only left, right and size, and attaches and detaches in 0.68–0.91 of + the time of the recursionless tree. +* Use `RecursionlessSizeBalancedTreeMethods` when the stack is limited or the + tree comes from data that other code may have linked badly: it builds the + same trees as `SizeBalancedTreeMethods` and searches as fast, but its stack + use does not depend on the tree, for 1.1–1.46 times the attach and detach + time. +* Use a list when the order of the elements is the order they were added in + and no search by key is needed: its attach and detach are O(1), 24 to 145 times + faster than those of a tree with 1000 elements. The + `*Open*` lists are about 0.8 of the time of the `*Circular*` ones. + +## Memory + +The methods store nothing per node: the inheritor decides where the fields of +a node live (an array, memory mapped file and so on) and the methods read and +write them through abstract accessors. The bytes per node are those of the +test and benchmark storages, which keep the fields in an array of structs; +they double for `ulong` nodes. + +| Structure | Fields of a node | Bytes per node (`uint`) | Memory besides the nodes | +| --- | --- | --- | --- | +| `SizeBalancedTreeMethods` | left, right, size | 12 | one stack frame per level of the path, at most 1.44 log₂(n + 2) levels | +| `RecursionlessSizeBalancedTreeMethods` | left, right, size | 12 | a reused path of steps (parent and two flags, 8 bytes for `uint`): C# allocates 64 + 8 steps with the tree and doubles them when a path is longer; C++ grows a `std::vector` on the first attach | +| `SizedAndThreadedAVLBalancedTreeMethods` | left, right, size, balance, two thread flags | 16 | a path of 11 · sizeof(TElement) + 4 nodes (192 bytes for `uint`): a field array allocated with the tree in C#, a `std::array` on the stack in C++ | +| Doubly linked lists | previous, next | 8 | first, last and size once (`Absolute*`) or per head element (`Relative*`) | + +Attach and detach allocate nothing on the heap once the path buffers have +grown to the height of the tree; the tests count the allocated bytes in both +languages to prove it. + +## Limits + +* Nodes are the numbers 1..`TElement.MaxValue`, 0 means no node. A tree or a + list holds at most 255 `byte`, 65 535 `ushort`, 4 294 967 295 `uint` or + 2⁶⁴ − 1 `ulong` nodes, and the size of a tree always fits in `TElement`. + The tests fill `byte` trees with all 255 nodes. In practice the storage is + the limit: 4 294 967 295 `uint` nodes take 48 GiB in the size balanced tree + storage above. +* A tree of n nodes is at most 1.44 log₂(n + 2) levels high, which is 91 + levels for 2⁶⁴ − 1 nodes, so search, attach and detach are O(log n) in the + worst case. +* Keys must be unique. The AVL tree refuses to attach a node whose key is in + the tree; the size balanced trees attach it, but cannot detach nodes whose + key is shared and throw `InvalidOperationException`. +* Detaching a node that is not in the tree throws `InvalidOperationException` + and leaves the tree intact. +* A tree that other code linked deeper than any balanced tree: the size + balanced trees rebuild it on the next attach or detach (the recursive tree + recurses along that path once, so prefer the recursionless tree for such + data); the AVL tree throws `IndexOutOfRangeException` in C# and + `std::out_of_range` in C++ instead of overflowing its path. +* An instance is not thread-safe: the recursionless and AVL trees reuse their + path buffers, and all structures write the nodes. Use an instance per + thread or a lock. + +## Tests + +The C# and C++ tests run on every pull request and on `main` +([csharp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/csharp.yml), +[Test cpp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/cpp-test.yml)). +They check after every attach and detach that the trees keep their sizes, order +and balance property, that the height stays within the AVL bound, that the +recursive and the recursionless tree build identical trees with the minimum +number of rotations, and that every line of the libraries is executed (100% +line coverage for C# and C++). They also run with +`ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION`, which makes every tree validate itself +after each change: + +```sh +cd csharp && dotnet test -c Release -p:TreeValidation=true +TREE_VALIDATION=1 BUILD_TYPE=Debug SANITIZERS='address;undefined' cpp/build-and-test.sh +``` + +The trees pay nothing for being inspected. The library has no counters, logs +or hooks for tests: the test trees inherit from the library trees and count +rotations and size reads in the node accessors (`GetSize`, `SetLeft`, +`SetRight`) that every tree implements anyway. `LeftRotate` and `RightRotate` +stay non-virtual in C#, and in C++ the test trees shadow them through CRTP, +which compiles to direct calls. The validation mode is a compile-time switch, +so it costs nothing when it is off. + +## Benchmarks + +The benchmarks compare the three trees with each other and the four lists with +each other, in C# ([BenchmarkDotNet](https://benchmarkdotnet.org)) and C++ +([Google Benchmark](https://github.com/google/benchmark)), with the same +storages as the tests: time and allocated bytes of attach and detach, of +search, and the memory of the storage itself. Shared runners are noisy, so +they run only on request: Actions > +[Benchmarks](https://github.com/linksplatform/Collections.Methods/actions/workflows/benchmarks.yml) +\> Run workflow. The run summary shows the tables below for that run; with +`commit-results` the workflow also commits them to this README and to +[benchmarks/results.json](https://github.com/linksplatform/Collections.Methods/blob/main/benchmarks/results.json). +Locally: + +```sh +cd csharp && dotnet run -c Release --project Platform.Collections.Methods.Benchmarks -- --filter '*' --exporters json +BENCHMARKS=1 cpp/build-and-test.sh && cpp/build/bin/Platform.Collections.Methods.Benchmarks --benchmark_out=cpp.json --benchmark_out_format=json +node .github/scripts/render-benchmarks.mjs normalize --csharp csharp/BenchmarkDotNet.Artifacts/results --cpp cpp.json +node .github/scripts/render-benchmarks.mjs readme +``` + +The C# allocated column comes from BenchmarkDotNet's MemoryDiagnoser, which +also counts what the runtime allocates for itself (JIT, timers) during the +measurement and divides it by the invocations; the long benchmarks run few +invocations, so this noise shows as a few dozen bytes. The tests above prove +that attach and detach allocate nothing in both languages. + + + + +Run the [Benchmarks +workflow](https://github.com/linksplatform/Collections.Methods/actions/workflows/benchmarks.yml) +with commit-results to update these results, which come from: + +* C#: .NET 8.0.34 (8.0.3426.52217), BenchmarkDotNet 0.14.0, Ubuntu 24.04.5 LTS + (Noble Numbat), Intel Xeon 6975P-C, 4 logical cores ([Benchmarks workflow + run](https://github.com/linksplatform/Collections.Methods/actions/runs/46286800162) + of commit `47bd4ee` on 2026-11-29). +* C++: g++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0, Google Benchmark v1.9.1, 4 + CPUs at 3241 MHz ([Benchmarks workflow + run](https://github.com/linksplatform/Collections.Methods/actions/runs/46286800162) + of commit `47bd4ee` on 2026-11-29). + +Mean is the time of one invocation, which handles all N nodes; ratio compares it +with the first structure of the same table, language and parameters; allocated +is the heap memory one invocation allocates. Shared runners are noisy, so +compare ratios rather than absolute times, and measure on your own hardware for +decisions. + +### Trees: attach and detach + +Attaches the nodes 1..N to an empty tree in the given order, then detaches all +of them (in another random order for Random). + +| N | Order | Tree | C# mean | C# ratio | C# allocated | C++ mean | C++ ratio | C++ allocated | +| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 1000 | Ascending | SizeBalancedTree | 363 μs | 1.00 | 0 B | 127 μs | 1.00 | 0 B | +| 1000 | Ascending | RecursionlessSizeBalancedTree | 412 μs | 1.13 | 0 B | 159 μs | 1.25 | 0 B | +| 1000 | Ascending | SizedAndThreadedAVLBalancedTree | 209 μs | 0.58 | 0 B | 73.4 μs | 0.58 | 0 B | +| 1000 | Descending | SizeBalancedTree | 380 μs | 1.00 | 0 B | 118 μs | 1.00 | 0 B | +| 1000 | Descending | RecursionlessSizeBalancedTree | 427 μs | 1.12 | 0 B | 161 μs | 1.36 | 0 B | +| 1000 | Descending | SizedAndThreadedAVLBalancedTree | 209 μs | 0.55 | 0 B | 74.9 μs | 0.63 | 0 B | +| 1000 | Random | SizeBalancedTree | 441 μs | 1.00 | 0 B | 170 μs | 1.00 | 0 B | +| 1000 | Random | RecursionlessSizeBalancedTree | 595 μs | 1.35 | 1 B | 248 μs | 1.46 | 0 B | +| 1000 | Random | SizedAndThreadedAVLBalancedTree | 323 μs | 0.73 | 0 B | 81.3 μs | 0.48 | 0 B | +| 100000 | Ascending | SizeBalancedTree | 56.6 ms | 1.00 | 82 B | 26.4 ms | 1.00 | 0 B | +| 100000 | Ascending | RecursionlessSizeBalancedTree | 67.8 ms | 1.20 | 92 B | 29.1 ms | 1.10 | 0 B | +| 100000 | Ascending | SizedAndThreadedAVLBalancedTree | 28.8 ms | 0.51 | 23 B | 10.5 ms | 0.40 | 0 B | +| 100000 | Descending | SizeBalancedTree | 59.4 ms | 1.00 | 82 B | 27.4 ms | 1.00 | 0 B | +| 100000 | Descending | RecursionlessSizeBalancedTree | 68.1 ms | 1.15 | 92 B | 30.2 ms | 1.10 | 0 B | +| 100000 | Descending | SizedAndThreadedAVLBalancedTree | 28.1 ms | 0.47 | 23 B | 11.2 ms | 0.41 | 0 B | +| 100000 | Random | SizeBalancedTree | 75.7 ms | 1.00 | 105 B | 43.5 ms | 1.00 | 0 B | +| 100000 | Random | RecursionlessSizeBalancedTree | 104 ms | 1.38 | 147 B | 54.1 ms | 1.25 | 0 B | +| 100000 | Random | SizedAndThreadedAVLBalancedTree | 49.2 ms | 0.65 | 67 B | 32.1 ms | 0.74 | 0 B | + +### Trees: search + +Looks every one of the N nodes up (Contains) in a tree built by attaching them +in the given order. + +| N | Order | Tree | C# mean | C# ratio | C# allocated | C++ mean | C++ ratio | C++ allocated | +| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 1000 | Ascending | SizeBalancedTree | 29.3 μs | 1.00 | 0 B | 8.43 μs | 1.00 | 0 B | +| 1000 | Ascending | RecursionlessSizeBalancedTree | 28.8 μs | 0.98 | 0 B | 8.37 μs | 0.99 | 0 B | +| 1000 | Ascending | SizedAndThreadedAVLBalancedTree | 48.1 μs | 1.64 | 0 B | 10.4 μs | 1.24 | 0 B | +| 1000 | Descending | SizeBalancedTree | 28.2 μs | 1.00 | 0 B | 8.06 μs | 1.00 | 0 B | +| 1000 | Descending | RecursionlessSizeBalancedTree | 28.2 μs | 1.00 | 0 B | 7.97 μs | 0.99 | 0 B | +| 1000 | Descending | SizedAndThreadedAVLBalancedTree | 48 μs | 1.70 | 0 B | 9.77 μs | 1.21 | 0 B | +| 1000 | Random | SizeBalancedTree | 25.1 μs | 1.00 | 0 B | 10.7 μs | 1.00 | 0 B | +| 1000 | Random | RecursionlessSizeBalancedTree | 25.2 μs | 1.00 | 0 B | 10.8 μs | 1.01 | 0 B | +| 1000 | Random | SizedAndThreadedAVLBalancedTree | 52.1 μs | 2.07 | 0 B | 12.4 μs | 1.15 | 0 B | +| 100000 | Ascending | SizeBalancedTree | 4.92 ms | 1.00 | 6 B | 4.16 ms | 1.00 | 0 B | +| 100000 | Ascending | RecursionlessSizeBalancedTree | 4.79 ms | 0.97 | 6 B | 4.16 ms | 1.00 | 0 B | +| 100000 | Ascending | SizedAndThreadedAVLBalancedTree | 6.88 ms | 1.40 | 6 B | 5.34 ms | 1.28 | 0 B | +| 100000 | Descending | SizeBalancedTree | 4.95 ms | 1.00 | 6 B | 4.22 ms | 1.00 | 0 B | +| 100000 | Descending | RecursionlessSizeBalancedTree | 4.88 ms | 0.99 | 6 B | 4.23 ms | 1.00 | 0 B | +| 100000 | Descending | SizedAndThreadedAVLBalancedTree | 6.52 ms | 1.32 | 6 B | 5.34 ms | 1.26 | 0 B | +| 100000 | Random | SizeBalancedTree | 10.5 ms | 1.00 | 12 B | 10.7 ms | 1.00 | 0 B | +| 100000 | Random | RecursionlessSizeBalancedTree | 10.6 ms | 1.01 | 12 B | 10.8 ms | 1.00 | 0 B | +| 100000 | Random | SizedAndThreadedAVLBalancedTree | 12.5 ms | 1.19 | 12 B | 11.4 ms | 1.06 | 0 B | + +### Lists: attach and detach + +Attaches the elements 1..N to an empty list as last ones, then detaches all of +them from the first one. + +| N | List | C# mean | C# ratio | C# allocated | C++ mean | C++ ratio | C++ allocated | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 1000 | AbsoluteCircularDoublyLinkedList | 3.59 μs | 1.00 | 0 B | 3.12 μs | 1.00 | 0 B | +| 1000 | AbsoluteOpenDoublyLinkedList | 3.05 μs | 0.85 | 0 B | 2.5 μs | 0.80 | 0 B | +| 1000 | RelativeCircularDoublyLinkedList | 5.53 μs | 1.54 | 0 B | 3.12 μs | 1.00 | 0 B | +| 1000 | RelativeOpenDoublyLinkedList | 4.38 μs | 1.22 | 0 B | 2.49 μs | 0.80 | 0 B | +| 100000 | AbsoluteCircularDoublyLinkedList | 372 μs | 1.00 | 0 B | 320 μs | 1.00 | 0 B | +| 100000 | AbsoluteOpenDoublyLinkedList | 308 μs | 0.83 | 0 B | 253 μs | 0.79 | 0 B | +| 100000 | RelativeCircularDoublyLinkedList | 548 μs | 1.47 | 1 B | 319 μs | 1.00 | 0 B | +| 100000 | RelativeOpenDoublyLinkedList | 451 μs | 1.21 | 0 B | 252 μs | 0.79 | 0 B | + +### Memory: storage of N nodes + +Creates an empty tree or list that can hold N nodes besides the zero node; the +allocated bytes are the memory it uses, the bytes per node divide them by N + 1. + +| N | Structure | C# allocated | C# bytes per node | C++ allocated | C++ bytes per node | +| --- | --- | ---: | ---: | ---: | ---: | +| 1000 | SizeBalancedTree | 11.83 KB | 12.1 | 11.74 KB | 12.0 | +| 1000 | RecursionlessSizeBalancedTree | 12.45 KB | 12.7 | 11.79 KB | 12.1 | +| 1000 | SizedAndThreadedAVLBalancedTree | 15.95 KB | 16.3 | 15.65 KB | 16.0 | +| 1000 | AbsoluteCircularDoublyLinkedList | 7.92 KB | 8.1 | 7.83 KB | 8.0 | +| 1000 | AbsoluteOpenDoublyLinkedList | 7.92 KB | 8.1 | 7.83 KB | 8.0 | +| 1000 | RelativeCircularDoublyLinkedList | 8.02 KB | 8.2 | 7.83 KB | 8.0 | +| 1000 | RelativeOpenDoublyLinkedList | 8.02 KB | 8.2 | 7.83 KB | 8.0 | +| 100000 | SizeBalancedTree | 1.14 MB | 12.0 | 1.14 MB | 12.0 | +| 100000 | RecursionlessSizeBalancedTree | 1.15 MB | 12.0 | 1.14 MB | 12.0 | +| 100000 | SizedAndThreadedAVLBalancedTree | 1.53 MB | 16.0 | 1.53 MB | 16.0 | +| 100000 | AbsoluteCircularDoublyLinkedList | 781.51 KB | 8.0 | 781.27 KB | 8.0 | +| 100000 | AbsoluteOpenDoublyLinkedList | 781.52 KB | 8.0 | 781.27 KB | 8.0 | +| 100000 | RelativeCircularDoublyLinkedList | 781.63 KB | 8.0 | 781.27 KB | 8.0 | +| 100000 | RelativeOpenDoublyLinkedList | 781.62 KB | 8.0 | 781.27 KB | 8.0 | + + + +## Releasing + +A version bump in +`csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj` or +`cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec` +merged to `main` publishes the package to nuget.org and creates a GitHub +release, after the tests passed. Publishing uses +[trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) +first: + +1. On nuget.org, add trusted publishing policies for the repository + `linksplatform/Collections.Methods` with the workflows `csharp.yml` and + `deploy-cpp.yml`. +2. Set the repository variable `NUGET_USER` to the nuget.org user that owns + the policies. + +Without `NUGET_USER` the workflows fall back to the `NUGET_TOKEN` secret (a +nuget.org API key with push scope). A release preflight fails early with an +explanation when neither works. Dependabot pull requests are merged +automatically with the `DEPENDABOT_AUTO_MERGE_TOKEN` secret once "Allow +auto-merge" is enabled. diff --git a/benchmarks/results.json b/benchmarks/results.json new file mode 100644 index 0000000..3cab143 --- /dev/null +++ b/benchmarks/results.json @@ -0,0 +1,1258 @@ +{ + "environments": { + "C#": { + "benchmarkDotNet": "0.14.0", + "runtime": ".NET 8.0.34 (8.0.3426.52217)", + "os": "Ubuntu 24.04.5 LTS (Noble Numbat)", + "processor": "Intel Xeon 6975P-C", + "logicalCores": 4, + "date": "2026-11-29T17:25:34.142Z", + "commit": "47bd4ee1d377cd4402755a17caba5ce62642dd84", + "runUrl": "https://github.com/linksplatform/Collections.Methods/actions/runs/46286800162" + }, + "C++": { + "googleBenchmark": "v1.9.1", + "compiler": "g++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0", + "cpus": 4, + "mhzPerCpu": 3241, + "buildType": "release", + "date": "2026-11-29T17:25:34.142Z", + "commit": "47bd4ee1d377cd4402755a17caba5ce62642dd84", + "runUrl": "https://github.com/linksplatform/Collections.Methods/actions/runs/46286800162" + } + }, + "records": [ + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 363317.80126953125, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 412011.76341145835, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 209401.92294921874, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 380453.4845052083, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 427362.70060221356, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 209287.59957682292, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 440625.84221540176, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 594744.0941080729, + "allocatedBytes": 1 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 322593.4829752604, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 56568440.97435899, + "allocatedBytes": 82 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 67839631.14166667, + "allocatedBytes": 92 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 28805639.776785713, + "allocatedBytes": 23 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 59400689.79259259, + "allocatedBytes": 82 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 68115761.75833334, + "allocatedBytes": 92 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 28074291.472916666, + "allocatedBytes": 23 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 75704818.00000001, + "allocatedBytes": 105 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 104174083.94285715, + "allocatedBytes": 147 + }, + { + "language": "C#", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 49242937.35151515, + "allocatedBytes": 67 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 29347.542177327476, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 28778.515207926434, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 48078.106457519534, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 28234.031848144532, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 28181.16096394857, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 48018.272937011716, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 25120.0672068278, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 25195.275268554688, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 52065.06161295573, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 4916176.770647322, + "allocatedBytes": 6 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 4791781.259375, + "allocatedBytes": 6 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 6875503.228385417, + "allocatedBytes": 6 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 4945318.399553572, + "allocatedBytes": 6 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 4877948.364583333, + "allocatedBytes": 6 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 6520326.137760417, + "allocatedBytes": 6 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 10487123.496875, + "allocatedBytes": 12 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 10565199.287259616, + "allocatedBytes": 12 + }, + { + "language": "C#", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 12467705.072916666, + "allocatedBytes": 12 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 3586.3363156636556, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 3050.9036158243816, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 5526.893932596842, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 4378.115559895833, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 372178.96330915176, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 308229.0709798177, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 547717.7956705729, + "allocatedBytes": 1 + }, + { + "language": "C#", + "group": "ListBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 450694.0397135417, + "allocatedBytes": 0 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 723.2520366001129, + "allocatedBytes": 12112 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 813.1326993370056, + "allocatedBytes": 12752 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 1059.2832892990111, + "allocatedBytes": 16336 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 593.0442112350464, + "allocatedBytes": 8112 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 577.8065072631836, + "allocatedBytes": 8112 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 535.490009431839, + "allocatedBytes": 8216 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 591.6601769828796, + "allocatedBytes": 8216 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 28621.566881965187, + "allocatedBytes": 1200223 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 28561.97294108073, + "allocatedBytes": 1200822 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 37639.34317220052, + "allocatedBytes": 1600408 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 22920.729197184246, + "allocatedBytes": 800269 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 22949.32341512044, + "allocatedBytes": 800280 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 22874.326881917317, + "allocatedBytes": 800384 + }, + { + "language": "C#", + "group": "StorageBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 22908.447760009767, + "allocatedBytes": 800380 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 126873.32312097319, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 158872.025076596, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 73386.68227529839, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 118436.7899624446, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 161051.56513339508, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 74946.23426935251, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 170011.15594389598, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 248404.89032258265, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 81334.7219410259, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 26438612.75384624, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 29131701.23333326, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 10475776.623880632, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 27361032.383999944, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 30151004.9304348, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 11217471.967213124, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 43454953.137499616, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 54148800.41538483, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 32063986.036363512, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 8431.75798571511, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 8372.525644647674, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Ascending" + }, + "meanNanoseconds": 10433.883217406712, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 8062.620939291856, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 7974.844807212923, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Descending" + }, + "meanNanoseconds": 9767.363556364824, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 10748.575071334268, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 10824.43845857533, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000, + "Order": "Random" + }, + "meanNanoseconds": 12381.331926266272, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 4161331.0345238084, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 4160761.7333332384, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Ascending" + }, + "meanNanoseconds": 5340907.69923662, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 4224942.536526959, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 4234026.798795162, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Descending" + }, + "meanNanoseconds": 5344126.255639133, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 10738284.412307736, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 10780455.228125077, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "TreeSearchBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000, + "Order": "Random" + }, + "meanNanoseconds": 11414833.099999923, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 3123.487824168295, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 2501.3790938362827, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 3116.928198720172, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 2494.7314688897973, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 319869.548792709, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 252790.72735135155, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 319327.56654511986, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "ListBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 252471.7154868924, + "allocatedBytes": 0 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 174.50242632632785, + "allocatedBytes": 12020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 181.47657013014808, + "allocatedBytes": 12072 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 215.1025384622996, + "allocatedBytes": 16024 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 124.19558510328531, + "allocatedBytes": 8020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 124.07809782229776, + "allocatedBytes": 8020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 124.14931677145864, + "allocatedBytes": 8020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 1000 + }, + "meanNanoseconds": 124.05811808522489, + "allocatedBytes": 8020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "SizeBalancedTree", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 18182.98901413593, + "allocatedBytes": 1200020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "RecursionlessSizeBalancedTree", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 36471.3340186822, + "allocatedBytes": 1200072 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "SizedAndThreadedAVLBalancedTree", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 24363.209676410257, + "allocatedBytes": 1600024 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "AbsoluteCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 11692.698556494019, + "allocatedBytes": 800020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "AbsoluteOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 13695.47196377094, + "allocatedBytes": 800020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "RelativeCircularDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 13729.595015381166, + "allocatedBytes": 800020 + }, + { + "language": "C++", + "group": "StorageBenchmarks", + "structure": "RelativeOpenDoublyLinkedList", + "parameters": { + "N": 100000 + }, + "meanNanoseconds": 13805.663509032354, + "allocatedBytes": 800020 + } + ] +} diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index aca73d4..35bb3f2 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -1,33 +1,98 @@ -cmake_minimum_required(VERSION 3.13) +cmake_minimum_required(VERSION 3.16) set(LINKS_PLATFORM_TESTS ON CACHE BOOL "Whether to compile tests") set(LINKS_PLATFORM_BENCHMARKS ON CACHE BOOL "Whether to compile benchmarks") set(LINKS_PLATFORM_EXTRA_FLAGS "" CACHE STRING "Extra compiler flags") +set(LINKS_PLATFORM_SANITIZERS "" CACHE STRING "Sanitizers for the tests, e.g. address;undefined") +set(LINKS_PLATFORM_COVERAGE OFF CACHE BOOL "Whether to instrument the tests for gcov line coverage") +set(LINKS_PLATFORM_TREE_VALIDATION OFF CACHE BOOL "Whether the trees validate themselves after every attach and detach (ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION)") set(CONAN_DISABLE_CHECK_COMPILER TRUE) project(Platform.Collections.Methods CXX) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) -find_package(GTest) -find_package(benchmark) -find_package(Platform.Interfaces) +include(FetchContent) add_library(${PROJECT_NAME}.Library INTERFACE) target_include_directories(${PROJECT_NAME}.Library INTERFACE ${PROJECT_NAME}) +target_compile_features(${PROJECT_NAME}.Library INTERFACE cxx_std_20) + +# The headers need Platform.Interfaces (Polymorph.h). Conan provides it when its toolchain is used; +# otherwise the headers of the same release (cpp_0.3.41) are fetched from GitHub by commit. +find_package(Platform.Interfaces QUIET) +if(NOT TARGET Platform.Interfaces::Platform.Interfaces) + FetchContent_Declare(PlatformInterfaces + GIT_REPOSITORY https://github.com/linksplatform/Interfaces.git + GIT_TAG 6b48e959bf25b5574fe2ee30afcccd8d7261403a # cpp_0.3.41 + # Only the headers are used, so the Interfaces CMake project (and its tests) is not added. + SOURCE_SUBDIR headers-only) + FetchContent_MakeAvailable(PlatformInterfaces) + add_library(Platform.Interfaces INTERFACE) + target_include_directories(Platform.Interfaces INTERFACE ${platforminterfaces_SOURCE_DIR}/cpp/Platform.Interfaces) + add_library(Platform.Interfaces::Platform.Interfaces ALIAS Platform.Interfaces) +endif() target_link_libraries(${PROJECT_NAME}.Library INTERFACE Platform.Interfaces::Platform.Interfaces) +# Applies the options of this file to a test or benchmark executable. +function(links_platform_configure target) + set_target_properties(${target} PROPERTIES CXX_STANDARD 20 CXX_STANDARD_REQUIRED ON) + target_link_libraries(${target} PRIVATE ${PROJECT_NAME}.Library) + if(LINKS_PLATFORM_EXTRA_FLAGS) + separate_arguments(extra_flags NATIVE_COMMAND "${LINKS_PLATFORM_EXTRA_FLAGS}") + target_compile_options(${target} PRIVATE ${extra_flags}) + endif() + if(LINKS_PLATFORM_TREE_VALIDATION) + target_compile_definitions(${target} PRIVATE ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION=1) + endif() + if(MSVC) + target_compile_options(${target} PRIVATE /W3 /bigobj /permissive-) + else() + target_compile_options(${target} PRIVATE -Wall -Wextra) + endif() +endfunction() + if(${LINKS_PLATFORM_TESTS}) + find_package(GTest QUIET) + if(NOT TARGET GTest::gtest_main) + # Platforms without a GTest package (Windows, macOS without Homebrew's googletest) build it from source. + set(INSTALL_GTEST OFF CACHE BOOL "" FORCE) + set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + FetchContent_Declare(googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG b514bdc898e2951020cbdca1304b75f5950d1f59 # v1.15.2 + GIT_SHALLOW FALSE) + FetchContent_MakeAvailable(googletest) + endif() + enable_testing() add_executable(${PROJECT_NAME}.Tests ${PROJECT_NAME}.Tests/AllTests.cpp) - set_target_properties(${PROJECT_NAME}.Tests PROPERTIES CXX_STANDARD 20) - target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest) - target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest_main) - target_link_libraries(${PROJECT_NAME}.Tests PRIVATE ${PROJECT_NAME}.Library) + links_platform_configure(${PROJECT_NAME}.Tests) + target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest GTest::gtest_main) + if(LINKS_PLATFORM_SANITIZERS) + list(JOIN LINKS_PLATFORM_SANITIZERS "," sanitizers) + target_compile_options(${PROJECT_NAME}.Tests PRIVATE -fsanitize=${sanitizers} -fno-sanitize-recover=all -fno-omit-frame-pointer) + target_link_options(${PROJECT_NAME}.Tests PRIVATE -fsanitize=${sanitizers}) + endif() + if(LINKS_PLATFORM_COVERAGE) + target_compile_options(${PROJECT_NAME}.Tests PRIVATE --coverage -O0 -fno-inline -fno-elide-constructors) + target_link_options(${PROJECT_NAME}.Tests PRIVATE --coverage) + endif() + add_test(NAME ${PROJECT_NAME}.Tests COMMAND ${PROJECT_NAME}.Tests) endif() if(${LINKS_PLATFORM_BENCHMARKS}) + find_package(benchmark QUIET) + if(NOT TARGET benchmark::benchmark) + set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE) + set(BENCHMARK_ENABLE_GTEST_TESTS OFF CACHE BOOL "" FORCE) + set(BENCHMARK_ENABLE_INSTALL OFF CACHE BOOL "" FORCE) + FetchContent_Declare(benchmark + GIT_REPOSITORY https://github.com/google/benchmark.git + GIT_TAG c58e6d0710581e3a08d65c349664128a8d9a2461 # v1.9.1 + GIT_SHALLOW FALSE) + FetchContent_MakeAvailable(benchmark) + endif() add_executable(${PROJECT_NAME}.Benchmarks ${PROJECT_NAME}.Benchmarks/AllBenchmarks.cpp) - set_target_properties(${PROJECT_NAME}.Benchmarks PROPERTIES CXX_STANDARD 20) + links_platform_configure(${PROJECT_NAME}.Benchmarks) target_link_libraries(${PROJECT_NAME}.Benchmarks PRIVATE benchmark::benchmark) - target_link_libraries(${PROJECT_NAME}.Benchmarks PRIVATE ${PROJECT_NAME}.Library) -endif() \ No newline at end of file +endif() diff --git a/cpp/Platform.Collections.Methods.Benchmarks/AllBenchmarks.cpp b/cpp/Platform.Collections.Methods.Benchmarks/AllBenchmarks.cpp index 2639a91..daa1f16 100644 --- a/cpp/Platform.Collections.Methods.Benchmarks/AllBenchmarks.cpp +++ b/cpp/Platform.Collections.Methods.Benchmarks/AllBenchmarks.cpp @@ -1,3 +1,34 @@ #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include +#include "../Platform.Collections.Methods.Tests/Trees.h" + +#include "../Platform.Collections.Methods.Tests/AllocationCounter.cpp" +#include "Measurement.cpp" #include "TreesBenchmark.cpp" +#include "ListsBenchmark.cpp" + +int main(int argc, char** argv) +{ + Platform::Collections::Methods::Benchmarks::RegisterTrees(); + Platform::Collections::Methods::Benchmarks::RegisterLists(); + benchmark::Initialize(&argc, argv); + if (benchmark::ReportUnrecognizedArguments(argc, argv)) + { + return 1; + } + benchmark::RunSpecifiedBenchmarks(); + benchmark::Shutdown(); + return 0; +} diff --git a/cpp/Platform.Collections.Methods.Benchmarks/ListsBenchmark.cpp b/cpp/Platform.Collections.Methods.Benchmarks/ListsBenchmark.cpp new file mode 100644 index 0000000..a6fefd2 --- /dev/null +++ b/cpp/Platform.Collections.Methods.Benchmarks/ListsBenchmark.cpp @@ -0,0 +1,57 @@ +namespace Platform::Collections::Methods::Benchmarks +{ + using namespace Platform::Collections::Methods::Tests; + + // The relative lists of the benchmarks hold one list, whose head is this element. + constexpr std::uint32_t Head = 0; + + template using RelativeCircularList = RelativeCircularDoublyLinkedList; + + template using RelativeOpenList = RelativeOpenDoublyLinkedList; + + // Attaches the elements 1..n to a list as last ones and then detaches all of them from the first one. + template void AttachAndDetachList(benchmark::State& state, std::size_t n) + { + auto list = std::make_unique(); + Measure(state, [&] + { + for (std::uint32_t element = 1; element <= n; element++) + { + if constexpr (Relative) { list->AttachAsLast(Head, element); } else { list->AttachAsLast(element); } + } + benchmark::DoNotOptimize(list.get()); + for (std::uint32_t element = 1; element <= n; element++) + { + if constexpr (Relative) { list->Detach(Head, element); } else { list->Detach(element); } + } + }); + } + + // Creates an empty list storage that can hold n elements besides the zero element. + template void CreateList(benchmark::State& state) + { + Measure(state, [&] + { + auto list = std::make_unique(); + benchmark::DoNotOptimize(list.get()); + }); + } + + template